1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/18 15:52:22 $
7 Version: $Revision: 1.196 $
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__) || defined(__MINGW32__)
42 #ifdef CMAKE_HAVE_NETINET_IN_H
43 #include <netinet/in.h>
49 //-----------------------------------------------------------------------------
50 // Refer to Document::CheckSwap()
51 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
53 // Refer to Document::SetMaxSizeLoadEntry()
54 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
55 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
57 //-----------------------------------------------------------------------------
58 // Constructor / Destructor
62 * @param filename file to be opened for parsing
64 Document::Document( std::string const &filename ) : ElementSet(-1)
66 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
76 Group0002Parsed = false;
78 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
79 // Fp->seekg( 0, std::ios::beg);
81 Fp->seekg(0, std::ios::end);
82 long lgt = Fp->tellg();
84 Fp->seekg( 0, std::ios::beg);
87 long beg = Fp->tellg();
90 ParseDES( this, beg, lgt, false); // Loading is done during parsing
92 Fp->seekg( 0, std::ios::beg);
94 // Load 'non string' values
96 std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);
97 if( PhotometricInterpretation == "PALETTE COLOR " )
99 LoadEntryBinArea(0x0028,0x1200); // gray LUT
100 /// FIXME FIXME FIXME
101 /// The tags refered by the three following lines used to be CORRECTLY
102 /// defined as having an US Value Representation in the public
103 /// dictionary. BUT the semantics implied by the three following
104 /// lines state that the corresponding tag contents are in fact
105 /// the ones of a BinEntry.
106 /// In order to fix things "Quick and Dirty" the dictionary was
107 /// altered on PURPOSE but now contains a WRONG value.
108 /// In order to fix things and restore the dictionary to its
109 /// correct value, one needs to decided of the semantics by deciding
110 /// whether the following tags are either:
111 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
112 /// also used as BinEntry, which requires the proper conversion,
113 /// - OW, and hence loaded as BinEntry, but afterwards also used
114 /// as ValEntry, which requires the proper conversion.
115 LoadEntryBinArea(0x0028,0x1201); // R LUT
116 LoadEntryBinArea(0x0028,0x1202); // G LUT
117 LoadEntryBinArea(0x0028,0x1203); // B LUT
119 // Segmented Red Palette Color LUT Data
120 LoadEntryBinArea(0x0028,0x1221);
121 // Segmented Green Palette Color LUT Data
122 LoadEntryBinArea(0x0028,0x1222);
123 // Segmented Blue Palette Color LUT Data
124 LoadEntryBinArea(0x0028,0x1223);
126 //FIXME later : how to use it?
127 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
131 // --------------------------------------------------------------
132 // Specific code to allow gdcm to read ACR-LibIDO formated images
133 // Note: ACR-LibIDO is an extension of the ACR standard that was
134 // used at CREATIS. For the time being (say a couple years)
135 // we keep this kludge to allow a smooth move to gdcm for
136 // CREATIS developpers (sorry folks).
138 // if recognition code tells us we deal with a LibIDO image
139 // we switch lineNumber and columnNumber
142 RecCode = GetEntry(0x0008, 0x0010); // recognition code
143 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
144 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
145 // with "little-endian strings"
147 Filetype = ACR_LIBIDO;
148 std::string rows = GetEntry(0x0028, 0x0010);
149 std::string columns = GetEntry(0x0028, 0x0011);
150 SetEntry(columns, 0x0028, 0x0010);
151 SetEntry(rows , 0x0028, 0x0011);
153 // ----------------- End of ACR-LibIDO kludge ------------------
157 * \brief This default constructor doesn't parse the file. You should
158 * then invoke \ref Document::SetFileName and then the parsing.
160 Document::Document() : ElementSet(-1)
164 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
167 Filetype = ExplicitVR;
168 Group0002Parsed = false;
172 * \brief Canonical destructor.
174 Document::~Document ()
183 //-----------------------------------------------------------------------------
187 * \brief Prints The Dict Entries of THE public Dicom Dictionary
190 void Document::PrintPubDict(std::ostream &os)
192 RefPubDict->SetPrintLevel(PrintLevel);
193 RefPubDict->Print(os);
197 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
200 void Document::PrintShaDict(std::ostream &os)
202 RefShaDict->SetPrintLevel(PrintLevel);
203 RefShaDict->Print(os);
206 //-----------------------------------------------------------------------------
209 * \brief Get the public dictionary used
211 Dict *Document::GetPubDict()
217 * \brief Get the shadow dictionary used
219 Dict *Document::GetShaDict()
225 * \brief Set the shadow dictionary used
226 * @param dict dictionary to use in shadow
228 bool Document::SetShaDict(Dict *dict)
235 * \brief Set the shadow dictionary used
236 * @param dictName name of the dictionary to use in shadow
238 bool Document::SetShaDict(DictKey const &dictName)
240 RefShaDict = Global::GetDicts()->GetDict(dictName);
245 * \brief This predicate, based on hopefully reasonable heuristics,
246 * decides whether or not the current Document was properly parsed
247 * and contains the mandatory information for being considered as
248 * a well formed and usable Dicom/Acr File.
249 * @return true when Document is the one of a reasonable Dicom/Acr file,
252 bool Document::IsReadable()
254 if( Filetype == Unknown)
256 gdcmVerboseMacro( "Wrong filetype");
262 gdcmVerboseMacro( "No tags in internal hash table.");
270 * \brief Accessor to the Transfer Syntax (when present) of the
271 * current document (it internally handles reading the
272 * value from disk when only parsing occured).
273 * @return The encountered Transfer Syntax of the current document.
275 std::string Document::GetTransferSyntax()
277 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
283 // The entry might be present but not loaded (parsing and loading
284 // happen at different stages): try loading and proceed with check...
285 LoadDocEntrySafe(entry);
286 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
288 std::string transfer = valEntry->GetValue();
289 // The actual transfer (as read from disk) might be padded. We
290 // first need to remove the potential padding. We can make the
291 // weak assumption that padding was not executed with digits...
292 if ( transfer.length() == 0 )
294 // for brain damaged headers
297 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
299 transfer.erase(transfer.length()-1, 1);
307 * \brief Predicate for dicom version 3 file.
308 * @return True when the file is a dicom version 3.
310 bool Document::IsDicomV3()
312 // Checking if Transfer Syntax exists is enough
313 // Anyway, it's to late check if the 'Preamble' was found ...
314 // And ... would it be a rich idea to check ?
315 // (some 'no Preamble' DICOM images exist !)
316 return GetDocEntry(0x0002, 0x0010) != NULL;
320 * \brief returns the File Type
321 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
322 * @return the FileType code
324 FileType Document::GetFileType()
330 * \brief Tries to open the file \ref Document::Filename and
331 * checks the preamble when existing.
332 * @return The FILE pointer on success.
334 std::ifstream *Document::OpenFile()
337 HasDCMPreamble = false;
338 if (Filename.length() == 0)
345 gdcmVerboseMacro( "File already open: " << Filename.c_str());
348 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
351 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
358 Fp->read((char*)&zero, (size_t)2);
365 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
367 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
368 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
369 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
370 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
373 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
374 gdcmVerboseMacro( msg.c_str() );
379 Fp->seekg(126L, std::ios::cur);
381 Fp->read(dicm, (size_t)4);
387 if( memcmp(dicm, "DICM", 4) == 0 )
389 HasDCMPreamble = true;
394 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
400 * \brief closes the file
401 * @return TRUE if the close was successfull
403 bool Document::CloseFile()
412 return true; //FIXME how do we detect a non-close ifstream ?
416 * \brief Writes in a file all the Header Entries (Dicom Elements)
417 * @param fp file pointer on an already open file (actually: Output File Stream)
418 * @param filetype Type of the File to be written
419 * (ACR-NEMA, ExplicitVR, ImplicitVR)
420 * \return Always true.
422 void Document::WriteContent(std::ofstream *fp, FileType filetype)
424 /// \todo move the following lines (and a lot of others, to be written)
425 /// to a future function CheckAndCorrectHeader
426 /// (necessary if user wants to write a DICOM V3 file
427 /// starting from an ACR-NEMA (V2) Header
429 if ( filetype == ImplicitVR || filetype == ExplicitVR )
431 // writing Dicom File Preamble
432 char filePreamble[128];
433 memset(filePreamble, 0, 128);
434 fp->write(filePreamble, 128);
435 fp->write("DICM", 4);
439 * \todo rewrite later, if really usefull
440 * - 'Group Length' element is optional in DICOM
441 * - but un-updated odd groups lengthes can causes pb
444 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
445 * UpdateGroupLength(false,filetype);
446 * if ( filetype == ACR)
447 * UpdateGroupLength(true,ACR);
450 ElementSet::WriteContent(fp, filetype); // This one is recursive
454 * \brief Modifies the value of a given Doc Entry (Dicom Element)
455 * when it exists. Create it with the given value when unexistant.
456 * @param value (string) Value to be set
457 * @param group Group number of the Entry
458 * @param elem Element number of the Entry
459 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
460 * \return pointer to the modified/created Header Entry (NULL when creation
463 ValEntry *Document::ReplaceOrCreate(std::string const &value,
468 ValEntry *valEntry = 0;
469 DocEntry *currentEntry = GetDocEntry( group, elem);
473 valEntry = dynamic_cast< ValEntry* >(currentEntry);
477 if( valEntry->GetVR()!=vr )
480 // if currentEntry doesn't correspond to the requested valEntry
483 if (!RemoveEntry(currentEntry))
485 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
492 // Create a new valEntry if necessary
495 valEntry = NewValEntry(group, elem, vr);
497 if ( !AddEntry(valEntry))
499 gdcmVerboseMacro("AddEntry failed although this is a creation.");
506 // Set the binEntry value
507 SetEntry(value, valEntry);
512 * \brief Modifies the value of a given Header Entry (Dicom Element)
513 * when it exists. Create it with the given value when unexistant.
514 * A copy of the binArea is made to be kept in the Document.
515 * @param binArea (binary) value to be set
516 * @param Group Group number of the Entry
517 * @param Elem Element number of the Entry
518 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
519 * \return pointer to the modified/created Header Entry (NULL when creation
522 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
528 BinEntry *binEntry = 0;
529 DocEntry *currentEntry = GetDocEntry( group, elem);
531 // Verify the currentEntry
534 binEntry = dynamic_cast< BinEntry* >(currentEntry);
538 if( binEntry->GetVR()!=vr )
541 // if currentEntry doesn't correspond to the requested valEntry
544 if (!RemoveEntry(currentEntry))
546 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
553 // Create a new binEntry if necessary
556 binEntry = NewBinEntry(group, elem, vr);
558 if ( !AddEntry(binEntry))
560 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
567 // Set the binEntry value
569 if (lgth>0 && binArea)
571 tmpArea = new uint8_t[lgth];
572 memcpy(tmpArea,binArea,lgth);
578 if (!SetEntry(tmpArea,lgth,binEntry))
590 * \brief Modifies the value of a given Header Entry (Dicom Element)
591 * when it exists. Create it when unexistant.
592 * @param group Group number of the Entry
593 * @param elem Element number of the Entry
594 * \return pointer to the modified/created SeqEntry (NULL when creation
597 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
599 SeqEntry *seqEntry = 0;
600 DocEntry *currentEntry = GetDocEntry( group, elem);
602 // Verify the currentEntry
605 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
609 if( seqEntry->GetVR()!="SQ" )
612 // if currentEntry doesn't correspond to the requested valEntry
615 if (!RemoveEntry(currentEntry))
617 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
624 // Create a new seqEntry if necessary
627 seqEntry = NewSeqEntry(group, elem);
629 if ( !AddEntry(seqEntry))
631 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
642 * \brief Set a new value if the invoked element exists
643 * Seems to be useless !!!
644 * @param value new element value
645 * @param group group number of the Entry
646 * @param elem element number of the Entry
649 bool Document::ReplaceIfExist(std::string const &value,
650 uint16_t group, uint16_t elem )
652 SetEntry(value, group, elem);
657 //-----------------------------------------------------------------------------
661 * \brief Checks if a given Dicom Element exists within the H table
662 * @param group Group number of the searched Dicom Element
663 * @param elem Element number of the searched Dicom Element
664 * @return true is found
666 bool Document::CheckIfEntryExist(uint16_t group, uint16_t elem )
668 const std::string &key = DictEntry::TranslateToKey(group, elem );
669 return TagHT.count(key) != 0;
674 * \brief Searches within Header Entries (Dicom Elements) parsed with
675 * the public and private dictionaries
676 * for the element value representation of a given tag.
677 * @param group Group number of the searched tag.
678 * @param elem Element number of the searched tag.
679 * @return Corresponding element value representation when it exists,
680 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
682 std::string Document::GetEntry(uint16_t group, uint16_t elem)
684 TagKey key = DictEntry::TranslateToKey(group, elem);
685 if ( !TagHT.count(key))
690 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
694 * \brief Searches within Header Entries (Dicom Elements) parsed with
695 * the public and private dictionaries
696 * for the element value representation of a given tag..
697 * Obtaining the VR (Value Representation) might be needed by caller
698 * to convert the string typed content to caller's native type
699 * (think of C++ vs Python). The VR is actually of a higher level
700 * of semantics than just the native C++ type.
701 * @param group Group number of the searched tag.
702 * @param elem Element number of the searched tag.
703 * @return Corresponding element value representation when it exists,
704 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
706 std::string Document::GetEntryVR(uint16_t group, uint16_t elem)
708 DocEntry *element = GetDocEntry(group, elem);
713 return element->GetVR();
717 * \brief Searches within Header Entries (Dicom Elements) parsed with
718 * the public and private dictionaries
719 * for the value length of a given tag..
720 * @param group Group number of the searched tag.
721 * @param elem Element number of the searched tag.
722 * @return Corresponding element length; -2 if not found
724 int Document::GetEntryLength(uint16_t group, uint16_t elem)
726 DocEntry *element = GetDocEntry(group, elem);
729 return -2; //magic number
731 return element->GetLength();
735 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
736 * through it's (group, element) and modifies it's content with
738 * @param content new value (string) to substitute with
739 * @param group group number of the Dicom Element to modify
740 * @param elem element number of the Dicom Element to modify
742 bool Document::SetEntry(std::string const& content,
743 uint16_t group, uint16_t elem)
745 ValEntry *entry = GetValEntry(group, elem);
748 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
751 return SetEntry(content,entry);
755 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
756 * through it's (group, element) and modifies it's content with
758 * @param content new value (void* -> uint8_t*) to substitute with
759 * @param lgth new value length
760 * @param group group number of the Dicom Element to modify
761 * @param elem element number of the Dicom Element to modify
763 bool Document::SetEntry(uint8_t*content, int lgth,
764 uint16_t group, uint16_t elem)
766 BinEntry *entry = GetBinEntry(group, elem);
769 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
773 return SetEntry(content,lgth,entry);
777 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
778 * and modifies it's content with the given value.
779 * @param content new value (string) to substitute with
780 * @param entry Entry to be modified
782 bool Document::SetEntry(std::string const &content,ValEntry *entry)
786 entry->SetValue(content);
793 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
794 * and modifies it's content with the given value.
795 * @param content new value (void* -> uint8_t*) to substitute with
796 * @param entry Entry to be modified
797 * @param lgth new value length
799 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
803 // Hope Binary field length is *never* wrong
804 /*if(lgth%2) // Non even length are padded with a space (020H).
807 //content = content + '\0'; // fing a trick to enlarge a binary field?
810 entry->SetBinArea(content);
811 entry->SetLength(lgth);
812 entry->SetValue(GDCM_BINLOADED);
819 * \brief Gets (from Header) a 'non string' element value
820 * (LoadElementValues has already be executed)
821 * @param group group number of the Entry
822 * @param elem element number of the Entry
823 * @return Pointer to the 'non string' area
825 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
827 DocEntry *entry = GetDocEntry(group, elem);
830 gdcmVerboseMacro( "No entry");
833 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
835 return binEntry->GetBinArea();
842 * \brief Loads (from disk) the element content
843 * when a string is not suitable
844 * @param group group number of the Entry
845 * @param elem element number of the Entry
847 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
849 // Search the corresponding DocEntry
850 DocEntry *docElement = GetDocEntry(group, elem);
854 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
858 LoadEntryBinArea(binElement);
862 * \brief Loads (from disk) the element content
863 * when a string is not suitable
864 * @param elem Entry whose binArea is going to be loaded
866 void Document::LoadEntryBinArea(BinEntry *elem)
868 if(elem->GetBinArea())
875 size_t o =(size_t)elem->GetOffset();
876 Fp->seekg(o, std::ios::beg);
878 size_t l = elem->GetLength();
879 uint8_t *a = new uint8_t[l];
882 gdcmVerboseMacro( "Cannot allocate a");
886 /// \todo check the result
887 Fp->read((char*)a, l);
888 if( Fp->fail() || Fp->eof())
901 * \brief Sets a 'non string' value to a given Dicom Element
902 * @param area area containing the 'non string' value
903 * @param group Group number of the searched Dicom Element
904 * @param elem Element number of the searched Dicom Element
907 /*bool Document::SetEntryBinArea(uint8_t *area,
908 uint16_t group, uint16_t elem)
910 DocEntry *currentEntry = GetDocEntry(group, elem);
916 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
918 binEntry->SetBinArea( area );
926 * \brief retrieves a Dicom Element (the first one) using (group, element)
927 * \warning (group, element) IS NOT an identifier inside the Dicom Header
928 * if you think it's NOT UNIQUE, check the count number
929 * and use iterators to retrieve ALL the Dicoms Elements within
930 * a given couple (group, element)
931 * @param group Group number of the searched Dicom Element
932 * @param elem Element number of the searched Dicom Element
935 DocEntry *Document::GetDocEntry(uint16_t group, uint16_t elem)
937 TagKey key = DictEntry::TranslateToKey(group, elem);
938 if ( !TagHT.count(key))
942 return TagHT.find(key)->second;
946 * \brief Same as \ref Document::GetDocEntry except it only
947 * returns a result when the corresponding entry is of type
949 * @param group Group number of the searched Dicom Element
950 * @param elem Element number of the searched Dicom Element
951 * @return When present, the corresponding ValEntry.
953 ValEntry *Document::GetValEntry(uint16_t group, uint16_t elem)
955 DocEntry *currentEntry = GetDocEntry(group, elem);
960 if ( ValEntry *entry = dynamic_cast<ValEntry*>(currentEntry) )
964 gdcmVerboseMacro( "Unfound ValEntry.");
970 * \brief Same as \ref Document::GetDocEntry except it only
971 * returns a result when the corresponding entry is of type
973 * @param group Group number of the searched Dicom Element
974 * @param elem Element number of the searched Dicom Element
975 * @return When present, the corresponding BinEntry.
977 BinEntry *Document::GetBinEntry(uint16_t group, uint16_t elem)
979 DocEntry *currentEntry = GetDocEntry(group, elem);
984 if ( BinEntry *entry = dynamic_cast<BinEntry*>(currentEntry) )
988 gdcmVerboseMacro( "Unfound BinEntry.");
994 * \brief Loads the element while preserving the current
995 * underlying file position indicator as opposed to
996 * to LoadDocEntry that modifies it.
997 * @param entry Header Entry whose value will be loaded.
1000 void Document::LoadDocEntrySafe(DocEntry *entry)
1004 long PositionOnEntry = Fp->tellg();
1005 LoadDocEntry(entry);
1006 Fp->seekg(PositionOnEntry, std::ios::beg);
1011 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1013 * @return The properly swaped 32 bits integer.
1015 uint32_t Document::SwapLong(uint32_t a)
1022 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1023 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1026 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1029 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1032 gdcmErrorMacro( "Unset swap code:" << SwapCode );
1039 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1041 * @return The properly unswaped 32 bits integer.
1043 uint32_t Document::UnswapLong(uint32_t a)
1049 * \brief Swaps the bytes so they agree with the processor order
1050 * @return The properly swaped 16 bits integer.
1052 uint16_t Document::SwapShort(uint16_t a)
1054 if ( SwapCode == 4321 || SwapCode == 2143 )
1056 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1062 * \brief Unswaps the bytes so they agree with the processor order
1063 * @return The properly unswaped 16 bits integer.
1065 uint16_t Document::UnswapShort(uint16_t a)
1067 return SwapShort(a);
1070 //-----------------------------------------------------------------------------
1074 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1075 * @return length of the parsed set.
1077 void Document::ParseDES(DocEntrySet *set, long offset,
1078 long l_max, bool delim_mode)
1080 DocEntry *newDocEntry = 0;
1081 ValEntry *newValEntry;
1082 BinEntry *newBinEntry;
1083 SeqEntry *newSeqEntry;
1089 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1095 newDocEntry = ReadNextDocEntry( );
1102 vr = newDocEntry->GetVR();
1103 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1104 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1105 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1107 if ( newValEntry || newBinEntry )
1111 if ( ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1113 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1114 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
1115 << "|" << newDocEntry->GetElement()
1116 << " : Neither Valentry, nor BinEntry."
1117 "Probably unknown VR.");
1120 //////////////////// BinEntry or UNKOWN VR:
1121 // When "this" is a Document the Key is simply of the
1122 // form ( group, elem )...
1123 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1126 newBinEntry->SetKey( newBinEntry->GetKey() );
1128 // but when "this" is a SQItem, we are inserting this new
1129 // valEntry in a sequence item, and the key has the
1130 // generalized form (refer to \ref BaseTagKey):
1131 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1133 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1134 + newBinEntry->GetKey() );
1137 LoadDocEntry( newBinEntry );
1138 if( !set->AddEntry( newBinEntry ) )
1140 //Expect big troubles if here
1141 //delete newBinEntry;
1147 /////////////////////// ValEntry
1148 // When "set" is a Document, then we are at the top of the
1149 // hierarchy and the Key is simply of the form ( group, elem )...
1150 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1153 newValEntry->SetKey( newValEntry->GetKey() );
1155 // ...but when "set" is a SQItem, we are inserting this new
1156 // valEntry in a sequence item. Hence the key has the
1157 // generalized form (refer to \ref BaseTagKey):
1158 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1160 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1161 + newValEntry->GetKey() );
1164 LoadDocEntry( newValEntry );
1165 bool delimitor=newValEntry->IsItemDelimitor();
1166 if( !set->AddEntry( newValEntry ) )
1168 // If here expect big troubles
1169 //delete newValEntry; //otherwise mem leak
1179 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1187 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1188 && ( newDocEntry->GetElement() == 0x0010 ) )
1190 std::string ts = GetTransferSyntax();
1191 if ( Global::GetTS()->IsRLELossless(ts) )
1193 long positionOnEntry = Fp->tellg();
1194 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1196 Fp->seekg( positionOnEntry, std::ios::beg );
1198 else if ( Global::GetTS()->IsJPEG(ts) )
1200 long positionOnEntry = Fp->tellg();
1201 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1202 ComputeJPEGFragmentInfo();
1203 Fp->seekg( positionOnEntry, std::ios::beg );
1207 // Just to make sure we are at the beginning of next entry.
1208 SkipToNextDocEntry(newDocEntry);
1213 unsigned long l = newDocEntry->GetReadLength();
1214 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1216 if ( l == 0xffffffff )
1225 // no other way to create it ...
1226 newSeqEntry->SetDelimitorMode( delim_mode );
1228 // At the top of the hierarchy, stands a Document. When "set"
1229 // is a Document, then we are building the first depth level.
1230 // Hence the SeqEntry we are building simply has a depth
1232 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1235 newSeqEntry->SetDepthLevel( 1 );
1236 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1238 // But when "set" is already a SQItem, we are building a nested
1239 // sequence, and hence the depth level of the new SeqEntry
1240 // we are building, is one level deeper:
1241 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1243 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1244 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1245 + newSeqEntry->GetKey() );
1249 { // Don't try to parse zero-length sequences
1250 ParseSQ( newSeqEntry,
1251 newDocEntry->GetOffset(),
1254 set->AddEntry( newSeqEntry );
1255 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1267 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1268 * @return parsed length for this level
1270 void Document::ParseSQ( SeqEntry *seqEntry,
1271 long offset, long l_max, bool delim_mode)
1273 int SQItemNumber = 0;
1275 long offsetStartCurrentSQItem = offset;
1279 // the first time, we read the fff0,e000 of the first SQItem
1280 DocEntry *newDocEntry = ReadNextDocEntry();
1284 // FIXME Should warn user
1289 if ( newDocEntry->IsSequenceDelimitor() )
1291 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1295 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1300 // create the current SQItem
1301 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1302 std::ostringstream newBase;
1303 newBase << seqEntry->GetKey()
1307 itemSQ->SetBaseTagKey( newBase.str() );
1308 unsigned int l = newDocEntry->GetReadLength();
1310 if ( l == 0xffffffff )
1319 // when we're here, element fffe,e000 is already passed.
1320 // it's lost for the SQItem we're going to process !!
1322 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1323 //delete newDocEntry; // FIXME well ... it's too late to use it !
1325 // Let's try :------------
1326 // remove fff0,e000, created out of the SQItem
1328 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1329 // fill up the current SQItem, starting at the beginning of fff0,e000
1330 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1331 offsetStartCurrentSQItem = Fp->tellg();
1332 // end try -----------------
1334 seqEntry->AddEntry( itemSQ, SQItemNumber );
1336 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1344 * \brief Loads the element content if its length doesn't exceed
1345 * the value specified with Document::SetMaxSizeLoadEntry()
1346 * @param entry Header Entry (Dicom Element) to be dealt with
1348 void Document::LoadDocEntry(DocEntry *entry)
1350 uint16_t group = entry->GetGroup();
1351 std::string vr = entry->GetVR();
1352 uint32_t length = entry->GetLength();
1354 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1356 // A SeQuence "contains" a set of Elements.
1357 // (fffe e000) tells us an Element is beginning
1358 // (fffe e00d) tells us an Element just ended
1359 // (fffe e0dd) tells us the current SeQuence just ended
1360 if( group == 0xfffe )
1362 // NO more value field for SQ !
1366 // When the length is zero things are easy:
1369 ((ValEntry *)entry)->SetValue("");
1373 // The elements whose length is bigger than the specified upper bound
1374 // are not loaded. Instead we leave a short notice of the offset of
1375 // the element content and it's length.
1377 std::ostringstream s;
1378 if (length > MaxSizeLoadEntry)
1380 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1382 //s << "gdcm::NotLoaded (BinEntry)";
1383 s << GDCM_NOTLOADED;
1384 s << " Address:" << (long)entry->GetOffset();
1385 s << " Length:" << entry->GetLength();
1386 s << " x(" << std::hex << entry->GetLength() << ")";
1387 binEntryPtr->SetValue(s.str());
1389 // Be carefull : a BinEntry IS_A ValEntry ...
1390 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1392 // s << "gdcm::NotLoaded. (ValEntry)";
1393 s << GDCM_NOTLOADED;
1394 s << " Address:" << (long)entry->GetOffset();
1395 s << " Length:" << entry->GetLength();
1396 s << " x(" << std::hex << entry->GetLength() << ")";
1397 valEntryPtr->SetValue(s.str());
1402 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1403 << "nor a ValEntry ?! Should never print that !" );
1406 // to be sure we are at the end of the value ...
1407 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1412 // When we find a BinEntry not very much can be done :
1413 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1415 s << GDCM_BINLOADED;
1416 binEntryPtr->SetValue(s.str());
1417 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1421 /// \todo Any compacter code suggested (?)
1422 if ( IsDocEntryAnInteger(entry) )
1426 // When short integer(s) are expected, read and convert the following
1427 // n *two characters properly i.e. consider them as short integers as
1428 // opposed to strings.
1429 // Elements with Value Multiplicity > 1
1430 // contain a set of integers (not a single one)
1431 if (vr == "US" || vr == "SS")
1434 NewInt = ReadInt16();
1438 for (int i=1; i < nbInt; i++)
1441 NewInt = ReadInt16();
1446 // See above comment on multiple integers (mutatis mutandis).
1447 else if (vr == "UL" || vr == "SL")
1450 NewInt = ReadInt32();
1454 for (int i=1; i < nbInt; i++)
1457 NewInt = ReadInt32();
1462 #ifdef GDCM_NO_ANSI_STRING_STREAM
1463 s << std::ends; // to avoid oddities on Solaris
1464 #endif //GDCM_NO_ANSI_STRING_STREAM
1466 ((ValEntry *)entry)->SetValue(s.str());
1470 // FIXME: We need an additional byte for storing \0 that is not on disk
1471 char *str = new char[length+1];
1472 Fp->read(str, (size_t)length);
1473 str[length] = '\0'; //this is only useful when length is odd
1474 // Special DicomString call to properly handle \0 and even length
1475 std::string newValue;
1478 newValue = Util::DicomString(str, length+1);
1479 gdcmVerboseMacro("Warning: bad length: " << length <<
1480 ",For string :" << newValue.c_str());
1481 // Since we change the length of string update it length
1482 //entry->SetReadLength(length+1);
1486 newValue = Util::DicomString(str, length);
1490 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1492 if ( Fp->fail() || Fp->eof())
1494 gdcmVerboseMacro("Unread element value");
1495 valEntry->SetValue(GDCM_UNREAD);
1501 // Because of correspondance with the VR dic
1502 valEntry->SetValue(newValue);
1506 valEntry->SetValue(newValue);
1511 gdcmErrorMacro( "Should have a ValEntry, here !");
1517 * \brief Find the value Length of the passed Header Entry
1518 * @param entry Header Entry whose length of the value shall be loaded.
1520 void Document::FindDocEntryLength( DocEntry *entry )
1521 throw ( FormatError )
1523 std::string vr = entry->GetVR();
1526 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1528 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1530 // The following reserved two bytes (see PS 3.5-2003, section
1531 // "7.1.2 Data element structure with explicit vr", p 27) must be
1532 // skipped before proceeding on reading the length on 4 bytes.
1533 Fp->seekg( 2L, std::ios::cur);
1534 uint32_t length32 = ReadInt32();
1536 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1541 lengthOB = FindDocEntryLengthOBOrOW();
1543 catch ( FormatUnexpected )
1545 // Computing the length failed (this happens with broken
1546 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1547 // chance to get the pixels by deciding the element goes
1548 // until the end of the file. Hence we artificially fix the
1549 // the length and proceed.
1550 long currentPosition = Fp->tellg();
1551 Fp->seekg(0L,std::ios::end);
1553 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1554 Fp->seekg(currentPosition, std::ios::beg);
1556 entry->SetReadLength(lengthUntilEOF);
1557 entry->SetLength(lengthUntilEOF);
1560 entry->SetReadLength(lengthOB);
1561 entry->SetLength(lengthOB);
1564 FixDocEntryFoundLength(entry, length32);
1568 // Length is encoded on 2 bytes.
1569 length16 = ReadInt16();
1571 // FIXME : This heuristic supposes that the first group following
1572 // group 0002 *has* and element 0000.
1573 // BUT ... Element 0000 is optionnal :-(
1576 // Fixed using : HandleOutOfGroup0002()
1577 // (first hereafter strategy ...)
1579 // We can tell the current file is encoded in big endian (like
1580 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1581 // and it's value is the one of the encoding of a big endian file.
1582 // In order to deal with such big endian encoded files, we have
1583 // (at least) two strategies:
1584 // * when we load the "Transfer Syntax" tag with value of big endian
1585 // encoding, we raise the proper flags. Then we wait for the end
1586 // of the META group (0x0002) among which is "Transfer Syntax",
1587 // before switching the swap code to big endian. We have to postpone
1588 // the switching of the swap code since the META group is fully encoded
1589 // in little endian, and big endian coding only starts at the next
1590 // group. The corresponding code can be hard to analyse and adds
1591 // many additional unnecessary tests for regular tags.
1592 // * the second strategy consists in waiting for trouble, that shall
1593 // appear when we find the first group with big endian encoding. This
1594 // is easy to detect since the length of a "Group Length" tag (the
1595 // ones with zero as element number) has to be of 4 (0x0004). When we
1596 // encounter 1024 (0x0400) chances are the encoding changed and we
1597 // found a group with big endian encoding.
1598 //---> Unfortunately, element 0000 is optional.
1599 //---> This will not work when missing!
1600 // We shall use this second strategy. In order to make sure that we
1601 // can interpret the presence of an apparently big endian encoded
1602 // length of a "Group Length" without committing a big mistake, we
1603 // add an additional check: we look in the already parsed elements
1604 // for the presence of a "Transfer Syntax" whose value has to be "big
1605 // endian encoding". When this is the case, chances are we have got our
1606 // hands on a big endian encoded file: we switch the swap code to
1607 // big endian and proceed...
1610 // if ( element == 0x0000 && length16 == 0x0400 )
1612 // std::string ts = GetTransferSyntax();
1613 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1614 // != TS::ExplicitVRBigEndian )
1616 // throw FormatError( "Document::FindDocEntryLength()",
1617 // " not explicit VR." );
1621 // SwitchByteSwapCode();
1623 // Restore the unproperly loaded values i.e. the group, the element
1624 // and the dictionary entry depending on them.
1625 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1626 // uint16_t correctElem = SwapShort( entry->GetElement() );
1627 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem ); if ( !newTag )
1629 // This correct tag is not in the dictionary. Create a new one.
1630 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1632 // FIXME this can create a memory leaks on the old entry that be
1633 // left unreferenced.
1634 // entry->SetDictEntry( newTag );
1638 // 0xffff means that we deal with 'No Length' Sequence
1639 // or 'No Length' SQItem
1640 if ( length16 == 0xffff)
1644 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1649 // Either implicit VR or a non DICOM conformal (see note below) explicit
1650 // VR that ommited the VR of (at least) this element. Farts happen.
1651 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1652 // on Data elements "Implicit and Explicit VR Data Elements shall
1653 // not coexist in a Data Set and Data Sets nested within it".]
1654 // Length is on 4 bytes.
1656 FixDocEntryFoundLength( entry, ReadInt32() );
1662 * \brief Find the Value Representation of the current Dicom Element.
1663 * @return Value Representation of the current Entry
1665 std::string Document::FindDocEntryVR()
1667 if ( Filetype != ExplicitVR )
1668 return GDCM_UNKNOWN;
1670 long positionOnEntry = Fp->tellg();
1671 // Warning: we believe this is explicit VR (Value Representation) because
1672 // we used a heuristic that found "UL" in the first tag. Alas this
1673 // doesn't guarantee that all the tags will be in explicit VR. In some
1674 // cases (see e-film filtered files) one finds implicit VR tags mixed
1675 // within an explicit VR file. Hence we make sure the present tag
1676 // is in explicit VR and try to fix things if it happens not to be
1680 Fp->read (vr, (size_t)2);
1683 if( !CheckDocEntryVR(vr) )
1685 Fp->seekg(positionOnEntry, std::ios::beg);
1686 return GDCM_UNKNOWN;
1692 * \brief Check the correspondance between the VR of the header entry
1693 * and the taken VR. If they are different, the header entry is
1694 * updated with the new VR.
1695 * @param vr Dicom Value Representation
1696 * @return false if the VR is incorrect of if the VR isn't referenced
1697 * otherwise, it returns true
1699 bool Document::CheckDocEntryVR(VRKey vr)
1701 // CLEANME searching the dicom_vr at each occurence is expensive.
1702 // PostPone this test in an optional integrity check at the end
1703 // of parsing or only in debug mode.
1704 if ( !Global::GetVR()->IsValidVR(vr) )
1711 * \brief Get the transformed value of the header entry. The VR value
1712 * is used to define the transformation to operate on the value
1713 * \warning NOT end user intended method !
1714 * @param entry entry to tranform
1715 * @return Transformed entry value
1717 std::string Document::GetDocEntryValue(DocEntry *entry)
1719 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1721 std::string val = ((ValEntry *)entry)->GetValue();
1722 std::string vr = entry->GetVR();
1723 uint32_t length = entry->GetLength();
1724 std::ostringstream s;
1727 // When short integer(s) are expected, read and convert the following
1728 // n * 2 bytes properly i.e. as a multivaluated strings
1729 // (each single value is separated fromthe next one by '\'
1730 // as usual for standard multivaluated filels
1731 // Elements with Value Multiplicity > 1
1732 // contain a set of short integers (not a single one)
1734 if( vr == "US" || vr == "SS" )
1739 for (int i=0; i < nbInt; i++)
1745 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1746 newInt16 = SwapShort( newInt16 );
1751 // When integer(s) are expected, read and convert the following
1752 // n * 4 bytes properly i.e. as a multivaluated strings
1753 // (each single value is separated fromthe next one by '\'
1754 // as usual for standard multivaluated filels
1755 // Elements with Value Multiplicity > 1
1756 // contain a set of integers (not a single one)
1757 else if( vr == "UL" || vr == "SL" )
1762 for (int i=0; i < nbInt; i++)
1768 newInt32 = ( val[4*i+0] & 0xFF )
1769 + (( val[4*i+1] & 0xFF ) << 8 )
1770 + (( val[4*i+2] & 0xFF ) << 16 )
1771 + (( val[4*i+3] & 0xFF ) << 24 );
1772 newInt32 = SwapLong( newInt32 );
1776 #ifdef GDCM_NO_ANSI_STRING_STREAM
1777 s << std::ends; // to avoid oddities on Solaris
1778 #endif //GDCM_NO_ANSI_STRING_STREAM
1782 return ((ValEntry *)entry)->GetValue();
1786 * \brief Get the reverse transformed value of the header entry. The VR
1787 * value is used to define the reverse transformation to operate on
1789 * \warning NOT end user intended method !
1790 * @param entry Entry to reverse transform
1791 * @return Reverse transformed entry value
1793 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1795 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1797 std::string vr = entry->GetVR();
1798 std::vector<std::string> tokens;
1799 std::ostringstream s;
1801 if ( vr == "US" || vr == "SS" )
1805 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1806 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1807 for (unsigned int i=0; i<tokens.size(); i++)
1809 newInt16 = atoi(tokens[i].c_str());
1810 s << ( newInt16 & 0xFF )
1811 << (( newInt16 >> 8 ) & 0xFF );
1815 if ( vr == "UL" || vr == "SL")
1819 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1820 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1821 for (unsigned int i=0; i<tokens.size();i++)
1823 newInt32 = atoi(tokens[i].c_str());
1824 s << (char)( newInt32 & 0xFF )
1825 << (char)(( newInt32 >> 8 ) & 0xFF )
1826 << (char)(( newInt32 >> 16 ) & 0xFF )
1827 << (char)(( newInt32 >> 24 ) & 0xFF );
1832 #ifdef GDCM_NO_ANSI_STRING_STREAM
1833 s << std::ends; // to avoid oddities on Solaris
1834 #endif //GDCM_NO_ANSI_STRING_STREAM
1838 return ((ValEntry *)entry)->GetValue();
1842 * \brief Skip a given Header Entry
1843 * \warning NOT end user intended method !
1844 * @param entry entry to skip
1846 void Document::SkipDocEntry(DocEntry *entry)
1848 SkipBytes(entry->GetLength());
1852 * \brief Skips to the begining of the next Header Entry
1853 * \warning NOT end user intended method !
1854 * @param currentDocEntry entry to skip
1856 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1858 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1859 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1860 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1864 * \brief When the length of an element value is obviously wrong (because
1865 * the parser went Jabberwocky) one can hope improving things by
1866 * applying some heuristics.
1867 * @param entry entry to check
1868 * @param foundLength first assumption about length
1870 void Document::FixDocEntryFoundLength(DocEntry *entry,
1871 uint32_t foundLength)
1873 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1874 if ( foundLength == 0xffffffff)
1879 uint16_t gr = entry->GetGroup();
1880 uint16_t elem = entry->GetElement();
1882 if ( foundLength % 2)
1884 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1885 << " in x(" << std::hex << gr << "," << elem <<")");
1888 //////// Fix for some naughty General Electric images.
1889 // Allthough not recent many such GE corrupted images are still present
1890 // on Creatis hard disks. Hence this fix shall remain when such images
1891 // are no longer in use (we are talking a few years, here)...
1892 // Note: XMedCom probably uses such a trick since it is able to read
1893 // those pesky GE images ...
1894 if ( foundLength == 13)
1896 // Only happens for this length !
1897 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1900 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1904 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1905 // Occurence of such images is quite low (unless one leaves close to a
1906 // 'Leonardo' source. Hence, one might consider commenting out the
1907 // following fix on efficiency reasons.
1908 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1911 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1914 else if ( entry->GetVR() == "SQ" )
1916 foundLength = 0; // ReadLength is unchanged
1919 //////// We encountered a 'delimiter' element i.e. a tag of the form
1920 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1921 // taken into account.
1922 else if( gr == 0xfffe )
1924 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1925 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1926 // causes extra troubles...
1927 if( entry->GetElement() != 0x0000 )
1933 entry->SetLength(foundLength);
1937 * \brief Apply some heuristics to predict whether the considered
1938 * element value contains/represents an integer or not.
1939 * @param entry The element value on which to apply the predicate.
1940 * @return The result of the heuristical predicate.
1942 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1944 uint16_t elem = entry->GetElement();
1945 uint16_t group = entry->GetGroup();
1946 const std::string &vr = entry->GetVR();
1947 uint32_t length = entry->GetLength();
1949 // When we have some semantics on the element we just read, and if we
1950 // a priori know we are dealing with an integer, then we shall be
1951 // able to swap it's element value properly.
1952 if ( elem == 0 ) // This is the group length of the group
1960 // Allthough this should never happen, still some images have a
1961 // corrupted group length [e.g. have a glance at offset x(8336) of
1962 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1963 // Since for dicom compliant and well behaved headers, the present
1964 // test is useless (and might even look a bit paranoid), when we
1965 // encounter such an ill-formed image, we simply display a warning
1966 // message and proceed on parsing (while crossing fingers).
1967 long filePosition = Fp->tellg();
1968 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1969 << std::hex << group << " , " << elem
1970 << ") -before- position x(" << filePosition << ")"
1971 << "lgt : " << length );
1975 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1983 * \brief Find the Length till the next sequence delimiter
1984 * \warning NOT end user intended method !
1988 uint32_t Document::FindDocEntryLengthOBOrOW()
1989 throw( FormatUnexpected )
1991 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1992 long positionOnEntry = Fp->tellg();
1993 bool foundSequenceDelimiter = false;
1994 uint32_t totalLength = 0;
1996 while ( !foundSequenceDelimiter )
2002 group = ReadInt16();
2005 catch ( FormatError )
2007 throw FormatError("Unexpected end of file encountered during ",
2008 "Document::FindDocEntryLengthOBOrOW()");
2011 // We have to decount the group and element we just read
2014 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2016 long filePosition = Fp->tellg();
2017 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
2018 << std::hex << group << " , " << elem
2019 << ") -before- position x(" << filePosition << ")" );
2021 Fp->seekg(positionOnEntry, std::ios::beg);
2022 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
2025 if ( elem == 0xe0dd )
2027 foundSequenceDelimiter = true;
2030 uint32_t itemLength = ReadInt32();
2031 // We add 4 bytes since we just read the ItemLength with ReadInt32
2032 totalLength += itemLength + 4;
2033 SkipBytes(itemLength);
2035 if ( foundSequenceDelimiter )
2040 Fp->seekg( positionOnEntry, std::ios::beg);
2045 * \brief Reads a supposed to be 16 Bits integer
2046 * (swaps it depending on processor endianity)
2047 * @return read value
2049 uint16_t Document::ReadInt16()
2050 throw( FormatError )
2053 Fp->read ((char*)&g, (size_t)2);
2056 throw FormatError( "Document::ReadInt16()", " file error." );
2060 throw FormatError( "Document::ReadInt16()", "EOF." );
2067 * \brief Reads a supposed to be 32 Bits integer
2068 * (swaps it depending on processor endianity)
2069 * @return read value
2071 uint32_t Document::ReadInt32()
2072 throw( FormatError )
2075 Fp->read ((char*)&g, (size_t)4);
2078 throw FormatError( "Document::ReadInt32()", " file error." );
2082 throw FormatError( "Document::ReadInt32()", "EOF." );
2089 * \brief skips bytes inside the source file
2090 * \warning NOT end user intended method !
2093 void Document::SkipBytes(uint32_t nBytes)
2095 //FIXME don't dump the returned value
2096 Fp->seekg((long)nBytes, std::ios::cur);
2100 * \brief Loads all the needed Dictionaries
2101 * \warning NOT end user intended method !
2103 void Document::Initialise()
2105 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2107 RLEInfo = new RLEFramesInfo;
2108 JPEGInfo = new JPEGFragmentsInfo;
2113 * \brief Discover what the swap code is (among little endian, big endian,
2114 * bad little endian, bad big endian).
2116 * @return false when we are absolutely sure
2117 * it's neither ACR-NEMA nor DICOM
2118 * true when we hope ours assuptions are OK
2120 bool Document::CheckSwap()
2122 // The only guaranted way of finding the swap code is to find a
2123 // group tag since we know it's length has to be of four bytes i.e.
2124 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2125 // occurs when we can't find such group...
2127 uint32_t x = 4; // x : for ntohs
2128 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2134 // First, compare HostByteOrder and NetworkByteOrder in order to
2135 // determine if we shall need to swap bytes (i.e. the Endian type).
2136 if ( x == ntohs(x) )
2145 // The easiest case is the one of a 'true' DICOM header, we just have
2146 // to look for the string "DICM" inside the file preamble.
2149 char *entCur = deb + 128;
2150 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2152 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2154 // Group 0002 should always be VR, and the first element 0000
2155 // Let's be carefull (so many wrong headers ...)
2156 // and determine the value representation (VR) :
2157 // Let's skip to the first element (0002,0000) and check there if we find
2158 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2159 // in which case we (almost) know it is explicit VR.
2160 // WARNING: if it happens to be implicit VR then what we will read
2161 // is the length of the group. If this ascii representation of this
2162 // length happens to be "UL" then we shall believe it is explicit VR.
2163 // We need to skip :
2164 // * the 128 bytes of File Preamble (often padded with zeroes),
2165 // * the 4 bytes of "DICM" string,
2166 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2167 // i.e. a total of 136 bytes.
2170 // group 0x0002 *is always* Explicit VR Sometimes ,
2171 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2172 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2174 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2175 memcmp(entCur, "OB", (size_t)2) == 0 ||
2176 memcmp(entCur, "UI", (size_t)2) == 0 ||
2177 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2178 // when Write DCM *adds*
2180 // Use Document::dicom_vr to test all the possibilities
2181 // instead of just checking for UL, OB and UI !? group 0000
2183 Filetype = ExplicitVR;
2184 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2188 Filetype = ImplicitVR;
2189 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2190 << "Looks like a bugged Header!");
2196 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2201 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2204 // Position the file position indicator at first tag
2205 // (i.e. after the file preamble and the "DICM" string).
2206 Fp->seekg(0, std::ios::beg);
2207 Fp->seekg ( 132L, std::ios::beg);
2211 // Alas, this is not a DicomV3 file and whatever happens there is no file
2212 // preamble. We can reset the file position indicator to where the data
2213 // is (i.e. the beginning of the file).
2214 gdcmVerboseMacro( "Not a DICOM Version3 file");
2215 Fp->seekg(0, std::ios::beg);
2217 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2218 // By clean we mean that the length of the first tag is written down.
2219 // If this is the case and since the length of the first group HAS to be
2220 // four (bytes), then determining the proper swap code is straightforward.
2223 // We assume the array of char we are considering contains the binary
2224 // representation of a 32 bits integer. Hence the following dirty
2226 s32 = *((uint32_t *)(entCur));
2247 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2248 // It is time for despaired wild guesses.
2249 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2250 // i.e. the 'group length' element is not present :
2252 // check the supposed-to-be 'group number'
2253 // in ( 0x0001 .. 0x0008 )
2254 // to determine ' SwapCode' value .
2255 // Only 0 or 4321 will be possible
2256 // (no oportunity to check for the formerly well known
2257 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2258 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2259 // the file IS NOT ACR-NEMA nor DICOM V3
2260 // Find a trick to tell it the caller...
2262 s16 = *((uint16_t *)(deb));
2289 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2299 * \brief Change the Byte Swap code.
2301 void Document::SwitchByteSwapCode()
2303 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2304 if ( SwapCode == 1234 )
2308 else if ( SwapCode == 4321 )
2312 else if ( SwapCode == 3412 )
2316 else if ( SwapCode == 2143 )
2323 * \brief during parsing, Header Elements too long are not loaded in memory
2326 void Document::SetMaxSizeLoadEntry(long newSize)
2332 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2334 MaxSizeLoadEntry = 0xffffffff;
2337 MaxSizeLoadEntry = newSize;
2342 * \brief Header Elements too long will not be printed
2343 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2346 void Document::SetMaxSizePrintEntry(long newSize)
2348 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2353 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2355 MaxSizePrintEntry = 0xffffffff;
2358 MaxSizePrintEntry = newSize;
2364 * \brief Handle broken private tag from Philips NTSCAN
2365 * where the endianess is being switch to BigEndian for no
2369 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2371 // Endian reversion. Some files contain groups of tags with reversed endianess.
2372 static int reversedEndian = 0;
2373 // try to fix endian switching in the middle of headers
2374 if ((group == 0xfeff) && (elem == 0x00e0))
2376 // start endian swap mark for group found
2378 SwitchByteSwapCode();
2383 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2385 // end of reversed endian group
2387 SwitchByteSwapCode();
2392 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2394 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2396 std::string Document::GetTransferSyntaxName()
2398 // use the TS (TS : Transfer Syntax)
2399 std::string transferSyntax = GetEntry(0x0002,0x0010);
2401 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2403 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2404 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2405 return "Uncompressed ACR-NEMA";
2407 if ( transferSyntax == GDCM_UNFOUND )
2409 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2410 return "Uncompressed ACR-NEMA";
2413 // we do it only when we need it
2414 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2416 // Global::GetTS() is a global static you shall never try to delete it!
2421 * \brief Group 0002 is always coded Little Endian
2422 * whatever Transfer Syntax is
2425 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2427 // Endian reversion. Some files contain groups of tags with reversed endianess.
2428 if ( !Group0002Parsed && group != 0x0002)
2430 Group0002Parsed = true;
2431 // we just came out of group 0002
2432 // if Transfer syntax is Big Endian we have to change CheckSwap
2434 std::string ts = GetTransferSyntax();
2435 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2437 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2441 // FIXME Strangely, this works with
2442 //'Implicit VR Transfer Syntax (GE Private)
2443 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2445 gdcmVerboseMacro("Transfer Syntax Name = ["
2446 << GetTransferSyntaxName() << "]" );
2447 SwitchByteSwapCode();
2448 group = SwapShort(group);
2449 elem = SwapShort(elem);
2455 * \brief Read the next tag but WITHOUT loading it's value
2456 * (read the 'Group Number', the 'Element Number',
2457 * gets the Dict Entry
2458 * gets the VR, gets the length, gets the offset value)
2459 * @return On succes the newly created DocEntry, NULL on failure.
2461 DocEntry *Document::ReadNextDocEntry()
2468 group = ReadInt16();
2471 catch ( FormatError e )
2473 // We reached the EOF (or an error occured) therefore
2474 // header parsing has to be considered as finished.
2479 // Sometimes file contains groups of tags with reversed endianess.
2480 HandleBrokenEndian(group, elem);
2482 // In 'true DICOM' files Group 0002 is always little endian
2483 if ( HasDCMPreamble )
2484 HandleOutOfGroup0002(group, elem);
2486 std::string vr = FindDocEntryVR();
2487 std::string realVR = vr;
2489 if( vr == GDCM_UNKNOWN)
2491 DictEntry *dictEntry = GetDictEntry(group,elem);
2493 realVR = dictEntry->GetVR();
2497 if( Global::GetVR()->IsVROfSequence(realVR) )
2498 newEntry = NewSeqEntry(group, elem);
2499 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2500 newEntry = NewValEntry(group, elem,vr);
2502 newEntry = NewBinEntry(group, elem,vr);
2504 if( vr == GDCM_UNKNOWN )
2506 if( Filetype == ExplicitVR )
2508 // We thought this was explicit VR, but we end up with an
2509 // implicit VR tag. Let's backtrack.
2510 if ( newEntry->GetGroup() != 0xfffe )
2513 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2514 newEntry->GetGroup(), newEntry->GetElement());
2515 gdcmVerboseMacro( msg.c_str() );
2518 newEntry->SetImplicitVR();
2523 FindDocEntryLength(newEntry);
2525 catch ( FormatError e )
2533 newEntry->SetOffset(Fp->tellg());
2540 * \brief Generate a free TagKey i.e. a TagKey that is not present
2541 * in the TagHt dictionary.
2542 * @param group The generated tag must belong to this group.
2543 * @return The element of tag with given group which is fee.
2545 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2547 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2549 TagKey key = DictEntry::TranslateToKey(group, elem);
2550 if (TagHT.count(key) == 0)
2559 * \brief Assuming the internal file pointer \ref Document::Fp
2560 * is placed at the beginning of a tag check whether this
2561 * tag is (TestGroup, TestElement).
2562 * \warning On success the internal file pointer \ref Document::Fp
2563 * is modified to point after the tag.
2564 * On failure (i.e. when the tag wasn't the expected tag
2565 * (TestGroup, TestElement) the internal file pointer
2566 * \ref Document::Fp is restored to it's original position.
2567 * @param testGroup The expected group of the tag.
2568 * @param testElement The expected Element of the tag.
2569 * @return True on success, false otherwise.
2571 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2573 long positionOnEntry = Fp->tellg();
2574 long currentPosition = Fp->tellg(); // On debugging purposes
2576 //// Read the Item Tag group and element, and make
2577 // sure they are what we expected:
2578 uint16_t itemTagGroup;
2579 uint16_t itemTagElement;
2582 itemTagGroup = ReadInt16();
2583 itemTagElement = ReadInt16();
2585 catch ( FormatError e )
2587 //std::cerr << e << std::endl;
2590 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2592 gdcmVerboseMacro( "Wrong Item Tag found:"
2593 << " We should have found tag ("
2594 << std::hex << testGroup << "," << testElement << ")" << std::endl
2595 << " but instead we encountered tag ("
2596 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2597 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2599 Fp->seekg(positionOnEntry, std::ios::beg);
2607 * \brief Assuming the internal file pointer \ref Document::Fp
2608 * is placed at the beginning of a tag (TestGroup, TestElement),
2609 * read the length associated to the Tag.
2610 * \warning On success the internal file pointer \ref Document::Fp
2611 * is modified to point after the tag and it's length.
2612 * On failure (i.e. when the tag wasn't the expected tag
2613 * (TestGroup, TestElement) the internal file pointer
2614 * \ref Document::Fp is restored to it's original position.
2615 * @param testGroup The expected group of the tag.
2616 * @param testElement The expected Element of the tag.
2617 * @return On success returns the length associated to the tag. On failure
2620 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2623 if ( !ReadTag(testGroup, testElement) )
2628 //// Then read the associated Item Length
2629 long currentPosition = Fp->tellg();
2630 uint32_t itemLength = ReadInt32();
2632 gdcmVerboseMacro( "Basic Item Length is: "
2633 << itemLength << std::endl
2634 << " at address: " << std::hex << (unsigned int)currentPosition);
2640 * \brief When parsing the Pixel Data of an encapsulated file, read
2641 * the basic offset table (when present, and BTW dump it).
2643 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2645 //// Read the Basic Offset Table Item Tag length...
2646 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2648 // When present, read the basic offset table itself.
2649 // Notes: - since the presence of this basic offset table is optional
2650 // we can't rely on it for the implementation, and we will simply
2651 // trash it's content (when present).
2652 // - still, when present, we could add some further checks on the
2653 // lengths, but we won't bother with such fuses for the time being.
2654 if ( itemLength != 0 )
2656 char *basicOffsetTableItemValue = new char[itemLength + 1];
2657 Fp->read(basicOffsetTableItemValue, itemLength);
2660 for (unsigned int i=0; i < itemLength; i += 4 )
2662 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2664 gdcmVerboseMacro( "Read one length: " <<
2665 std::hex << individualLength );
2669 delete[] basicOffsetTableItemValue;
2674 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2675 * Compute the RLE extra information and store it in \ref RLEInfo
2676 * for later pixel retrieval usage.
2678 void Document::ComputeRLEInfo()
2680 std::string ts = GetTransferSyntax();
2681 if ( !Global::GetTS()->IsRLELossless(ts) )
2686 // Encoded pixel data: for the time being we are only concerned with
2687 // Jpeg or RLE Pixel data encodings.
2688 // As stated in PS 3.5-2003, section 8.2 p44:
2689 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2690 // value representation OB is used".
2691 // Hence we expect an OB value representation. Concerning OB VR,
2692 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2693 // "For the Value Representations OB and OW, the encoding shall meet the
2694 // following specifications depending on the Data element tag:"
2696 // - the first item in the sequence of items before the encoded pixel
2697 // data stream shall be basic offset table item. The basic offset table
2698 // item value, however, is not required to be present"
2700 ReadAndSkipEncapsulatedBasicOffsetTable();
2702 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2703 // Loop on the individual frame[s] and store the information
2704 // on the RLE fragments in a RLEFramesInfo.
2705 // Note: - when only a single frame is present, this is a
2707 // - when more than one frame are present, then we are in
2708 // the case of a multi-frame image.
2710 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2712 // Parse the RLE Header and store the corresponding RLE Segment
2713 // Offset Table information on fragments of this current Frame.
2714 // Note that the fragment pixels themselves are not loaded
2715 // (but just skipped).
2716 long frameOffset = Fp->tellg();
2718 uint32_t nbRleSegments = ReadInt32();
2719 if ( nbRleSegments > 16 )
2721 // There should be at most 15 segments (refer to RLEFrame class)
2722 gdcmVerboseMacro( "Too many segments.");
2725 uint32_t rleSegmentOffsetTable[16];
2726 for( int k = 1; k <= 15; k++ )
2728 rleSegmentOffsetTable[k] = ReadInt32();
2731 // Deduce from both the RLE Header and the frameLength the
2732 // fragment length, and again store this info in a
2734 long rleSegmentLength[15];
2735 // skipping (not reading) RLE Segments
2736 if ( nbRleSegments > 1)
2738 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2740 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2741 - rleSegmentOffsetTable[k];
2742 SkipBytes(rleSegmentLength[k]);
2746 rleSegmentLength[nbRleSegments] = frameLength
2747 - rleSegmentOffsetTable[nbRleSegments];
2748 SkipBytes(rleSegmentLength[nbRleSegments]);
2750 // Store the collected info
2751 RLEFrame *newFrameInfo = new RLEFrame;
2752 newFrameInfo->NumberFragments = nbRleSegments;
2753 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2755 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2756 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2758 RLEInfo->Frames.push_back( newFrameInfo );
2761 // Make sure that at the end of the item we encounter a 'Sequence
2763 if ( !ReadTag(0xfffe, 0xe0dd) )
2765 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2770 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2771 * Compute the jpeg extra information (fragment[s] offset[s] and
2772 * length) and store it[them] in \ref JPEGInfo for later pixel
2775 void Document::ComputeJPEGFragmentInfo()
2777 // If you need to, look for comments of ComputeRLEInfo().
2778 std::string ts = GetTransferSyntax();
2779 if ( ! Global::GetTS()->IsJPEG(ts) )
2784 ReadAndSkipEncapsulatedBasicOffsetTable();
2786 // Loop on the fragments[s] and store the parsed information in a
2788 long fragmentLength;
2789 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2791 long fragmentOffset = Fp->tellg();
2793 // Store the collected info
2794 JPEGFragment *newFragment = new JPEGFragment;
2795 newFragment->Offset = fragmentOffset;
2796 newFragment->Length = fragmentLength;
2797 JPEGInfo->Fragments.push_back( newFragment );
2799 SkipBytes( fragmentLength );
2802 // Make sure that at the end of the item we encounter a 'Sequence
2804 if ( !ReadTag(0xfffe, 0xe0dd) )
2806 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2811 * \brief Walk recursively the given \ref DocEntrySet, and feed
2812 * the given hash table (\ref TagDocEntryHT) with all the
2813 * \ref DocEntry (Dicom entries) encountered.
2814 * This method does the job for \ref BuildFlatHashTable.
2815 * @param builtHT Where to collect all the \ref DocEntry encountered
2816 * when recursively walking the given set.
2817 * @param set The structure to be traversed (recursively).
2819 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2822 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2824 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2825 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2826 i != currentHT.end();
2829 DocEntry *entry = i->second;
2830 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2832 const ListSQItem& items = seqEntry->GetSQItems();
2833 for( ListSQItem::const_iterator item = items.begin();
2834 item != items.end();
2837 BuildFlatHashTableRecurse( builtHT, *item );
2841 builtHT[entry->GetKey()] = entry;
2846 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2848 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2849 for (ListDocEntry::const_iterator i = currentList.begin();
2850 i != currentList.end();
2853 DocEntry *entry = *i;
2854 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2856 const ListSQItem& items = seqEntry->GetSQItems();
2857 for( ListSQItem::const_iterator item = items.begin();
2858 item != items.end();
2861 BuildFlatHashTableRecurse( builtHT, *item );
2865 builtHT[entry->GetKey()] = entry;
2872 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2875 * The structure used by a Document (through \ref ElementSet),
2876 * in order to hold the parsed entries of a Dicom header, is a recursive
2877 * one. This is due to the fact that the sequences (when present)
2878 * can be nested. Additionaly, the sequence items (represented in
2879 * gdcm as \ref SQItem) add an extra complexity to the data
2880 * structure. Hence, a gdcm user whishing to visit all the entries of
2881 * a Dicom header will need to dig in the gdcm internals (which
2882 * implies exposing all the internal data structures to the API).
2883 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2884 * recursively builds a temporary hash table, which holds all the
2885 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2887 * \warning Of course there is NO integrity constrain between the
2888 * returned \ref TagDocEntryHT and the \ref ElementSet used
2889 * to build it. Hence if the underlying \ref ElementSet is
2890 * altered, then it is the caller responsability to invoke
2891 * \ref BuildFlatHashTable again...
2892 * @return The flat std::map<> we juste build.
2894 /*TagDocEntryHT *Document::BuildFlatHashTable()
2896 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2897 BuildFlatHashTableRecurse( *FlatHT, this );
2904 * \brief Compares two documents, according to \ref DicomDir rules
2905 * \warning Does NOT work with ACR-NEMA files
2906 * \todo Find a trick to solve the pb (use RET fields ?)
2908 * @return true if 'smaller'
2910 bool Document::operator<(Document &document)
2913 std::string s1 = GetEntry(0x0010,0x0010);
2914 std::string s2 = document.GetEntry(0x0010,0x0010);
2926 s1 = GetEntry(0x0010,0x0020);
2927 s2 = document.GetEntry(0x0010,0x0020);
2938 // Study Instance UID
2939 s1 = GetEntry(0x0020,0x000d);
2940 s2 = document.GetEntry(0x0020,0x000d);
2951 // Serie Instance UID
2952 s1 = GetEntry(0x0020,0x000e);
2953 s2 = document.GetEntry(0x0020,0x000e);
2970 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2971 * @param filetype Type of the File to be written
2973 int Document::ComputeGroup0002Length( FileType filetype )
2978 int groupLength = 0;
2979 bool found0002 = false;
2981 // for each zero-level Tag in the DCM Header
2982 DocEntry *entry = GetFirstEntry();
2985 gr = entry->GetGroup();
2991 el = entry->GetElement();
2992 vr = entry->GetVR();
2994 if (filetype == ExplicitVR)
2996 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2998 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
3001 groupLength += 2 + 2 + 4 + entry->GetLength();
3003 else if (found0002 )
3006 entry = GetNextEntry();
3011 } // end namespace gdcm
3013 //-----------------------------------------------------------------------------