1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/24 14:14:11 $
7 Version: $Revision: 1.205 $
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 = GetEntry(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 = GetEntry(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 = GetEntry(0x0028, 0x0010);
151 std::string columns = GetEntry(0x0028, 0x0011);
152 SetEntry(columns, 0x0028, 0x0010);
153 SetEntry(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 SetEntry(value, valEntry);
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 (!SetEntry(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 SetEntry(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::SetEntry(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 SetEntry(content,entry);
745 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
746 * through it's (group, element) and modifies it's content with
748 * @param content new value (void* -> uint8_t*) to substitute with
749 * @param lgth new value length
750 * @param group group number of the Dicom Element to modify
751 * @param elem element number of the Dicom Element to modify
753 bool Document::SetEntry(uint8_t*content, int lgth,
754 uint16_t group, uint16_t elem)
756 BinEntry *entry = GetBinEntry(group, elem);
759 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
763 return SetEntry(content,lgth,entry);
767 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
768 * and modifies it's content with the given value.
769 * @param content new value (string) to substitute with
770 * @param entry Entry to be modified
772 bool Document::SetEntry(std::string const &content, ValEntry *entry)
776 entry->SetValue(content);
783 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
784 * and modifies it's content with the given value.
785 * @param content new value (void* -> uint8_t*) to substitute with
786 * @param entry Entry to be modified
787 * @param lgth new value length
789 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
793 // Hope Binary field length is *never* wrong
794 /*if(lgth%2) // Non even length are padded with a space (020H).
797 //content = content + '\0'; // fing a trick to enlarge a binary field?
800 entry->SetBinArea(content);
801 entry->SetLength(lgth);
802 entry->SetValue(GDCM_BINLOADED);
809 * \brief Gets (from Header) a 'non string' element value
810 * (LoadElementValues has already be executed)
811 * @param group group number of the Entry
812 * @param elem element number of the Entry
813 * @return Pointer to the 'non string' area
815 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
817 DocEntry *entry = GetDocEntry(group, elem);
820 gdcmVerboseMacro( "No entry");
823 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
825 return binEntry->GetBinArea();
832 * \brief Loads (from disk) the element content
833 * when a string is not suitable
834 * @param group group number of the Entry
835 * @param elem element number of the Entry
837 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
839 // Search the corresponding DocEntry
840 DocEntry *docElement = GetDocEntry(group, elem);
844 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
848 LoadEntryBinArea(binElement);
852 * \brief Loads (from disk) the element content
853 * when a string is not suitable
854 * @param elem Entry whose binArea is going to be loaded
856 void Document::LoadEntryBinArea(BinEntry *elem)
858 if(elem->GetBinArea())
865 size_t o =(size_t)elem->GetOffset();
866 Fp->seekg(o, std::ios::beg);
868 size_t l = elem->GetLength();
869 uint8_t *a = new uint8_t[l];
872 gdcmVerboseMacro( "Cannot allocate BinEntry content");
876 /// \todo check the result
877 Fp->read((char*)a, l);
878 if( Fp->fail() || Fp->eof())
891 * \brief Sets a 'non string' value to a given Dicom Element
892 * @param area area containing the 'non string' value
893 * @param group Group number of the searched Dicom Element
894 * @param elem Element number of the searched Dicom Element
897 /*bool Document::SetEntryBinArea(uint8_t *area,
898 uint16_t group, uint16_t elem)
900 DocEntry *currentEntry = GetDocEntry(group, elem);
906 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
908 binEntry->SetBinArea( area );
917 * \brief Loads the element while preserving the current
918 * underlying file position indicator as opposed to
919 * LoadDocEntry that modifies it.
920 * @param entry Header Entry whose value will be loaded.
923 void Document::LoadDocEntrySafe(DocEntry *entry)
927 long PositionOnEntry = Fp->tellg();
929 Fp->seekg(PositionOnEntry, std::ios::beg);
934 * \brief Swaps back the bytes of 4-byte long integer accordingly to
936 * @return The properly swaped 32 bits integer.
938 uint32_t Document::SwapLong(uint32_t a)
945 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
946 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
949 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
952 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
955 gdcmErrorMacro( "Unset swap code:" << SwapCode );
962 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
964 * @return The properly unswaped 32 bits integer.
966 uint32_t Document::UnswapLong(uint32_t a)
972 * \brief Swaps the bytes so they agree with the processor order
973 * @return The properly swaped 16 bits integer.
975 uint16_t Document::SwapShort(uint16_t a)
977 if ( SwapCode == 4321 || SwapCode == 2143 )
979 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
985 * \brief Unswaps the bytes so they agree with the processor order
986 * @return The properly unswaped 16 bits integer.
988 uint16_t Document::UnswapShort(uint16_t a)
993 //-----------------------------------------------------------------------------
997 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
998 * @return length of the parsed set.
1000 void Document::ParseDES(DocEntrySet *set, long offset,
1001 long l_max, bool delim_mode)
1003 DocEntry *newDocEntry = 0;
1004 ValEntry *newValEntry;
1005 BinEntry *newBinEntry;
1006 SeqEntry *newSeqEntry;
1012 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1018 newDocEntry = ReadNextDocEntry( );
1025 vr = newDocEntry->GetVR();
1026 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1027 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1028 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1030 if ( newValEntry || newBinEntry )
1034 if ( Filetype == ExplicitVR && ! 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 set->AddEntry( newSeqEntry );
1176 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1188 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1189 * @return parsed length for this level
1191 void Document::ParseSQ( SeqEntry *seqEntry,
1192 long offset, long l_max, bool delim_mode)
1194 int SQItemNumber = 0;
1196 long offsetStartCurrentSQItem = offset;
1200 // the first time, we read the fff0,e000 of the first SQItem
1201 DocEntry *newDocEntry = ReadNextDocEntry();
1205 // FIXME Should warn user
1210 if ( newDocEntry->IsSequenceDelimitor() )
1212 seqEntry->SetDelimitationItem( newDocEntry );
1216 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1221 // create the current SQItem
1222 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1223 std::ostringstream newBase;
1224 newBase << seqEntry->GetKey()
1228 itemSQ->SetBaseTagKey( newBase.str() );
1229 unsigned int l = newDocEntry->GetReadLength();
1231 if ( l == 0xffffffff )
1240 // when we're here, element fffe,e000 is already passed.
1241 // it's lost for the SQItem we're going to process !!
1243 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1244 //delete newDocEntry; // FIXME well ... it's too late to use it !
1246 // Let's try :------------
1247 // remove fff0,e000, created out of the SQItem
1249 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1250 // fill up the current SQItem, starting at the beginning of fff0,e000
1251 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1252 offsetStartCurrentSQItem = Fp->tellg();
1253 // end try -----------------
1255 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1257 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1265 * \brief Loads the element content if its length doesn't exceed
1266 * the value specified with Document::SetMaxSizeLoadEntry()
1267 * @param entry Header Entry (Dicom Element) to be dealt with
1269 void Document::LoadDocEntry(DocEntry *entry)
1271 uint16_t group = entry->GetGroup();
1272 std::string vr = entry->GetVR();
1273 uint32_t length = entry->GetLength();
1275 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1277 // A SeQuence "contains" a set of Elements.
1278 // (fffe e000) tells us an Element is beginning
1279 // (fffe e00d) tells us an Element just ended
1280 // (fffe e0dd) tells us the current SeQuence just ended
1281 if( group == 0xfffe )
1283 // NO more value field for SQ !
1287 // When the length is zero things are easy:
1290 ((ValEntry *)entry)->SetValue("");
1294 // The elements whose length is bigger than the specified upper bound
1295 // are not loaded. Instead we leave a short notice of the offset of
1296 // the element content and it's length.
1298 std::ostringstream s;
1299 if (length > MaxSizeLoadEntry)
1301 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1303 //s << "gdcm::NotLoaded (BinEntry)";
1304 s << GDCM_NOTLOADED;
1305 s << " Address:" << (long)entry->GetOffset();
1306 s << " Length:" << entry->GetLength();
1307 s << " x(" << std::hex << entry->GetLength() << ")";
1308 binEntryPtr->SetValue(s.str());
1310 // Be carefull : a BinEntry IS_A ValEntry ...
1311 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1313 // s << "gdcm::NotLoaded. (ValEntry)";
1314 s << GDCM_NOTLOADED;
1315 s << " Address:" << (long)entry->GetOffset();
1316 s << " Length:" << entry->GetLength();
1317 s << " x(" << std::hex << entry->GetLength() << ")";
1318 valEntryPtr->SetValue(s.str());
1323 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1324 << "nor a ValEntry ?! Should never print that !" );
1327 // to be sure we are at the end of the value ...
1328 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1333 // When we find a BinEntry not very much can be done :
1334 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1336 s << GDCM_BINLOADED;
1337 binEntryPtr->SetValue(s.str());
1338 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1342 /// \todo Any compacter code suggested (?)
1343 if ( IsDocEntryAnInteger(entry) )
1347 // When short integer(s) are expected, read and convert the following
1348 // n *two characters properly i.e. consider them as short integers as
1349 // opposed to strings.
1350 // Elements with Value Multiplicity > 1
1351 // contain a set of integers (not a single one)
1352 if (vr == "US" || vr == "SS")
1355 NewInt = ReadInt16();
1359 for (int i=1; i < nbInt; i++)
1362 NewInt = ReadInt16();
1367 // See above comment on multiple integers (mutatis mutandis).
1368 else if (vr == "UL" || vr == "SL")
1371 NewInt = ReadInt32();
1375 for (int i=1; i < nbInt; i++)
1378 NewInt = ReadInt32();
1383 #ifdef GDCM_NO_ANSI_STRING_STREAM
1384 s << std::ends; // to avoid oddities on Solaris
1385 #endif //GDCM_NO_ANSI_STRING_STREAM
1387 ((ValEntry *)entry)->SetValue(s.str());
1391 // FIXME: We need an additional byte for storing \0 that is not on disk
1392 char *str = new char[length+1];
1393 Fp->read(str, (size_t)length);
1394 str[length] = '\0'; //this is only useful when length is odd
1395 // Special DicomString call to properly handle \0 and even length
1396 std::string newValue;
1399 newValue = Util::DicomString(str, length+1);
1400 gdcmVerboseMacro("Warning: bad length: " << length <<
1401 ",For string :" << newValue.c_str());
1402 // Since we change the length of string update it length
1403 //entry->SetReadLength(length+1);
1407 newValue = Util::DicomString(str, length);
1411 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1413 if ( Fp->fail() || Fp->eof())
1415 gdcmVerboseMacro("Unread element value");
1416 valEntry->SetValue(GDCM_UNREAD);
1422 // Because of correspondance with the VR dic
1423 valEntry->SetValue(newValue);
1427 valEntry->SetValue(newValue);
1432 gdcmErrorMacro( "Should have a ValEntry, here !");
1438 * \brief Find the value Length of the passed Header Entry
1439 * @param entry Header Entry whose length of the value shall be loaded.
1441 void Document::FindDocEntryLength( DocEntry *entry )
1442 throw ( FormatError )
1444 std::string vr = entry->GetVR();
1447 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1449 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1451 // The following reserved two bytes (see PS 3.5-2003, section
1452 // "7.1.2 Data element structure with explicit vr", p 27) must be
1453 // skipped before proceeding on reading the length on 4 bytes.
1454 Fp->seekg( 2L, std::ios::cur);
1455 uint32_t length32 = ReadInt32();
1457 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1462 lengthOB = FindDocEntryLengthOBOrOW();
1464 catch ( FormatUnexpected )
1466 // Computing the length failed (this happens with broken
1467 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1468 // chance to get the pixels by deciding the element goes
1469 // until the end of the file. Hence we artificially fix the
1470 // the length and proceed.
1471 long currentPosition = Fp->tellg();
1472 Fp->seekg(0L,std::ios::end);
1474 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1475 Fp->seekg(currentPosition, std::ios::beg);
1477 entry->SetReadLength(lengthUntilEOF);
1478 entry->SetLength(lengthUntilEOF);
1481 entry->SetReadLength(lengthOB);
1482 entry->SetLength(lengthOB);
1485 FixDocEntryFoundLength(entry, length32);
1489 // Length is encoded on 2 bytes.
1490 length16 = ReadInt16();
1492 // FIXME : This heuristic supposes that the first group following
1493 // group 0002 *has* and element 0000.
1494 // BUT ... Element 0000 is optionnal :-(
1497 // Fixed using : HandleOutOfGroup0002()
1498 // (first hereafter strategy ...)
1500 // We can tell the current file is encoded in big endian (like
1501 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1502 // and it's value is the one of the encoding of a big endian file.
1503 // In order to deal with such big endian encoded files, we have
1504 // (at least) two strategies:
1505 // * when we load the "Transfer Syntax" tag with value of big endian
1506 // encoding, we raise the proper flags. Then we wait for the end
1507 // of the META group (0x0002) among which is "Transfer Syntax",
1508 // before switching the swap code to big endian. We have to postpone
1509 // the switching of the swap code since the META group is fully encoded
1510 // in little endian, and big endian coding only starts at the next
1511 // group. The corresponding code can be hard to analyse and adds
1512 // many additional unnecessary tests for regular tags.
1513 // * the second strategy consists in waiting for trouble, that shall
1514 // appear when we find the first group with big endian encoding. This
1515 // is easy to detect since the length of a "Group Length" tag (the
1516 // ones with zero as element number) has to be of 4 (0x0004). When we
1517 // encounter 1024 (0x0400) chances are the encoding changed and we
1518 // found a group with big endian encoding.
1519 //---> Unfortunately, element 0000 is optional.
1520 //---> This will not work when missing!
1521 // We shall use this second strategy. In order to make sure that we
1522 // can interpret the presence of an apparently big endian encoded
1523 // length of a "Group Length" without committing a big mistake, we
1524 // add an additional check: we look in the already parsed elements
1525 // for the presence of a "Transfer Syntax" whose value has to be "big
1526 // endian encoding". When this is the case, chances are we have got our
1527 // hands on a big endian encoded file: we switch the swap code to
1528 // big endian and proceed...
1530 // if ( element == 0x0000 && length16 == 0x0400 )
1532 // std::string ts = GetTransferSyntax();
1533 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1534 // != TS::ExplicitVRBigEndian )
1536 // throw FormatError( "Document::FindDocEntryLength()",
1537 // " not explicit VR." );
1541 // SwitchByteSwapCode();
1543 // // Restore the unproperly loaded values i.e. the group, the element
1544 // // and the dictionary entry depending on them.
1545 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1546 // uint16_t correctElem = SwapShort( entry->GetElement() );
1547 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1550 // // This correct tag is not in the dictionary. Create a new one.
1551 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1553 // // FIXME this can create a memory leaks on the old entry that be
1554 // // left unreferenced.
1555 // entry->SetDictEntry( newTag );
1558 // 0xffff means that we deal with 'No Length' Sequence
1559 // or 'No Length' SQItem
1560 if ( length16 == 0xffff)
1564 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1569 // Either implicit VR or a non DICOM conformal (see note below) explicit
1570 // VR that ommited the VR of (at least) this element. Farts happen.
1571 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1572 // on Data elements "Implicit and Explicit VR Data Elements shall
1573 // not coexist in a Data Set and Data Sets nested within it".]
1574 // Length is on 4 bytes.
1576 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1577 // even if Transfer Syntax is 'Implicit VR ...'
1579 FixDocEntryFoundLength( entry, ReadInt32() );
1585 * \brief Find the Value Representation of the current Dicom Element.
1586 * @return Value Representation of the current Entry
1588 std::string Document::FindDocEntryVR()
1590 if ( Filetype != ExplicitVR )
1591 return GDCM_UNKNOWN;
1593 long positionOnEntry = Fp->tellg();
1594 // Warning: we believe this is explicit VR (Value Representation) because
1595 // we used a heuristic that found "UL" in the first tag. Alas this
1596 // doesn't guarantee that all the tags will be in explicit VR. In some
1597 // cases (see e-film filtered files) one finds implicit VR tags mixed
1598 // within an explicit VR file. Hence we make sure the present tag
1599 // is in explicit VR and try to fix things if it happens not to be
1603 Fp->read (vr, (size_t)2);
1606 if( !CheckDocEntryVR(vr) )
1608 Fp->seekg(positionOnEntry, std::ios::beg);
1609 return GDCM_UNKNOWN;
1615 * \brief Check the correspondance between the VR of the header entry
1616 * and the taken VR. If they are different, the header entry is
1617 * updated with the new VR.
1618 * @param vr Dicom Value Representation
1619 * @return false if the VR is incorrect of if the VR isn't referenced
1620 * otherwise, it returns true
1622 bool Document::CheckDocEntryVR(VRKey vr)
1624 // CLEANME searching the dicom_vr at each occurence is expensive.
1625 // PostPone this test in an optional integrity check at the end
1626 // of parsing or only in debug mode.
1627 if ( !Global::GetVR()->IsValidVR(vr) )
1634 * \brief Get the transformed value of the header entry. The VR value
1635 * is used to define the transformation to operate on the value
1636 * \warning NOT end user intended method !
1637 * @param entry entry to tranform
1638 * @return Transformed entry value
1640 std::string Document::GetDocEntryValue(DocEntry *entry)
1642 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1644 std::string val = ((ValEntry *)entry)->GetValue();
1645 std::string vr = entry->GetVR();
1646 uint32_t length = entry->GetLength();
1647 std::ostringstream s;
1650 // When short integer(s) are expected, read and convert the following
1651 // n * 2 bytes properly i.e. as a multivaluated strings
1652 // (each single value is separated fromthe next one by '\'
1653 // as usual for standard multivaluated filels
1654 // Elements with Value Multiplicity > 1
1655 // contain a set of short integers (not a single one)
1657 if( vr == "US" || vr == "SS" )
1662 for (int i=0; i < nbInt; i++)
1668 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1669 newInt16 = SwapShort( newInt16 );
1674 // When integer(s) are expected, read and convert the following
1675 // n * 4 bytes properly i.e. as a multivaluated strings
1676 // (each single value is separated fromthe next one by '\'
1677 // as usual for standard multivaluated filels
1678 // Elements with Value Multiplicity > 1
1679 // contain a set of integers (not a single one)
1680 else if( vr == "UL" || vr == "SL" )
1685 for (int i=0; i < nbInt; i++)
1691 newInt32 = ( val[4*i+0] & 0xFF )
1692 + (( val[4*i+1] & 0xFF ) << 8 )
1693 + (( val[4*i+2] & 0xFF ) << 16 )
1694 + (( val[4*i+3] & 0xFF ) << 24 );
1695 newInt32 = SwapLong( newInt32 );
1699 #ifdef GDCM_NO_ANSI_STRING_STREAM
1700 s << std::ends; // to avoid oddities on Solaris
1701 #endif //GDCM_NO_ANSI_STRING_STREAM
1705 return ((ValEntry *)entry)->GetValue();
1709 * \brief Get the reverse transformed value of the header entry. The VR
1710 * value is used to define the reverse transformation to operate on
1712 * \warning NOT end user intended method !
1713 * @param entry Entry to reverse transform
1714 * @return Reverse transformed entry value
1716 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1718 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1720 std::string vr = entry->GetVR();
1721 std::vector<std::string> tokens;
1722 std::ostringstream s;
1724 if ( vr == "US" || vr == "SS" )
1728 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1729 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1730 for (unsigned int i=0; i<tokens.size(); i++)
1732 newInt16 = atoi(tokens[i].c_str());
1733 s << ( newInt16 & 0xFF )
1734 << (( newInt16 >> 8 ) & 0xFF );
1738 if ( vr == "UL" || vr == "SL")
1742 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1743 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1744 for (unsigned int i=0; i<tokens.size();i++)
1746 newInt32 = atoi(tokens[i].c_str());
1747 s << (char)( newInt32 & 0xFF )
1748 << (char)(( newInt32 >> 8 ) & 0xFF )
1749 << (char)(( newInt32 >> 16 ) & 0xFF )
1750 << (char)(( newInt32 >> 24 ) & 0xFF );
1755 #ifdef GDCM_NO_ANSI_STRING_STREAM
1756 s << std::ends; // to avoid oddities on Solaris
1757 #endif //GDCM_NO_ANSI_STRING_STREAM
1761 return ((ValEntry *)entry)->GetValue();
1765 * \brief Skip a given Header Entry
1766 * \warning NOT end user intended method !
1767 * @param entry entry to skip
1769 void Document::SkipDocEntry(DocEntry *entry)
1771 SkipBytes(entry->GetLength());
1775 * \brief Skips to the begining of the next Header Entry
1776 * \warning NOT end user intended method !
1777 * @param currentDocEntry entry to skip
1779 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1781 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1782 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1783 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1787 * \brief When the length of an element value is obviously wrong (because
1788 * the parser went Jabberwocky) one can hope improving things by
1789 * applying some heuristics.
1790 * @param entry entry to check
1791 * @param foundLength first assumption about length
1793 void Document::FixDocEntryFoundLength(DocEntry *entry,
1794 uint32_t foundLength)
1796 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1797 if ( foundLength == 0xffffffff)
1802 uint16_t gr = entry->GetGroup();
1803 uint16_t elem = entry->GetElement();
1805 if ( foundLength % 2)
1807 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1808 << " in x(" << std::hex << gr << "," << elem <<")");
1811 //////// Fix for some naughty General Electric images.
1812 // Allthough not recent many such GE corrupted images are still present
1813 // on Creatis hard disks. Hence this fix shall remain when such images
1814 // are no longer in use (we are talking a few years, here)...
1815 // Note: XMedCom probably uses such a trick since it is able to read
1816 // those pesky GE images ...
1817 if ( foundLength == 13)
1819 // Only happens for this length !
1820 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1823 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1827 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1828 // Occurence of such images is quite low (unless one leaves close to a
1829 // 'Leonardo' source. Hence, one might consider commenting out the
1830 // following fix on efficiency reasons.
1831 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1834 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1837 else if ( entry->GetVR() == "SQ" )
1839 foundLength = 0; // ReadLength is unchanged
1842 //////// We encountered a 'delimiter' element i.e. a tag of the form
1843 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1844 // taken into account.
1845 else if( gr == 0xfffe )
1847 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1848 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1849 // causes extra troubles...
1850 if( entry->GetElement() != 0x0000 )
1856 entry->SetLength(foundLength);
1860 * \brief Apply some heuristics to predict whether the considered
1861 * element value contains/represents an integer or not.
1862 * @param entry The element value on which to apply the predicate.
1863 * @return The result of the heuristical predicate.
1865 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1867 uint16_t elem = entry->GetElement();
1868 uint16_t group = entry->GetGroup();
1869 const std::string &vr = entry->GetVR();
1870 uint32_t length = entry->GetLength();
1872 // When we have some semantics on the element we just read, and if we
1873 // a priori know we are dealing with an integer, then we shall be
1874 // able to swap it's element value properly.
1875 if ( elem == 0 ) // This is the group length of the group
1883 // Allthough this should never happen, still some images have a
1884 // corrupted group length [e.g. have a glance at offset x(8336) of
1885 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1886 // Since for dicom compliant and well behaved headers, the present
1887 // test is useless (and might even look a bit paranoid), when we
1888 // encounter such an ill-formed image, we simply display a warning
1889 // message and proceed on parsing (while crossing fingers).
1890 long filePosition = Fp->tellg();
1891 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1892 << std::hex << group << " , " << elem
1893 << ") -before- position x(" << filePosition << ")"
1894 << "lgt : " << length );
1898 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1906 * \brief Find the Length till the next sequence delimiter
1907 * \warning NOT end user intended method !
1911 uint32_t Document::FindDocEntryLengthOBOrOW()
1912 throw( FormatUnexpected )
1914 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1915 long positionOnEntry = Fp->tellg();
1916 bool foundSequenceDelimiter = false;
1917 uint32_t totalLength = 0;
1919 while ( !foundSequenceDelimiter )
1925 group = ReadInt16();
1928 catch ( FormatError )
1930 throw FormatError("Unexpected end of file encountered during ",
1931 "Document::FindDocEntryLengthOBOrOW()");
1934 // We have to decount the group and element we just read
1937 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1939 long filePosition = Fp->tellg();
1940 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1941 << std::hex << group << " , " << elem
1942 << ") -before- position x(" << filePosition << ")" );
1944 Fp->seekg(positionOnEntry, std::ios::beg);
1945 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1948 if ( elem == 0xe0dd )
1950 foundSequenceDelimiter = true;
1953 uint32_t itemLength = ReadInt32();
1954 // We add 4 bytes since we just read the ItemLength with ReadInt32
1955 totalLength += itemLength + 4;
1956 SkipBytes(itemLength);
1958 if ( foundSequenceDelimiter )
1963 Fp->seekg( positionOnEntry, std::ios::beg);
1968 * \brief Reads a supposed to be 16 Bits integer
1969 * (swaps it depending on processor endianity)
1970 * @return read value
1972 uint16_t Document::ReadInt16()
1973 throw( FormatError )
1976 Fp->read ((char*)&g, (size_t)2);
1979 throw FormatError( "Document::ReadInt16()", " file error." );
1983 throw FormatError( "Document::ReadInt16()", "EOF." );
1990 * \brief Reads a supposed to be 32 Bits integer
1991 * (swaps it depending on processor endianity)
1992 * @return read value
1994 uint32_t Document::ReadInt32()
1995 throw( FormatError )
1998 Fp->read ((char*)&g, (size_t)4);
2001 throw FormatError( "Document::ReadInt32()", " file error." );
2005 throw FormatError( "Document::ReadInt32()", "EOF." );
2012 * \brief skips bytes inside the source file
2013 * \warning NOT end user intended method !
2016 void Document::SkipBytes(uint32_t nBytes)
2018 //FIXME don't dump the returned value
2019 Fp->seekg((long)nBytes, std::ios::cur);
2023 * \brief Loads all the needed Dictionaries
2024 * \warning NOT end user intended method !
2026 void Document::Initialize()
2028 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2030 RLEInfo = new RLEFramesInfo;
2031 JPEGInfo = new JPEGFragmentsInfo;
2036 * \brief Discover what the swap code is (among little endian, big endian,
2037 * bad little endian, bad big endian).
2039 * @return false when we are absolutely sure
2040 * it's neither ACR-NEMA nor DICOM
2041 * true when we hope ours assuptions are OK
2043 bool Document::CheckSwap()
2045 // The only guaranted way of finding the swap code is to find a
2046 // group tag since we know it's length has to be of four bytes i.e.
2047 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2048 // occurs when we can't find such group...
2050 uint32_t x = 4; // x : for ntohs
2051 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2057 // First, compare HostByteOrder and NetworkByteOrder in order to
2058 // determine if we shall need to swap bytes (i.e. the Endian type).
2059 if ( x == ntohs(x) )
2068 // The easiest case is the one of a 'true' DICOM header, we just have
2069 // to look for the string "DICM" inside the file preamble.
2072 char *entCur = deb + 128;
2073 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2075 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2077 // Group 0002 should always be VR, and the first element 0000
2078 // Let's be carefull (so many wrong headers ...)
2079 // and determine the value representation (VR) :
2080 // Let's skip to the first element (0002,0000) and check there if we find
2081 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2082 // in which case we (almost) know it is explicit VR.
2083 // WARNING: if it happens to be implicit VR then what we will read
2084 // is the length of the group. If this ascii representation of this
2085 // length happens to be "UL" then we shall believe it is explicit VR.
2086 // We need to skip :
2087 // * the 128 bytes of File Preamble (often padded with zeroes),
2088 // * the 4 bytes of "DICM" string,
2089 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2090 // i.e. a total of 136 bytes.
2093 // group 0x0002 *is always* Explicit VR Sometimes ,
2094 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2095 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2097 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2098 memcmp(entCur, "OB", (size_t)2) == 0 ||
2099 memcmp(entCur, "UI", (size_t)2) == 0 ||
2100 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2101 // when Write DCM *adds*
2103 // Use Document::dicom_vr to test all the possibilities
2104 // instead of just checking for UL, OB and UI !? group 0000
2106 Filetype = ExplicitVR;
2107 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2111 Filetype = ImplicitVR;
2112 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2113 << "Looks like a bugged Header!");
2119 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2124 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2127 // Position the file position indicator at first tag
2128 // (i.e. after the file preamble and the "DICM" string).
2129 Fp->seekg(0, std::ios::beg);
2130 Fp->seekg ( 132L, std::ios::beg);
2134 // Alas, this is not a DicomV3 file and whatever happens there is no file
2135 // preamble. We can reset the file position indicator to where the data
2136 // is (i.e. the beginning of the file).
2137 gdcmVerboseMacro( "Not a DICOM Version3 file");
2138 Fp->seekg(0, std::ios::beg);
2140 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2141 // By clean we mean that the length of the first tag is written down.
2142 // If this is the case and since the length of the first group HAS to be
2143 // four (bytes), then determining the proper swap code is straightforward.
2146 // We assume the array of char we are considering contains the binary
2147 // representation of a 32 bits integer. Hence the following dirty
2149 s32 = *((uint32_t *)(entCur));
2170 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2171 // It is time for despaired wild guesses.
2172 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2173 // i.e. the 'group length' element is not present :
2175 // check the supposed-to-be 'group number'
2176 // in ( 0x0001 .. 0x0008 )
2177 // to determine ' SwapCode' value .
2178 // Only 0 or 4321 will be possible
2179 // (no oportunity to check for the formerly well known
2180 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2181 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2182 // the file IS NOT ACR-NEMA nor DICOM V3
2183 // Find a trick to tell it the caller...
2185 s16 = *((uint16_t *)(deb));
2212 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2220 * \brief Change the Byte Swap code.
2222 void Document::SwitchByteSwapCode()
2224 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2225 if ( SwapCode == 1234 )
2229 else if ( SwapCode == 4321 )
2233 else if ( SwapCode == 3412 )
2237 else if ( SwapCode == 2143 )
2244 * \brief during parsing, Header Elements too long are not loaded in memory
2247 void Document::SetMaxSizeLoadEntry(long newSize)
2253 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2255 MaxSizeLoadEntry = 0xffffffff;
2258 MaxSizeLoadEntry = newSize;
2263 * \brief Header Elements too long will not be printed
2264 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2267 void Document::SetMaxSizePrintEntry(long newSize)
2273 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2275 MaxSizePrintEntry = 0xffffffff;
2278 MaxSizePrintEntry = newSize;
2284 * \brief Handle broken private tag from Philips NTSCAN
2285 * where the endianess is being switch to BigEndian for no
2289 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2291 // Endian reversion. Some files contain groups of tags with reversed endianess.
2292 static int reversedEndian = 0;
2293 // try to fix endian switching in the middle of headers
2294 if ((group == 0xfeff) && (elem == 0x00e0))
2296 // start endian swap mark for group found
2298 SwitchByteSwapCode();
2303 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2305 // end of reversed endian group
2307 SwitchByteSwapCode();
2312 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2313 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2315 std::string Document::GetTransferSyntaxName()
2317 // use the TS (TS : Transfer Syntax)
2318 std::string transferSyntax = GetEntry(0x0002,0x0010);
2320 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2322 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2323 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2324 return "Uncompressed ACR-NEMA";
2326 if ( transferSyntax == GDCM_UNFOUND )
2328 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2329 return "Uncompressed ACR-NEMA";
2332 // we do it only when we need it
2333 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2335 // Global::GetTS() is a global static you shall never try to delete it!
2340 * \brief Group 0002 is always coded Little Endian
2341 * whatever Transfer Syntax is
2344 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2346 // Endian reversion. Some files contain groups of tags with reversed endianess.
2347 if ( !Group0002Parsed && group != 0x0002)
2349 Group0002Parsed = true;
2350 // we just came out of group 0002
2351 // if Transfer syntax is Big Endian we have to change CheckSwap
2353 std::string ts = GetTransferSyntax();
2354 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2356 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2360 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2362 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2364 Filetype = ImplicitVR;
2367 // FIXME Strangely, this works with
2368 //'Implicit VR Transfer Syntax (GE Private)
2369 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2371 gdcmVerboseMacro("Transfer Syntax Name = ["
2372 << GetTransferSyntaxName() << "]" );
2373 SwitchByteSwapCode();
2374 group = SwapShort(group);
2375 elem = SwapShort(elem);
2381 * \brief Read the next tag but WITHOUT loading it's value
2382 * (read the 'Group Number', the 'Element Number',
2383 * gets the Dict Entry
2384 * gets the VR, gets the length, gets the offset value)
2385 * @return On succes the newly created DocEntry, NULL on failure.
2387 DocEntry *Document::ReadNextDocEntry()
2394 group = ReadInt16();
2397 catch ( FormatError e )
2399 // We reached the EOF (or an error occured) therefore
2400 // header parsing has to be considered as finished.
2405 // Sometimes file contains groups of tags with reversed endianess.
2406 HandleBrokenEndian(group, elem);
2408 // In 'true DICOM' files Group 0002 is always little endian
2409 if ( HasDCMPreamble )
2410 HandleOutOfGroup0002(group, elem);
2412 std::string vr = FindDocEntryVR();
2413 std::string realVR = vr;
2415 if( vr == GDCM_UNKNOWN)
2417 DictEntry *dictEntry = GetDictEntry(group,elem);
2419 realVR = dictEntry->GetVR();
2423 if( Global::GetVR()->IsVROfSequence(realVR) )
2424 newEntry = NewSeqEntry(group, elem);
2425 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2426 newEntry = NewValEntry(group, elem,vr);
2428 newEntry = NewBinEntry(group, elem,vr);
2430 if( vr == GDCM_UNKNOWN )
2432 if( Filetype == ExplicitVR )
2434 // We thought this was explicit VR, but we end up with an
2435 // implicit VR tag. Let's backtrack.
2436 if ( newEntry->GetGroup() != 0xfffe )
2439 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2440 newEntry->GetGroup(), newEntry->GetElement());
2441 gdcmVerboseMacro( msg.c_str() );
2444 newEntry->SetImplicitVR();
2449 FindDocEntryLength(newEntry);
2451 catch ( FormatError e )
2459 newEntry->SetOffset(Fp->tellg());
2464 //GenerateFreeTagKeyInGroup? What was it designed for ?!?
2466 * \brief Generate a free TagKey i.e. a TagKey that is not present
2467 * in the TagHt dictionary.
2468 * @param group The generated tag must belong to this group.
2469 * @return The element of tag with given group which is fee.
2471 //uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2473 // for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2475 // TagKey key = DictEntry::TranslateToKey(group, elem);
2476 // if (TagHT.count(key) == 0)
2481 // return UINT32_MAX;
2485 * \brief Assuming the internal file pointer \ref Document::Fp
2486 * is placed at the beginning of a tag check whether this
2487 * tag is (TestGroup, TestElement).
2488 * \warning On success the internal file pointer \ref Document::Fp
2489 * is modified to point after the tag.
2490 * On failure (i.e. when the tag wasn't the expected tag
2491 * (TestGroup, TestElement) the internal file pointer
2492 * \ref Document::Fp is restored to it's original position.
2493 * @param testGroup The expected group of the tag.
2494 * @param testElement The expected Element of the tag.
2495 * @return True on success, false otherwise.
2497 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2499 long positionOnEntry = Fp->tellg();
2500 long currentPosition = Fp->tellg(); // On debugging purposes
2502 //// Read the Item Tag group and element, and make
2503 // sure they are what we expected:
2504 uint16_t itemTagGroup;
2505 uint16_t itemTagElement;
2508 itemTagGroup = ReadInt16();
2509 itemTagElement = ReadInt16();
2511 catch ( FormatError e )
2513 //std::cerr << e << std::endl;
2516 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2518 gdcmVerboseMacro( "Wrong Item Tag found:"
2519 << " We should have found tag ("
2520 << std::hex << testGroup << "," << testElement << ")" << std::endl
2521 << " but instead we encountered tag ("
2522 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2523 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2525 Fp->seekg(positionOnEntry, std::ios::beg);
2533 * \brief Assuming the internal file pointer \ref Document::Fp
2534 * is placed at the beginning of a tag (TestGroup, TestElement),
2535 * read the length associated to the Tag.
2536 * \warning On success the internal file pointer \ref Document::Fp
2537 * is modified to point after the tag and it's length.
2538 * On failure (i.e. when the tag wasn't the expected tag
2539 * (TestGroup, TestElement) the internal file pointer
2540 * \ref Document::Fp is restored to it's original position.
2541 * @param testGroup The expected group of the tag.
2542 * @param testElement The expected Element of the tag.
2543 * @return On success returns the length associated to the tag. On failure
2546 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2549 if ( !ReadTag(testGroup, testElement) )
2554 //// Then read the associated Item Length
2555 long currentPosition = Fp->tellg();
2556 uint32_t itemLength = ReadInt32();
2558 gdcmVerboseMacro( "Basic Item Length is: "
2559 << itemLength << std::endl
2560 << " at address: " << std::hex << (unsigned int)currentPosition);
2566 * \brief When parsing the Pixel Data of an encapsulated file, read
2567 * the basic offset table (when present, and BTW dump it).
2569 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2571 //// Read the Basic Offset Table Item Tag length...
2572 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2574 // When present, read the basic offset table itself.
2575 // Notes: - since the presence of this basic offset table is optional
2576 // we can't rely on it for the implementation, and we will simply
2577 // trash it's content (when present).
2578 // - still, when present, we could add some further checks on the
2579 // lengths, but we won't bother with such fuses for the time being.
2580 if ( itemLength != 0 )
2582 char *basicOffsetTableItemValue = new char[itemLength + 1];
2583 Fp->read(basicOffsetTableItemValue, itemLength);
2586 for (unsigned int i=0; i < itemLength; i += 4 )
2588 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2590 gdcmVerboseMacro( "Read one length: " <<
2591 std::hex << individualLength );
2595 delete[] basicOffsetTableItemValue;
2600 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2601 * Compute the RLE extra information and store it in \ref RLEInfo
2602 * for later pixel retrieval usage.
2604 void Document::ComputeRLEInfo()
2606 std::string ts = GetTransferSyntax();
2607 if ( !Global::GetTS()->IsRLELossless(ts) )
2612 // Encoded pixel data: for the time being we are only concerned with
2613 // Jpeg or RLE Pixel data encodings.
2614 // As stated in PS 3.5-2003, section 8.2 p44:
2615 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2616 // value representation OB is used".
2617 // Hence we expect an OB value representation. Concerning OB VR,
2618 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2619 // "For the Value Representations OB and OW, the encoding shall meet the
2620 // following specifications depending on the Data element tag:"
2622 // - the first item in the sequence of items before the encoded pixel
2623 // data stream shall be basic offset table item. The basic offset table
2624 // item value, however, is not required to be present"
2626 ReadAndSkipEncapsulatedBasicOffsetTable();
2628 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2629 // Loop on the individual frame[s] and store the information
2630 // on the RLE fragments in a RLEFramesInfo.
2631 // Note: - when only a single frame is present, this is a
2633 // - when more than one frame are present, then we are in
2634 // the case of a multi-frame image.
2636 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2638 // Parse the RLE Header and store the corresponding RLE Segment
2639 // Offset Table information on fragments of this current Frame.
2640 // Note that the fragment pixels themselves are not loaded
2641 // (but just skipped).
2642 long frameOffset = Fp->tellg();
2644 uint32_t nbRleSegments = ReadInt32();
2645 if ( nbRleSegments > 16 )
2647 // There should be at most 15 segments (refer to RLEFrame class)
2648 gdcmVerboseMacro( "Too many segments.");
2651 uint32_t rleSegmentOffsetTable[16];
2652 for( int k = 1; k <= 15; k++ )
2654 rleSegmentOffsetTable[k] = ReadInt32();
2657 // Deduce from both the RLE Header and the frameLength the
2658 // fragment length, and again store this info in a
2660 long rleSegmentLength[15];
2661 // skipping (not reading) RLE Segments
2662 if ( nbRleSegments > 1)
2664 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2666 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2667 - rleSegmentOffsetTable[k];
2668 SkipBytes(rleSegmentLength[k]);
2672 rleSegmentLength[nbRleSegments] = frameLength
2673 - rleSegmentOffsetTable[nbRleSegments];
2674 SkipBytes(rleSegmentLength[nbRleSegments]);
2676 // Store the collected info
2677 RLEFrame *newFrameInfo = new RLEFrame;
2678 newFrameInfo->NumberFragments = nbRleSegments;
2679 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2681 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2682 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2684 RLEInfo->Frames.push_back( newFrameInfo );
2687 // Make sure that at the end of the item we encounter a 'Sequence
2689 if ( !ReadTag(0xfffe, 0xe0dd) )
2691 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2696 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2697 * Compute the jpeg extra information (fragment[s] offset[s] and
2698 * length) and store it[them] in \ref JPEGInfo for later pixel
2701 void Document::ComputeJPEGFragmentInfo()
2703 // If you need to, look for comments of ComputeRLEInfo().
2704 std::string ts = GetTransferSyntax();
2705 if ( ! Global::GetTS()->IsJPEG(ts) )
2710 ReadAndSkipEncapsulatedBasicOffsetTable();
2712 // Loop on the fragments[s] and store the parsed information in a
2714 long fragmentLength;
2715 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2717 long fragmentOffset = Fp->tellg();
2719 // Store the collected info
2720 JPEGFragment *newFragment = new JPEGFragment;
2721 newFragment->Offset = fragmentOffset;
2722 newFragment->Length = fragmentLength;
2723 JPEGInfo->Fragments.push_back( newFragment );
2725 SkipBytes( fragmentLength );
2728 // Make sure that at the end of the item we encounter a 'Sequence
2730 if ( !ReadTag(0xfffe, 0xe0dd) )
2732 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2737 * \brief Walk recursively the given \ref DocEntrySet, and feed
2738 * the given hash table (\ref TagDocEntryHT) with all the
2739 * \ref DocEntry (Dicom entries) encountered.
2740 * This method does the job for \ref BuildFlatHashTable.
2741 * @param builtHT Where to collect all the \ref DocEntry encountered
2742 * when recursively walking the given set.
2743 * @param set The structure to be traversed (recursively).
2745 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2748 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2750 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2751 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2752 i != currentHT.end();
2755 DocEntry *entry = i->second;
2756 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2758 const ListSQItem& items = seqEntry->GetSQItems();
2759 for( ListSQItem::const_iterator item = items.begin();
2760 item != items.end();
2763 BuildFlatHashTableRecurse( builtHT, *item );
2767 builtHT[entry->GetKey()] = entry;
2772 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2774 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2775 for (ListDocEntry::const_iterator i = currentList.begin();
2776 i != currentList.end();
2779 DocEntry *entry = *i;
2780 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2782 const ListSQItem& items = seqEntry->GetSQItems();
2783 for( ListSQItem::const_iterator item = items.begin();
2784 item != items.end();
2787 BuildFlatHashTableRecurse( builtHT, *item );
2791 builtHT[entry->GetKey()] = entry;
2798 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2801 * The structure used by a Document (through \ref ElementSet),
2802 * in order to hold the parsed entries of a Dicom header, is a recursive
2803 * one. This is due to the fact that the sequences (when present)
2804 * can be nested. Additionaly, the sequence items (represented in
2805 * gdcm as \ref SQItem) add an extra complexity to the data
2806 * structure. Hence, a gdcm user whishing to visit all the entries of
2807 * a Dicom header will need to dig in the gdcm internals (which
2808 * implies exposing all the internal data structures to the API).
2809 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2810 * recursively builds a temporary hash table, which holds all the
2811 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2813 * \warning Of course there is NO integrity constrain between the
2814 * returned \ref TagDocEntryHT and the \ref ElementSet used
2815 * to build it. Hence if the underlying \ref ElementSet is
2816 * altered, then it is the caller responsability to invoke
2817 * \ref BuildFlatHashTable again...
2818 * @return The flat std::map<> we juste build.
2820 /*TagDocEntryHT *Document::BuildFlatHashTable()
2822 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2823 BuildFlatHashTableRecurse( *FlatHT, this );
2830 * \brief Compares two documents, according to \ref DicomDir rules
2831 * \warning Does NOT work with ACR-NEMA files
2832 * \todo Find a trick to solve the pb (use RET fields ?)
2834 * @return true if 'smaller'
2836 bool Document::operator<(Document &document)
2839 std::string s1 = GetEntry(0x0010,0x0010);
2840 std::string s2 = document.GetEntry(0x0010,0x0010);
2852 s1 = GetEntry(0x0010,0x0020);
2853 s2 = document.GetEntry(0x0010,0x0020);
2864 // Study Instance UID
2865 s1 = GetEntry(0x0020,0x000d);
2866 s2 = document.GetEntry(0x0020,0x000d);
2877 // Serie Instance UID
2878 s1 = GetEntry(0x0020,0x000e);
2879 s2 = document.GetEntry(0x0020,0x000e);
2896 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2897 * @param filetype Type of the File to be written
2899 int Document::ComputeGroup0002Length( FileType filetype )
2904 int groupLength = 0;
2905 bool found0002 = false;
2907 // for each zero-level Tag in the DCM Header
2908 DocEntry *entry = GetFirstEntry();
2911 gr = entry->GetGroup();
2917 el = entry->GetElement();
2918 vr = entry->GetVR();
2920 if (filetype == ExplicitVR)
2922 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2924 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2927 groupLength += 2 + 2 + 4 + entry->GetLength();
2929 else if (found0002 )
2932 entry = GetNextEntry();
2937 } // end namespace gdcm
2939 //-----------------------------------------------------------------------------