1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/20 11:37:37 $
7 Version: $Revision: 1.203 $
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)
69 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
79 Group0002Parsed = false;
81 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
82 // Fp->seekg( 0, std::ios::beg);
84 Fp->seekg(0, std::ios::end);
85 long lgt = Fp->tellg();
87 Fp->seekg( 0, std::ios::beg);
90 long beg = Fp->tellg();
93 ParseDES( this, beg, lgt, false); // Loading is done during parsing
95 Fp->seekg( 0, std::ios::beg);
97 // Load 'non string' values
99 std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);
100 if( PhotometricInterpretation == "PALETTE COLOR " )
102 LoadEntryBinArea(0x0028,0x1200); // gray LUT
103 /// FIXME FIXME FIXME
104 /// The tags refered by the three following lines used to be CORRECTLY
105 /// defined as having an US Value Representation in the public
106 /// dictionary. BUT the semantics implied by the three following
107 /// lines state that the corresponding tag contents are in fact
108 /// the ones of a BinEntry.
109 /// In order to fix things "Quick and Dirty" the dictionary was
110 /// altered on PURPOSE but now contains a WRONG value.
111 /// In order to fix things and restore the dictionary to its
112 /// correct value, one needs to decided of the semantics by deciding
113 /// whether the following tags are either:
114 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
115 /// also used as BinEntry, which requires the proper conversion,
116 /// - OW, and hence loaded as BinEntry, but afterwards also used
117 /// as ValEntry, which requires the proper conversion.
118 LoadEntryBinArea(0x0028,0x1201); // R LUT
119 LoadEntryBinArea(0x0028,0x1202); // G LUT
120 LoadEntryBinArea(0x0028,0x1203); // B LUT
122 // Segmented Red Palette Color LUT Data
123 LoadEntryBinArea(0x0028,0x1221);
124 // Segmented Green Palette Color LUT Data
125 LoadEntryBinArea(0x0028,0x1222);
126 // Segmented Blue Palette Color LUT Data
127 LoadEntryBinArea(0x0028,0x1223);
129 //FIXME later : how to use it?
130 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
134 // --------------------------------------------------------------
135 // Specific code to allow gdcm to read ACR-LibIDO formated images
136 // Note: ACR-LibIDO is an extension of the ACR standard that was
137 // used at CREATIS. For the time being (say a couple years)
138 // we keep this kludge to allow a smooth move to gdcm for
139 // CREATIS developpers (sorry folks).
141 // if recognition code tells us we deal with a LibIDO image
142 // we switch lineNumber and columnNumber
145 RecCode = GetEntry(0x0008, 0x0010); // recognition code (RET)
146 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
147 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
148 // with "little-endian strings"
150 Filetype = ACR_LIBIDO;
151 std::string rows = GetEntry(0x0028, 0x0010);
152 std::string columns = GetEntry(0x0028, 0x0011);
153 SetEntry(columns, 0x0028, 0x0010);
154 SetEntry(rows , 0x0028, 0x0011);
156 // ----------------- End of ACR-LibIDO kludge ------------------
160 * \brief This default constructor doesn't parse the file. You should
161 * then invoke \ref Document::SetFileName and then the parsing.
163 Document::Document() : ElementSet(-1)
170 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
173 Filetype = ExplicitVR;
174 Group0002Parsed = false;
178 * \brief Canonical destructor.
180 Document::~Document ()
191 //-----------------------------------------------------------------------------
195 * \brief Prints The Dict Entries of THE public Dicom Dictionary
198 void Document::PrintPubDict(std::ostream &os)
200 RefPubDict->SetPrintLevel(PrintLevel);
201 RefPubDict->Print(os);
205 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
208 void Document::PrintShaDict(std::ostream &os)
210 RefShaDict->SetPrintLevel(PrintLevel);
211 RefShaDict->Print(os);
214 //-----------------------------------------------------------------------------
217 * \brief Get the public dictionary used
219 Dict *Document::GetPubDict()
225 * \brief Get the shadow dictionary used
227 Dict *Document::GetShaDict()
233 * \brief Set the shadow dictionary used
234 * @param dict dictionary to use in shadow
236 bool Document::SetShaDict(Dict *dict)
243 * \brief Set the shadow dictionary used
244 * @param dictName name of the dictionary to use in shadow
246 bool Document::SetShaDict(DictKey const &dictName)
248 RefShaDict = Global::GetDicts()->GetDict(dictName);
253 * \brief This predicate, based on hopefully reasonable heuristics,
254 * decides whether or not the current Document was properly parsed
255 * and contains the mandatory information for being considered as
256 * a well formed and usable Dicom/Acr File.
257 * @return true when Document is the one of a reasonable Dicom/Acr file,
260 bool Document::IsReadable()
262 if( Filetype == Unknown)
264 gdcmVerboseMacro( "Wrong filetype");
270 gdcmVerboseMacro( "No tag in internal hash table.");
278 * \brief Accessor to the Transfer Syntax (when present) of the
279 * current document (it internally handles reading the
280 * value from disk when only parsing occured).
281 * @return The encountered Transfer Syntax of the current document.
283 std::string Document::GetTransferSyntax()
285 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
291 // The entry might be present but not loaded (parsing and loading
292 // happen at different stages): try loading and proceed with check...
293 LoadDocEntrySafe(entry);
294 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
296 std::string transfer = valEntry->GetValue();
297 // The actual transfer (as read from disk) might be padded. We
298 // first need to remove the potential padding. We can make the
299 // weak assumption that padding was not executed with digits...
300 if ( transfer.length() == 0 )
302 // for brain damaged headers
305 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
307 transfer.erase(transfer.length()-1, 1);
315 * \brief Predicate for dicom version 3 file.
316 * @return True when the file is a dicom version 3.
318 bool Document::IsDicomV3()
320 // Checking if Transfer Syntax exists is enough
321 // Anyway, it's to late check if the 'Preamble' was found ...
322 // And ... would it be a rich idea to check ?
323 // (some 'no Preamble' DICOM images exist !)
324 return GetDocEntry(0x0002, 0x0010) != NULL;
328 * \brief returns the File Type
329 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
330 * @return the FileType code
332 FileType Document::GetFileType()
338 * \brief Tries to open the file \ref Document::Filename and
339 * checks the preamble when existing.
340 * @return The FILE pointer on success.
342 std::ifstream *Document::OpenFile()
345 HasDCMPreamble = false;
346 if (Filename.length() == 0)
353 gdcmVerboseMacro( "File already open: " << Filename.c_str());
356 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
359 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
366 Fp->read((char*)&zero, (size_t)2);
373 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
375 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
376 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
377 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
378 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
381 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
382 gdcmVerboseMacro( msg.c_str() );
387 Fp->seekg(126L, std::ios::cur);
389 Fp->read(dicm, (size_t)4);
395 if( memcmp(dicm, "DICM", 4) == 0 )
397 HasDCMPreamble = true;
402 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
408 * \brief closes the file
409 * @return TRUE if the close was successfull
411 bool Document::CloseFile()
420 return true; //FIXME how do we detect a non-closed ifstream ?
424 * \brief Writes in a file all the Header Entries (Dicom Elements)
425 * @param fp file pointer on an already open file (actually: Output File Stream)
426 * @param filetype Type of the File to be written
427 * (ACR-NEMA, ExplicitVR, ImplicitVR)
428 * \return Always true.
430 void Document::WriteContent(std::ofstream *fp, FileType filetype)
432 /// \todo move the following lines (and a lot of others, to be written)
433 /// to a future function CheckAndCorrectHeader
434 /// (necessary if user wants to write a DICOM V3 file
435 /// starting from an ACR-NEMA (V2) Header
437 if ( filetype == ImplicitVR || filetype == ExplicitVR )
439 // writing Dicom File Preamble
440 char filePreamble[128];
441 memset(filePreamble, 0, 128);
442 fp->write(filePreamble, 128);
443 fp->write("DICM", 4);
447 * \todo rewrite later, if really usefull
448 * - 'Group Length' element is optional in DICOM
449 * - but un-updated odd groups lengthes can causes pb
452 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
453 * UpdateGroupLength(false,filetype);
454 * if ( filetype == ACR)
455 * UpdateGroupLength(true,ACR);
458 ElementSet::WriteContent(fp, filetype); // This one is recursive
462 * \brief Modifies the value of a given Doc Entry (Dicom Element)
463 * when it exists. Create it with the given value when unexistant.
464 * @param value (string) Value to be set
465 * @param group Group number of the Entry
466 * @param elem Element number of the Entry
467 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
468 * \return pointer to the modified/created Header Entry (NULL when creation
471 ValEntry *Document::ReplaceOrCreate(std::string const &value,
476 ValEntry *valEntry = 0;
477 DocEntry *currentEntry = GetDocEntry( group, elem);
481 valEntry = dynamic_cast< ValEntry* >(currentEntry);
485 if( valEntry->GetVR()!=vr )
488 // if currentEntry doesn't correspond to the requested valEntry
491 if (!RemoveEntry(currentEntry))
493 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
500 // Create a new valEntry if necessary
503 valEntry = NewValEntry(group, elem, vr);
505 if ( !AddEntry(valEntry))
507 gdcmVerboseMacro("AddEntry failed although this is a creation.");
514 // Set the binEntry value
515 SetEntry(value, valEntry);
520 * \brief Modifies the value of a given Header Entry (Dicom Element)
521 * when it exists. Create it with the given value when unexistant.
522 * A copy of the binArea is made to be kept in the Document.
523 * @param binArea (binary) value to be set
524 * @param group Group number of the Entry
525 * @param elem Element number of the Entry
526 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
527 * \return pointer to the modified/created Header Entry (NULL when creation
530 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
536 BinEntry *binEntry = 0;
537 DocEntry *currentEntry = GetDocEntry( group, elem);
539 // Verify the currentEntry
542 binEntry = dynamic_cast< BinEntry* >(currentEntry);
546 if( binEntry->GetVR()!=vr )
549 // if currentEntry doesn't correspond to the requested valEntry
552 if (!RemoveEntry(currentEntry))
554 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
561 // Create a new binEntry if necessary
564 binEntry = NewBinEntry(group, elem, vr);
566 if ( !AddEntry(binEntry))
568 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
575 // Set the binEntry value
577 if (lgth>0 && binArea)
579 tmpArea = new uint8_t[lgth];
580 memcpy(tmpArea,binArea,lgth);
586 if (!SetEntry(tmpArea,lgth,binEntry))
598 * \brief Modifies the value of a given Header Entry (Dicom Element)
599 * when it exists. Create it when unexistant.
600 * @param group Group number of the Entry
601 * @param elem Element number of the Entry
602 * \return pointer to the modified/created SeqEntry (NULL when creation
605 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
607 SeqEntry *seqEntry = 0;
608 DocEntry *currentEntry = GetDocEntry( group, elem);
610 // Verify the currentEntry
613 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
617 if( seqEntry->GetVR()!="SQ" )
620 // if currentEntry doesn't correspond to the requested valEntry
623 if (!RemoveEntry(currentEntry))
625 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
631 // Create a new seqEntry if necessary
634 seqEntry = NewSeqEntry(group, elem);
636 if ( !AddEntry(seqEntry))
638 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
648 * \brief Set a new value if the invoked element exists
649 * Seems to be useless !!!
650 * @param value new element value
651 * @param group group number of the Entry
652 * @param elem element number of the Entry
655 bool Document::ReplaceIfExist(std::string const &value,
656 uint16_t group, uint16_t elem )
658 SetEntry(value, group, elem);
663 //-----------------------------------------------------------------------------
667 * \brief Checks if a given Dicom Element exists within the H table
668 * @param group Group number of the searched Dicom Element
669 * @param elem Element number of the searched Dicom Element
670 * @return true is found
672 bool Document::CheckIfEntryExist(uint16_t group, uint16_t elem )
674 const std::string &key = DictEntry::TranslateToKey(group, elem );
675 return TagHT.count(key) != 0;
680 * \brief Searches within Header Entries (Dicom Elements) parsed with
681 * the public and private dictionaries
682 * for the element value representation of a given tag.
683 * @param group Group number of the searched tag.
684 * @param elem Element number of the searched tag.
685 * @return Corresponding element value representation when it exists,
686 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
688 std::string Document::GetEntry(uint16_t group, uint16_t elem)
690 TagKey key = DictEntry::TranslateToKey(group, elem);
691 if ( !TagHT.count(key))
696 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
700 * \brief Searches within Header Entries (Dicom Elements) parsed with
701 * the public and private dictionaries
702 * for the element value representation of a given tag..
703 * Obtaining the VR (Value Representation) might be needed by caller
704 * to convert the string typed content to caller's native type
705 * (think of C++ vs Python). The VR is actually of a higher level
706 * of semantics than just the native C++ type.
707 * @param group Group number of the searched tag.
708 * @param elem Element number of the searched tag.
709 * @return Corresponding element value representation when it exists,
710 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
712 std::string Document::GetEntryVR(uint16_t group, uint16_t elem)
714 DocEntry *element = GetDocEntry(group, elem);
719 return element->GetVR();
723 * \brief Searches within Header Entries (Dicom Elements) parsed with
724 * the public and private dictionaries
725 * for the value length of a given tag..
726 * @param group Group number of the searched tag.
727 * @param elem Element number of the searched tag.
728 * @return Corresponding element length; -2 if not found
730 int Document::GetEntryLength(uint16_t group, uint16_t elem)
732 DocEntry *element = GetDocEntry(group, elem);
735 return -2; //magic number
737 return element->GetLength();
741 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
742 * through it's (group, element) and modifies it's content with
744 * @param content new value (string) to substitute with
745 * @param group group number of the Dicom Element to modify
746 * @param elem element number of the Dicom Element to modify
748 bool Document::SetEntry(std::string const& content,
749 uint16_t group, uint16_t elem)
751 ValEntry *entry = GetValEntry(group, elem);
754 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
757 return SetEntry(content,entry);
761 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
762 * through it's (group, element) and modifies it's content with
764 * @param content new value (void* -> uint8_t*) to substitute with
765 * @param lgth new value length
766 * @param group group number of the Dicom Element to modify
767 * @param elem element number of the Dicom Element to modify
769 bool Document::SetEntry(uint8_t*content, int lgth,
770 uint16_t group, uint16_t elem)
772 BinEntry *entry = GetBinEntry(group, elem);
775 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
779 return SetEntry(content,lgth,entry);
783 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
784 * and modifies it's content with the given value.
785 * @param content new value (string) to substitute with
786 * @param entry Entry to be modified
788 bool Document::SetEntry(std::string const &content, ValEntry *entry)
792 entry->SetValue(content);
799 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
800 * and modifies it's content with the given value.
801 * @param content new value (void* -> uint8_t*) to substitute with
802 * @param entry Entry to be modified
803 * @param lgth new value length
805 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
809 // Hope Binary field length is *never* wrong
810 /*if(lgth%2) // Non even length are padded with a space (020H).
813 //content = content + '\0'; // fing a trick to enlarge a binary field?
816 entry->SetBinArea(content);
817 entry->SetLength(lgth);
818 entry->SetValue(GDCM_BINLOADED);
825 * \brief Gets (from Header) a 'non string' element value
826 * (LoadElementValues has already be executed)
827 * @param group group number of the Entry
828 * @param elem element number of the Entry
829 * @return Pointer to the 'non string' area
831 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
833 DocEntry *entry = GetDocEntry(group, elem);
836 gdcmVerboseMacro( "No entry");
839 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
841 return binEntry->GetBinArea();
848 * \brief Loads (from disk) the element content
849 * when a string is not suitable
850 * @param group group number of the Entry
851 * @param elem element number of the Entry
853 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
855 // Search the corresponding DocEntry
856 DocEntry *docElement = GetDocEntry(group, elem);
860 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
864 LoadEntryBinArea(binElement);
868 * \brief Loads (from disk) the element content
869 * when a string is not suitable
870 * @param elem Entry whose binArea is going to be loaded
872 void Document::LoadEntryBinArea(BinEntry *elem)
874 if(elem->GetBinArea())
881 size_t o =(size_t)elem->GetOffset();
882 Fp->seekg(o, std::ios::beg);
884 size_t l = elem->GetLength();
885 uint8_t *a = new uint8_t[l];
888 gdcmVerboseMacro( "Cannot allocate BinEntry content");
892 /// \todo check the result
893 Fp->read((char*)a, l);
894 if( Fp->fail() || Fp->eof())
907 * \brief Sets a 'non string' value to a given Dicom Element
908 * @param area area containing the 'non string' value
909 * @param group Group number of the searched Dicom Element
910 * @param elem Element number of the searched Dicom Element
913 /*bool Document::SetEntryBinArea(uint8_t *area,
914 uint16_t group, uint16_t elem)
916 DocEntry *currentEntry = GetDocEntry(group, elem);
922 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
924 binEntry->SetBinArea( area );
933 * \brief Loads the element while preserving the current
934 * underlying file position indicator as opposed to
935 * LoadDocEntry that modifies it.
936 * @param entry Header Entry whose value will be loaded.
939 void Document::LoadDocEntrySafe(DocEntry *entry)
943 long PositionOnEntry = Fp->tellg();
945 Fp->seekg(PositionOnEntry, std::ios::beg);
950 * \brief Swaps back the bytes of 4-byte long integer accordingly to
952 * @return The properly swaped 32 bits integer.
954 uint32_t Document::SwapLong(uint32_t a)
961 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
962 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
965 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
968 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
971 gdcmErrorMacro( "Unset swap code:" << SwapCode );
978 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
980 * @return The properly unswaped 32 bits integer.
982 uint32_t Document::UnswapLong(uint32_t a)
988 * \brief Swaps the bytes so they agree with the processor order
989 * @return The properly swaped 16 bits integer.
991 uint16_t Document::SwapShort(uint16_t a)
993 if ( SwapCode == 4321 || SwapCode == 2143 )
995 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1001 * \brief Unswaps the bytes so they agree with the processor order
1002 * @return The properly unswaped 16 bits integer.
1004 uint16_t Document::UnswapShort(uint16_t a)
1006 return SwapShort(a);
1009 //-----------------------------------------------------------------------------
1013 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1014 * @return length of the parsed set.
1016 void Document::ParseDES(DocEntrySet *set, long offset,
1017 long l_max, bool delim_mode)
1019 DocEntry *newDocEntry = 0;
1020 ValEntry *newValEntry;
1021 BinEntry *newBinEntry;
1022 SeqEntry *newSeqEntry;
1028 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1034 newDocEntry = ReadNextDocEntry( );
1041 vr = newDocEntry->GetVR();
1042 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1043 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1044 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1046 if ( newValEntry || newBinEntry )
1050 if ( Filetype == ExplicitVR && ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1052 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1053 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
1054 << "|" << newDocEntry->GetElement()
1055 << " : Neither Valentry, nor BinEntry."
1056 "Probably unknown VR.");
1059 //////////////////// BinEntry or UNKOWN VR:
1060 // When "this" is a Document the Key is simply of the
1061 // form ( group, elem )...
1062 if ( dynamic_cast< Document* > ( set ) )
1064 newBinEntry->SetKey( newBinEntry->GetKey() );
1066 // but when "this" is a SQItem, we are inserting this new
1067 // valEntry in a sequence item, and the key has the
1068 // generalized form (refer to \ref BaseTagKey):
1069 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1071 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1072 + newBinEntry->GetKey() );
1075 LoadDocEntry( newBinEntry );
1076 if( !set->AddEntry( newBinEntry ) )
1078 //Expect big troubles if here
1079 //delete newBinEntry;
1085 /////////////////////// ValEntry
1086 // When "set" is a Document, then we are at the top of the
1087 // hierarchy and the Key is simply of the form ( group, elem )...
1088 if ( dynamic_cast< Document* > ( set ) )
1090 newValEntry->SetKey( newValEntry->GetKey() );
1092 // ...but when "set" is a SQItem, we are inserting this new
1093 // valEntry in a sequence item. Hence the key has the
1094 // generalized form (refer to \ref BaseTagKey):
1095 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1097 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1098 + newValEntry->GetKey() );
1101 LoadDocEntry( newValEntry );
1102 bool delimitor=newValEntry->IsItemDelimitor();
1103 if( !set->AddEntry( newValEntry ) )
1105 // If here expect big troubles
1106 //delete newValEntry; //otherwise mem leak
1116 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1124 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1125 && ( newDocEntry->GetElement() == 0x0010 ) )
1127 std::string ts = GetTransferSyntax();
1128 if ( Global::GetTS()->IsRLELossless(ts) )
1130 long positionOnEntry = Fp->tellg();
1131 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1133 Fp->seekg( positionOnEntry, std::ios::beg );
1135 else if ( Global::GetTS()->IsJPEG(ts) )
1137 long positionOnEntry = Fp->tellg();
1138 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1139 ComputeJPEGFragmentInfo();
1140 Fp->seekg( positionOnEntry, std::ios::beg );
1144 // Just to make sure we are at the beginning of next entry.
1145 SkipToNextDocEntry(newDocEntry);
1150 unsigned long l = newDocEntry->GetReadLength();
1151 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1153 if ( l == 0xffffffff )
1162 // no other way to create it ...
1163 newSeqEntry->SetDelimitorMode( delim_mode );
1165 // At the top of the hierarchy, stands a Document. When "set"
1166 // is a Document, then we are building the first depth level.
1167 // Hence the SeqEntry we are building simply has a depth
1169 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1172 newSeqEntry->SetDepthLevel( 1 );
1173 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1175 // But when "set" is already a SQItem, we are building a nested
1176 // sequence, and hence the depth level of the new SeqEntry
1177 // we are building, is one level deeper:
1178 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1180 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1181 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1182 + newSeqEntry->GetKey() );
1186 { // Don't try to parse zero-length sequences
1187 ParseSQ( newSeqEntry,
1188 newDocEntry->GetOffset(),
1191 set->AddEntry( newSeqEntry );
1192 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1204 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1205 * @return parsed length for this level
1207 void Document::ParseSQ( SeqEntry *seqEntry,
1208 long offset, long l_max, bool delim_mode)
1210 int SQItemNumber = 0;
1212 long offsetStartCurrentSQItem = offset;
1216 // the first time, we read the fff0,e000 of the first SQItem
1217 DocEntry *newDocEntry = ReadNextDocEntry();
1221 // FIXME Should warn user
1226 if ( newDocEntry->IsSequenceDelimitor() )
1228 seqEntry->SetDelimitationItem( newDocEntry );
1232 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1237 // create the current SQItem
1238 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1239 std::ostringstream newBase;
1240 newBase << seqEntry->GetKey()
1244 itemSQ->SetBaseTagKey( newBase.str() );
1245 unsigned int l = newDocEntry->GetReadLength();
1247 if ( l == 0xffffffff )
1256 // when we're here, element fffe,e000 is already passed.
1257 // it's lost for the SQItem we're going to process !!
1259 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1260 //delete newDocEntry; // FIXME well ... it's too late to use it !
1262 // Let's try :------------
1263 // remove fff0,e000, created out of the SQItem
1265 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1266 // fill up the current SQItem, starting at the beginning of fff0,e000
1267 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1268 offsetStartCurrentSQItem = Fp->tellg();
1269 // end try -----------------
1271 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1273 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1281 * \brief Loads the element content if its length doesn't exceed
1282 * the value specified with Document::SetMaxSizeLoadEntry()
1283 * @param entry Header Entry (Dicom Element) to be dealt with
1285 void Document::LoadDocEntry(DocEntry *entry)
1287 uint16_t group = entry->GetGroup();
1288 std::string vr = entry->GetVR();
1289 uint32_t length = entry->GetLength();
1291 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1293 // A SeQuence "contains" a set of Elements.
1294 // (fffe e000) tells us an Element is beginning
1295 // (fffe e00d) tells us an Element just ended
1296 // (fffe e0dd) tells us the current SeQuence just ended
1297 if( group == 0xfffe )
1299 // NO more value field for SQ !
1303 // When the length is zero things are easy:
1306 ((ValEntry *)entry)->SetValue("");
1310 // The elements whose length is bigger than the specified upper bound
1311 // are not loaded. Instead we leave a short notice of the offset of
1312 // the element content and it's length.
1314 std::ostringstream s;
1315 if (length > MaxSizeLoadEntry)
1317 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1319 //s << "gdcm::NotLoaded (BinEntry)";
1320 s << GDCM_NOTLOADED;
1321 s << " Address:" << (long)entry->GetOffset();
1322 s << " Length:" << entry->GetLength();
1323 s << " x(" << std::hex << entry->GetLength() << ")";
1324 binEntryPtr->SetValue(s.str());
1326 // Be carefull : a BinEntry IS_A ValEntry ...
1327 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1329 // s << "gdcm::NotLoaded. (ValEntry)";
1330 s << GDCM_NOTLOADED;
1331 s << " Address:" << (long)entry->GetOffset();
1332 s << " Length:" << entry->GetLength();
1333 s << " x(" << std::hex << entry->GetLength() << ")";
1334 valEntryPtr->SetValue(s.str());
1339 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1340 << "nor a ValEntry ?! Should never print that !" );
1343 // to be sure we are at the end of the value ...
1344 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1349 // When we find a BinEntry not very much can be done :
1350 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1352 s << GDCM_BINLOADED;
1353 binEntryPtr->SetValue(s.str());
1354 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1358 /// \todo Any compacter code suggested (?)
1359 if ( IsDocEntryAnInteger(entry) )
1363 // When short integer(s) are expected, read and convert the following
1364 // n *two characters properly i.e. consider them as short integers as
1365 // opposed to strings.
1366 // Elements with Value Multiplicity > 1
1367 // contain a set of integers (not a single one)
1368 if (vr == "US" || vr == "SS")
1371 NewInt = ReadInt16();
1375 for (int i=1; i < nbInt; i++)
1378 NewInt = ReadInt16();
1383 // See above comment on multiple integers (mutatis mutandis).
1384 else if (vr == "UL" || vr == "SL")
1387 NewInt = ReadInt32();
1391 for (int i=1; i < nbInt; i++)
1394 NewInt = ReadInt32();
1399 #ifdef GDCM_NO_ANSI_STRING_STREAM
1400 s << std::ends; // to avoid oddities on Solaris
1401 #endif //GDCM_NO_ANSI_STRING_STREAM
1403 ((ValEntry *)entry)->SetValue(s.str());
1407 // FIXME: We need an additional byte for storing \0 that is not on disk
1408 char *str = new char[length+1];
1409 Fp->read(str, (size_t)length);
1410 str[length] = '\0'; //this is only useful when length is odd
1411 // Special DicomString call to properly handle \0 and even length
1412 std::string newValue;
1415 newValue = Util::DicomString(str, length+1);
1416 gdcmVerboseMacro("Warning: bad length: " << length <<
1417 ",For string :" << newValue.c_str());
1418 // Since we change the length of string update it length
1419 //entry->SetReadLength(length+1);
1423 newValue = Util::DicomString(str, length);
1427 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1429 if ( Fp->fail() || Fp->eof())
1431 gdcmVerboseMacro("Unread element value");
1432 valEntry->SetValue(GDCM_UNREAD);
1438 // Because of correspondance with the VR dic
1439 valEntry->SetValue(newValue);
1443 valEntry->SetValue(newValue);
1448 gdcmErrorMacro( "Should have a ValEntry, here !");
1454 * \brief Find the value Length of the passed Header Entry
1455 * @param entry Header Entry whose length of the value shall be loaded.
1457 void Document::FindDocEntryLength( DocEntry *entry )
1458 throw ( FormatError )
1460 std::string vr = entry->GetVR();
1463 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1465 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1467 // The following reserved two bytes (see PS 3.5-2003, section
1468 // "7.1.2 Data element structure with explicit vr", p 27) must be
1469 // skipped before proceeding on reading the length on 4 bytes.
1470 Fp->seekg( 2L, std::ios::cur);
1471 uint32_t length32 = ReadInt32();
1473 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1478 lengthOB = FindDocEntryLengthOBOrOW();
1480 catch ( FormatUnexpected )
1482 // Computing the length failed (this happens with broken
1483 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1484 // chance to get the pixels by deciding the element goes
1485 // until the end of the file. Hence we artificially fix the
1486 // the length and proceed.
1487 long currentPosition = Fp->tellg();
1488 Fp->seekg(0L,std::ios::end);
1490 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1491 Fp->seekg(currentPosition, std::ios::beg);
1493 entry->SetReadLength(lengthUntilEOF);
1494 entry->SetLength(lengthUntilEOF);
1497 entry->SetReadLength(lengthOB);
1498 entry->SetLength(lengthOB);
1501 FixDocEntryFoundLength(entry, length32);
1505 // Length is encoded on 2 bytes.
1506 length16 = ReadInt16();
1508 // FIXME : This heuristic supposes that the first group following
1509 // group 0002 *has* and element 0000.
1510 // BUT ... Element 0000 is optionnal :-(
1513 // Fixed using : HandleOutOfGroup0002()
1514 // (first hereafter strategy ...)
1516 // We can tell the current file is encoded in big endian (like
1517 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1518 // and it's value is the one of the encoding of a big endian file.
1519 // In order to deal with such big endian encoded files, we have
1520 // (at least) two strategies:
1521 // * when we load the "Transfer Syntax" tag with value of big endian
1522 // encoding, we raise the proper flags. Then we wait for the end
1523 // of the META group (0x0002) among which is "Transfer Syntax",
1524 // before switching the swap code to big endian. We have to postpone
1525 // the switching of the swap code since the META group is fully encoded
1526 // in little endian, and big endian coding only starts at the next
1527 // group. The corresponding code can be hard to analyse and adds
1528 // many additional unnecessary tests for regular tags.
1529 // * the second strategy consists in waiting for trouble, that shall
1530 // appear when we find the first group with big endian encoding. This
1531 // is easy to detect since the length of a "Group Length" tag (the
1532 // ones with zero as element number) has to be of 4 (0x0004). When we
1533 // encounter 1024 (0x0400) chances are the encoding changed and we
1534 // found a group with big endian encoding.
1535 //---> Unfortunately, element 0000 is optional.
1536 //---> This will not work when missing!
1537 // We shall use this second strategy. In order to make sure that we
1538 // can interpret the presence of an apparently big endian encoded
1539 // length of a "Group Length" without committing a big mistake, we
1540 // add an additional check: we look in the already parsed elements
1541 // for the presence of a "Transfer Syntax" whose value has to be "big
1542 // endian encoding". When this is the case, chances are we have got our
1543 // hands on a big endian encoded file: we switch the swap code to
1544 // big endian and proceed...
1546 // if ( element == 0x0000 && length16 == 0x0400 )
1548 // std::string ts = GetTransferSyntax();
1549 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1550 // != TS::ExplicitVRBigEndian )
1552 // throw FormatError( "Document::FindDocEntryLength()",
1553 // " not explicit VR." );
1557 // SwitchByteSwapCode();
1559 // // Restore the unproperly loaded values i.e. the group, the element
1560 // // and the dictionary entry depending on them.
1561 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1562 // uint16_t correctElem = SwapShort( entry->GetElement() );
1563 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1566 // // This correct tag is not in the dictionary. Create a new one.
1567 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1569 // // FIXME this can create a memory leaks on the old entry that be
1570 // // left unreferenced.
1571 // entry->SetDictEntry( newTag );
1574 // 0xffff means that we deal with 'No Length' Sequence
1575 // or 'No Length' SQItem
1576 if ( length16 == 0xffff)
1580 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1585 // Either implicit VR or a non DICOM conformal (see note below) explicit
1586 // VR that ommited the VR of (at least) this element. Farts happen.
1587 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1588 // on Data elements "Implicit and Explicit VR Data Elements shall
1589 // not coexist in a Data Set and Data Sets nested within it".]
1590 // Length is on 4 bytes.
1592 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1593 // even if Transfer Syntax is 'Implicit VR ...'
1595 FixDocEntryFoundLength( entry, ReadInt32() );
1601 * \brief Find the Value Representation of the current Dicom Element.
1602 * @return Value Representation of the current Entry
1604 std::string Document::FindDocEntryVR()
1606 if ( Filetype != ExplicitVR )
1607 return GDCM_UNKNOWN;
1609 long positionOnEntry = Fp->tellg();
1610 // Warning: we believe this is explicit VR (Value Representation) because
1611 // we used a heuristic that found "UL" in the first tag. Alas this
1612 // doesn't guarantee that all the tags will be in explicit VR. In some
1613 // cases (see e-film filtered files) one finds implicit VR tags mixed
1614 // within an explicit VR file. Hence we make sure the present tag
1615 // is in explicit VR and try to fix things if it happens not to be
1619 Fp->read (vr, (size_t)2);
1622 if( !CheckDocEntryVR(vr) )
1624 Fp->seekg(positionOnEntry, std::ios::beg);
1625 return GDCM_UNKNOWN;
1631 * \brief Check the correspondance between the VR of the header entry
1632 * and the taken VR. If they are different, the header entry is
1633 * updated with the new VR.
1634 * @param vr Dicom Value Representation
1635 * @return false if the VR is incorrect of if the VR isn't referenced
1636 * otherwise, it returns true
1638 bool Document::CheckDocEntryVR(VRKey vr)
1640 // CLEANME searching the dicom_vr at each occurence is expensive.
1641 // PostPone this test in an optional integrity check at the end
1642 // of parsing or only in debug mode.
1643 if ( !Global::GetVR()->IsValidVR(vr) )
1650 * \brief Get the transformed value of the header entry. The VR value
1651 * is used to define the transformation to operate on the value
1652 * \warning NOT end user intended method !
1653 * @param entry entry to tranform
1654 * @return Transformed entry value
1656 std::string Document::GetDocEntryValue(DocEntry *entry)
1658 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1660 std::string val = ((ValEntry *)entry)->GetValue();
1661 std::string vr = entry->GetVR();
1662 uint32_t length = entry->GetLength();
1663 std::ostringstream s;
1666 // When short integer(s) are expected, read and convert the following
1667 // n * 2 bytes properly i.e. as a multivaluated strings
1668 // (each single value is separated fromthe next one by '\'
1669 // as usual for standard multivaluated filels
1670 // Elements with Value Multiplicity > 1
1671 // contain a set of short integers (not a single one)
1673 if( vr == "US" || vr == "SS" )
1678 for (int i=0; i < nbInt; i++)
1684 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1685 newInt16 = SwapShort( newInt16 );
1690 // When integer(s) are expected, read and convert the following
1691 // n * 4 bytes properly i.e. as a multivaluated strings
1692 // (each single value is separated fromthe next one by '\'
1693 // as usual for standard multivaluated filels
1694 // Elements with Value Multiplicity > 1
1695 // contain a set of integers (not a single one)
1696 else if( vr == "UL" || vr == "SL" )
1701 for (int i=0; i < nbInt; i++)
1707 newInt32 = ( val[4*i+0] & 0xFF )
1708 + (( val[4*i+1] & 0xFF ) << 8 )
1709 + (( val[4*i+2] & 0xFF ) << 16 )
1710 + (( val[4*i+3] & 0xFF ) << 24 );
1711 newInt32 = SwapLong( newInt32 );
1715 #ifdef GDCM_NO_ANSI_STRING_STREAM
1716 s << std::ends; // to avoid oddities on Solaris
1717 #endif //GDCM_NO_ANSI_STRING_STREAM
1721 return ((ValEntry *)entry)->GetValue();
1725 * \brief Get the reverse transformed value of the header entry. The VR
1726 * value is used to define the reverse transformation to operate on
1728 * \warning NOT end user intended method !
1729 * @param entry Entry to reverse transform
1730 * @return Reverse transformed entry value
1732 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1734 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1736 std::string vr = entry->GetVR();
1737 std::vector<std::string> tokens;
1738 std::ostringstream s;
1740 if ( vr == "US" || vr == "SS" )
1744 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1745 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1746 for (unsigned int i=0; i<tokens.size(); i++)
1748 newInt16 = atoi(tokens[i].c_str());
1749 s << ( newInt16 & 0xFF )
1750 << (( newInt16 >> 8 ) & 0xFF );
1754 if ( vr == "UL" || vr == "SL")
1758 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1759 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1760 for (unsigned int i=0; i<tokens.size();i++)
1762 newInt32 = atoi(tokens[i].c_str());
1763 s << (char)( newInt32 & 0xFF )
1764 << (char)(( newInt32 >> 8 ) & 0xFF )
1765 << (char)(( newInt32 >> 16 ) & 0xFF )
1766 << (char)(( newInt32 >> 24 ) & 0xFF );
1771 #ifdef GDCM_NO_ANSI_STRING_STREAM
1772 s << std::ends; // to avoid oddities on Solaris
1773 #endif //GDCM_NO_ANSI_STRING_STREAM
1777 return ((ValEntry *)entry)->GetValue();
1781 * \brief Skip a given Header Entry
1782 * \warning NOT end user intended method !
1783 * @param entry entry to skip
1785 void Document::SkipDocEntry(DocEntry *entry)
1787 SkipBytes(entry->GetLength());
1791 * \brief Skips to the begining of the next Header Entry
1792 * \warning NOT end user intended method !
1793 * @param currentDocEntry entry to skip
1795 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1797 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1798 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1799 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1803 * \brief When the length of an element value is obviously wrong (because
1804 * the parser went Jabberwocky) one can hope improving things by
1805 * applying some heuristics.
1806 * @param entry entry to check
1807 * @param foundLength first assumption about length
1809 void Document::FixDocEntryFoundLength(DocEntry *entry,
1810 uint32_t foundLength)
1812 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1813 if ( foundLength == 0xffffffff)
1818 uint16_t gr = entry->GetGroup();
1819 uint16_t elem = entry->GetElement();
1821 if ( foundLength % 2)
1823 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1824 << " in x(" << std::hex << gr << "," << elem <<")");
1827 //////// Fix for some naughty General Electric images.
1828 // Allthough not recent many such GE corrupted images are still present
1829 // on Creatis hard disks. Hence this fix shall remain when such images
1830 // are no longer in use (we are talking a few years, here)...
1831 // Note: XMedCom probably uses such a trick since it is able to read
1832 // those pesky GE images ...
1833 if ( foundLength == 13)
1835 // Only happens for this length !
1836 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1839 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1843 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1844 // Occurence of such images is quite low (unless one leaves close to a
1845 // 'Leonardo' source. Hence, one might consider commenting out the
1846 // following fix on efficiency reasons.
1847 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1850 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1853 else if ( entry->GetVR() == "SQ" )
1855 foundLength = 0; // ReadLength is unchanged
1858 //////// We encountered a 'delimiter' element i.e. a tag of the form
1859 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1860 // taken into account.
1861 else if( gr == 0xfffe )
1863 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1864 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1865 // causes extra troubles...
1866 if( entry->GetElement() != 0x0000 )
1872 entry->SetLength(foundLength);
1876 * \brief Apply some heuristics to predict whether the considered
1877 * element value contains/represents an integer or not.
1878 * @param entry The element value on which to apply the predicate.
1879 * @return The result of the heuristical predicate.
1881 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1883 uint16_t elem = entry->GetElement();
1884 uint16_t group = entry->GetGroup();
1885 const std::string &vr = entry->GetVR();
1886 uint32_t length = entry->GetLength();
1888 // When we have some semantics on the element we just read, and if we
1889 // a priori know we are dealing with an integer, then we shall be
1890 // able to swap it's element value properly.
1891 if ( elem == 0 ) // This is the group length of the group
1899 // Allthough this should never happen, still some images have a
1900 // corrupted group length [e.g. have a glance at offset x(8336) of
1901 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1902 // Since for dicom compliant and well behaved headers, the present
1903 // test is useless (and might even look a bit paranoid), when we
1904 // encounter such an ill-formed image, we simply display a warning
1905 // message and proceed on parsing (while crossing fingers).
1906 long filePosition = Fp->tellg();
1907 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1908 << std::hex << group << " , " << elem
1909 << ") -before- position x(" << filePosition << ")"
1910 << "lgt : " << length );
1914 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1922 * \brief Find the Length till the next sequence delimiter
1923 * \warning NOT end user intended method !
1927 uint32_t Document::FindDocEntryLengthOBOrOW()
1928 throw( FormatUnexpected )
1930 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1931 long positionOnEntry = Fp->tellg();
1932 bool foundSequenceDelimiter = false;
1933 uint32_t totalLength = 0;
1935 while ( !foundSequenceDelimiter )
1941 group = ReadInt16();
1944 catch ( FormatError )
1946 throw FormatError("Unexpected end of file encountered during ",
1947 "Document::FindDocEntryLengthOBOrOW()");
1950 // We have to decount the group and element we just read
1953 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1955 long filePosition = Fp->tellg();
1956 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1957 << std::hex << group << " , " << elem
1958 << ") -before- position x(" << filePosition << ")" );
1960 Fp->seekg(positionOnEntry, std::ios::beg);
1961 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1964 if ( elem == 0xe0dd )
1966 foundSequenceDelimiter = true;
1969 uint32_t itemLength = ReadInt32();
1970 // We add 4 bytes since we just read the ItemLength with ReadInt32
1971 totalLength += itemLength + 4;
1972 SkipBytes(itemLength);
1974 if ( foundSequenceDelimiter )
1979 Fp->seekg( positionOnEntry, std::ios::beg);
1984 * \brief Reads a supposed to be 16 Bits integer
1985 * (swaps it depending on processor endianity)
1986 * @return read value
1988 uint16_t Document::ReadInt16()
1989 throw( FormatError )
1992 Fp->read ((char*)&g, (size_t)2);
1995 throw FormatError( "Document::ReadInt16()", " file error." );
1999 throw FormatError( "Document::ReadInt16()", "EOF." );
2006 * \brief Reads a supposed to be 32 Bits integer
2007 * (swaps it depending on processor endianity)
2008 * @return read value
2010 uint32_t Document::ReadInt32()
2011 throw( FormatError )
2014 Fp->read ((char*)&g, (size_t)4);
2017 throw FormatError( "Document::ReadInt32()", " file error." );
2021 throw FormatError( "Document::ReadInt32()", "EOF." );
2028 * \brief skips bytes inside the source file
2029 * \warning NOT end user intended method !
2032 void Document::SkipBytes(uint32_t nBytes)
2034 //FIXME don't dump the returned value
2035 Fp->seekg((long)nBytes, std::ios::cur);
2039 * \brief Loads all the needed Dictionaries
2040 * \warning NOT end user intended method !
2042 void Document::Initialize()
2044 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2046 RLEInfo = new RLEFramesInfo;
2047 JPEGInfo = new JPEGFragmentsInfo;
2052 * \brief Discover what the swap code is (among little endian, big endian,
2053 * bad little endian, bad big endian).
2055 * @return false when we are absolutely sure
2056 * it's neither ACR-NEMA nor DICOM
2057 * true when we hope ours assuptions are OK
2059 bool Document::CheckSwap()
2061 // The only guaranted way of finding the swap code is to find a
2062 // group tag since we know it's length has to be of four bytes i.e.
2063 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2064 // occurs when we can't find such group...
2066 uint32_t x = 4; // x : for ntohs
2067 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2073 // First, compare HostByteOrder and NetworkByteOrder in order to
2074 // determine if we shall need to swap bytes (i.e. the Endian type).
2075 if ( x == ntohs(x) )
2084 // The easiest case is the one of a 'true' DICOM header, we just have
2085 // to look for the string "DICM" inside the file preamble.
2088 char *entCur = deb + 128;
2089 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2091 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2093 // Group 0002 should always be VR, and the first element 0000
2094 // Let's be carefull (so many wrong headers ...)
2095 // and determine the value representation (VR) :
2096 // Let's skip to the first element (0002,0000) and check there if we find
2097 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2098 // in which case we (almost) know it is explicit VR.
2099 // WARNING: if it happens to be implicit VR then what we will read
2100 // is the length of the group. If this ascii representation of this
2101 // length happens to be "UL" then we shall believe it is explicit VR.
2102 // We need to skip :
2103 // * the 128 bytes of File Preamble (often padded with zeroes),
2104 // * the 4 bytes of "DICM" string,
2105 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2106 // i.e. a total of 136 bytes.
2109 // group 0x0002 *is always* Explicit VR Sometimes ,
2110 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2111 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2113 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2114 memcmp(entCur, "OB", (size_t)2) == 0 ||
2115 memcmp(entCur, "UI", (size_t)2) == 0 ||
2116 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2117 // when Write DCM *adds*
2119 // Use Document::dicom_vr to test all the possibilities
2120 // instead of just checking for UL, OB and UI !? group 0000
2122 Filetype = ExplicitVR;
2123 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2127 Filetype = ImplicitVR;
2128 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2129 << "Looks like a bugged Header!");
2135 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2140 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2143 // Position the file position indicator at first tag
2144 // (i.e. after the file preamble and the "DICM" string).
2145 Fp->seekg(0, std::ios::beg);
2146 Fp->seekg ( 132L, std::ios::beg);
2150 // Alas, this is not a DicomV3 file and whatever happens there is no file
2151 // preamble. We can reset the file position indicator to where the data
2152 // is (i.e. the beginning of the file).
2153 gdcmVerboseMacro( "Not a DICOM Version3 file");
2154 Fp->seekg(0, std::ios::beg);
2156 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2157 // By clean we mean that the length of the first tag is written down.
2158 // If this is the case and since the length of the first group HAS to be
2159 // four (bytes), then determining the proper swap code is straightforward.
2162 // We assume the array of char we are considering contains the binary
2163 // representation of a 32 bits integer. Hence the following dirty
2165 s32 = *((uint32_t *)(entCur));
2186 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2187 // It is time for despaired wild guesses.
2188 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2189 // i.e. the 'group length' element is not present :
2191 // check the supposed-to-be 'group number'
2192 // in ( 0x0001 .. 0x0008 )
2193 // to determine ' SwapCode' value .
2194 // Only 0 or 4321 will be possible
2195 // (no oportunity to check for the formerly well known
2196 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2197 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2198 // the file IS NOT ACR-NEMA nor DICOM V3
2199 // Find a trick to tell it the caller...
2201 s16 = *((uint16_t *)(deb));
2228 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2236 * \brief Change the Byte Swap code.
2238 void Document::SwitchByteSwapCode()
2240 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2241 if ( SwapCode == 1234 )
2245 else if ( SwapCode == 4321 )
2249 else if ( SwapCode == 3412 )
2253 else if ( SwapCode == 2143 )
2260 * \brief during parsing, Header Elements too long are not loaded in memory
2263 void Document::SetMaxSizeLoadEntry(long newSize)
2269 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2271 MaxSizeLoadEntry = 0xffffffff;
2274 MaxSizeLoadEntry = newSize;
2279 * \brief Header Elements too long will not be printed
2280 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2283 void Document::SetMaxSizePrintEntry(long newSize)
2289 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2291 MaxSizePrintEntry = 0xffffffff;
2294 MaxSizePrintEntry = newSize;
2300 * \brief Handle broken private tag from Philips NTSCAN
2301 * where the endianess is being switch to BigEndian for no
2305 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2307 // Endian reversion. Some files contain groups of tags with reversed endianess.
2308 static int reversedEndian = 0;
2309 // try to fix endian switching in the middle of headers
2310 if ((group == 0xfeff) && (elem == 0x00e0))
2312 // start endian swap mark for group found
2314 SwitchByteSwapCode();
2319 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2321 // end of reversed endian group
2323 SwitchByteSwapCode();
2328 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2329 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2331 std::string Document::GetTransferSyntaxName()
2333 // use the TS (TS : Transfer Syntax)
2334 std::string transferSyntax = GetEntry(0x0002,0x0010);
2336 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2338 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2339 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2340 return "Uncompressed ACR-NEMA";
2342 if ( transferSyntax == GDCM_UNFOUND )
2344 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2345 return "Uncompressed ACR-NEMA";
2348 // we do it only when we need it
2349 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2351 // Global::GetTS() is a global static you shall never try to delete it!
2356 * \brief Group 0002 is always coded Little Endian
2357 * whatever Transfer Syntax is
2360 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2362 // Endian reversion. Some files contain groups of tags with reversed endianess.
2363 if ( !Group0002Parsed && group != 0x0002)
2365 Group0002Parsed = true;
2366 // we just came out of group 0002
2367 // if Transfer syntax is Big Endian we have to change CheckSwap
2369 std::string ts = GetTransferSyntax();
2370 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2372 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2376 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2378 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2380 Filetype = ImplicitVR;
2383 // FIXME Strangely, this works with
2384 //'Implicit VR Transfer Syntax (GE Private)
2385 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2387 gdcmVerboseMacro("Transfer Syntax Name = ["
2388 << GetTransferSyntaxName() << "]" );
2389 SwitchByteSwapCode();
2390 group = SwapShort(group);
2391 elem = SwapShort(elem);
2397 * \brief Read the next tag but WITHOUT loading it's value
2398 * (read the 'Group Number', the 'Element Number',
2399 * gets the Dict Entry
2400 * gets the VR, gets the length, gets the offset value)
2401 * @return On succes the newly created DocEntry, NULL on failure.
2403 DocEntry *Document::ReadNextDocEntry()
2410 group = ReadInt16();
2413 catch ( FormatError e )
2415 // We reached the EOF (or an error occured) therefore
2416 // header parsing has to be considered as finished.
2421 // Sometimes file contains groups of tags with reversed endianess.
2422 HandleBrokenEndian(group, elem);
2424 // In 'true DICOM' files Group 0002 is always little endian
2425 if ( HasDCMPreamble )
2426 HandleOutOfGroup0002(group, elem);
2428 std::string vr = FindDocEntryVR();
2429 std::string realVR = vr;
2431 if( vr == GDCM_UNKNOWN)
2433 DictEntry *dictEntry = GetDictEntry(group,elem);
2435 realVR = dictEntry->GetVR();
2439 if( Global::GetVR()->IsVROfSequence(realVR) )
2440 newEntry = NewSeqEntry(group, elem);
2441 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2442 newEntry = NewValEntry(group, elem,vr);
2444 newEntry = NewBinEntry(group, elem,vr);
2446 if( vr == GDCM_UNKNOWN )
2448 if( Filetype == ExplicitVR )
2450 // We thought this was explicit VR, but we end up with an
2451 // implicit VR tag. Let's backtrack.
2452 if ( newEntry->GetGroup() != 0xfffe )
2455 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2456 newEntry->GetGroup(), newEntry->GetElement());
2457 gdcmVerboseMacro( msg.c_str() );
2460 newEntry->SetImplicitVR();
2465 FindDocEntryLength(newEntry);
2467 catch ( FormatError e )
2475 newEntry->SetOffset(Fp->tellg());
2482 * \brief Generate a free TagKey i.e. a TagKey that is not present
2483 * in the TagHt dictionary.
2484 * @param group The generated tag must belong to this group.
2485 * @return The element of tag with given group which is fee.
2487 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2489 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2491 TagKey key = DictEntry::TranslateToKey(group, elem);
2492 if (TagHT.count(key) == 0)
2501 * \brief Assuming the internal file pointer \ref Document::Fp
2502 * is placed at the beginning of a tag check whether this
2503 * tag is (TestGroup, TestElement).
2504 * \warning On success the internal file pointer \ref Document::Fp
2505 * is modified to point after the tag.
2506 * On failure (i.e. when the tag wasn't the expected tag
2507 * (TestGroup, TestElement) the internal file pointer
2508 * \ref Document::Fp is restored to it's original position.
2509 * @param testGroup The expected group of the tag.
2510 * @param testElement The expected Element of the tag.
2511 * @return True on success, false otherwise.
2513 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2515 long positionOnEntry = Fp->tellg();
2516 long currentPosition = Fp->tellg(); // On debugging purposes
2518 //// Read the Item Tag group and element, and make
2519 // sure they are what we expected:
2520 uint16_t itemTagGroup;
2521 uint16_t itemTagElement;
2524 itemTagGroup = ReadInt16();
2525 itemTagElement = ReadInt16();
2527 catch ( FormatError e )
2529 //std::cerr << e << std::endl;
2532 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2534 gdcmVerboseMacro( "Wrong Item Tag found:"
2535 << " We should have found tag ("
2536 << std::hex << testGroup << "," << testElement << ")" << std::endl
2537 << " but instead we encountered tag ("
2538 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2539 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2541 Fp->seekg(positionOnEntry, std::ios::beg);
2549 * \brief Assuming the internal file pointer \ref Document::Fp
2550 * is placed at the beginning of a tag (TestGroup, TestElement),
2551 * read the length associated to the Tag.
2552 * \warning On success the internal file pointer \ref Document::Fp
2553 * is modified to point after the tag and it's length.
2554 * On failure (i.e. when the tag wasn't the expected tag
2555 * (TestGroup, TestElement) the internal file pointer
2556 * \ref Document::Fp is restored to it's original position.
2557 * @param testGroup The expected group of the tag.
2558 * @param testElement The expected Element of the tag.
2559 * @return On success returns the length associated to the tag. On failure
2562 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2565 if ( !ReadTag(testGroup, testElement) )
2570 //// Then read the associated Item Length
2571 long currentPosition = Fp->tellg();
2572 uint32_t itemLength = ReadInt32();
2574 gdcmVerboseMacro( "Basic Item Length is: "
2575 << itemLength << std::endl
2576 << " at address: " << std::hex << (unsigned int)currentPosition);
2582 * \brief When parsing the Pixel Data of an encapsulated file, read
2583 * the basic offset table (when present, and BTW dump it).
2585 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2587 //// Read the Basic Offset Table Item Tag length...
2588 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2590 // When present, read the basic offset table itself.
2591 // Notes: - since the presence of this basic offset table is optional
2592 // we can't rely on it for the implementation, and we will simply
2593 // trash it's content (when present).
2594 // - still, when present, we could add some further checks on the
2595 // lengths, but we won't bother with such fuses for the time being.
2596 if ( itemLength != 0 )
2598 char *basicOffsetTableItemValue = new char[itemLength + 1];
2599 Fp->read(basicOffsetTableItemValue, itemLength);
2602 for (unsigned int i=0; i < itemLength; i += 4 )
2604 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2606 gdcmVerboseMacro( "Read one length: " <<
2607 std::hex << individualLength );
2611 delete[] basicOffsetTableItemValue;
2616 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2617 * Compute the RLE extra information and store it in \ref RLEInfo
2618 * for later pixel retrieval usage.
2620 void Document::ComputeRLEInfo()
2622 std::string ts = GetTransferSyntax();
2623 if ( !Global::GetTS()->IsRLELossless(ts) )
2628 // Encoded pixel data: for the time being we are only concerned with
2629 // Jpeg or RLE Pixel data encodings.
2630 // As stated in PS 3.5-2003, section 8.2 p44:
2631 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2632 // value representation OB is used".
2633 // Hence we expect an OB value representation. Concerning OB VR,
2634 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2635 // "For the Value Representations OB and OW, the encoding shall meet the
2636 // following specifications depending on the Data element tag:"
2638 // - the first item in the sequence of items before the encoded pixel
2639 // data stream shall be basic offset table item. The basic offset table
2640 // item value, however, is not required to be present"
2642 ReadAndSkipEncapsulatedBasicOffsetTable();
2644 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2645 // Loop on the individual frame[s] and store the information
2646 // on the RLE fragments in a RLEFramesInfo.
2647 // Note: - when only a single frame is present, this is a
2649 // - when more than one frame are present, then we are in
2650 // the case of a multi-frame image.
2652 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2654 // Parse the RLE Header and store the corresponding RLE Segment
2655 // Offset Table information on fragments of this current Frame.
2656 // Note that the fragment pixels themselves are not loaded
2657 // (but just skipped).
2658 long frameOffset = Fp->tellg();
2660 uint32_t nbRleSegments = ReadInt32();
2661 if ( nbRleSegments > 16 )
2663 // There should be at most 15 segments (refer to RLEFrame class)
2664 gdcmVerboseMacro( "Too many segments.");
2667 uint32_t rleSegmentOffsetTable[16];
2668 for( int k = 1; k <= 15; k++ )
2670 rleSegmentOffsetTable[k] = ReadInt32();
2673 // Deduce from both the RLE Header and the frameLength the
2674 // fragment length, and again store this info in a
2676 long rleSegmentLength[15];
2677 // skipping (not reading) RLE Segments
2678 if ( nbRleSegments > 1)
2680 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2682 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2683 - rleSegmentOffsetTable[k];
2684 SkipBytes(rleSegmentLength[k]);
2688 rleSegmentLength[nbRleSegments] = frameLength
2689 - rleSegmentOffsetTable[nbRleSegments];
2690 SkipBytes(rleSegmentLength[nbRleSegments]);
2692 // Store the collected info
2693 RLEFrame *newFrameInfo = new RLEFrame;
2694 newFrameInfo->NumberFragments = nbRleSegments;
2695 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2697 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2698 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2700 RLEInfo->Frames.push_back( newFrameInfo );
2703 // Make sure that at the end of the item we encounter a 'Sequence
2705 if ( !ReadTag(0xfffe, 0xe0dd) )
2707 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2712 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2713 * Compute the jpeg extra information (fragment[s] offset[s] and
2714 * length) and store it[them] in \ref JPEGInfo for later pixel
2717 void Document::ComputeJPEGFragmentInfo()
2719 // If you need to, look for comments of ComputeRLEInfo().
2720 std::string ts = GetTransferSyntax();
2721 if ( ! Global::GetTS()->IsJPEG(ts) )
2726 ReadAndSkipEncapsulatedBasicOffsetTable();
2728 // Loop on the fragments[s] and store the parsed information in a
2730 long fragmentLength;
2731 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2733 long fragmentOffset = Fp->tellg();
2735 // Store the collected info
2736 JPEGFragment *newFragment = new JPEGFragment;
2737 newFragment->Offset = fragmentOffset;
2738 newFragment->Length = fragmentLength;
2739 JPEGInfo->Fragments.push_back( newFragment );
2741 SkipBytes( fragmentLength );
2744 // Make sure that at the end of the item we encounter a 'Sequence
2746 if ( !ReadTag(0xfffe, 0xe0dd) )
2748 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2753 * \brief Walk recursively the given \ref DocEntrySet, and feed
2754 * the given hash table (\ref TagDocEntryHT) with all the
2755 * \ref DocEntry (Dicom entries) encountered.
2756 * This method does the job for \ref BuildFlatHashTable.
2757 * @param builtHT Where to collect all the \ref DocEntry encountered
2758 * when recursively walking the given set.
2759 * @param set The structure to be traversed (recursively).
2761 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2764 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2766 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2767 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2768 i != currentHT.end();
2771 DocEntry *entry = i->second;
2772 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2774 const ListSQItem& items = seqEntry->GetSQItems();
2775 for( ListSQItem::const_iterator item = items.begin();
2776 item != items.end();
2779 BuildFlatHashTableRecurse( builtHT, *item );
2783 builtHT[entry->GetKey()] = entry;
2788 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2790 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2791 for (ListDocEntry::const_iterator i = currentList.begin();
2792 i != currentList.end();
2795 DocEntry *entry = *i;
2796 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2798 const ListSQItem& items = seqEntry->GetSQItems();
2799 for( ListSQItem::const_iterator item = items.begin();
2800 item != items.end();
2803 BuildFlatHashTableRecurse( builtHT, *item );
2807 builtHT[entry->GetKey()] = entry;
2814 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2817 * The structure used by a Document (through \ref ElementSet),
2818 * in order to hold the parsed entries of a Dicom header, is a recursive
2819 * one. This is due to the fact that the sequences (when present)
2820 * can be nested. Additionaly, the sequence items (represented in
2821 * gdcm as \ref SQItem) add an extra complexity to the data
2822 * structure. Hence, a gdcm user whishing to visit all the entries of
2823 * a Dicom header will need to dig in the gdcm internals (which
2824 * implies exposing all the internal data structures to the API).
2825 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2826 * recursively builds a temporary hash table, which holds all the
2827 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2829 * \warning Of course there is NO integrity constrain between the
2830 * returned \ref TagDocEntryHT and the \ref ElementSet used
2831 * to build it. Hence if the underlying \ref ElementSet is
2832 * altered, then it is the caller responsability to invoke
2833 * \ref BuildFlatHashTable again...
2834 * @return The flat std::map<> we juste build.
2836 /*TagDocEntryHT *Document::BuildFlatHashTable()
2838 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2839 BuildFlatHashTableRecurse( *FlatHT, this );
2846 * \brief Compares two documents, according to \ref DicomDir rules
2847 * \warning Does NOT work with ACR-NEMA files
2848 * \todo Find a trick to solve the pb (use RET fields ?)
2850 * @return true if 'smaller'
2852 bool Document::operator<(Document &document)
2855 std::string s1 = GetEntry(0x0010,0x0010);
2856 std::string s2 = document.GetEntry(0x0010,0x0010);
2868 s1 = GetEntry(0x0010,0x0020);
2869 s2 = document.GetEntry(0x0010,0x0020);
2880 // Study Instance UID
2881 s1 = GetEntry(0x0020,0x000d);
2882 s2 = document.GetEntry(0x0020,0x000d);
2893 // Serie Instance UID
2894 s1 = GetEntry(0x0020,0x000e);
2895 s2 = document.GetEntry(0x0020,0x000e);
2912 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2913 * @param filetype Type of the File to be written
2915 int Document::ComputeGroup0002Length( FileType filetype )
2920 int groupLength = 0;
2921 bool found0002 = false;
2923 // for each zero-level Tag in the DCM Header
2924 DocEntry *entry = GetFirstEntry();
2927 gr = entry->GetGroup();
2933 el = entry->GetElement();
2934 vr = entry->GetVR();
2936 if (filetype == ExplicitVR)
2938 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2940 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2943 groupLength += 2 + 2 + 4 + entry->GetLength();
2945 else if (found0002 )
2948 entry = GetNextEntry();
2953 } // end namespace gdcm
2955 //-----------------------------------------------------------------------------