1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/24 16:10:52 $
7 Version: $Revision: 1.206 $
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 "gdcmDictSet.h"
28 #include "gdcmRLEFramesInfo.h"
29 #include "gdcmJPEGFragmentsInfo.h"
30 #include "gdcmDocEntrySet.h"
31 #include "gdcmSQItem.h"
37 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
41 #ifdef CMAKE_HAVE_NETINET_IN_H
42 #include <netinet/in.h>
48 //-----------------------------------------------------------------------------
49 // Refer to Document::CheckSwap()
50 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
52 // Refer to Document::SetMaxSizeLoadEntry()
53 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
54 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
56 //-----------------------------------------------------------------------------
57 // Constructor / Destructor
61 * @param filename 'Document' (File or DicomDir) to be opened for parsing
63 Document::Document( std::string const &filename ) : ElementSet(-1)
68 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
78 Group0002Parsed = false;
80 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
81 // Fp->seekg( 0, std::ios::beg);
83 Fp->seekg(0, std::ios::end);
84 long lgt = Fp->tellg();
86 Fp->seekg( 0, std::ios::beg);
89 long beg = Fp->tellg();
92 ParseDES( this, beg, lgt, false); // Loading is done during parsing
94 Fp->seekg( 0, std::ios::beg);
96 // Load 'non string' values
98 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
99 if( PhotometricInterpretation == "PALETTE COLOR " )
101 LoadEntryBinArea(0x0028,0x1200); // gray LUT
102 /// FIXME FIXME FIXME
103 /// The tags refered by the three following lines used to be CORRECTLY
104 /// defined as having an US Value Representation in the public
105 /// dictionary. BUT the semantics implied by the three following
106 /// lines state that the corresponding tag contents are in fact
107 /// the ones of a BinEntry.
108 /// In order to fix things "Quick and Dirty" the dictionary was
109 /// altered on PURPOSE but now contains a WRONG value.
110 /// In order to fix things and restore the dictionary to its
111 /// correct value, one needs to decided of the semantics by deciding
112 /// whether the following tags are either:
113 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
114 /// also used as BinEntry, which requires the proper conversion,
115 /// - OW, and hence loaded as BinEntry, but afterwards also used
116 /// as ValEntry, which requires the proper conversion.
117 LoadEntryBinArea(0x0028,0x1201); // R LUT
118 LoadEntryBinArea(0x0028,0x1202); // G LUT
119 LoadEntryBinArea(0x0028,0x1203); // B LUT
121 // Segmented Red Palette Color LUT Data
122 LoadEntryBinArea(0x0028,0x1221);
123 // Segmented Green Palette Color LUT Data
124 LoadEntryBinArea(0x0028,0x1222);
125 // Segmented Blue Palette Color LUT Data
126 LoadEntryBinArea(0x0028,0x1223);
128 //FIXME later : how to use it?
129 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
133 // --------------------------------------------------------------
134 // Specific code to allow gdcm to read ACR-LibIDO formated images
135 // Note: ACR-LibIDO is an extension of the ACR standard that was
136 // used at CREATIS. For the time being (say a couple years)
137 // we keep this kludge to allow a smooth move to gdcm for
138 // CREATIS developpers (sorry folks).
140 // if recognition code tells us we deal with a LibIDO image
141 // we switch lineNumber and columnNumber
144 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
145 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
146 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
147 // with "little-endian strings"
149 Filetype = ACR_LIBIDO;
150 std::string rows = GetEntryValue(0x0028, 0x0010);
151 std::string columns = GetEntryValue(0x0028, 0x0011);
152 SetEntryValue(columns, 0x0028, 0x0010);
153 SetEntryValue(rows , 0x0028, 0x0011);
155 // ----------------- End of ACR-LibIDO kludge ------------------
159 * \brief This default constructor doesn't parse the file. You should
160 * then invoke \ref Document::SetFileName and then the parsing.
162 Document::Document() : ElementSet(-1)
169 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
172 Filetype = ExplicitVR;
173 Group0002Parsed = false;
177 * \brief Canonical destructor.
179 Document::~Document ()
190 //-----------------------------------------------------------------------------
194 * \brief Prints The Dict Entries of THE public Dicom Dictionary
197 void Document::PrintPubDict(std::ostream &os)
199 RefPubDict->SetPrintLevel(PrintLevel);
200 RefPubDict->Print(os);
204 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
207 void Document::PrintShaDict(std::ostream &os)
209 RefShaDict->SetPrintLevel(PrintLevel);
210 RefShaDict->Print(os);
213 //-----------------------------------------------------------------------------
216 * \brief Get the public dictionary used
218 Dict *Document::GetPubDict()
224 * \brief Get the shadow dictionary used
226 Dict *Document::GetShaDict()
232 * \brief Set the shadow dictionary used
233 * @param dict dictionary to use in shadow
235 bool Document::SetShaDict(Dict *dict)
242 * \brief Set the shadow dictionary used
243 * @param dictName name of the dictionary to use in shadow
245 bool Document::SetShaDict(DictKey const &dictName)
247 RefShaDict = Global::GetDicts()->GetDict(dictName);
252 * \brief This predicate, based on hopefully reasonable heuristics,
253 * decides whether or not the current Document was properly parsed
254 * and contains the mandatory information for being considered as
255 * a well formed and usable Dicom/Acr File.
256 * @return true when Document is the one of a reasonable Dicom/Acr file,
259 bool Document::IsReadable()
261 if( Filetype == Unknown)
263 gdcmVerboseMacro( "Wrong filetype");
267 //if( TagHT.empty() )
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 Predicate for Papyrus file
329 * Dedicated to whomsoever it may concern
330 * @return True when the file is a Papyrus file.
332 bool Document::IsPapyrus()
334 // check for Papyrus private Sequence
335 DocEntry *e = GetDocEntry(0x0041, 0x1050);
338 // check if it's actually a Sequence
339 if ( !dynamic_cast<SeqEntry*>(e) )
345 * \brief returns the File Type
346 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
347 * @return the FileType code
349 FileType Document::GetFileType()
355 * \brief Tries to open the file \ref Document::Filename and
356 * checks the preamble when existing.
357 * @return The FILE pointer on success.
359 std::ifstream *Document::OpenFile()
362 HasDCMPreamble = false;
363 if (Filename.length() == 0)
370 gdcmVerboseMacro( "File already open: " << Filename.c_str());
373 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
376 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
383 Fp->read((char*)&zero, (size_t)2);
390 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
392 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
393 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
394 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
395 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
398 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
399 gdcmVerboseMacro( msg.c_str() );
404 Fp->seekg(126L, std::ios::cur);
406 Fp->read(dicm, (size_t)4);
412 if( memcmp(dicm, "DICM", 4) == 0 )
414 HasDCMPreamble = true;
419 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
425 * \brief closes the file
426 * @return TRUE if the close was successfull
428 bool Document::CloseFile()
437 return true; //FIXME how do we detect a non-closed ifstream ?
441 * \brief Writes in a file all the Header Entries (Dicom Elements)
442 * @param fp file pointer on an already open file (actually: Output File Stream)
443 * @param filetype Type of the File to be written
444 * (ACR-NEMA, ExplicitVR, ImplicitVR)
445 * \return Always true.
447 void Document::WriteContent(std::ofstream *fp, FileType filetype)
449 /// \todo move the following lines (and a lot of others, to be written)
450 /// to a future function CheckAndCorrectHeader
451 /// (necessary if user wants to write a DICOM V3 file
452 /// starting from an ACR-NEMA (V2) Header
454 if ( filetype == ImplicitVR || filetype == ExplicitVR )
456 // writing Dicom File Preamble
457 char filePreamble[128];
458 memset(filePreamble, 0, 128);
459 fp->write(filePreamble, 128);
460 fp->write("DICM", 4);
464 * \todo rewrite later, if really usefull
465 * - 'Group Length' element is optional in DICOM
466 * - but un-updated odd groups lengthes can causes pb
469 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
470 * UpdateGroupLength(false,filetype);
471 * if ( filetype == ACR)
472 * UpdateGroupLength(true,ACR);
475 ElementSet::WriteContent(fp, filetype); // This one is recursive
479 * \brief Modifies the value of a given Doc Entry (Dicom Element)
480 * when it exists. Create it with the given value when unexistant.
481 * @param value (string) Value to be set
482 * @param group Group number of the Entry
483 * @param elem Element number of the Entry
484 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
485 * \return pointer to the modified/created Header Entry (NULL when creation
488 ValEntry *Document::ReplaceOrCreate(std::string const &value,
493 ValEntry *valEntry = 0;
494 DocEntry *currentEntry = GetDocEntry( group, elem);
498 valEntry = dynamic_cast< ValEntry* >(currentEntry);
502 if( valEntry->GetVR()!=vr )
505 // if currentEntry doesn't correspond to the requested valEntry
508 if (!RemoveEntry(currentEntry))
510 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
517 // Create a new valEntry if necessary
520 valEntry = NewValEntry(group, elem, vr);
522 if ( !AddEntry(valEntry))
524 gdcmVerboseMacro("AddEntry failed although this is a creation.");
531 // Set the binEntry value
532 SetEntryValue(value, valEntry); // The std::string value
537 * \brief Modifies the value of a given Header Entry (Dicom Element)
538 * when it exists. Create it with the given value when unexistant.
539 * A copy of the binArea is made to be kept in the Document.
540 * @param binArea (binary) value to be set
541 * @param group Group number of the Entry
542 * @param elem Element number of the Entry
543 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
544 * \return pointer to the modified/created Header Entry (NULL when creation
547 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
553 BinEntry *binEntry = 0;
554 DocEntry *currentEntry = GetDocEntry( group, elem);
556 // Verify the currentEntry
559 binEntry = dynamic_cast< BinEntry* >(currentEntry);
563 if( binEntry->GetVR()!=vr )
566 // if currentEntry doesn't correspond to the requested valEntry
569 if (!RemoveEntry(currentEntry))
571 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
578 // Create a new binEntry if necessary
581 binEntry = NewBinEntry(group, elem, vr);
583 if ( !AddEntry(binEntry))
585 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
592 // Set the binEntry value
594 if (lgth>0 && binArea)
596 tmpArea = new uint8_t[lgth];
597 memcpy(tmpArea,binArea,lgth);
603 if (!SetEntryBinArea(tmpArea,lgth,binEntry))
615 * \brief Modifies the value of a given Header Entry (Dicom Element)
616 * when it exists. Create it when unexistant.
617 * @param group Group number of the Entry
618 * @param elem Element number of the Entry
619 * \return pointer to the modified/created SeqEntry (NULL when creation
622 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
624 SeqEntry *seqEntry = 0;
625 DocEntry *currentEntry = GetDocEntry( group, elem);
627 // Verify the currentEntry
630 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
634 if( seqEntry->GetVR()!="SQ" )
637 // if currentEntry doesn't correspond to the requested valEntry
640 if (!RemoveEntry(currentEntry))
642 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
648 // Create a new seqEntry if necessary
651 seqEntry = NewSeqEntry(group, elem);
653 if ( !AddEntry(seqEntry))
655 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
665 * \brief Set a new value if the invoked element exists
666 * Seems to be useless !!!
667 * @param value new element value
668 * @param group group number of the Entry
669 * @param elem element number of the Entry
672 bool Document::ReplaceIfExist(std::string const &value,
673 uint16_t group, uint16_t elem )
675 SetEntryValue(value, group, elem);
680 //-----------------------------------------------------------------------------
684 * \brief Searches within Header Entries (Dicom Elements) parsed with
685 * the public and private dictionaries
686 * for the element value representation of a given tag..
687 * Obtaining the VR (Value Representation) might be needed by caller
688 * to convert the string typed content to caller's native type
689 * (think of C++ vs Python). The VR is actually of a higher level
690 * of semantics than just the native C++ type.
691 * @param group Group number of the searched tag.
692 * @param elem Element number of the searched tag.
693 * @return Corresponding element value representation when it exists,
694 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
696 std::string Document::GetEntryVR(uint16_t group, uint16_t elem)
698 DocEntry *element = GetDocEntry(group, elem);
703 return element->GetVR();
707 * \brief Searches within Header Entries (Dicom Elements) parsed with
708 * the public and private dictionaries
709 * for the value length of a given tag..
710 * @param group Group number of the searched tag.
711 * @param elem Element number of the searched tag.
712 * @return Corresponding element length; -2 if not found
714 int Document::GetEntryLength(uint16_t group, uint16_t elem)
716 DocEntry *element = GetDocEntry(group, elem);
719 return -2; //magic number
721 return element->GetLength();
725 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
726 * through it's (group, element) and modifies it's content with
728 * @param content new value (string) to substitute with
729 * @param group group number of the Dicom Element to modify
730 * @param elem element number of the Dicom Element to modify
732 bool Document::SetEntryValue(std::string const& content,
733 uint16_t group, uint16_t elem)
735 ValEntry *entry = GetValEntry(group, elem);
738 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
741 return SetEntryValue(content,entry);
744 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
745 * through it's (group, element) and modifies it's content with
747 * @param content new value (void* -> uint8_t*) to substitute with
748 * @param lgth new value length
749 * @param group group number of the Dicom Element to modify
750 * @param elem element number of the Dicom Element to modify
752 bool Document::SetEntryBinArea(uint8_t*content, int lgth,
753 uint16_t group, uint16_t elem)
755 BinEntry *entry = GetBinEntry(group, elem);
758 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
762 return SetEntryBinArea(content,lgth,entry);
766 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
767 * and modifies it's content with the given value.
768 * @param content new value (string) to substitute with
769 * @param entry Entry to be modified
771 bool Document::SetEntryValue(std::string const &content, ValEntry *entry)
775 entry->SetValue(content);
782 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
783 * and modifies it's content with the given value.
784 * @param content new value (void* -> uint8_t*) to substitute with
785 * @param entry Entry to be modified
786 * @param lgth new value length
788 bool Document::SetEntryBinArea(uint8_t *content, int lgth, BinEntry *entry)
792 // Hope Binary field length is *never* wrong
793 /*if(lgth%2) // Non even length are padded with a space (020H).
796 //content = content + '\0'; // fing a trick to enlarge a binary field?
799 entry->SetBinArea(content);
800 entry->SetLength(lgth);
801 entry->SetValue(GDCM_BINLOADED);
808 * \brief Gets (from Header) a 'non string' element value
809 * (LoadElementValues has already be executed)
810 * @param group group number of the Entry
811 * @param elem element number of the Entry
812 * @return Pointer to the 'non string' area
814 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
816 DocEntry *entry = GetDocEntry(group, elem);
819 gdcmVerboseMacro( "No entry");
822 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
824 return binEntry->GetBinArea();
831 * \brief Loads (from disk) the element content
832 * when a string is not suitable
833 * @param group group number of the Entry
834 * @param elem element number of the Entry
836 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
838 // Search the corresponding DocEntry
839 DocEntry *docElement = GetDocEntry(group, elem);
843 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
847 LoadEntryBinArea(binElement);
851 * \brief Loads (from disk) the element content
852 * when a string is not suitable
853 * @param elem Entry whose binArea is going to be loaded
855 void Document::LoadEntryBinArea(BinEntry *elem)
857 if(elem->GetBinArea())
864 size_t o =(size_t)elem->GetOffset();
865 Fp->seekg(o, std::ios::beg);
867 size_t l = elem->GetLength();
868 uint8_t *a = new uint8_t[l];
871 gdcmVerboseMacro( "Cannot allocate BinEntry content");
875 /// \todo check the result
876 Fp->read((char*)a, l);
877 if( Fp->fail() || Fp->eof())
890 * \brief Sets a 'non string' value to a given Dicom Element
891 * @param area area containing the 'non string' value
892 * @param group Group number of the searched Dicom Element
893 * @param elem Element number of the searched Dicom Element
896 /*bool Document::SetEntryBinArea(uint8_t *area,
897 uint16_t group, uint16_t elem)
899 DocEntry *currentEntry = GetDocEntry(group, elem);
905 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
907 binEntry->SetBinArea( area );
916 * \brief Loads the element while preserving the current
917 * underlying file position indicator as opposed to
918 * LoadDocEntry that modifies it.
919 * @param entry Header Entry whose value will be loaded.
922 void Document::LoadDocEntrySafe(DocEntry *entry)
926 long PositionOnEntry = Fp->tellg();
928 Fp->seekg(PositionOnEntry, std::ios::beg);
933 * \brief Swaps back the bytes of 4-byte long integer accordingly to
935 * @return The properly swaped 32 bits integer.
937 uint32_t Document::SwapLong(uint32_t a)
944 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
945 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
948 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
951 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
954 gdcmErrorMacro( "Unset swap code:" << SwapCode );
961 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
963 * @return The properly unswaped 32 bits integer.
965 uint32_t Document::UnswapLong(uint32_t a)
971 * \brief Swaps the bytes so they agree with the processor order
972 * @return The properly swaped 16 bits integer.
974 uint16_t Document::SwapShort(uint16_t a)
976 if ( SwapCode == 4321 || SwapCode == 2143 )
978 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
984 * \brief Unswaps the bytes so they agree with the processor order
985 * @return The properly unswaped 16 bits integer.
987 uint16_t Document::UnswapShort(uint16_t a)
992 //-----------------------------------------------------------------------------
996 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
997 * @return length of the parsed set.
999 void Document::ParseDES(DocEntrySet *set, long offset,
1000 long l_max, bool delim_mode)
1002 DocEntry *newDocEntry = 0;
1003 ValEntry *newValEntry;
1004 BinEntry *newBinEntry;
1005 SeqEntry *newSeqEntry;
1011 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1017 newDocEntry = ReadNextDocEntry( );
1024 vr = newDocEntry->GetVR();
1025 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1026 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1027 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1029 if ( newValEntry || newBinEntry )
1033 if ( Filetype == ExplicitVR && ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1035 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1036 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
1037 << "|" << newDocEntry->GetElement()
1038 << " : Neither Valentry, nor BinEntry."
1039 "Probably unknown VR.");
1042 //////////////////// BinEntry or UNKOWN VR:
1043 // When "this" is a Document the Key is simply of the
1044 // form ( group, elem )...
1045 if ( dynamic_cast< Document* > ( set ) )
1047 newBinEntry->SetKey( newBinEntry->GetKey() );
1049 // but when "this" is a SQItem, we are inserting this new
1050 // valEntry in a sequence item, and the key has the
1051 // generalized form (refer to \ref BaseTagKey):
1052 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1054 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1055 + newBinEntry->GetKey() );
1058 LoadDocEntry( newBinEntry );
1059 if( !set->AddEntry( newBinEntry ) )
1061 //Expect big troubles if here
1062 //delete newBinEntry;
1068 /////////////////////// ValEntry
1069 // When "set" is a Document, then we are at the top of the
1070 // hierarchy and the Key is simply of the form ( group, elem )...
1071 if ( dynamic_cast< Document* > ( set ) )
1073 newValEntry->SetKey( newValEntry->GetKey() );
1075 // ...but when "set" is a SQItem, we are inserting this new
1076 // valEntry in a sequence item. Hence the key has the
1077 // generalized form (refer to \ref BaseTagKey):
1078 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1080 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1081 + newValEntry->GetKey() );
1084 LoadDocEntry( newValEntry );
1085 bool delimitor=newValEntry->IsItemDelimitor();
1086 if( !set->AddEntry( newValEntry ) )
1088 // If here expect big troubles
1089 //delete newValEntry; //otherwise mem leak
1099 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1107 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1108 && ( newDocEntry->GetElement() == 0x0010 ) )
1110 std::string ts = GetTransferSyntax();
1111 if ( Global::GetTS()->IsRLELossless(ts) )
1113 long positionOnEntry = Fp->tellg();
1114 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1116 Fp->seekg( positionOnEntry, std::ios::beg );
1118 else if ( Global::GetTS()->IsJPEG(ts) )
1120 long positionOnEntry = Fp->tellg();
1121 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1122 ComputeJPEGFragmentInfo();
1123 Fp->seekg( positionOnEntry, std::ios::beg );
1127 // Just to make sure we are at the beginning of next entry.
1128 SkipToNextDocEntry(newDocEntry);
1133 unsigned long l = newDocEntry->GetReadLength();
1134 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1136 if ( l == 0xffffffff )
1145 // no other way to create it ...
1146 newSeqEntry->SetDelimitorMode( delim_mode );
1148 // At the top of the hierarchy, stands a Document. When "set"
1149 // is a Document, then we are building the first depth level.
1150 // Hence the SeqEntry we are building simply has a depth
1152 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1155 newSeqEntry->SetDepthLevel( 1 );
1156 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1158 // But when "set" is already a SQItem, we are building a nested
1159 // sequence, and hence the depth level of the new SeqEntry
1160 // we are building, is one level deeper:
1161 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1163 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1164 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1165 + newSeqEntry->GetKey() );
1169 { // Don't try to parse zero-length sequences
1170 ParseSQ( newSeqEntry,
1171 newDocEntry->GetOffset(),
1174 set->AddEntry( newSeqEntry );
1175 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1187 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1188 * @return parsed length for this level
1190 void Document::ParseSQ( SeqEntry *seqEntry,
1191 long offset, long l_max, bool delim_mode)
1193 int SQItemNumber = 0;
1195 long offsetStartCurrentSQItem = offset;
1199 // the first time, we read the fff0,e000 of the first SQItem
1200 DocEntry *newDocEntry = ReadNextDocEntry();
1204 // FIXME Should warn user
1209 if ( newDocEntry->IsSequenceDelimitor() )
1211 seqEntry->SetDelimitationItem( newDocEntry );
1215 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1220 // create the current SQItem
1221 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1222 std::ostringstream newBase;
1223 newBase << seqEntry->GetKey()
1227 itemSQ->SetBaseTagKey( newBase.str() );
1228 unsigned int l = newDocEntry->GetReadLength();
1230 if ( l == 0xffffffff )
1239 // when we're here, element fffe,e000 is already passed.
1240 // it's lost for the SQItem we're going to process !!
1242 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1243 //delete newDocEntry; // FIXME well ... it's too late to use it !
1245 // Let's try :------------
1246 // remove fff0,e000, created out of the SQItem
1248 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1249 // fill up the current SQItem, starting at the beginning of fff0,e000
1250 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1251 offsetStartCurrentSQItem = Fp->tellg();
1252 // end try -----------------
1254 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1256 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1264 * \brief Loads the element content if its length doesn't exceed
1265 * the value specified with Document::SetMaxSizeLoadEntry()
1266 * @param entry Header Entry (Dicom Element) to be dealt with
1268 void Document::LoadDocEntry(DocEntry *entry)
1270 uint16_t group = entry->GetGroup();
1271 std::string vr = entry->GetVR();
1272 uint32_t length = entry->GetLength();
1274 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1276 // A SeQuence "contains" a set of Elements.
1277 // (fffe e000) tells us an Element is beginning
1278 // (fffe e00d) tells us an Element just ended
1279 // (fffe e0dd) tells us the current SeQuence just ended
1280 if( group == 0xfffe )
1282 // NO more value field for SQ !
1286 // When the length is zero things are easy:
1289 ((ValEntry *)entry)->SetValue("");
1293 // The elements whose length is bigger than the specified upper bound
1294 // are not loaded. Instead we leave a short notice of the offset of
1295 // the element content and it's length.
1297 std::ostringstream s;
1298 if (length > MaxSizeLoadEntry)
1300 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1302 //s << "gdcm::NotLoaded (BinEntry)";
1303 s << GDCM_NOTLOADED;
1304 s << " Address:" << (long)entry->GetOffset();
1305 s << " Length:" << entry->GetLength();
1306 s << " x(" << std::hex << entry->GetLength() << ")";
1307 binEntryPtr->SetValue(s.str());
1309 // Be carefull : a BinEntry IS_A ValEntry ...
1310 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1312 // s << "gdcm::NotLoaded. (ValEntry)";
1313 s << GDCM_NOTLOADED;
1314 s << " Address:" << (long)entry->GetOffset();
1315 s << " Length:" << entry->GetLength();
1316 s << " x(" << std::hex << entry->GetLength() << ")";
1317 valEntryPtr->SetValue(s.str());
1322 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1323 << "nor a ValEntry ?! Should never print that !" );
1326 // to be sure we are at the end of the value ...
1327 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1332 // When we find a BinEntry not very much can be done :
1333 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1335 s << GDCM_BINLOADED;
1336 binEntryPtr->SetValue(s.str());
1337 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1341 /// \todo Any compacter code suggested (?)
1342 if ( IsDocEntryAnInteger(entry) )
1346 // When short integer(s) are expected, read and convert the following
1347 // n *two characters properly i.e. consider them as short integers as
1348 // opposed to strings.
1349 // Elements with Value Multiplicity > 1
1350 // contain a set of integers (not a single one)
1351 if (vr == "US" || vr == "SS")
1354 NewInt = ReadInt16();
1358 for (int i=1; i < nbInt; i++)
1361 NewInt = ReadInt16();
1366 // See above comment on multiple integers (mutatis mutandis).
1367 else if (vr == "UL" || vr == "SL")
1370 NewInt = ReadInt32();
1374 for (int i=1; i < nbInt; i++)
1377 NewInt = ReadInt32();
1382 #ifdef GDCM_NO_ANSI_STRING_STREAM
1383 s << std::ends; // to avoid oddities on Solaris
1384 #endif //GDCM_NO_ANSI_STRING_STREAM
1386 ((ValEntry *)entry)->SetValue(s.str());
1390 // FIXME: We need an additional byte for storing \0 that is not on disk
1391 char *str = new char[length+1];
1392 Fp->read(str, (size_t)length);
1393 str[length] = '\0'; //this is only useful when length is odd
1394 // Special DicomString call to properly handle \0 and even length
1395 std::string newValue;
1398 newValue = Util::DicomString(str, length+1);
1399 gdcmVerboseMacro("Warning: bad length: " << length <<
1400 ",For string :" << newValue.c_str());
1401 // Since we change the length of string update it length
1402 //entry->SetReadLength(length+1);
1406 newValue = Util::DicomString(str, length);
1410 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1412 if ( Fp->fail() || Fp->eof())
1414 gdcmVerboseMacro("Unread element value");
1415 valEntry->SetValue(GDCM_UNREAD);
1421 // Because of correspondance with the VR dic
1422 valEntry->SetValue(newValue);
1426 valEntry->SetValue(newValue);
1431 gdcmErrorMacro( "Should have a ValEntry, here !");
1437 * \brief Find the value Length of the passed Header Entry
1438 * @param entry Header Entry whose length of the value shall be loaded.
1440 void Document::FindDocEntryLength( DocEntry *entry )
1441 throw ( FormatError )
1443 std::string vr = entry->GetVR();
1446 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1448 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1450 // The following reserved two bytes (see PS 3.5-2003, section
1451 // "7.1.2 Data element structure with explicit vr", p 27) must be
1452 // skipped before proceeding on reading the length on 4 bytes.
1453 Fp->seekg( 2L, std::ios::cur);
1454 uint32_t length32 = ReadInt32();
1456 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1461 lengthOB = FindDocEntryLengthOBOrOW();
1463 catch ( FormatUnexpected )
1465 // Computing the length failed (this happens with broken
1466 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1467 // chance to get the pixels by deciding the element goes
1468 // until the end of the file. Hence we artificially fix the
1469 // the length and proceed.
1470 long currentPosition = Fp->tellg();
1471 Fp->seekg(0L,std::ios::end);
1473 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1474 Fp->seekg(currentPosition, std::ios::beg);
1476 entry->SetReadLength(lengthUntilEOF);
1477 entry->SetLength(lengthUntilEOF);
1480 entry->SetReadLength(lengthOB);
1481 entry->SetLength(lengthOB);
1484 FixDocEntryFoundLength(entry, length32);
1488 // Length is encoded on 2 bytes.
1489 length16 = ReadInt16();
1491 // FIXME : This heuristic supposes that the first group following
1492 // group 0002 *has* and element 0000.
1493 // BUT ... Element 0000 is optionnal :-(
1496 // Fixed using : HandleOutOfGroup0002()
1497 // (first hereafter strategy ...)
1499 // We can tell the current file is encoded in big endian (like
1500 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1501 // and it's value is the one of the encoding of a big endian file.
1502 // In order to deal with such big endian encoded files, we have
1503 // (at least) two strategies:
1504 // * when we load the "Transfer Syntax" tag with value of big endian
1505 // encoding, we raise the proper flags. Then we wait for the end
1506 // of the META group (0x0002) among which is "Transfer Syntax",
1507 // before switching the swap code to big endian. We have to postpone
1508 // the switching of the swap code since the META group is fully encoded
1509 // in little endian, and big endian coding only starts at the next
1510 // group. The corresponding code can be hard to analyse and adds
1511 // many additional unnecessary tests for regular tags.
1512 // * the second strategy consists in waiting for trouble, that shall
1513 // appear when we find the first group with big endian encoding. This
1514 // is easy to detect since the length of a "Group Length" tag (the
1515 // ones with zero as element number) has to be of 4 (0x0004). When we
1516 // encounter 1024 (0x0400) chances are the encoding changed and we
1517 // found a group with big endian encoding.
1518 //---> Unfortunately, element 0000 is optional.
1519 //---> This will not work when missing!
1520 // We shall use this second strategy. In order to make sure that we
1521 // can interpret the presence of an apparently big endian encoded
1522 // length of a "Group Length" without committing a big mistake, we
1523 // add an additional check: we look in the already parsed elements
1524 // for the presence of a "Transfer Syntax" whose value has to be "big
1525 // endian encoding". When this is the case, chances are we have got our
1526 // hands on a big endian encoded file: we switch the swap code to
1527 // big endian and proceed...
1529 // if ( element == 0x0000 && length16 == 0x0400 )
1531 // std::string ts = GetTransferSyntax();
1532 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1533 // != TS::ExplicitVRBigEndian )
1535 // throw FormatError( "Document::FindDocEntryLength()",
1536 // " not explicit VR." );
1540 // SwitchByteSwapCode();
1542 // // Restore the unproperly loaded values i.e. the group, the element
1543 // // and the dictionary entry depending on them.
1544 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1545 // uint16_t correctElem = SwapShort( entry->GetElement() );
1546 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1549 // // This correct tag is not in the dictionary. Create a new one.
1550 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1552 // // FIXME this can create a memory leaks on the old entry that be
1553 // // left unreferenced.
1554 // entry->SetDictEntry( newTag );
1557 // 0xffff means that we deal with 'No Length' Sequence
1558 // or 'No Length' SQItem
1559 if ( length16 == 0xffff)
1563 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1568 // Either implicit VR or a non DICOM conformal (see note below) explicit
1569 // VR that ommited the VR of (at least) this element. Farts happen.
1570 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1571 // on Data elements "Implicit and Explicit VR Data Elements shall
1572 // not coexist in a Data Set and Data Sets nested within it".]
1573 // Length is on 4 bytes.
1575 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1576 // even if Transfer Syntax is 'Implicit VR ...'
1578 FixDocEntryFoundLength( entry, ReadInt32() );
1584 * \brief Find the Value Representation of the current Dicom Element.
1585 * @return Value Representation of the current Entry
1587 std::string Document::FindDocEntryVR()
1589 if ( Filetype != ExplicitVR )
1590 return GDCM_UNKNOWN;
1592 long positionOnEntry = Fp->tellg();
1593 // Warning: we believe this is explicit VR (Value Representation) because
1594 // we used a heuristic that found "UL" in the first tag. Alas this
1595 // doesn't guarantee that all the tags will be in explicit VR. In some
1596 // cases (see e-film filtered files) one finds implicit VR tags mixed
1597 // within an explicit VR file. Hence we make sure the present tag
1598 // is in explicit VR and try to fix things if it happens not to be
1602 Fp->read (vr, (size_t)2);
1605 if( !CheckDocEntryVR(vr) )
1607 Fp->seekg(positionOnEntry, std::ios::beg);
1608 return GDCM_UNKNOWN;
1614 * \brief Check the correspondance between the VR of the header entry
1615 * and the taken VR. If they are different, the header entry is
1616 * updated with the new VR.
1617 * @param vr Dicom Value Representation
1618 * @return false if the VR is incorrect of if the VR isn't referenced
1619 * otherwise, it returns true
1621 bool Document::CheckDocEntryVR(VRKey vr)
1623 // CLEANME searching the dicom_vr at each occurence is expensive.
1624 // PostPone this test in an optional integrity check at the end
1625 // of parsing or only in debug mode.
1626 if ( !Global::GetVR()->IsValidVR(vr) )
1633 * \brief Get the transformed value of the header entry. The VR value
1634 * is used to define the transformation to operate on the value
1635 * \warning NOT end user intended method !
1636 * @param entry entry to tranform
1637 * @return Transformed entry value
1639 std::string Document::GetDocEntryValue(DocEntry *entry)
1641 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1643 std::string val = ((ValEntry *)entry)->GetValue();
1644 std::string vr = entry->GetVR();
1645 uint32_t length = entry->GetLength();
1646 std::ostringstream s;
1649 // When short integer(s) are expected, read and convert the following
1650 // n * 2 bytes properly i.e. as a multivaluated strings
1651 // (each single value is separated fromthe next one by '\'
1652 // as usual for standard multivaluated filels
1653 // Elements with Value Multiplicity > 1
1654 // contain a set of short integers (not a single one)
1656 if( vr == "US" || vr == "SS" )
1661 for (int i=0; i < nbInt; i++)
1667 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1668 newInt16 = SwapShort( newInt16 );
1673 // When integer(s) are expected, read and convert the following
1674 // n * 4 bytes properly i.e. as a multivaluated strings
1675 // (each single value is separated fromthe next one by '\'
1676 // as usual for standard multivaluated filels
1677 // Elements with Value Multiplicity > 1
1678 // contain a set of integers (not a single one)
1679 else if( vr == "UL" || vr == "SL" )
1684 for (int i=0; i < nbInt; i++)
1690 newInt32 = ( val[4*i+0] & 0xFF )
1691 + (( val[4*i+1] & 0xFF ) << 8 )
1692 + (( val[4*i+2] & 0xFF ) << 16 )
1693 + (( val[4*i+3] & 0xFF ) << 24 );
1694 newInt32 = SwapLong( newInt32 );
1698 #ifdef GDCM_NO_ANSI_STRING_STREAM
1699 s << std::ends; // to avoid oddities on Solaris
1700 #endif //GDCM_NO_ANSI_STRING_STREAM
1704 return ((ValEntry *)entry)->GetValue();
1708 * \brief Get the reverse transformed value of the header entry. The VR
1709 * value is used to define the reverse transformation to operate on
1711 * \warning NOT end user intended method !
1712 * @param entry Entry to reverse transform
1713 * @return Reverse transformed entry value
1715 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1717 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1719 std::string vr = entry->GetVR();
1720 std::vector<std::string> tokens;
1721 std::ostringstream s;
1723 if ( vr == "US" || vr == "SS" )
1727 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1728 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1729 for (unsigned int i=0; i<tokens.size(); i++)
1731 newInt16 = atoi(tokens[i].c_str());
1732 s << ( newInt16 & 0xFF )
1733 << (( newInt16 >> 8 ) & 0xFF );
1737 if ( vr == "UL" || vr == "SL")
1741 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1742 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1743 for (unsigned int i=0; i<tokens.size();i++)
1745 newInt32 = atoi(tokens[i].c_str());
1746 s << (char)( newInt32 & 0xFF )
1747 << (char)(( newInt32 >> 8 ) & 0xFF )
1748 << (char)(( newInt32 >> 16 ) & 0xFF )
1749 << (char)(( newInt32 >> 24 ) & 0xFF );
1754 #ifdef GDCM_NO_ANSI_STRING_STREAM
1755 s << std::ends; // to avoid oddities on Solaris
1756 #endif //GDCM_NO_ANSI_STRING_STREAM
1760 return ((ValEntry *)entry)->GetValue();
1764 * \brief Skip a given Header Entry
1765 * \warning NOT end user intended method !
1766 * @param entry entry to skip
1768 void Document::SkipDocEntry(DocEntry *entry)
1770 SkipBytes(entry->GetLength());
1774 * \brief Skips to the begining of the next Header Entry
1775 * \warning NOT end user intended method !
1776 * @param currentDocEntry entry to skip
1778 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1780 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1781 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1782 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1786 * \brief When the length of an element value is obviously wrong (because
1787 * the parser went Jabberwocky) one can hope improving things by
1788 * applying some heuristics.
1789 * @param entry entry to check
1790 * @param foundLength first assumption about length
1792 void Document::FixDocEntryFoundLength(DocEntry *entry,
1793 uint32_t foundLength)
1795 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1796 if ( foundLength == 0xffffffff)
1801 uint16_t gr = entry->GetGroup();
1802 uint16_t elem = entry->GetElement();
1804 if ( foundLength % 2)
1806 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1807 << " in x(" << std::hex << gr << "," << elem <<")");
1810 //////// Fix for some naughty General Electric images.
1811 // Allthough not recent many such GE corrupted images are still present
1812 // on Creatis hard disks. Hence this fix shall remain when such images
1813 // are no longer in use (we are talking a few years, here)...
1814 // Note: XMedCom probably uses such a trick since it is able to read
1815 // those pesky GE images ...
1816 if ( foundLength == 13)
1818 // Only happens for this length !
1819 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1822 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1826 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1827 // Occurence of such images is quite low (unless one leaves close to a
1828 // 'Leonardo' source. Hence, one might consider commenting out the
1829 // following fix on efficiency reasons.
1830 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1833 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1836 else if ( entry->GetVR() == "SQ" )
1838 foundLength = 0; // ReadLength is unchanged
1841 //////// We encountered a 'delimiter' element i.e. a tag of the form
1842 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1843 // taken into account.
1844 else if( gr == 0xfffe )
1846 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1847 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1848 // causes extra troubles...
1849 if( entry->GetElement() != 0x0000 )
1855 entry->SetLength(foundLength);
1859 * \brief Apply some heuristics to predict whether the considered
1860 * element value contains/represents an integer or not.
1861 * @param entry The element value on which to apply the predicate.
1862 * @return The result of the heuristical predicate.
1864 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1866 uint16_t elem = entry->GetElement();
1867 uint16_t group = entry->GetGroup();
1868 const std::string &vr = entry->GetVR();
1869 uint32_t length = entry->GetLength();
1871 // When we have some semantics on the element we just read, and if we
1872 // a priori know we are dealing with an integer, then we shall be
1873 // able to swap it's element value properly.
1874 if ( elem == 0 ) // This is the group length of the group
1882 // Allthough this should never happen, still some images have a
1883 // corrupted group length [e.g. have a glance at offset x(8336) of
1884 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1885 // Since for dicom compliant and well behaved headers, the present
1886 // test is useless (and might even look a bit paranoid), when we
1887 // encounter such an ill-formed image, we simply display a warning
1888 // message and proceed on parsing (while crossing fingers).
1889 long filePosition = Fp->tellg();
1890 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1891 << std::hex << group << " , " << elem
1892 << ") -before- position x(" << filePosition << ")"
1893 << "lgt : " << length );
1897 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1905 * \brief Find the Length till the next sequence delimiter
1906 * \warning NOT end user intended method !
1910 uint32_t Document::FindDocEntryLengthOBOrOW()
1911 throw( FormatUnexpected )
1913 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1914 long positionOnEntry = Fp->tellg();
1915 bool foundSequenceDelimiter = false;
1916 uint32_t totalLength = 0;
1918 while ( !foundSequenceDelimiter )
1924 group = ReadInt16();
1927 catch ( FormatError )
1929 throw FormatError("Unexpected end of file encountered during ",
1930 "Document::FindDocEntryLengthOBOrOW()");
1933 // We have to decount the group and element we just read
1936 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1938 long filePosition = Fp->tellg();
1939 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1940 << std::hex << group << " , " << elem
1941 << ") -before- position x(" << filePosition << ")" );
1943 Fp->seekg(positionOnEntry, std::ios::beg);
1944 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1947 if ( elem == 0xe0dd )
1949 foundSequenceDelimiter = true;
1952 uint32_t itemLength = ReadInt32();
1953 // We add 4 bytes since we just read the ItemLength with ReadInt32
1954 totalLength += itemLength + 4;
1955 SkipBytes(itemLength);
1957 if ( foundSequenceDelimiter )
1962 Fp->seekg( positionOnEntry, std::ios::beg);
1967 * \brief Reads a supposed to be 16 Bits integer
1968 * (swaps it depending on processor endianity)
1969 * @return read value
1971 uint16_t Document::ReadInt16()
1972 throw( FormatError )
1975 Fp->read ((char*)&g, (size_t)2);
1978 throw FormatError( "Document::ReadInt16()", " file error." );
1982 throw FormatError( "Document::ReadInt16()", "EOF." );
1989 * \brief Reads a supposed to be 32 Bits integer
1990 * (swaps it depending on processor endianity)
1991 * @return read value
1993 uint32_t Document::ReadInt32()
1994 throw( FormatError )
1997 Fp->read ((char*)&g, (size_t)4);
2000 throw FormatError( "Document::ReadInt32()", " file error." );
2004 throw FormatError( "Document::ReadInt32()", "EOF." );
2011 * \brief skips bytes inside the source file
2012 * \warning NOT end user intended method !
2015 void Document::SkipBytes(uint32_t nBytes)
2017 //FIXME don't dump the returned value
2018 Fp->seekg((long)nBytes, std::ios::cur);
2022 * \brief Loads all the needed Dictionaries
2023 * \warning NOT end user intended method !
2025 void Document::Initialize()
2027 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2029 RLEInfo = new RLEFramesInfo;
2030 JPEGInfo = new JPEGFragmentsInfo;
2035 * \brief Discover what the swap code is (among little endian, big endian,
2036 * bad little endian, bad big endian).
2038 * @return false when we are absolutely sure
2039 * it's neither ACR-NEMA nor DICOM
2040 * true when we hope ours assuptions are OK
2042 bool Document::CheckSwap()
2044 // The only guaranted way of finding the swap code is to find a
2045 // group tag since we know it's length has to be of four bytes i.e.
2046 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2047 // occurs when we can't find such group...
2049 uint32_t x = 4; // x : for ntohs
2050 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2056 // First, compare HostByteOrder and NetworkByteOrder in order to
2057 // determine if we shall need to swap bytes (i.e. the Endian type).
2058 if ( x == ntohs(x) )
2067 // The easiest case is the one of a 'true' DICOM header, we just have
2068 // to look for the string "DICM" inside the file preamble.
2071 char *entCur = deb + 128;
2072 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2074 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2076 // Group 0002 should always be VR, and the first element 0000
2077 // Let's be carefull (so many wrong headers ...)
2078 // and determine the value representation (VR) :
2079 // Let's skip to the first element (0002,0000) and check there if we find
2080 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2081 // in which case we (almost) know it is explicit VR.
2082 // WARNING: if it happens to be implicit VR then what we will read
2083 // is the length of the group. If this ascii representation of this
2084 // length happens to be "UL" then we shall believe it is explicit VR.
2085 // We need to skip :
2086 // * the 128 bytes of File Preamble (often padded with zeroes),
2087 // * the 4 bytes of "DICM" string,
2088 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2089 // i.e. a total of 136 bytes.
2092 // group 0x0002 *is always* Explicit VR Sometimes ,
2093 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2094 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2096 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2097 memcmp(entCur, "OB", (size_t)2) == 0 ||
2098 memcmp(entCur, "UI", (size_t)2) == 0 ||
2099 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2100 // when Write DCM *adds*
2102 // Use Document::dicom_vr to test all the possibilities
2103 // instead of just checking for UL, OB and UI !? group 0000
2105 Filetype = ExplicitVR;
2106 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2110 Filetype = ImplicitVR;
2111 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2112 << "Looks like a bugged Header!");
2118 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2123 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2126 // Position the file position indicator at first tag
2127 // (i.e. after the file preamble and the "DICM" string).
2128 Fp->seekg(0, std::ios::beg);
2129 Fp->seekg ( 132L, std::ios::beg);
2133 // Alas, this is not a DicomV3 file and whatever happens there is no file
2134 // preamble. We can reset the file position indicator to where the data
2135 // is (i.e. the beginning of the file).
2136 gdcmVerboseMacro( "Not a DICOM Version3 file");
2137 Fp->seekg(0, std::ios::beg);
2139 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2140 // By clean we mean that the length of the first tag is written down.
2141 // If this is the case and since the length of the first group HAS to be
2142 // four (bytes), then determining the proper swap code is straightforward.
2145 // We assume the array of char we are considering contains the binary
2146 // representation of a 32 bits integer. Hence the following dirty
2148 s32 = *((uint32_t *)(entCur));
2169 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2170 // It is time for despaired wild guesses.
2171 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2172 // i.e. the 'group length' element is not present :
2174 // check the supposed-to-be 'group number'
2175 // in ( 0x0001 .. 0x0008 )
2176 // to determine ' SwapCode' value .
2177 // Only 0 or 4321 will be possible
2178 // (no oportunity to check for the formerly well known
2179 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2180 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2181 // the file IS NOT ACR-NEMA nor DICOM V3
2182 // Find a trick to tell it the caller...
2184 s16 = *((uint16_t *)(deb));
2211 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2219 * \brief Change the Byte Swap code.
2221 void Document::SwitchByteSwapCode()
2223 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2224 if ( SwapCode == 1234 )
2228 else if ( SwapCode == 4321 )
2232 else if ( SwapCode == 3412 )
2236 else if ( SwapCode == 2143 )
2243 * \brief during parsing, Header Elements too long are not loaded in memory
2246 void Document::SetMaxSizeLoadEntry(long newSize)
2252 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2254 MaxSizeLoadEntry = 0xffffffff;
2257 MaxSizeLoadEntry = newSize;
2262 * \brief Header Elements too long will not be printed
2263 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2266 void Document::SetMaxSizePrintEntry(long newSize)
2272 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2274 MaxSizePrintEntry = 0xffffffff;
2277 MaxSizePrintEntry = newSize;
2283 * \brief Handle broken private tag from Philips NTSCAN
2284 * where the endianess is being switch to BigEndian for no
2288 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2290 // Endian reversion. Some files contain groups of tags with reversed endianess.
2291 static int reversedEndian = 0;
2292 // try to fix endian switching in the middle of headers
2293 if ((group == 0xfeff) && (elem == 0x00e0))
2295 // start endian swap mark for group found
2297 SwitchByteSwapCode();
2302 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2304 // end of reversed endian group
2306 SwitchByteSwapCode();
2311 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2312 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2314 std::string Document::GetTransferSyntaxName()
2316 // use the TS (TS : Transfer Syntax)
2317 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
2319 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2321 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2322 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2323 return "Uncompressed ACR-NEMA";
2325 if ( transferSyntax == GDCM_UNFOUND )
2327 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2328 return "Uncompressed ACR-NEMA";
2331 // we do it only when we need it
2332 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2334 // Global::GetTS() is a global static you shall never try to delete it!
2339 * \brief Group 0002 is always coded Little Endian
2340 * whatever Transfer Syntax is
2343 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2345 // Endian reversion. Some files contain groups of tags with reversed endianess.
2346 if ( !Group0002Parsed && group != 0x0002)
2348 Group0002Parsed = true;
2349 // we just came out of group 0002
2350 // if Transfer syntax is Big Endian we have to change CheckSwap
2352 std::string ts = GetTransferSyntax();
2353 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2355 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2359 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2361 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2363 Filetype = ImplicitVR;
2366 // FIXME Strangely, this works with
2367 //'Implicit VR Transfer Syntax (GE Private)
2368 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2370 gdcmVerboseMacro("Transfer Syntax Name = ["
2371 << GetTransferSyntaxName() << "]" );
2372 SwitchByteSwapCode();
2373 group = SwapShort(group);
2374 elem = SwapShort(elem);
2380 * \brief Read the next tag but WITHOUT loading it's value
2381 * (read the 'Group Number', the 'Element Number',
2382 * gets the Dict Entry
2383 * gets the VR, gets the length, gets the offset value)
2384 * @return On succes the newly created DocEntry, NULL on failure.
2386 DocEntry *Document::ReadNextDocEntry()
2393 group = ReadInt16();
2396 catch ( FormatError e )
2398 // We reached the EOF (or an error occured) therefore
2399 // header parsing has to be considered as finished.
2404 // Sometimes file contains groups of tags with reversed endianess.
2405 HandleBrokenEndian(group, elem);
2407 // In 'true DICOM' files Group 0002 is always little endian
2408 if ( HasDCMPreamble )
2409 HandleOutOfGroup0002(group, elem);
2411 std::string vr = FindDocEntryVR();
2412 std::string realVR = vr;
2414 if( vr == GDCM_UNKNOWN)
2416 DictEntry *dictEntry = GetDictEntry(group,elem);
2418 realVR = dictEntry->GetVR();
2422 if( Global::GetVR()->IsVROfSequence(realVR) )
2423 newEntry = NewSeqEntry(group, elem);
2424 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2425 newEntry = NewValEntry(group, elem,vr);
2427 newEntry = NewBinEntry(group, elem,vr);
2429 if( vr == GDCM_UNKNOWN )
2431 if( Filetype == ExplicitVR )
2433 // We thought this was explicit VR, but we end up with an
2434 // implicit VR tag. Let's backtrack.
2435 if ( newEntry->GetGroup() != 0xfffe )
2438 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2439 newEntry->GetGroup(), newEntry->GetElement());
2440 gdcmVerboseMacro( msg.c_str() );
2443 newEntry->SetImplicitVR();
2448 FindDocEntryLength(newEntry);
2450 catch ( FormatError e )
2458 newEntry->SetOffset(Fp->tellg());
2463 //GenerateFreeTagKeyInGroup? What was it designed for ?!?
2465 * \brief Generate a free TagKey i.e. a TagKey that is not present
2466 * in the TagHt dictionary.
2467 * @param group The generated tag must belong to this group.
2468 * @return The element of tag with given group which is fee.
2470 //uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2472 // for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2474 // TagKey key = DictEntry::TranslateToKey(group, elem);
2475 // if (TagHT.count(key) == 0)
2480 // return UINT32_MAX;
2484 * \brief Assuming the internal file pointer \ref Document::Fp
2485 * is placed at the beginning of a tag check whether this
2486 * tag is (TestGroup, TestElement).
2487 * \warning On success the internal file pointer \ref Document::Fp
2488 * is modified to point after the tag.
2489 * On failure (i.e. when the tag wasn't the expected tag
2490 * (TestGroup, TestElement) the internal file pointer
2491 * \ref Document::Fp is restored to it's original position.
2492 * @param testGroup The expected group of the tag.
2493 * @param testElement The expected Element of the tag.
2494 * @return True on success, false otherwise.
2496 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2498 long positionOnEntry = Fp->tellg();
2499 long currentPosition = Fp->tellg(); // On debugging purposes
2501 //// Read the Item Tag group and element, and make
2502 // sure they are what we expected:
2503 uint16_t itemTagGroup;
2504 uint16_t itemTagElement;
2507 itemTagGroup = ReadInt16();
2508 itemTagElement = ReadInt16();
2510 catch ( FormatError e )
2512 //std::cerr << e << std::endl;
2515 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2517 gdcmVerboseMacro( "Wrong Item Tag found:"
2518 << " We should have found tag ("
2519 << std::hex << testGroup << "," << testElement << ")" << std::endl
2520 << " but instead we encountered tag ("
2521 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2522 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2524 Fp->seekg(positionOnEntry, std::ios::beg);
2532 * \brief Assuming the internal file pointer \ref Document::Fp
2533 * is placed at the beginning of a tag (TestGroup, TestElement),
2534 * read the length associated to the Tag.
2535 * \warning On success the internal file pointer \ref Document::Fp
2536 * is modified to point after the tag and it's length.
2537 * On failure (i.e. when the tag wasn't the expected tag
2538 * (TestGroup, TestElement) the internal file pointer
2539 * \ref Document::Fp is restored to it's original position.
2540 * @param testGroup The expected group of the tag.
2541 * @param testElement The expected Element of the tag.
2542 * @return On success returns the length associated to the tag. On failure
2545 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2548 if ( !ReadTag(testGroup, testElement) )
2553 //// Then read the associated Item Length
2554 long currentPosition = Fp->tellg();
2555 uint32_t itemLength = ReadInt32();
2557 gdcmVerboseMacro( "Basic Item Length is: "
2558 << itemLength << std::endl
2559 << " at address: " << std::hex << (unsigned int)currentPosition);
2565 * \brief When parsing the Pixel Data of an encapsulated file, read
2566 * the basic offset table (when present, and BTW dump it).
2568 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2570 //// Read the Basic Offset Table Item Tag length...
2571 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2573 // When present, read the basic offset table itself.
2574 // Notes: - since the presence of this basic offset table is optional
2575 // we can't rely on it for the implementation, and we will simply
2576 // trash it's content (when present).
2577 // - still, when present, we could add some further checks on the
2578 // lengths, but we won't bother with such fuses for the time being.
2579 if ( itemLength != 0 )
2581 char *basicOffsetTableItemValue = new char[itemLength + 1];
2582 Fp->read(basicOffsetTableItemValue, itemLength);
2585 for (unsigned int i=0; i < itemLength; i += 4 )
2587 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2589 gdcmVerboseMacro( "Read one length: " <<
2590 std::hex << individualLength );
2594 delete[] basicOffsetTableItemValue;
2599 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2600 * Compute the RLE extra information and store it in \ref RLEInfo
2601 * for later pixel retrieval usage.
2603 void Document::ComputeRLEInfo()
2605 std::string ts = GetTransferSyntax();
2606 if ( !Global::GetTS()->IsRLELossless(ts) )
2611 // Encoded pixel data: for the time being we are only concerned with
2612 // Jpeg or RLE Pixel data encodings.
2613 // As stated in PS 3.5-2003, section 8.2 p44:
2614 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2615 // value representation OB is used".
2616 // Hence we expect an OB value representation. Concerning OB VR,
2617 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2618 // "For the Value Representations OB and OW, the encoding shall meet the
2619 // following specifications depending on the Data element tag:"
2621 // - the first item in the sequence of items before the encoded pixel
2622 // data stream shall be basic offset table item. The basic offset table
2623 // item value, however, is not required to be present"
2625 ReadAndSkipEncapsulatedBasicOffsetTable();
2627 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2628 // Loop on the individual frame[s] and store the information
2629 // on the RLE fragments in a RLEFramesInfo.
2630 // Note: - when only a single frame is present, this is a
2632 // - when more than one frame are present, then we are in
2633 // the case of a multi-frame image.
2635 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2637 // Parse the RLE Header and store the corresponding RLE Segment
2638 // Offset Table information on fragments of this current Frame.
2639 // Note that the fragment pixels themselves are not loaded
2640 // (but just skipped).
2641 long frameOffset = Fp->tellg();
2643 uint32_t nbRleSegments = ReadInt32();
2644 if ( nbRleSegments > 16 )
2646 // There should be at most 15 segments (refer to RLEFrame class)
2647 gdcmVerboseMacro( "Too many segments.");
2650 uint32_t rleSegmentOffsetTable[16];
2651 for( int k = 1; k <= 15; k++ )
2653 rleSegmentOffsetTable[k] = ReadInt32();
2656 // Deduce from both the RLE Header and the frameLength the
2657 // fragment length, and again store this info in a
2659 long rleSegmentLength[15];
2660 // skipping (not reading) RLE Segments
2661 if ( nbRleSegments > 1)
2663 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2665 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2666 - rleSegmentOffsetTable[k];
2667 SkipBytes(rleSegmentLength[k]);
2671 rleSegmentLength[nbRleSegments] = frameLength
2672 - rleSegmentOffsetTable[nbRleSegments];
2673 SkipBytes(rleSegmentLength[nbRleSegments]);
2675 // Store the collected info
2676 RLEFrame *newFrameInfo = new RLEFrame;
2677 newFrameInfo->NumberFragments = nbRleSegments;
2678 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2680 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2681 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2683 RLEInfo->Frames.push_back( newFrameInfo );
2686 // Make sure that at the end of the item we encounter a 'Sequence
2688 if ( !ReadTag(0xfffe, 0xe0dd) )
2690 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2695 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2696 * Compute the jpeg extra information (fragment[s] offset[s] and
2697 * length) and store it[them] in \ref JPEGInfo for later pixel
2700 void Document::ComputeJPEGFragmentInfo()
2702 // If you need to, look for comments of ComputeRLEInfo().
2703 std::string ts = GetTransferSyntax();
2704 if ( ! Global::GetTS()->IsJPEG(ts) )
2709 ReadAndSkipEncapsulatedBasicOffsetTable();
2711 // Loop on the fragments[s] and store the parsed information in a
2713 long fragmentLength;
2714 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2716 long fragmentOffset = Fp->tellg();
2718 // Store the collected info
2719 JPEGFragment *newFragment = new JPEGFragment;
2720 newFragment->Offset = fragmentOffset;
2721 newFragment->Length = fragmentLength;
2722 JPEGInfo->Fragments.push_back( newFragment );
2724 SkipBytes( fragmentLength );
2727 // Make sure that at the end of the item we encounter a 'Sequence
2729 if ( !ReadTag(0xfffe, 0xe0dd) )
2731 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2736 * \brief Walk recursively the given \ref DocEntrySet, and feed
2737 * the given hash table (\ref TagDocEntryHT) with all the
2738 * \ref DocEntry (Dicom entries) encountered.
2739 * This method does the job for \ref BuildFlatHashTable.
2740 * @param builtHT Where to collect all the \ref DocEntry encountered
2741 * when recursively walking the given set.
2742 * @param set The structure to be traversed (recursively).
2744 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2747 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2749 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2750 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2751 i != currentHT.end();
2754 DocEntry *entry = i->second;
2755 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2757 const ListSQItem& items = seqEntry->GetSQItems();
2758 for( ListSQItem::const_iterator item = items.begin();
2759 item != items.end();
2762 BuildFlatHashTableRecurse( builtHT, *item );
2766 builtHT[entry->GetKey()] = entry;
2771 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2773 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2774 for (ListDocEntry::const_iterator i = currentList.begin();
2775 i != currentList.end();
2778 DocEntry *entry = *i;
2779 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2781 const ListSQItem& items = seqEntry->GetSQItems();
2782 for( ListSQItem::const_iterator item = items.begin();
2783 item != items.end();
2786 BuildFlatHashTableRecurse( builtHT, *item );
2790 builtHT[entry->GetKey()] = entry;
2797 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2800 * The structure used by a Document (through \ref ElementSet),
2801 * in order to hold the parsed entries of a Dicom header, is a recursive
2802 * one. This is due to the fact that the sequences (when present)
2803 * can be nested. Additionaly, the sequence items (represented in
2804 * gdcm as \ref SQItem) add an extra complexity to the data
2805 * structure. Hence, a gdcm user whishing to visit all the entries of
2806 * a Dicom header will need to dig in the gdcm internals (which
2807 * implies exposing all the internal data structures to the API).
2808 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2809 * recursively builds a temporary hash table, which holds all the
2810 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2812 * \warning Of course there is NO integrity constrain between the
2813 * returned \ref TagDocEntryHT and the \ref ElementSet used
2814 * to build it. Hence if the underlying \ref ElementSet is
2815 * altered, then it is the caller responsability to invoke
2816 * \ref BuildFlatHashTable again...
2817 * @return The flat std::map<> we juste build.
2819 /*TagDocEntryHT *Document::BuildFlatHashTable()
2821 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2822 BuildFlatHashTableRecurse( *FlatHT, this );
2829 * \brief Compares two documents, according to \ref DicomDir rules
2830 * \warning Does NOT work with ACR-NEMA files
2831 * \todo Find a trick to solve the pb (use RET fields ?)
2833 * @return true if 'smaller'
2835 bool Document::operator<(Document &document)
2838 std::string s1 = GetEntryValue(0x0010,0x0010);
2839 std::string s2 = document.GetEntryValue(0x0010,0x0010);
2851 s1 = GetEntryValue(0x0010,0x0020);
2852 s2 = document.GetEntryValue(0x0010,0x0020);
2863 // Study Instance UID
2864 s1 = GetEntryValue(0x0020,0x000d);
2865 s2 = document.GetEntryValue(0x0020,0x000d);
2876 // Serie Instance UID
2877 s1 = GetEntryValue(0x0020,0x000e);
2878 s2 = document.GetEntryValue(0x0020,0x000e);
2895 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2896 * @param filetype Type of the File to be written
2898 int Document::ComputeGroup0002Length( FileType filetype )
2903 int groupLength = 0;
2904 bool found0002 = false;
2906 // for each zero-level Tag in the DCM Header
2907 DocEntry *entry = GetFirstEntry();
2910 gr = entry->GetGroup();
2916 el = entry->GetElement();
2917 vr = entry->GetVR();
2919 if (filetype == ExplicitVR)
2921 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2923 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2926 groupLength += 2 + 2 + 4 + entry->GetLength();
2928 else if (found0002 )
2931 entry = GetNextEntry();
2936 } // end namespace gdcm
2938 //-----------------------------------------------------------------------------