1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/25 11:25:33 $
7 Version: $Revision: 1.209 $
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::Insert(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::Insert(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. Creates 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::Insert( 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 &&
1034 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1036 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1037 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
1038 << "|" << newDocEntry->GetElement()
1039 << " : Neither Valentry, nor BinEntry."
1040 "Probably unknown VR.");
1043 //////////////////// BinEntry or UNKOWN VR:
1044 // When "this" is a Document the Key is simply of the
1045 // form ( group, elem )...
1046 if ( dynamic_cast< Document* > ( set ) )
1048 newBinEntry->SetKey( newBinEntry->GetKey() );
1050 // but when "this" is a SQItem, we are inserting this new
1051 // valEntry in a sequence item, and the key has the
1052 // generalized form (refer to \ref BaseTagKey):
1053 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1055 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1056 + newBinEntry->GetKey() );
1059 LoadDocEntry( newBinEntry );
1060 if( !set->AddEntry( newBinEntry ) )
1062 //Expect big troubles if here
1063 //delete newBinEntry;
1069 /////////////////////// ValEntry
1070 // When "set" is a Document, then we are at the top of the
1071 // hierarchy and the Key is simply of the form ( group, elem )...
1072 if ( dynamic_cast< Document* > ( set ) )
1074 newValEntry->SetKey( newValEntry->GetKey() );
1076 // ...but when "set" is a SQItem, we are inserting this new
1077 // valEntry in a sequence item. Hence the key has the
1078 // generalized form (refer to \ref BaseTagKey):
1079 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1081 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1082 + newValEntry->GetKey() );
1085 LoadDocEntry( newValEntry );
1086 bool delimitor=newValEntry->IsItemDelimitor();
1087 if( !set->AddEntry( newValEntry ) )
1089 // If here expect big troubles
1090 //delete newValEntry; //otherwise mem leak
1100 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1108 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1109 && ( newDocEntry->GetElement() == 0x0010 ) )
1111 std::string ts = GetTransferSyntax();
1112 if ( Global::GetTS()->IsRLELossless(ts) )
1114 long positionOnEntry = Fp->tellg();
1115 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1117 Fp->seekg( positionOnEntry, std::ios::beg );
1119 else if ( Global::GetTS()->IsJPEG(ts) )
1121 long positionOnEntry = Fp->tellg();
1122 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1123 ComputeJPEGFragmentInfo();
1124 Fp->seekg( positionOnEntry, std::ios::beg );
1128 // Just to make sure we are at the beginning of next entry.
1129 SkipToNextDocEntry(newDocEntry);
1134 unsigned long l = newDocEntry->GetReadLength();
1135 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1137 if ( l == 0xffffffff )
1146 // no other way to create it ...
1147 newSeqEntry->SetDelimitorMode( delim_mode );
1149 // At the top of the hierarchy, stands a Document. When "set"
1150 // is a Document, then we are building the first depth level.
1151 // Hence the SeqEntry we are building simply has a depth
1153 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1156 newSeqEntry->SetDepthLevel( 1 );
1157 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1159 // But when "set" is already a SQItem, we are building a nested
1160 // sequence, and hence the depth level of the new SeqEntry
1161 // we are building, is one level deeper:
1162 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1164 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1165 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1166 + newSeqEntry->GetKey() );
1170 { // Don't try to parse zero-length sequences
1171 ParseSQ( newSeqEntry,
1172 newDocEntry->GetOffset(),
1175 if( !set->AddEntry( newSeqEntry ) )
1179 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1193 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1194 * @return parsed length for this level
1196 void Document::ParseSQ( SeqEntry *seqEntry,
1197 long offset, long l_max, bool delim_mode)
1199 int SQItemNumber = 0;
1201 long offsetStartCurrentSQItem = offset;
1205 // the first time, we read the fff0,e000 of the first SQItem
1206 DocEntry *newDocEntry = ReadNextDocEntry();
1210 // FIXME Should warn user
1215 if ( newDocEntry->IsSequenceDelimitor() )
1217 seqEntry->SetDelimitationItem( newDocEntry );
1221 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1226 // create the current SQItem
1227 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1228 std::ostringstream newBase;
1229 newBase << seqEntry->GetKey()
1233 itemSQ->SetBaseTagKey( newBase.str() );
1234 unsigned int l = newDocEntry->GetReadLength();
1236 if ( l == 0xffffffff )
1245 // when we're here, element fffe,e000 is already passed.
1246 // it's lost for the SQItem we're going to process !!
1248 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1249 //delete newDocEntry; // FIXME well ... it's too late to use it !
1251 // Let's try :------------
1252 // remove fff0,e000, created out of the SQItem
1254 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1255 // fill up the current SQItem, starting at the beginning of fff0,e000
1256 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1257 offsetStartCurrentSQItem = Fp->tellg();
1258 // end try -----------------
1260 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1262 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1270 * \brief Loads the element content if its length doesn't exceed
1271 * the value specified with Document::SetMaxSizeLoadEntry()
1272 * @param entry Header Entry (Dicom Element) to be dealt with
1274 void Document::LoadDocEntry(DocEntry *entry)
1276 uint16_t group = entry->GetGroup();
1277 std::string vr = entry->GetVR();
1278 uint32_t length = entry->GetLength();
1280 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1282 // A SeQuence "contains" a set of Elements.
1283 // (fffe e000) tells us an Element is beginning
1284 // (fffe e00d) tells us an Element just ended
1285 // (fffe e0dd) tells us the current SeQuence just ended
1286 if( group == 0xfffe )
1288 // NO more value field for SQ !
1292 // When the length is zero things are easy:
1295 ((ValEntry *)entry)->SetValue("");
1299 // The elements whose length is bigger than the specified upper bound
1300 // are not loaded. Instead we leave a short notice of the offset of
1301 // the element content and it's length.
1303 std::ostringstream s;
1304 if (length > MaxSizeLoadEntry)
1306 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1308 //s << "gdcm::NotLoaded (BinEntry)";
1309 s << GDCM_NOTLOADED;
1310 s << " Address:" << (long)entry->GetOffset();
1311 s << " Length:" << entry->GetLength();
1312 s << " x(" << std::hex << entry->GetLength() << ")";
1313 binEntryPtr->SetValue(s.str());
1315 // Be carefull : a BinEntry IS_A ValEntry ...
1316 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1318 // s << "gdcm::NotLoaded. (ValEntry)";
1319 s << GDCM_NOTLOADED;
1320 s << " Address:" << (long)entry->GetOffset();
1321 s << " Length:" << entry->GetLength();
1322 s << " x(" << std::hex << entry->GetLength() << ")";
1323 valEntryPtr->SetValue(s.str());
1328 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1329 << "nor a ValEntry ?! Should never print that !" );
1332 // to be sure we are at the end of the value ...
1333 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1338 // When we find a BinEntry not very much can be done :
1339 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1341 s << GDCM_BINLOADED;
1342 binEntryPtr->SetValue(s.str());
1343 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1347 /// \todo Any compacter code suggested (?)
1348 if ( IsDocEntryAnInteger(entry) )
1352 // When short integer(s) are expected, read and convert the following
1353 // n *two characters properly i.e. consider them as short integers as
1354 // opposed to strings.
1355 // Elements with Value Multiplicity > 1
1356 // contain a set of integers (not a single one)
1357 if (vr == "US" || vr == "SS")
1360 NewInt = ReadInt16();
1364 for (int i=1; i < nbInt; i++)
1367 NewInt = ReadInt16();
1372 // See above comment on multiple integers (mutatis mutandis).
1373 else if (vr == "UL" || vr == "SL")
1376 NewInt = ReadInt32();
1380 for (int i=1; i < nbInt; i++)
1383 NewInt = ReadInt32();
1388 #ifdef GDCM_NO_ANSI_STRING_STREAM
1389 s << std::ends; // to avoid oddities on Solaris
1390 #endif //GDCM_NO_ANSI_STRING_STREAM
1392 ((ValEntry *)entry)->SetValue(s.str());
1396 // FIXME: We need an additional byte for storing \0 that is not on disk
1397 char *str = new char[length+1];
1398 Fp->read(str, (size_t)length);
1399 str[length] = '\0'; //this is only useful when length is odd
1400 // Special DicomString call to properly handle \0 and even length
1401 std::string newValue;
1404 newValue = Util::DicomString(str, length+1);
1405 gdcmVerboseMacro("Warning: bad length: " << length <<
1406 ",For string :" << newValue.c_str());
1407 // Since we change the length of string update it length
1408 //entry->SetReadLength(length+1);
1412 newValue = Util::DicomString(str, length);
1416 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1418 if ( Fp->fail() || Fp->eof())
1420 gdcmVerboseMacro("Unread element value");
1421 valEntry->SetValue(GDCM_UNREAD);
1427 // Because of correspondance with the VR dic
1428 valEntry->SetValue(newValue);
1432 valEntry->SetValue(newValue);
1437 gdcmErrorMacro( "Should have a ValEntry, here !");
1443 * \brief Find the value Length of the passed Header Entry
1444 * @param entry Header Entry whose length of the value shall be loaded.
1446 void Document::FindDocEntryLength( DocEntry *entry )
1447 throw ( FormatError )
1449 std::string vr = entry->GetVR();
1452 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1454 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1456 // The following reserved two bytes (see PS 3.5-2003, section
1457 // "7.1.2 Data element structure with explicit vr", p 27) must be
1458 // skipped before proceeding on reading the length on 4 bytes.
1459 Fp->seekg( 2L, std::ios::cur);
1460 uint32_t length32 = ReadInt32();
1462 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1467 lengthOB = FindDocEntryLengthOBOrOW();
1469 catch ( FormatUnexpected )
1471 // Computing the length failed (this happens with broken
1472 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1473 // chance to get the pixels by deciding the element goes
1474 // until the end of the file. Hence we artificially fix the
1475 // the length and proceed.
1476 long currentPosition = Fp->tellg();
1477 Fp->seekg(0L,std::ios::end);
1479 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1480 Fp->seekg(currentPosition, std::ios::beg);
1482 entry->SetReadLength(lengthUntilEOF);
1483 entry->SetLength(lengthUntilEOF);
1486 entry->SetReadLength(lengthOB);
1487 entry->SetLength(lengthOB);
1490 FixDocEntryFoundLength(entry, length32);
1494 // Length is encoded on 2 bytes.
1495 length16 = ReadInt16();
1497 // FIXME : This heuristic supposes that the first group following
1498 // group 0002 *has* and element 0000.
1499 // BUT ... Element 0000 is optionnal :-(
1502 // Fixed using : HandleOutOfGroup0002()
1503 // (first hereafter strategy ...)
1505 // We can tell the current file is encoded in big endian (like
1506 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1507 // and it's value is the one of the encoding of a big endian file.
1508 // In order to deal with such big endian encoded files, we have
1509 // (at least) two strategies:
1510 // * when we load the "Transfer Syntax" tag with value of big endian
1511 // encoding, we raise the proper flags. Then we wait for the end
1512 // of the META group (0x0002) among which is "Transfer Syntax",
1513 // before switching the swap code to big endian. We have to postpone
1514 // the switching of the swap code since the META group is fully encoded
1515 // in little endian, and big endian coding only starts at the next
1516 // group. The corresponding code can be hard to analyse and adds
1517 // many additional unnecessary tests for regular tags.
1518 // * the second strategy consists in waiting for trouble, that shall
1519 // appear when we find the first group with big endian encoding. This
1520 // is easy to detect since the length of a "Group Length" tag (the
1521 // ones with zero as element number) has to be of 4 (0x0004). When we
1522 // encounter 1024 (0x0400) chances are the encoding changed and we
1523 // found a group with big endian encoding.
1524 //---> Unfortunately, element 0000 is optional.
1525 //---> This will not work when missing!
1526 // We shall use this second strategy. In order to make sure that we
1527 // can interpret the presence of an apparently big endian encoded
1528 // length of a "Group Length" without committing a big mistake, we
1529 // add an additional check: we look in the already parsed elements
1530 // for the presence of a "Transfer Syntax" whose value has to be "big
1531 // endian encoding". When this is the case, chances are we have got our
1532 // hands on a big endian encoded file: we switch the swap code to
1533 // big endian and proceed...
1535 // if ( element == 0x0000 && length16 == 0x0400 )
1537 // std::string ts = GetTransferSyntax();
1538 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1539 // != TS::ExplicitVRBigEndian )
1541 // throw FormatError( "Document::FindDocEntryLength()",
1542 // " not explicit VR." );
1546 // SwitchByteSwapCode();
1548 // // Restore the unproperly loaded values i.e. the group, the element
1549 // // and the dictionary entry depending on them.
1550 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1551 // uint16_t correctElem = SwapShort( entry->GetElement() );
1552 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1555 // // This correct tag is not in the dictionary. Create a new one.
1556 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1558 // // FIXME this can create a memory leaks on the old entry that be
1559 // // left unreferenced.
1560 // entry->SetDictEntry( newTag );
1563 // 0xffff means that we deal with 'No Length' Sequence
1564 // or 'No Length' SQItem
1565 if ( length16 == 0xffff)
1569 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1574 // Either implicit VR or a non DICOM conformal (see note below) explicit
1575 // VR that ommited the VR of (at least) this element. Farts happen.
1576 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1577 // on Data elements "Implicit and Explicit VR Data Elements shall
1578 // not coexist in a Data Set and Data Sets nested within it".]
1579 // Length is on 4 bytes.
1581 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1582 // even if Transfer Syntax is 'Implicit VR ...'
1584 FixDocEntryFoundLength( entry, ReadInt32() );
1590 * \brief Find the Value Representation of the current Dicom Element.
1591 * @return Value Representation of the current Entry
1593 std::string Document::FindDocEntryVR()
1595 if ( Filetype != ExplicitVR )
1596 return GDCM_UNKNOWN;
1598 long positionOnEntry = Fp->tellg();
1599 // Warning: we believe this is explicit VR (Value Representation) because
1600 // we used a heuristic that found "UL" in the first tag. Alas this
1601 // doesn't guarantee that all the tags will be in explicit VR. In some
1602 // cases (see e-film filtered files) one finds implicit VR tags mixed
1603 // within an explicit VR file. Hence we make sure the present tag
1604 // is in explicit VR and try to fix things if it happens not to be
1608 Fp->read (vr, (size_t)2);
1611 if( !CheckDocEntryVR(vr) )
1613 Fp->seekg(positionOnEntry, std::ios::beg);
1614 return GDCM_UNKNOWN;
1620 * \brief Check the correspondance between the VR of the header entry
1621 * and the taken VR. If they are different, the header entry is
1622 * updated with the new VR.
1623 * @param vr Dicom Value Representation
1624 * @return false if the VR is incorrect of if the VR isn't referenced
1625 * otherwise, it returns true
1627 bool Document::CheckDocEntryVR(VRKey vr)
1629 // CLEANME searching the dicom_vr at each occurence is expensive.
1630 // PostPone this test in an optional integrity check at the end
1631 // of parsing or only in debug mode.
1632 if ( !Global::GetVR()->IsValidVR(vr) )
1639 * \brief Get the transformed value of the header entry. The VR value
1640 * is used to define the transformation to operate on the value
1641 * \warning NOT end user intended method !
1642 * @param entry entry to tranform
1643 * @return Transformed entry value
1645 std::string Document::GetDocEntryValue(DocEntry *entry)
1647 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1649 std::string val = ((ValEntry *)entry)->GetValue();
1650 std::string vr = entry->GetVR();
1651 uint32_t length = entry->GetLength();
1652 std::ostringstream s;
1655 // When short integer(s) are expected, read and convert the following
1656 // n * 2 bytes properly i.e. as a multivaluated strings
1657 // (each single value is separated fromthe next one by '\'
1658 // as usual for standard multivaluated filels
1659 // Elements with Value Multiplicity > 1
1660 // contain a set of short integers (not a single one)
1662 if( vr == "US" || vr == "SS" )
1667 for (int i=0; i < nbInt; i++)
1673 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1674 newInt16 = SwapShort( newInt16 );
1679 // When integer(s) are expected, read and convert the following
1680 // n * 4 bytes properly i.e. as a multivaluated strings
1681 // (each single value is separated fromthe next one by '\'
1682 // as usual for standard multivaluated filels
1683 // Elements with Value Multiplicity > 1
1684 // contain a set of integers (not a single one)
1685 else if( vr == "UL" || vr == "SL" )
1690 for (int i=0; i < nbInt; i++)
1696 newInt32 = ( val[4*i+0] & 0xFF )
1697 + (( val[4*i+1] & 0xFF ) << 8 )
1698 + (( val[4*i+2] & 0xFF ) << 16 )
1699 + (( val[4*i+3] & 0xFF ) << 24 );
1700 newInt32 = SwapLong( newInt32 );
1704 #ifdef GDCM_NO_ANSI_STRING_STREAM
1705 s << std::ends; // to avoid oddities on Solaris
1706 #endif //GDCM_NO_ANSI_STRING_STREAM
1710 return ((ValEntry *)entry)->GetValue();
1714 * \brief Get the reverse transformed value of the header entry. The VR
1715 * value is used to define the reverse transformation to operate on
1717 * \warning NOT end user intended method !
1718 * @param entry Entry to reverse transform
1719 * @return Reverse transformed entry value
1721 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1723 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1725 std::string vr = entry->GetVR();
1726 std::vector<std::string> tokens;
1727 std::ostringstream s;
1729 if ( vr == "US" || vr == "SS" )
1733 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1734 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1735 for (unsigned int i=0; i<tokens.size(); i++)
1737 newInt16 = atoi(tokens[i].c_str());
1738 s << ( newInt16 & 0xFF )
1739 << (( newInt16 >> 8 ) & 0xFF );
1743 if ( vr == "UL" || vr == "SL")
1747 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1748 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1749 for (unsigned int i=0; i<tokens.size();i++)
1751 newInt32 = atoi(tokens[i].c_str());
1752 s << (char)( newInt32 & 0xFF )
1753 << (char)(( newInt32 >> 8 ) & 0xFF )
1754 << (char)(( newInt32 >> 16 ) & 0xFF )
1755 << (char)(( newInt32 >> 24 ) & 0xFF );
1760 #ifdef GDCM_NO_ANSI_STRING_STREAM
1761 s << std::ends; // to avoid oddities on Solaris
1762 #endif //GDCM_NO_ANSI_STRING_STREAM
1766 return ((ValEntry *)entry)->GetValue();
1770 * \brief Skip a given Header Entry
1771 * \warning NOT end user intended method !
1772 * @param entry entry to skip
1774 void Document::SkipDocEntry(DocEntry *entry)
1776 SkipBytes(entry->GetLength());
1780 * \brief Skips to the begining of the next Header Entry
1781 * \warning NOT end user intended method !
1782 * @param currentDocEntry entry to skip
1784 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1786 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1787 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1788 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1792 * \brief When the length of an element value is obviously wrong (because
1793 * the parser went Jabberwocky) one can hope improving things by
1794 * applying some heuristics.
1795 * @param entry entry to check
1796 * @param foundLength first assumption about length
1798 void Document::FixDocEntryFoundLength(DocEntry *entry,
1799 uint32_t foundLength)
1801 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1802 if ( foundLength == 0xffffffff)
1807 uint16_t gr = entry->GetGroup();
1808 uint16_t elem = entry->GetElement();
1810 if ( foundLength % 2)
1812 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1813 << " in x(" << std::hex << gr << "," << elem <<")");
1816 //////// Fix for some naughty General Electric images.
1817 // Allthough not recent many such GE corrupted images are still present
1818 // on Creatis hard disks. Hence this fix shall remain when such images
1819 // are no longer in use (we are talking a few years, here)...
1820 // Note: XMedCom probably uses such a trick since it is able to read
1821 // those pesky GE images ...
1822 if ( foundLength == 13)
1824 // Only happens for this length !
1825 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1828 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1832 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1833 // Occurence of such images is quite low (unless one leaves close to a
1834 // 'Leonardo' source. Hence, one might consider commenting out the
1835 // following fix on efficiency reasons.
1836 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1839 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1842 else if ( entry->GetVR() == "SQ" )
1844 foundLength = 0; // ReadLength is unchanged
1847 //////// We encountered a 'delimiter' element i.e. a tag of the form
1848 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1849 // taken into account.
1850 else if( gr == 0xfffe )
1852 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1853 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1854 // causes extra troubles...
1855 if( entry->GetElement() != 0x0000 )
1861 entry->SetLength(foundLength);
1865 * \brief Apply some heuristics to predict whether the considered
1866 * element value contains/represents an integer or not.
1867 * @param entry The element value on which to apply the predicate.
1868 * @return The result of the heuristical predicate.
1870 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1872 uint16_t elem = entry->GetElement();
1873 uint16_t group = entry->GetGroup();
1874 const std::string &vr = entry->GetVR();
1875 uint32_t length = entry->GetLength();
1877 // When we have some semantics on the element we just read, and if we
1878 // a priori know we are dealing with an integer, then we shall be
1879 // able to swap it's element value properly.
1880 if ( elem == 0 ) // This is the group length of the group
1888 // Allthough this should never happen, still some images have a
1889 // corrupted group length [e.g. have a glance at offset x(8336) of
1890 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1891 // Since for dicom compliant and well behaved headers, the present
1892 // test is useless (and might even look a bit paranoid), when we
1893 // encounter such an ill-formed image, we simply display a warning
1894 // message and proceed on parsing (while crossing fingers).
1895 long filePosition = Fp->tellg();
1896 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1897 << std::hex << group << " , " << elem
1898 << ") -before- position x(" << filePosition << ")"
1899 << "lgt : " << length );
1903 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1911 * \brief Find the Length till the next sequence delimiter
1912 * \warning NOT end user intended method !
1916 uint32_t Document::FindDocEntryLengthOBOrOW()
1917 throw( FormatUnexpected )
1919 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1920 long positionOnEntry = Fp->tellg();
1921 bool foundSequenceDelimiter = false;
1922 uint32_t totalLength = 0;
1924 while ( !foundSequenceDelimiter )
1930 group = ReadInt16();
1933 catch ( FormatError )
1935 throw FormatError("Unexpected end of file encountered during ",
1936 "Document::FindDocEntryLengthOBOrOW()");
1939 // We have to decount the group and element we just read
1942 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1944 long filePosition = Fp->tellg();
1945 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1946 << std::hex << group << " , " << elem
1947 << ") -before- position x(" << filePosition << ")" );
1949 Fp->seekg(positionOnEntry, std::ios::beg);
1950 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1953 if ( elem == 0xe0dd )
1955 foundSequenceDelimiter = true;
1958 uint32_t itemLength = ReadInt32();
1959 // We add 4 bytes since we just read the ItemLength with ReadInt32
1960 totalLength += itemLength + 4;
1961 SkipBytes(itemLength);
1963 if ( foundSequenceDelimiter )
1968 Fp->seekg( positionOnEntry, std::ios::beg);
1973 * \brief Reads a supposed to be 16 Bits integer
1974 * (swaps it depending on processor endianity)
1975 * @return read value
1977 uint16_t Document::ReadInt16()
1978 throw( FormatError )
1981 Fp->read ((char*)&g, (size_t)2);
1984 throw FormatError( "Document::ReadInt16()", " file error." );
1988 throw FormatError( "Document::ReadInt16()", "EOF." );
1995 * \brief Reads a supposed to be 32 Bits integer
1996 * (swaps it depending on processor endianity)
1997 * @return read value
1999 uint32_t Document::ReadInt32()
2000 throw( FormatError )
2003 Fp->read ((char*)&g, (size_t)4);
2006 throw FormatError( "Document::ReadInt32()", " file error." );
2010 throw FormatError( "Document::ReadInt32()", "EOF." );
2017 * \brief skips bytes inside the source file
2018 * \warning NOT end user intended method !
2021 void Document::SkipBytes(uint32_t nBytes)
2023 //FIXME don't dump the returned value
2024 Fp->seekg((long)nBytes, std::ios::cur);
2028 * \brief Loads all the needed Dictionaries
2029 * \warning NOT end user intended method !
2031 void Document::Initialize()
2033 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2035 RLEInfo = new RLEFramesInfo;
2036 JPEGInfo = new JPEGFragmentsInfo;
2041 * \brief Discover what the swap code is (among little endian, big endian,
2042 * bad little endian, bad big endian).
2044 * @return false when we are absolutely sure
2045 * it's neither ACR-NEMA nor DICOM
2046 * true when we hope ours assuptions are OK
2048 bool Document::CheckSwap()
2050 // The only guaranted way of finding the swap code is to find a
2051 // group tag since we know it's length has to be of four bytes i.e.
2052 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2053 // occurs when we can't find such group...
2055 uint32_t x = 4; // x : for ntohs
2056 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2062 // First, compare HostByteOrder and NetworkByteOrder in order to
2063 // determine if we shall need to swap bytes (i.e. the Endian type).
2064 if ( x == ntohs(x) )
2073 // The easiest case is the one of a 'true' DICOM header, we just have
2074 // to look for the string "DICM" inside the file preamble.
2077 char *entCur = deb + 128;
2078 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2080 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2082 // Group 0002 should always be VR, and the first element 0000
2083 // Let's be carefull (so many wrong headers ...)
2084 // and determine the value representation (VR) :
2085 // Let's skip to the first element (0002,0000) and check there if we find
2086 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2087 // in which case we (almost) know it is explicit VR.
2088 // WARNING: if it happens to be implicit VR then what we will read
2089 // is the length of the group. If this ascii representation of this
2090 // length happens to be "UL" then we shall believe it is explicit VR.
2091 // We need to skip :
2092 // * the 128 bytes of File Preamble (often padded with zeroes),
2093 // * the 4 bytes of "DICM" string,
2094 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2095 // i.e. a total of 136 bytes.
2098 // group 0x0002 *is always* Explicit VR Sometimes ,
2099 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2100 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2102 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2103 memcmp(entCur, "OB", (size_t)2) == 0 ||
2104 memcmp(entCur, "UI", (size_t)2) == 0 ||
2105 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2106 // when Write DCM *adds*
2108 // Use Document::dicom_vr to test all the possibilities
2109 // instead of just checking for UL, OB and UI !? group 0000
2111 Filetype = ExplicitVR;
2112 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2116 Filetype = ImplicitVR;
2117 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2118 << "Looks like a bugged Header!");
2124 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2129 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2132 // Position the file position indicator at first tag
2133 // (i.e. after the file preamble and the "DICM" string).
2134 Fp->seekg(0, std::ios::beg);
2135 Fp->seekg ( 132L, std::ios::beg);
2139 // Alas, this is not a DicomV3 file and whatever happens there is no file
2140 // preamble. We can reset the file position indicator to where the data
2141 // is (i.e. the beginning of the file).
2142 gdcmVerboseMacro( "Not a DICOM Version3 file");
2143 Fp->seekg(0, std::ios::beg);
2145 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2146 // By clean we mean that the length of the first tag is written down.
2147 // If this is the case and since the length of the first group HAS to be
2148 // four (bytes), then determining the proper swap code is straightforward.
2151 // We assume the array of char we are considering contains the binary
2152 // representation of a 32 bits integer. Hence the following dirty
2154 s32 = *((uint32_t *)(entCur));
2175 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2176 // It is time for despaired wild guesses.
2177 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2178 // i.e. the 'group length' element is not present :
2180 // check the supposed-to-be 'group number'
2181 // in ( 0x0001 .. 0x0008 )
2182 // to determine ' SwapCode' value .
2183 // Only 0 or 4321 will be possible
2184 // (no oportunity to check for the formerly well known
2185 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2186 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2187 // the file IS NOT ACR-NEMA nor DICOM V3
2188 // Find a trick to tell it the caller...
2190 s16 = *((uint16_t *)(deb));
2217 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2225 * \brief Change the Byte Swap code.
2227 void Document::SwitchByteSwapCode()
2229 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2230 if ( SwapCode == 1234 )
2234 else if ( SwapCode == 4321 )
2238 else if ( SwapCode == 3412 )
2242 else if ( SwapCode == 2143 )
2249 * \brief during parsing, Header Elements too long are not loaded in memory
2252 void Document::SetMaxSizeLoadEntry(long newSize)
2258 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2260 MaxSizeLoadEntry = 0xffffffff;
2263 MaxSizeLoadEntry = newSize;
2268 * \brief Header Elements too long will not be printed
2269 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2272 void Document::SetMaxSizePrintEntry(long newSize)
2278 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2280 MaxSizePrintEntry = 0xffffffff;
2283 MaxSizePrintEntry = newSize;
2289 * \brief Handle broken private tag from Philips NTSCAN
2290 * where the endianess is being switch to BigEndian for no
2294 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2296 // Endian reversion. Some files contain groups of tags with reversed endianess.
2297 static int reversedEndian = 0;
2298 // try to fix endian switching in the middle of headers
2299 if ((group == 0xfeff) && (elem == 0x00e0))
2301 // start endian swap mark for group found
2303 SwitchByteSwapCode();
2308 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2310 // end of reversed endian group
2312 SwitchByteSwapCode();
2317 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2318 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2320 std::string Document::GetTransferSyntaxName()
2322 // use the TS (TS : Transfer Syntax)
2323 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
2325 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2327 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2328 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2329 return "Uncompressed ACR-NEMA";
2331 if ( transferSyntax == GDCM_UNFOUND )
2333 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2334 return "Uncompressed ACR-NEMA";
2337 // we do it only when we need it
2338 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2340 // Global::GetTS() is a global static you shall never try to delete it!
2345 * \brief Group 0002 is always coded Little Endian
2346 * whatever Transfer Syntax is
2349 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2351 // Endian reversion. Some files contain groups of tags with reversed endianess.
2352 if ( !Group0002Parsed && group != 0x0002)
2354 Group0002Parsed = true;
2355 // we just came out of group 0002
2356 // if Transfer syntax is Big Endian we have to change CheckSwap
2358 std::string ts = GetTransferSyntax();
2359 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2361 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2365 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2367 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2369 Filetype = ImplicitVR;
2372 // FIXME Strangely, this works with
2373 //'Implicit VR Transfer Syntax (GE Private)
2374 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2376 gdcmVerboseMacro("Transfer Syntax Name = ["
2377 << GetTransferSyntaxName() << "]" );
2378 SwitchByteSwapCode();
2379 group = SwapShort(group);
2380 elem = SwapShort(elem);
2386 * \brief Read the next tag but WITHOUT loading it's value
2387 * (read the 'Group Number', the 'Element Number',
2388 * gets the Dict Entry
2389 * gets the VR, gets the length, gets the offset value)
2390 * @return On succes the newly created DocEntry, NULL on failure.
2392 DocEntry *Document::ReadNextDocEntry()
2399 group = ReadInt16();
2402 catch ( FormatError e )
2404 // We reached the EOF (or an error occured) therefore
2405 // header parsing has to be considered as finished.
2410 // Sometimes file contains groups of tags with reversed endianess.
2411 HandleBrokenEndian(group, elem);
2413 // In 'true DICOM' files Group 0002 is always little endian
2414 if ( HasDCMPreamble )
2415 HandleOutOfGroup0002(group, elem);
2417 std::string vr = FindDocEntryVR();
2418 std::string realVR = vr;
2420 if( vr == GDCM_UNKNOWN)
2422 DictEntry *dictEntry = GetDictEntry(group,elem);
2424 realVR = dictEntry->GetVR();
2428 if( Global::GetVR()->IsVROfSequence(realVR) )
2429 newEntry = NewSeqEntry(group, elem);
2430 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2431 newEntry = NewValEntry(group, elem,vr);
2433 newEntry = NewBinEntry(group, elem,vr);
2435 if( vr == GDCM_UNKNOWN )
2437 if( Filetype == ExplicitVR )
2439 // We thought this was explicit VR, but we end up with an
2440 // implicit VR tag. Let's backtrack.
2441 if ( newEntry->GetGroup() != 0xfffe )
2444 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2445 newEntry->GetGroup(), newEntry->GetElement());
2446 gdcmVerboseMacro( msg.c_str() );
2449 newEntry->SetImplicitVR();
2454 FindDocEntryLength(newEntry);
2456 catch ( FormatError e )
2464 newEntry->SetOffset(Fp->tellg());
2469 //GenerateFreeTagKeyInGroup? What was it designed for ?!?
2471 * \brief Generate a free TagKey i.e. a TagKey that is not present
2472 * in the TagHt dictionary.
2473 * @param group The generated tag must belong to this group.
2474 * @return The element of tag with given group which is fee.
2476 //uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2478 // for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2480 // TagKey key = DictEntry::TranslateToKey(group, elem);
2481 // if (TagHT.count(key) == 0)
2486 // return UINT32_MAX;
2490 * \brief Assuming the internal file pointer \ref Document::Fp
2491 * is placed at the beginning of a tag check whether this
2492 * tag is (TestGroup, TestElement).
2493 * \warning On success the internal file pointer \ref Document::Fp
2494 * is modified to point after the tag.
2495 * On failure (i.e. when the tag wasn't the expected tag
2496 * (TestGroup, TestElement) the internal file pointer
2497 * \ref Document::Fp is restored to it's original position.
2498 * @param testGroup The expected group of the tag.
2499 * @param testElement The expected Element of the tag.
2500 * @return True on success, false otherwise.
2502 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2504 long positionOnEntry = Fp->tellg();
2505 long currentPosition = Fp->tellg(); // On debugging purposes
2507 //// Read the Item Tag group and element, and make
2508 // sure they are what we expected:
2509 uint16_t itemTagGroup;
2510 uint16_t itemTagElement;
2513 itemTagGroup = ReadInt16();
2514 itemTagElement = ReadInt16();
2516 catch ( FormatError e )
2518 //std::cerr << e << std::endl;
2521 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2523 gdcmVerboseMacro( "Wrong Item Tag found:"
2524 << " We should have found tag ("
2525 << std::hex << testGroup << "," << testElement << ")" << std::endl
2526 << " but instead we encountered tag ("
2527 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2528 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2530 Fp->seekg(positionOnEntry, std::ios::beg);
2538 * \brief Assuming the internal file pointer \ref Document::Fp
2539 * is placed at the beginning of a tag (TestGroup, TestElement),
2540 * read the length associated to the Tag.
2541 * \warning On success the internal file pointer \ref Document::Fp
2542 * is modified to point after the tag and it's length.
2543 * On failure (i.e. when the tag wasn't the expected tag
2544 * (TestGroup, TestElement) the internal file pointer
2545 * \ref Document::Fp is restored to it's original position.
2546 * @param testGroup The expected group of the tag.
2547 * @param testElement The expected Element of the tag.
2548 * @return On success returns the length associated to the tag. On failure
2551 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2554 if ( !ReadTag(testGroup, testElement) )
2559 //// Then read the associated Item Length
2560 long currentPosition = Fp->tellg();
2561 uint32_t itemLength = ReadInt32();
2563 gdcmVerboseMacro( "Basic Item Length is: "
2564 << itemLength << std::endl
2565 << " at address: " << std::hex << (unsigned int)currentPosition);
2571 * \brief When parsing the Pixel Data of an encapsulated file, read
2572 * the basic offset table (when present, and BTW dump it).
2574 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2576 //// Read the Basic Offset Table Item Tag length...
2577 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2579 // When present, read the basic offset table itself.
2580 // Notes: - since the presence of this basic offset table is optional
2581 // we can't rely on it for the implementation, and we will simply
2582 // trash it's content (when present).
2583 // - still, when present, we could add some further checks on the
2584 // lengths, but we won't bother with such fuses for the time being.
2585 if ( itemLength != 0 )
2587 char *basicOffsetTableItemValue = new char[itemLength + 1];
2588 Fp->read(basicOffsetTableItemValue, itemLength);
2591 for (unsigned int i=0; i < itemLength; i += 4 )
2593 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2595 gdcmVerboseMacro( "Read one length: " <<
2596 std::hex << individualLength );
2600 delete[] basicOffsetTableItemValue;
2605 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2606 * Compute the RLE extra information and store it in \ref RLEInfo
2607 * for later pixel retrieval usage.
2609 void Document::ComputeRLEInfo()
2611 std::string ts = GetTransferSyntax();
2612 if ( !Global::GetTS()->IsRLELossless(ts) )
2617 // Encoded pixel data: for the time being we are only concerned with
2618 // Jpeg or RLE Pixel data encodings.
2619 // As stated in PS 3.5-2003, section 8.2 p44:
2620 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2621 // value representation OB is used".
2622 // Hence we expect an OB value representation. Concerning OB VR,
2623 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2624 // "For the Value Representations OB and OW, the encoding shall meet the
2625 // following specifications depending on the Data element tag:"
2627 // - the first item in the sequence of items before the encoded pixel
2628 // data stream shall be basic offset table item. The basic offset table
2629 // item value, however, is not required to be present"
2631 ReadAndSkipEncapsulatedBasicOffsetTable();
2633 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2634 // Loop on the individual frame[s] and store the information
2635 // on the RLE fragments in a RLEFramesInfo.
2636 // Note: - when only a single frame is present, this is a
2638 // - when more than one frame are present, then we are in
2639 // the case of a multi-frame image.
2641 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2643 // Parse the RLE Header and store the corresponding RLE Segment
2644 // Offset Table information on fragments of this current Frame.
2645 // Note that the fragment pixels themselves are not loaded
2646 // (but just skipped).
2647 long frameOffset = Fp->tellg();
2649 uint32_t nbRleSegments = ReadInt32();
2650 if ( nbRleSegments > 16 )
2652 // There should be at most 15 segments (refer to RLEFrame class)
2653 gdcmVerboseMacro( "Too many segments.");
2656 uint32_t rleSegmentOffsetTable[16];
2657 for( int k = 1; k <= 15; k++ )
2659 rleSegmentOffsetTable[k] = ReadInt32();
2662 // Deduce from both the RLE Header and the frameLength the
2663 // fragment length, and again store this info in a
2665 long rleSegmentLength[15];
2666 // skipping (not reading) RLE Segments
2667 if ( nbRleSegments > 1)
2669 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2671 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2672 - rleSegmentOffsetTable[k];
2673 SkipBytes(rleSegmentLength[k]);
2677 rleSegmentLength[nbRleSegments] = frameLength
2678 - rleSegmentOffsetTable[nbRleSegments];
2679 SkipBytes(rleSegmentLength[nbRleSegments]);
2681 // Store the collected info
2682 RLEFrame *newFrameInfo = new RLEFrame;
2683 newFrameInfo->NumberFragments = nbRleSegments;
2684 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2686 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2687 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2689 RLEInfo->Frames.push_back( newFrameInfo );
2692 // Make sure that at the end of the item we encounter a 'Sequence
2694 if ( !ReadTag(0xfffe, 0xe0dd) )
2696 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2701 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2702 * Compute the jpeg extra information (fragment[s] offset[s] and
2703 * length) and store it[them] in \ref JPEGInfo for later pixel
2706 void Document::ComputeJPEGFragmentInfo()
2708 // If you need to, look for comments of ComputeRLEInfo().
2709 std::string ts = GetTransferSyntax();
2710 if ( ! Global::GetTS()->IsJPEG(ts) )
2715 ReadAndSkipEncapsulatedBasicOffsetTable();
2717 // Loop on the fragments[s] and store the parsed information in a
2719 long fragmentLength;
2720 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2722 long fragmentOffset = Fp->tellg();
2724 // Store the collected info
2725 JPEGFragment *newFragment = new JPEGFragment;
2726 newFragment->Offset = fragmentOffset;
2727 newFragment->Length = fragmentLength;
2728 JPEGInfo->Fragments.push_back( newFragment );
2730 SkipBytes( fragmentLength );
2733 // Make sure that at the end of the item we encounter a 'Sequence
2735 if ( !ReadTag(0xfffe, 0xe0dd) )
2737 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2742 * \brief Walk recursively the given \ref DocEntrySet, and feed
2743 * the given hash table (\ref TagDocEntryHT) with all the
2744 * \ref DocEntry (Dicom entries) encountered.
2745 * This method does the job for \ref BuildFlatHashTable.
2746 * @param builtHT Where to collect all the \ref DocEntry encountered
2747 * when recursively walking the given set.
2748 * @param set The structure to be traversed (recursively).
2750 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2753 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2755 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2756 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2757 i != currentHT.end();
2760 DocEntry *entry = i->second;
2761 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2763 const ListSQItem& items = seqEntry->GetSQItems();
2764 for( ListSQItem::const_iterator item = items.begin();
2765 item != items.end();
2768 BuildFlatHashTableRecurse( builtHT, *item );
2772 builtHT[entry->GetKey()] = entry;
2777 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2779 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2780 for (ListDocEntry::const_iterator i = currentList.begin();
2781 i != currentList.end();
2784 DocEntry *entry = *i;
2785 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2787 const ListSQItem& items = seqEntry->GetSQItems();
2788 for( ListSQItem::const_iterator item = items.begin();
2789 item != items.end();
2792 BuildFlatHashTableRecurse( builtHT, *item );
2796 builtHT[entry->GetKey()] = entry;
2803 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2806 * The structure used by a Document (through \ref ElementSet),
2807 * in order to hold the parsed entries of a Dicom header, is a recursive
2808 * one. This is due to the fact that the sequences (when present)
2809 * can be nested. Additionaly, the sequence items (represented in
2810 * gdcm as \ref SQItem) add an extra complexity to the data
2811 * structure. Hence, a gdcm user whishing to visit all the entries of
2812 * a Dicom header will need to dig in the gdcm internals (which
2813 * implies exposing all the internal data structures to the API).
2814 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2815 * recursively builds a temporary hash table, which holds all the
2816 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2818 * \warning Of course there is NO integrity constrain between the
2819 * returned \ref TagDocEntryHT and the \ref ElementSet used
2820 * to build it. Hence if the underlying \ref ElementSet is
2821 * altered, then it is the caller responsability to invoke
2822 * \ref BuildFlatHashTable again...
2823 * @return The flat std::map<> we juste build.
2825 /*TagDocEntryHT *Document::BuildFlatHashTable()
2827 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2828 BuildFlatHashTableRecurse( *FlatHT, this );
2835 * \brief Compares two documents, according to \ref DicomDir rules
2836 * \warning Does NOT work with ACR-NEMA files
2837 * \todo Find a trick to solve the pb (use RET fields ?)
2839 * @return true if 'smaller'
2841 bool Document::operator<(Document &document)
2844 std::string s1 = GetEntryValue(0x0010,0x0010);
2845 std::string s2 = document.GetEntryValue(0x0010,0x0010);
2857 s1 = GetEntryValue(0x0010,0x0020);
2858 s2 = document.GetEntryValue(0x0010,0x0020);
2869 // Study Instance UID
2870 s1 = GetEntryValue(0x0020,0x000d);
2871 s2 = document.GetEntryValue(0x0020,0x000d);
2882 // Serie Instance UID
2883 s1 = GetEntryValue(0x0020,0x000e);
2884 s2 = document.GetEntryValue(0x0020,0x000e);
2900 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2901 * @param filetype Type of the File to be written
2903 int Document::ComputeGroup0002Length( FileType filetype )
2908 int groupLength = 0;
2909 bool found0002 = false;
2911 // for each zero-level Tag in the DCM Header
2912 DocEntry *entry = GetFirstEntry();
2915 gr = entry->GetGroup();
2920 vr = entry->GetVR();
2922 if (filetype == ExplicitVR)
2924 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2926 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2929 groupLength += 2 + 2 + 4 + entry->GetLength();
2931 else if (found0002 )
2934 entry = GetNextEntry();
2939 } // end namespace gdcm
2941 //-----------------------------------------------------------------------------