1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/12 11:33:39 $
7 Version: $Revision: 1.182 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmException.h"
28 #include "gdcmDictSet.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
31 #include "gdcmDocEntrySet.h"
32 #include "gdcmSQItem.h"
38 #if defined(_MSC_VER) || defined(__BORLANDC__)
41 #include <netinet/in.h>
47 //-----------------------------------------------------------------------------
48 // Refer to Document::CheckSwap()
49 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
51 // Refer to Document::SetMaxSizeLoadEntry()
52 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
53 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
55 //-----------------------------------------------------------------------------
56 // Constructor / Destructor
60 * @param filename file to be opened for parsing
62 Document::Document( std::string const &filename ) : ElementSet(-1)
64 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
74 Group0002Parsed = false;
76 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
77 // Fp->seekg( 0, std::ios::beg);
79 Fp->seekg(0, std::ios::end);
80 long lgt = Fp->tellg();
82 Fp->seekg( 0, std::ios::beg);
84 long beg = Fp->tellg();
87 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
89 Fp->seekg( 0, std::ios::beg);
91 // Load 'non string' values
93 std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);
94 if( PhotometricInterpretation == "PALETTE COLOR " )
96 LoadEntryBinArea(0x0028,0x1200); // gray LUT
98 /// The tags refered by the three following lines used to be CORRECTLY
99 /// defined as having an US Value Representation in the public
100 /// dictionnary. BUT the semantics implied by the three following
101 /// lines state that the corresponding tag contents are in fact
102 /// the ones of a BinEntry.
103 /// In order to fix things "Quick and Dirty" the dictionnary was
104 /// altered on PURPOUS but now contains a WRONG value.
105 /// In order to fix things and restore the dictionary to its
106 /// correct value, one needs to decided of the semantics by deciding
107 /// wether the following tags are either:
108 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
109 /// also used as BinEntry, which requires the proper conversion,
110 /// - OW, and hence loaded as BinEntry, but afterwards also used
111 /// as ValEntry, which requires the proper conversion.
112 LoadEntryBinArea(0x0028,0x1201); // R LUT
113 LoadEntryBinArea(0x0028,0x1202); // G LUT
114 LoadEntryBinArea(0x0028,0x1203); // B LUT
116 // Segmented Red Palette Color LUT Data
117 LoadEntryBinArea(0x0028,0x1221);
118 // Segmented Green Palette Color LUT Data
119 LoadEntryBinArea(0x0028,0x1222);
120 // Segmented Blue Palette Color LUT Data
121 LoadEntryBinArea(0x0028,0x1223);
123 //FIXME later : how to use it?
124 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
128 // --------------------------------------------------------------
129 // Specific code to allow gdcm to read ACR-LibIDO formated images
130 // Note: ACR-LibIDO is an extension of the ACR standard that was
131 // used at CREATIS. For the time being (say a couple years)
132 // we keep this kludge to allow a smooth move to gdcm for
133 // CREATIS developpers (sorry folks).
135 // if recognition code tells us we deal with a LibIDO image
136 // we switch lineNumber and columnNumber
139 RecCode = GetEntry(0x0008, 0x0010); // recognition code
140 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
141 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
142 // with "little-endian strings"
144 Filetype = ACR_LIBIDO;
145 std::string rows = GetEntry(0x0028, 0x0010);
146 std::string columns = GetEntry(0x0028, 0x0011);
147 SetEntry(columns, 0x0028, 0x0010);
148 SetEntry(rows , 0x0028, 0x0011);
150 // ----------------- End of ACR-LibIDO kludge ------------------
154 * \brief This default constructor doesn't parse the file. You should
155 * then invoke \ref Document::SetFileName and then the parsing.
157 Document::Document() : ElementSet(-1)
161 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
164 Filetype = ExplicitVR;
165 Group0002Parsed = false;
169 * \brief Canonical destructor.
171 Document::~Document ()
180 //-----------------------------------------------------------------------------
184 * \brief Prints The Dict Entries of THE public Dicom Dictionary
187 void Document::PrintPubDict(std::ostream &os)
189 RefPubDict->SetPrintLevel(PrintLevel);
190 RefPubDict->Print(os);
194 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
197 void Document::PrintShaDict(std::ostream &os)
199 RefShaDict->SetPrintLevel(PrintLevel);
200 RefShaDict->Print(os);
203 //-----------------------------------------------------------------------------
206 * \brief Get the public dictionary used
208 Dict *Document::GetPubDict()
214 * \brief Get the shadow dictionary used
216 Dict *Document::GetShaDict()
222 * \brief Set the shadow dictionary used
223 * @param dict dictionary to use in shadow
225 bool Document::SetShaDict(Dict *dict)
232 * \brief Set the shadow dictionary used
233 * @param dictName name of the dictionary to use in shadow
235 bool Document::SetShaDict(DictKey const &dictName)
237 RefShaDict = Global::GetDicts()->GetDict(dictName);
242 * \brief This predicate, based on hopefully reasonable heuristics,
243 * decides whether or not the current Document was properly parsed
244 * and contains the mandatory information for being considered as
245 * a well formed and usable Dicom/Acr File.
246 * @return true when Document is the one of a reasonable Dicom/Acr file,
249 bool Document::IsReadable()
251 if( Filetype == Unknown)
253 gdcmVerboseMacro( "Wrong filetype");
259 gdcmVerboseMacro( "No tags in internal hash table.");
267 * \brief Accessor to the Transfer Syntax (when present) of the
268 * current document (it internally handles reading the
269 * value from disk when only parsing occured).
270 * @return The encountered Transfer Syntax of the current document.
272 std::string Document::GetTransferSyntax()
274 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
280 // The entry might be present but not loaded (parsing and loading
281 // happen at different stages): try loading and proceed with check...
282 LoadDocEntrySafe(entry);
283 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
285 std::string transfer = valEntry->GetValue();
286 // The actual transfer (as read from disk) might be padded. We
287 // first need to remove the potential padding. We can make the
288 // weak assumption that padding was not executed with digits...
289 if ( transfer.length() == 0 )
291 // for brain damaged headers
294 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
296 transfer.erase(transfer.length()-1, 1);
304 * \brief Predicate for dicom version 3 file.
305 * @return True when the file is a dicom version 3.
307 bool Document::IsDicomV3()
309 // Checking if Transfer Syntax exists is enough
310 // Anyway, it's to late check if the 'Preamble' was found ...
311 // And ... would it be a rich idea to check ?
312 // (some 'no Preamble' DICOM images exist !)
313 return GetDocEntry(0x0002, 0x0010) != NULL;
317 * \brief returns the File Type
318 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
319 * @return the FileType code
321 FileType Document::GetFileType()
327 * \brief Tries to open the file \ref Document::Filename and
328 * checks the preamble when existing.
329 * @return The FILE pointer on success.
331 std::ifstream *Document::OpenFile()
334 HasDCMPreamble = false;
335 if (Filename.length() == 0)
342 gdcmVerboseMacro( "File already open: " << Filename.c_str());
345 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
348 gdcmVerboseMacro( "Cannot open file: " << Filename.c_str());
355 Fp->read((char*)&zero, (size_t)2);
362 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
364 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
365 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
366 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
367 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
370 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
371 gdcmVerboseMacro( msg.c_str() );
376 Fp->seekg(126L, std::ios::cur);
378 Fp->read(dicm, (size_t)4);
384 if( memcmp(dicm, "DICM", 4) == 0 )
386 HasDCMPreamble = true;
391 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
397 * \brief closes the file
398 * @return TRUE if the close was successfull
400 bool Document::CloseFile()
409 return true; //FIXME how do we detect a non-close ifstream ?
413 * \brief Writes in a file all the Header Entries (Dicom Elements)
414 * @param fp file pointer on an already open file
415 * @param filetype Type of the File to be written
416 * (ACR-NEMA, ExplicitVR, ImplicitVR)
417 * \return Always true.
419 void Document::WriteContent(std::ofstream *fp, FileType filetype)
421 /// \todo move the following lines (and a lot of others, to be written)
422 /// to a future function CheckAndCorrectHeader
423 /// (necessary if user wants to write a DICOM V3 file
424 /// starting from an ACR-NEMA (V2) Header
426 if ( filetype == ImplicitVR || filetype == ExplicitVR )
428 // writing Dicom File Preamble
429 char filePreamble[128];
430 memset(filePreamble, 0, 128);
431 fp->write(filePreamble, 128);
432 fp->write("DICM", 4);
436 * \todo rewrite later, if really usefull
437 * - 'Group Length' element is optional in DICOM
438 * - but un-updated odd groups lengthes can causes pb
441 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
442 * UpdateGroupLength(false,filetype);
443 * if ( filetype == ACR)
444 * UpdateGroupLength(true,ACR);
447 ElementSet::WriteContent(fp, filetype); // This one is recursive
451 * \brief Modifies the value of a given Doc Entry (Dicom Element)
452 * when it exists. Create it with the given value when unexistant.
453 * @param value (string) Value to be set
454 * @param group Group number of the Entry
455 * @param elem Element number of the Entry
456 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
457 * \return pointer to the modified/created Header Entry (NULL when creation
460 ValEntry *Document::ReplaceOrCreate(std::string const &value,
465 ValEntry *valEntry = 0;
466 DocEntry *currentEntry = GetDocEntry( group, elem);
470 valEntry = dynamic_cast< ValEntry* >(currentEntry);
474 if( valEntry->GetVR()!=vr )
477 // if currentEntry doesn't correspond to the requested valEntry
480 if (!RemoveEntry(currentEntry))
482 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
489 // Create a new valEntry if necessary
492 valEntry = NewValEntry(group, elem, vr);
494 if ( !AddEntry(valEntry))
496 gdcmVerboseMacro("AddEntry failed although this is a creation.");
503 // Set the binEntry value
504 SetEntry(value, valEntry);
509 * \brief Modifies the value of a given Header Entry (Dicom Element)
510 * when it exists. Create it with the given value when unexistant.
511 * A copy of the binArea is made to be kept in the Document.
512 * @param binArea (binary) value to be set
513 * @param Group Group number of the Entry
514 * @param Elem Element number of the Entry
515 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
516 * \return pointer to the modified/created Header Entry (NULL when creation
519 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
525 BinEntry *binEntry = 0;
526 DocEntry *currentEntry = GetDocEntry( group, elem);
528 // Verify the currentEntry
531 binEntry = dynamic_cast< BinEntry* >(currentEntry);
535 if( binEntry->GetVR()!=vr )
538 // if currentEntry doesn't correspond to the requested valEntry
541 if (!RemoveEntry(currentEntry))
543 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
550 // Create a new binEntry if necessary
553 binEntry = NewBinEntry(group, elem, vr);
555 if ( !AddEntry(binEntry))
557 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
564 // Set the binEntry value
566 if (lgth>0 && binArea)
568 tmpArea = new uint8_t[lgth];
569 memcpy(tmpArea,binArea,lgth);
575 if (!SetEntry(tmpArea,lgth,binEntry))
587 * \brief Modifies the value of a given Header Entry (Dicom Element)
588 * when it exists. Create it when unexistant.
589 * @param Group Group number of the Entry
590 * @param Elem Element number of the Entry
591 * \return pointer to the modified/created SeqEntry (NULL when creation
594 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
596 SeqEntry *seqEntry = 0;
597 DocEntry *currentEntry = GetDocEntry( group, elem);
599 // Verify the currentEntry
602 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
606 if( seqEntry->GetVR()!="SQ" )
609 // if currentEntry doesn't correspond to the requested valEntry
612 if (!RemoveEntry(currentEntry))
614 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
621 // Create a new seqEntry if necessary
624 seqEntry = NewSeqEntry(group, elem);
626 if ( !AddEntry(seqEntry))
628 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
639 * \brief Set a new value if the invoked element exists
640 * Seems to be useless !!!
641 * @param value new element value
642 * @param group group number of the Entry
643 * @param elem element number of the Entry
646 bool Document::ReplaceIfExist(std::string const &value,
647 uint16_t group, uint16_t elem )
649 SetEntry(value, group, elem);
654 //-----------------------------------------------------------------------------
658 * \brief Checks if a given Dicom Element exists within the H table
659 * @param group Group number of the searched Dicom Element
660 * @param element Element number of the searched Dicom Element
661 * @return true is found
663 bool Document::CheckIfEntryExist(uint16_t group, uint16_t element )
665 const std::string &key = DictEntry::TranslateToKey(group, element );
666 return TagHT.count(key) != 0;
671 * \brief Searches within Header Entries (Dicom Elements) parsed with
672 * the public and private dictionaries
673 * for the element value representation of a given tag.
674 * @param group Group number of the searched tag.
675 * @param element Element number of the searched tag.
676 * @return Corresponding element value representation when it exists,
677 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
679 std::string Document::GetEntry(uint16_t group, uint16_t element)
681 TagKey key = DictEntry::TranslateToKey(group, element);
682 if ( !TagHT.count(key))
687 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
691 * \brief Searches within Header Entries (Dicom Elements) parsed with
692 * the public and private dictionaries
693 * for the element value representation of a given tag..
695 * Obtaining the VR (Value Representation) might be needed by caller
696 * to convert the string typed content to caller's native type
697 * (think of C++ vs Python). The VR is actually of a higher level
698 * of semantics than just the native C++ type.
699 * @param group Group number of the searched tag.
700 * @param element Element number of the searched tag.
701 * @return Corresponding element value representation when it exists,
702 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
704 std::string Document::GetEntryVR(uint16_t group, uint16_t element)
706 DocEntry *elem = GetDocEntry(group, element);
711 return elem->GetVR();
715 * \brief Searches within Header Entries (Dicom Elements) parsed with
716 * the public and private dictionaries
717 * for the value length of a given tag..
718 * @param group Group number of the searched tag.
719 * @param element Element number of the searched tag.
720 * @return Corresponding element length; -2 if not found
722 int Document::GetEntryLength(uint16_t group, uint16_t element)
724 DocEntry *elem = GetDocEntry(group, element);
727 return -2; //magic number
729 return elem->GetLength();
733 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
734 * through it's (group, element) and modifies it's content with
736 * @param content new value (string) to substitute with
737 * @param group group number of the Dicom Element to modify
738 * @param element element number of the Dicom Element to modify
740 bool Document::SetEntry(std::string const& content,
741 uint16_t group, uint16_t element)
743 ValEntry *entry = GetValEntry(group, element);
746 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
749 return SetEntry(content,entry);
753 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
754 * through it's (group, element) and modifies it's content with
756 * @param content new value (void* -> uint8_t*) to substitute with
757 * @param lgth new value length
758 * @param group group number of the Dicom Element to modify
759 * @param element element number of the Dicom Element to modify
761 bool Document::SetEntry(uint8_t*content, int lgth,
762 uint16_t group, uint16_t element)
764 BinEntry *entry = GetBinEntry(group, element);
767 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
771 return SetEntry(content,lgth,entry);
775 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
776 * and modifies it's content with the given value.
777 * @param content new value (string) to substitute with
778 * @param entry Entry to be modified
780 bool Document::SetEntry(std::string const &content,ValEntry *entry)
784 entry->SetValue(content);
791 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
792 * and modifies it's content with the given value.
793 * @param content new value (void* -> uint8_t*) to substitute with
794 * @param entry Entry to be modified
795 * @param lgth new value length
797 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
801 // Hope Binary field length is *never* wrong
802 /*if(lgth%2) // Non even length are padded with a space (020H).
805 //content = content + '\0'; // fing a trick to enlarge a binary field?
808 entry->SetBinArea(content);
809 entry->SetLength(lgth);
810 entry->SetValue(GDCM_BINLOADED);
817 * \brief Gets (from Header) a 'non string' element value
818 * (LoadElementValues has already be executed)
819 * @param group group number of the Entry
820 * @param elem element number of the Entry
821 * @return Pointer to the 'non string' area
823 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
825 DocEntry *entry = GetDocEntry(group, elem);
828 gdcmVerboseMacro( "No entry");
831 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
833 return binEntry->GetBinArea();
840 * \brief Loads (from disk) the element content
841 * when a string is not suitable
842 * @param group group number of the Entry
843 * @param elem element number of the Entry
845 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
847 // Search the corresponding DocEntry
848 DocEntry *docElement = GetDocEntry(group, elem);
852 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
856 LoadEntryBinArea(binElement);
860 * \brief Loads (from disk) the element content
861 * when a string is not suitable
862 * @param element Entry whose binArea is going to be loaded
864 void Document::LoadEntryBinArea(BinEntry *element)
866 if(element->GetBinArea())
873 size_t o =(size_t)element->GetOffset();
874 Fp->seekg(o, std::ios::beg);
876 size_t l = element->GetLength();
877 uint8_t *a = new uint8_t[l];
880 gdcmVerboseMacro( "Cannot allocate a");
884 /// \todo check the result
885 Fp->read((char*)a, l);
886 if( Fp->fail() || Fp->eof())
892 element->SetBinArea(a);
899 * \brief Sets a 'non string' value to a given Dicom Element
900 * @param area area containing the 'non string' value
901 * @param group Group number of the searched Dicom Element
902 * @param element Element number of the searched Dicom Element
905 /*bool Document::SetEntryBinArea(uint8_t *area,
906 uint16_t group, uint16_t element)
908 DocEntry *currentEntry = GetDocEntry(group, element);
914 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
916 binEntry->SetBinArea( area );
924 * \brief retrieves a Dicom Element (the first one) using (group, element)
925 * \warning (group, element) IS NOT an identifier inside the Dicom Header
926 * if you think it's NOT UNIQUE, check the count number
927 * and use iterators to retrieve ALL the Dicoms Elements within
928 * a given couple (group, element)
929 * @param group Group number of the searched Dicom Element
930 * @param element Element number of the searched Dicom Element
933 DocEntry *Document::GetDocEntry(uint16_t group, uint16_t element)
935 TagKey key = DictEntry::TranslateToKey(group, element);
936 if ( !TagHT.count(key))
940 return TagHT.find(key)->second;
944 * \brief Same as \ref Document::GetDocEntry except it only
945 * returns a result when the corresponding entry is of type
947 * @return When present, the corresponding ValEntry.
949 ValEntry *Document::GetValEntry(uint16_t group, uint16_t element)
951 DocEntry *currentEntry = GetDocEntry(group, element);
956 if ( ValEntry *entry = dynamic_cast<ValEntry*>(currentEntry) )
960 gdcmVerboseMacro( "Unfound ValEntry.");
966 * \brief Same as \ref Document::GetDocEntry except it only
967 * returns a result when the corresponding entry is of type
969 * @return When present, the corresponding BinEntry.
971 BinEntry *Document::GetBinEntry(uint16_t group, uint16_t element)
973 DocEntry *currentEntry = GetDocEntry(group, element);
978 if ( BinEntry *entry = dynamic_cast<BinEntry*>(currentEntry) )
982 gdcmVerboseMacro( "Unfound BinEntry.");
988 * \brief Loads the element while preserving the current
989 * underlying file position indicator as opposed to
990 * to LoadDocEntry that modifies it.
991 * @param entry Header Entry whose value shall be loaded.
994 void Document::LoadDocEntrySafe(DocEntry *entry)
998 long PositionOnEntry = Fp->tellg();
1000 Fp->seekg(PositionOnEntry, std::ios::beg);
1005 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1007 * @return The properly swaped 32 bits integer.
1009 uint32_t Document::SwapLong(uint32_t a)
1016 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1017 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1020 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1023 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1026 gdcmErrorMacro( "Unset swap code:" << SwapCode );
1033 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1035 * @return The properly unswaped 32 bits integer.
1037 uint32_t Document::UnswapLong(uint32_t a)
1043 * \brief Swaps the bytes so they agree with the processor order
1044 * @return The properly swaped 16 bits integer.
1046 uint16_t Document::SwapShort(uint16_t a)
1048 if ( SwapCode == 4321 || SwapCode == 2143 )
1050 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1056 * \brief Unswaps the bytes so they agree with the processor order
1057 * @return The properly unswaped 16 bits integer.
1059 uint16_t Document::UnswapShort(uint16_t a)
1061 return SwapShort(a);
1064 //-----------------------------------------------------------------------------
1068 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1069 * @return length of the parsed set.
1071 void Document::ParseDES(DocEntrySet *set, long offset,
1072 long l_max, bool delim_mode)
1074 DocEntry *newDocEntry = 0;
1075 ValEntry *newValEntry;
1076 BinEntry *newBinEntry;
1077 SeqEntry *newSeqEntry;
1083 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1089 newDocEntry = ReadNextDocEntry( );
1095 vr = newDocEntry->GetVR();
1096 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1097 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1098 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1100 if ( newValEntry || newBinEntry )
1104 if ( ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1106 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1107 gdcmVerboseMacro( "Neither Valentry, nor BinEntry."
1108 "Probably unknown VR.");
1111 //////////////////// BinEntry or UNKOWN VR:
1112 // When "this" is a Document the Key is simply of the
1113 // form ( group, elem )...
1114 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1117 newBinEntry->SetKey( newBinEntry->GetKey() );
1119 // but when "this" is a SQItem, we are inserting this new
1120 // valEntry in a sequence item, and the kay has the
1121 // generalized form (refer to \ref BaseTagKey):
1122 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1124 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1125 + newBinEntry->GetKey() );
1128 LoadDocEntry( newBinEntry );
1129 if( !set->AddEntry( newBinEntry ) )
1131 //Expect big troubles if here
1132 //delete newBinEntry;
1138 /////////////////////// ValEntry
1139 // When "set" is a Document, then we are at the top of the
1140 // hierarchy and the Key is simply of the form ( group, elem )...
1141 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1144 newValEntry->SetKey( newValEntry->GetKey() );
1146 // ...but when "set" is a SQItem, we are inserting this new
1147 // valEntry in a sequence item. Hence the key has the
1148 // generalized form (refer to \ref BaseTagKey):
1149 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1151 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1152 + newValEntry->GetKey() );
1155 LoadDocEntry( newValEntry );
1156 bool delimitor=newValEntry->IsItemDelimitor();
1157 if( !set->AddEntry( newValEntry ) )
1159 // If here expect big troubles
1160 //delete newValEntry; //otherwise mem leak
1170 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1178 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1179 && ( newDocEntry->GetElement() == 0x0010 ) )
1181 std::string ts = GetTransferSyntax();
1182 if ( Global::GetTS()->IsRLELossless(ts) )
1184 long positionOnEntry = Fp->tellg();
1185 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1187 Fp->seekg( positionOnEntry, std::ios::beg );
1189 else if ( Global::GetTS()->IsJPEG(ts) )
1191 long positionOnEntry = Fp->tellg();
1192 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1193 ComputeJPEGFragmentInfo();
1194 Fp->seekg( positionOnEntry, std::ios::beg );
1198 // Just to make sure we are at the beginning of next entry.
1199 SkipToNextDocEntry(newDocEntry);
1204 unsigned long l = newDocEntry->GetReadLength();
1205 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1207 if ( l == 0xffffffff )
1216 // no other way to create it ...
1217 newSeqEntry->SetDelimitorMode( delim_mode );
1219 // At the top of the hierarchy, stands a Document. When "set"
1220 // is a Document, then we are building the first depth level.
1221 // Hence the SeqEntry we are building simply has a depth
1223 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1226 newSeqEntry->SetDepthLevel( 1 );
1227 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1229 // But when "set" is allready a SQItem, we are building a nested
1230 // sequence, and hence the depth level of the new SeqEntry
1231 // we are building, is one level deeper:
1232 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1234 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1235 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1236 + newSeqEntry->GetKey() );
1240 { // Don't try to parse zero-length sequences
1241 ParseSQ( newSeqEntry,
1242 newDocEntry->GetOffset(),
1245 set->AddEntry( newSeqEntry );
1246 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1258 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1259 * @return parsed length for this level
1261 void Document::ParseSQ( SeqEntry *seqEntry,
1262 long offset, long l_max, bool delim_mode)
1264 int SQItemNumber = 0;
1269 DocEntry *newDocEntry = ReadNextDocEntry();
1272 // FIXME Should warn user
1277 if ( newDocEntry->IsSequenceDelimitor() )
1279 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1283 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1289 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1290 std::ostringstream newBase;
1291 newBase << seqEntry->GetKey()
1295 itemSQ->SetBaseTagKey( newBase.str() );
1296 unsigned int l = newDocEntry->GetReadLength();
1298 if ( l == 0xffffffff )
1307 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1310 seqEntry->AddEntry( itemSQ, SQItemNumber );
1312 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1320 * \brief Loads the element content if its length doesn't exceed
1321 * the value specified with Document::SetMaxSizeLoadEntry()
1322 * @param entry Header Entry (Dicom Element) to be dealt with
1324 void Document::LoadDocEntry(DocEntry *entry)
1326 uint16_t group = entry->GetGroup();
1327 std::string vr = entry->GetVR();
1328 uint32_t length = entry->GetLength();
1330 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1332 // A SeQuence "contains" a set of Elements.
1333 // (fffe e000) tells us an Element is beginning
1334 // (fffe e00d) tells us an Element just ended
1335 // (fffe e0dd) tells us the current SeQuence just ended
1336 if( group == 0xfffe )
1338 // NO more value field for SQ !
1342 // When the length is zero things are easy:
1345 ((ValEntry *)entry)->SetValue("");
1349 // The elements whose length is bigger than the specified upper bound
1350 // are not loaded. Instead we leave a short notice of the offset of
1351 // the element content and it's length.
1353 std::ostringstream s;
1354 if (length > MaxSizeLoadEntry)
1356 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1358 //s << "gdcm::NotLoaded (BinEntry)";
1359 s << GDCM_NOTLOADED;
1360 s << " Address:" << (long)entry->GetOffset();
1361 s << " Length:" << entry->GetLength();
1362 s << " x(" << std::hex << entry->GetLength() << ")";
1363 binEntryPtr->SetValue(s.str());
1365 // Be carefull : a BinEntry IS_A ValEntry ...
1366 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1368 // s << "gdcm::NotLoaded. (ValEntry)";
1369 s << GDCM_NOTLOADED;
1370 s << " Address:" << (long)entry->GetOffset();
1371 s << " Length:" << entry->GetLength();
1372 s << " x(" << std::hex << entry->GetLength() << ")";
1373 valEntryPtr->SetValue(s.str());
1378 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1379 << "nor a ValEntry ?! Should never print that !" );
1382 // to be sure we are at the end of the value ...
1383 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1388 // When we find a BinEntry not very much can be done :
1389 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1391 s << GDCM_BINLOADED;
1392 binEntryPtr->SetValue(s.str());
1393 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1397 /// \todo Any compacter code suggested (?)
1398 if ( IsDocEntryAnInteger(entry) )
1402 // When short integer(s) are expected, read and convert the following
1403 // n *two characters properly i.e. consider them as short integers as
1404 // opposed to strings.
1405 // Elements with Value Multiplicity > 1
1406 // contain a set of integers (not a single one)
1407 if (vr == "US" || vr == "SS")
1410 NewInt = ReadInt16();
1414 for (int i=1; i < nbInt; i++)
1417 NewInt = ReadInt16();
1422 // See above comment on multiple integers (mutatis mutandis).
1423 else if (vr == "UL" || vr == "SL")
1426 NewInt = ReadInt32();
1430 for (int i=1; i < nbInt; i++)
1433 NewInt = ReadInt32();
1438 #ifdef GDCM_NO_ANSI_STRING_STREAM
1439 s << std::ends; // to avoid oddities on Solaris
1440 #endif //GDCM_NO_ANSI_STRING_STREAM
1442 ((ValEntry *)entry)->SetValue(s.str());
1446 // FIXME: We need an additional byte for storing \0 that is not on disk
1447 char *str = new char[length+1];
1448 Fp->read(str, (size_t)length);
1449 str[length] = '\0'; //this is only useful when length is odd
1450 // Special DicomString call to properly handle \0 and even length
1451 std::string newValue;
1454 newValue = Util::DicomString(str, length+1);
1455 gdcmVerboseMacro("Warning: bad length: " << length <<
1456 ",For string :" << newValue.c_str());
1457 // Since we change the length of string update it length
1458 //entry->SetReadLength(length+1);
1462 newValue = Util::DicomString(str, length);
1466 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1468 if ( Fp->fail() || Fp->eof())
1470 gdcmVerboseMacro("Unread element value");
1471 valEntry->SetValue(GDCM_UNREAD);
1477 // Because of correspondance with the VR dic
1478 valEntry->SetValue(newValue);
1482 valEntry->SetValue(newValue);
1487 gdcmErrorMacro( "Should have a ValEntry, here !");
1493 * \brief Find the value Length of the passed Header Entry
1494 * @param entry Header Entry whose length of the value shall be loaded.
1496 void Document::FindDocEntryLength( DocEntry *entry )
1497 throw ( FormatError )
1499 uint16_t element = entry->GetElement();
1500 std::string vr = entry->GetVR();
1503 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1505 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1507 // The following reserved two bytes (see PS 3.5-2003, section
1508 // "7.1.2 Data element structure with explicit vr", p 27) must be
1509 // skipped before proceeding on reading the length on 4 bytes.
1510 Fp->seekg( 2L, std::ios::cur);
1511 uint32_t length32 = ReadInt32();
1513 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1518 lengthOB = FindDocEntryLengthOBOrOW();
1520 catch ( FormatUnexpected )
1522 // Computing the length failed (this happens with broken
1523 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1524 // chance to get the pixels by deciding the element goes
1525 // until the end of the file. Hence we artificially fix the
1526 // the length and proceed.
1527 long currentPosition = Fp->tellg();
1528 Fp->seekg(0L,std::ios::end);
1530 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1531 Fp->seekg(currentPosition, std::ios::beg);
1533 entry->SetReadLength(lengthUntilEOF);
1534 entry->SetLength(lengthUntilEOF);
1537 entry->SetReadLength(lengthOB);
1538 entry->SetLength(lengthOB);
1541 FixDocEntryFoundLength(entry, length32);
1545 // Length is encoded on 2 bytes.
1546 length16 = ReadInt16();
1548 // We can tell the current file is encoded in big endian (like
1549 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1550 // and it's value is the one of the encoding of a big endian file.
1551 // In order to deal with such big endian encoded files, we have
1552 // (at least) two strategies:
1553 // * when we load the "Transfer Syntax" tag with value of big endian
1554 // encoding, we raise the proper flags. Then we wait for the end
1555 // of the META group (0x0002) among which is "Transfer Syntax",
1556 // before switching the swap code to big endian. We have to postpone
1557 // the switching of the swap code since the META group is fully encoded
1558 // in little endian, and big endian coding only starts at the next
1559 // group. The corresponding code can be hard to analyse and adds
1560 // many additional unnecessary tests for regular tags.
1561 // * the second strategy consists in waiting for trouble, that shall
1562 // appear when we find the first group with big endian encoding. This
1563 // is easy to detect since the length of a "Group Length" tag (the
1564 // ones with zero as element number) has to be of 4 (0x0004). When we
1565 // encounter 1024 (0x0400) chances are the encoding changed and we
1566 // found a group with big endian encoding.
1567 // We shall use this second strategy. In order to make sure that we
1568 // can interpret the presence of an apparently big endian encoded
1569 // length of a "Group Length" without committing a big mistake, we
1570 // add an additional check: we look in the already parsed elements
1571 // for the presence of a "Transfer Syntax" whose value has to be "big
1572 // endian encoding". When this is the case, chances are we have got our
1573 // hands on a big endian encoded file: we switch the swap code to
1574 // big endian and proceed...
1575 if ( element == 0x0000 && length16 == 0x0400 )
1577 std::string ts = GetTransferSyntax();
1578 if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1579 != TS::ExplicitVRBigEndian )
1581 throw FormatError( "Document::FindDocEntryLength()",
1582 " not explicit VR." );
1586 SwitchByteSwapCode();
1588 // Restore the unproperly loaded values i.e. the group, the element
1589 // and the dictionary entry depending on them.
1590 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1591 uint16_t correctElem = SwapShort( entry->GetElement() );
1592 DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1595 // This correct tag is not in the dictionary. Create a new one.
1596 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1598 // FIXME this can create a memory leaks on the old entry that be
1599 // left unreferenced.
1600 entry->SetDictEntry( newTag );
1603 // Heuristic: well, some files are really ill-formed.
1604 if ( length16 == 0xffff)
1606 // 0xffff means that we deal with 'Unknown Length' Sequence
1609 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1614 // Either implicit VR or a non DICOM conformal (see note below) explicit
1615 // VR that ommited the VR of (at least) this element. Farts happen.
1616 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1617 // on Data elements "Implicit and Explicit VR Data Elements shall
1618 // not coexist in a Data Set and Data Sets nested within it".]
1619 // Length is on 4 bytes.
1621 FixDocEntryFoundLength( entry, ReadInt32() );
1627 * \brief Find the Value Representation of the current Dicom Element.
1628 * @return Value Representation of the current Entry
1630 std::string Document::FindDocEntryVR()
1632 if ( Filetype != ExplicitVR )
1633 return GDCM_UNKNOWN;
1635 long positionOnEntry = Fp->tellg();
1636 // Warning: we believe this is explicit VR (Value Representation) because
1637 // we used a heuristic that found "UL" in the first tag. Alas this
1638 // doesn't guarantee that all the tags will be in explicit VR. In some
1639 // cases (see e-film filtered files) one finds implicit VR tags mixed
1640 // within an explicit VR file. Hence we make sure the present tag
1641 // is in explicit VR and try to fix things if it happens not to be
1645 Fp->read (vr, (size_t)2);
1648 if( !CheckDocEntryVR(vr) )
1650 Fp->seekg(positionOnEntry, std::ios::beg);
1651 return GDCM_UNKNOWN;
1657 * \brief Check the correspondance between the VR of the header entry
1658 * and the taken VR. If they are different, the header entry is
1659 * updated with the new VR.
1660 * @param vr Dicom Value Representation
1661 * @return false if the VR is incorrect of if the VR isn't referenced
1662 * otherwise, it returns true
1664 bool Document::CheckDocEntryVR(VRKey vr)
1666 // CLEANME searching the dicom_vr at each occurence is expensive.
1667 // PostPone this test in an optional integrity check at the end
1668 // of parsing or only in debug mode.
1669 if ( !Global::GetVR()->IsValidVR(vr) )
1676 * \brief Get the transformed value of the header entry. The VR value
1677 * is used to define the transformation to operate on the value
1678 * \warning NOT end user intended method !
1679 * @param entry entry to tranform
1680 * @return Transformed entry value
1682 std::string Document::GetDocEntryValue(DocEntry *entry)
1684 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1686 std::string val = ((ValEntry *)entry)->GetValue();
1687 std::string vr = entry->GetVR();
1688 uint32_t length = entry->GetLength();
1689 std::ostringstream s;
1692 // When short integer(s) are expected, read and convert the following
1693 // n * 2 bytes properly i.e. as a multivaluated strings
1694 // (each single value is separated fromthe next one by '\'
1695 // as usual for standard multivaluated filels
1696 // Elements with Value Multiplicity > 1
1697 // contain a set of short integers (not a single one)
1699 if( vr == "US" || vr == "SS" )
1704 for (int i=0; i < nbInt; i++)
1710 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1711 newInt16 = SwapShort( newInt16 );
1716 // When integer(s) are expected, read and convert the following
1717 // n * 4 bytes properly i.e. as a multivaluated strings
1718 // (each single value is separated fromthe next one by '\'
1719 // as usual for standard multivaluated filels
1720 // Elements with Value Multiplicity > 1
1721 // contain a set of integers (not a single one)
1722 else if( vr == "UL" || vr == "SL" )
1727 for (int i=0; i < nbInt; i++)
1733 newInt32 = ( val[4*i+0] & 0xFF )
1734 + (( val[4*i+1] & 0xFF ) << 8 )
1735 + (( val[4*i+2] & 0xFF ) << 16 )
1736 + (( val[4*i+3] & 0xFF ) << 24 );
1737 newInt32 = SwapLong( newInt32 );
1741 #ifdef GDCM_NO_ANSI_STRING_STREAM
1742 s << std::ends; // to avoid oddities on Solaris
1743 #endif //GDCM_NO_ANSI_STRING_STREAM
1747 return ((ValEntry *)entry)->GetValue();
1751 * \brief Get the reverse transformed value of the header entry. The VR
1752 * value is used to define the reverse transformation to operate on
1754 * \warning NOT end user intended method !
1755 * @param entry Entry to reverse transform
1756 * @return Reverse transformed entry value
1758 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1760 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1762 std::string vr = entry->GetVR();
1763 std::vector<std::string> tokens;
1764 std::ostringstream s;
1766 if ( vr == "US" || vr == "SS" )
1770 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1771 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1772 for (unsigned int i=0; i<tokens.size(); i++)
1774 newInt16 = atoi(tokens[i].c_str());
1775 s << ( newInt16 & 0xFF )
1776 << (( newInt16 >> 8 ) & 0xFF );
1780 if ( vr == "UL" || vr == "SL")
1784 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1785 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1786 for (unsigned int i=0; i<tokens.size();i++)
1788 newInt32 = atoi(tokens[i].c_str());
1789 s << (char)( newInt32 & 0xFF )
1790 << (char)(( newInt32 >> 8 ) & 0xFF )
1791 << (char)(( newInt32 >> 16 ) & 0xFF )
1792 << (char)(( newInt32 >> 24 ) & 0xFF );
1797 #ifdef GDCM_NO_ANSI_STRING_STREAM
1798 s << std::ends; // to avoid oddities on Solaris
1799 #endif //GDCM_NO_ANSI_STRING_STREAM
1803 return ((ValEntry *)entry)->GetValue();
1807 * \brief Skip a given Header Entry
1808 * \warning NOT end user intended method !
1809 * @param entry entry to skip
1811 void Document::SkipDocEntry(DocEntry *entry)
1813 SkipBytes(entry->GetLength());
1817 * \brief Skips to the begining of the next Header Entry
1818 * \warning NOT end user intended method !
1819 * @param currentDocEntry entry to skip
1821 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1823 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1824 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1828 * \brief When the length of an element value is obviously wrong (because
1829 * the parser went Jabberwocky) one can hope improving things by
1830 * applying some heuristics.
1831 * @param entry entry to check
1832 * @param foundLength first assumption about length
1834 void Document::FixDocEntryFoundLength(DocEntry *entry,
1835 uint32_t foundLength)
1837 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1838 if ( foundLength == 0xffffffff)
1843 uint16_t gr = entry->GetGroup();
1844 uint16_t elem = entry->GetElement();
1846 if ( foundLength % 2)
1848 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1849 << " in x(" << std::hex << gr << "," << elem <<")");
1852 //////// Fix for some naughty General Electric images.
1853 // Allthough not recent many such GE corrupted images are still present
1854 // on Creatis hard disks. Hence this fix shall remain when such images
1855 // are no longer in use (we are talking a few years, here)...
1856 // Note: XMedCom probably uses such a trick since it is able to read
1857 // those pesky GE images ...
1858 if ( foundLength == 13)
1860 // Only happens for this length !
1861 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1864 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1868 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1869 // Occurence of such images is quite low (unless one leaves close to a
1870 // 'Leonardo' source. Hence, one might consider commenting out the
1871 // following fix on efficiency reasons.
1872 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1875 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1878 else if ( entry->GetVR() == "SQ" )
1880 foundLength = 0; // ReadLength is unchanged
1883 //////// We encountered a 'delimiter' element i.e. a tag of the form
1884 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1885 // taken into account.
1886 else if( gr == 0xfffe )
1888 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1889 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1890 // causes extra troubles...
1891 if( entry->GetElement() != 0x0000 )
1897 entry->SetLength(foundLength);
1901 * \brief Apply some heuristics to predict whether the considered
1902 * element value contains/represents an integer or not.
1903 * @param entry The element value on which to apply the predicate.
1904 * @return The result of the heuristical predicate.
1906 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1908 uint16_t elem = entry->GetElement();
1909 uint16_t group = entry->GetGroup();
1910 const std::string &vr = entry->GetVR();
1911 uint32_t length = entry->GetLength();
1913 // When we have some semantics on the element we just read, and if we
1914 // a priori know we are dealing with an integer, then we shall be
1915 // able to swap it's element value properly.
1916 if ( elem == 0 ) // This is the group length of the group
1924 // Allthough this should never happen, still some images have a
1925 // corrupted group length [e.g. have a glance at offset x(8336) of
1926 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1927 // Since for dicom compliant and well behaved headers, the present
1928 // test is useless (and might even look a bit paranoid), when we
1929 // encounter such an ill-formed image, we simply display a warning
1930 // message and proceed on parsing (while crossing fingers).
1931 long filePosition = Fp->tellg();
1932 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1933 << std::hex << group << " , " << elem
1934 << ") -before- position x(" << filePosition << ")"
1935 << "lgt : " << length );
1939 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1947 * \brief Find the Length till the next sequence delimiter
1948 * \warning NOT end user intended method !
1952 uint32_t Document::FindDocEntryLengthOBOrOW()
1953 throw( FormatUnexpected )
1955 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1956 long positionOnEntry = Fp->tellg();
1957 bool foundSequenceDelimiter = false;
1958 uint32_t totalLength = 0;
1960 while ( !foundSequenceDelimiter )
1966 group = ReadInt16();
1969 catch ( FormatError )
1971 throw FormatError("Unexpected end of file encountered during ",
1972 "Document::FindDocEntryLengthOBOrOW()");
1975 // We have to decount the group and element we just read
1978 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1980 long filePosition = Fp->tellg();
1981 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1982 << std::hex << group << " , " << elem
1983 << ") -before- position x(" << filePosition << ")" );
1985 Fp->seekg(positionOnEntry, std::ios::beg);
1986 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1989 if ( elem == 0xe0dd )
1991 foundSequenceDelimiter = true;
1994 uint32_t itemLength = ReadInt32();
1995 // We add 4 bytes since we just read the ItemLength with ReadInt32
1996 totalLength += itemLength + 4;
1997 SkipBytes(itemLength);
1999 if ( foundSequenceDelimiter )
2004 Fp->seekg( positionOnEntry, std::ios::beg);
2009 * \brief Reads a supposed to be 16 Bits integer
2010 * (swaps it depending on processor endianity)
2011 * @return read value
2013 uint16_t Document::ReadInt16()
2014 throw( FormatError )
2017 Fp->read ((char*)&g, (size_t)2);
2020 throw FormatError( "Document::ReadInt16()", " file error." );
2024 throw FormatError( "Document::ReadInt16()", "EOF." );
2031 * \brief Reads a supposed to be 32 Bits integer
2032 * (swaps it depending on processor endianity)
2033 * @return read value
2035 uint32_t Document::ReadInt32()
2036 throw( FormatError )
2039 Fp->read ((char*)&g, (size_t)4);
2042 throw FormatError( "Document::ReadInt32()", " file error." );
2046 throw FormatError( "Document::ReadInt32()", "EOF." );
2053 * \brief skips bytes inside the source file
2054 * \warning NOT end user intended method !
2057 void Document::SkipBytes(uint32_t nBytes)
2059 //FIXME don't dump the returned value
2060 Fp->seekg((long)nBytes, std::ios::cur);
2064 * \brief Loads all the needed Dictionaries
2065 * \warning NOT end user intended method !
2067 void Document::Initialise()
2069 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2071 RLEInfo = new RLEFramesInfo;
2072 JPEGInfo = new JPEGFragmentsInfo;
2077 * \brief Discover what the swap code is (among little endian, big endian,
2078 * bad little endian, bad big endian).
2080 * @return false when we are absolutely sure
2081 * it's neither ACR-NEMA nor DICOM
2082 * true when we hope ours assuptions are OK
2084 bool Document::CheckSwap()
2086 // The only guaranted way of finding the swap code is to find a
2087 // group tag since we know it's length has to be of four bytes i.e.
2088 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2089 // occurs when we can't find such group...
2091 uint32_t x = 4; // x : for ntohs
2092 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2098 // First, compare HostByteOrder and NetworkByteOrder in order to
2099 // determine if we shall need to swap bytes (i.e. the Endian type).
2100 if ( x == ntohs(x) )
2109 // The easiest case is the one of a DICOM header, since it possesses a
2110 // file preamble where it suffice to look for the string "DICM".
2113 char *entCur = deb + 128;
2114 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2116 gdcmVerboseMacro( "Looks like DICOM Version3" );
2118 // Next, determine the value representation (VR). Let's skip to the
2119 // first element (0002, 0000) and check there if we find "UL"
2120 // - or "OB" if the 1st one is (0002,0001) -,
2121 // in which case we (almost) know it is explicit VR.
2122 // WARNING: if it happens to be implicit VR then what we will read
2123 // is the length of the group. If this ascii representation of this
2124 // length happens to be "UL" then we shall believe it is explicit VR.
2125 // FIXME: in order to fix the above warning, we could read the next
2126 // element value (or a couple of elements values) in order to make
2127 // sure we are not commiting a big mistake.
2128 // We need to skip :
2129 // * the 128 bytes of File Preamble (often padded with zeroes),
2130 // * the 4 bytes of "DICM" string,
2131 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2132 // i.e. a total of 136 bytes.
2136 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2137 // but elem 0002,0010 (Transfer Syntax) tells us the file is
2138 // *Implicit* VR. -and it is !-
2140 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2141 memcmp(entCur, "OB", (size_t)2) == 0 ||
2142 memcmp(entCur, "UI", (size_t)2) == 0 ||
2143 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2144 // when Write DCM *adds*
2146 // Use Document::dicom_vr to test all the possibilities
2147 // instead of just checking for UL, OB and UI !? group 0000
2149 Filetype = ExplicitVR;
2150 gdcmVerboseMacro( "Explicit Value Representation");
2154 Filetype = ImplicitVR;
2155 gdcmVerboseMacro( "Not an explicit Value Representation");
2161 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2166 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2169 // Position the file position indicator at first tag (i.e.
2170 // after the file preamble and the "DICM" string).
2171 Fp->seekg(0, std::ios::beg);
2172 Fp->seekg ( 132L, std::ios::beg);
2176 // Alas, this is not a DicomV3 file and whatever happens there is no file
2177 // preamble. We can reset the file position indicator to where the data
2178 // is (i.e. the beginning of the file).
2179 gdcmVerboseMacro( "Not a DICOM Version3 file");
2180 Fp->seekg(0, std::ios::beg);
2182 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2183 // By clean we mean that the length of the first tag is written down.
2184 // If this is the case and since the length of the first group HAS to be
2185 // four (bytes), then determining the proper swap code is straightforward.
2188 // We assume the array of char we are considering contains the binary
2189 // representation of a 32 bits integer. Hence the following dirty
2191 s32 = *((uint32_t *)(entCur));
2212 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2213 // It is time for despaired wild guesses.
2214 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2215 // i.e. the 'group length' element is not present :
2217 // check the supposed-to-be 'group number'
2218 // in ( 0x0001 .. 0x0008 )
2219 // to determine ' SwapCode' value .
2220 // Only 0 or 4321 will be possible
2221 // (no oportunity to check for the formerly well known
2222 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2223 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2224 // the file IS NOT ACR-NEMA nor DICOM V3
2225 // Find a trick to tell it the caller...
2227 s16 = *((uint16_t *)(deb));
2254 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2264 * \brief Change the Byte Swap code.
2266 void Document::SwitchByteSwapCode()
2268 gdcmVerboseMacro( "Switching Byte Swap code.");
2269 if ( SwapCode == 1234 )
2273 else if ( SwapCode == 4321 )
2277 else if ( SwapCode == 3412 )
2281 else if ( SwapCode == 2143 )
2288 * \brief during parsing, Header Elements too long are not loaded in memory
2291 void Document::SetMaxSizeLoadEntry(long newSize)
2297 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2299 MaxSizeLoadEntry = 0xffffffff;
2302 MaxSizeLoadEntry = newSize;
2307 * \brief Header Elements too long will not be printed
2308 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2311 void Document::SetMaxSizePrintEntry(long newSize)
2313 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2318 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2320 MaxSizePrintEntry = 0xffffffff;
2323 MaxSizePrintEntry = newSize;
2329 * \brief Handle broken private tag from Philips NTSCAN
2330 * where the endianess is being switch to BigEndian for no
2334 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2336 // Endian reversion. Some files contain groups of tags with reversed endianess.
2337 static int reversedEndian = 0;
2338 // try to fix endian switching in the middle of headers
2339 if ((group == 0xfeff) && (elem == 0x00e0))
2341 // start endian swap mark for group found
2343 SwitchByteSwapCode();
2348 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2350 // end of reversed endian group
2352 SwitchByteSwapCode();
2357 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2359 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2361 std::string Document::GetTransferSyntaxName()
2363 // use the TS (TS : Transfer Syntax)
2364 std::string transferSyntax = GetEntry(0x0002,0x0010);
2366 if ( transferSyntax == GDCM_NOTLOADED )
2368 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2369 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2370 return "Uncompressed ACR-NEMA";
2372 if ( transferSyntax == GDCM_UNFOUND )
2374 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2375 return "Uncompressed ACR-NEMA";
2378 // we do it only when we need it
2379 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2381 // Global::GetTS() is a global static you shall never try to delete it!
2386 * \brief Group 0002 is always coded Little Endian
2387 * whatever Transfer Syntax is
2390 void Document::HandleOutOfGroup0002(uint16_t group)
2392 // Endian reversion. Some files contain groups of tags with reversed endianess.
2393 if ( !Group0002Parsed && group != 0x0002)
2395 Group0002Parsed = true;
2396 // we just came out of group 0002
2397 // if Transfer syntax is Big Endian we have to change CheckSwap
2399 std::string ts = GetTransferSyntaxName();
2400 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2402 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2406 // FIXME Strangely, this works with
2407 //'Implicit VR Transfer Syntax (GE Private)
2408 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2410 gdcmVerboseMacro("Tansfer Syntax = Explicit VR - Big Endian");
2411 SwitchByteSwapCode();
2417 * \brief Read the next tag but WITHOUT loading it's value
2418 * (read the 'Group Number', the 'Element Number',
2419 * gets the Dict Entry
2420 * gets the VR, gets the length, gets the offset value)
2421 * @return On succes the newly created DocEntry, NULL on failure.
2423 DocEntry *Document::ReadNextDocEntry()
2430 group = ReadInt16();
2433 catch ( FormatError e )
2435 // We reached the EOF (or an error occured) therefore
2436 // header parsing has to be considered as finished.
2441 // Sometimes file contains groups of tags with reversed endianess.
2442 HandleBrokenEndian(group, elem);
2444 // In 'true DICOM' files Group 0002 is allways little endian
2445 if ( HasDCMPreamble )
2446 HandleOutOfGroup0002(group);
2448 std::string vr = FindDocEntryVR();
2449 std::string realVR = vr;
2451 if( vr == GDCM_UNKNOWN)
2453 DictEntry *dictEntry = GetDictEntry(group,elem);
2455 realVR = dictEntry->GetVR();
2459 if( Global::GetVR()->IsVROfSequence(realVR) )
2460 newEntry = NewSeqEntry(group, elem);
2461 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2462 newEntry = NewValEntry(group, elem,vr);
2464 newEntry = NewBinEntry(group, elem,vr);
2466 if( vr == GDCM_UNKNOWN )
2468 if( Filetype == ExplicitVR )
2470 // We thought this was explicit VR, but we end up with an
2471 // implicit VR tag. Let's backtrack.
2473 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
2474 newEntry->GetGroup(), newEntry->GetElement());
2475 gdcmVerboseMacro( msg.c_str() );
2477 newEntry->SetImplicitVR();
2482 FindDocEntryLength(newEntry);
2484 catch ( FormatError e )
2492 newEntry->SetOffset(Fp->tellg());
2499 * \brief Generate a free TagKey i.e. a TagKey that is not present
2500 * in the TagHt dictionary.
2501 * @param group The generated tag must belong to this group.
2502 * @return The element of tag with given group which is fee.
2504 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2506 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2508 TagKey key = DictEntry::TranslateToKey(group, elem);
2509 if (TagHT.count(key) == 0)
2518 * \brief Assuming the internal file pointer \ref Document::Fp
2519 * is placed at the beginning of a tag check whether this
2520 * tag is (TestGroup, TestElement).
2521 * \warning On success the internal file pointer \ref Document::Fp
2522 * is modified to point after the tag.
2523 * On failure (i.e. when the tag wasn't the expected tag
2524 * (TestGroup, TestElement) the internal file pointer
2525 * \ref Document::Fp is restored to it's original position.
2526 * @param testGroup The expected group of the tag.
2527 * @param testElement The expected Element of the tag.
2528 * @return True on success, false otherwise.
2530 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2532 long positionOnEntry = Fp->tellg();
2533 long currentPosition = Fp->tellg(); // On debugging purposes
2535 //// Read the Item Tag group and element, and make
2536 // sure they are what we expected:
2537 uint16_t itemTagGroup;
2538 uint16_t itemTagElement;
2541 itemTagGroup = ReadInt16();
2542 itemTagElement = ReadInt16();
2544 catch ( FormatError e )
2546 //std::cerr << e << std::endl;
2549 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2551 gdcmVerboseMacro( "Wrong Item Tag found:"
2552 << " We should have found tag ("
2553 << std::hex << testGroup << "," << testElement << ")" << std::endl
2554 << " but instead we encountered tag ("
2555 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2556 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2558 Fp->seekg(positionOnEntry, std::ios::beg);
2566 * \brief Assuming the internal file pointer \ref Document::Fp
2567 * is placed at the beginning of a tag (TestGroup, TestElement),
2568 * read the length associated to the Tag.
2569 * \warning On success the internal file pointer \ref Document::Fp
2570 * is modified to point after the tag and it's length.
2571 * On failure (i.e. when the tag wasn't the expected tag
2572 * (TestGroup, TestElement) the internal file pointer
2573 * \ref Document::Fp is restored to it's original position.
2574 * @param testGroup The expected group of the tag.
2575 * @param testElement The expected Element of the tag.
2576 * @return On success returns the length associated to the tag. On failure
2579 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2581 long positionOnEntry = Fp->tellg();
2582 (void)positionOnEntry;
2584 if ( !ReadTag(testGroup, testElement) )
2589 //// Then read the associated Item Length
2590 long currentPosition = Fp->tellg();
2591 uint32_t itemLength = ReadInt32();
2593 gdcmVerboseMacro( "Basic Item Length is: "
2594 << itemLength << std::endl
2595 << " at address: " << std::hex << (unsigned int)currentPosition);
2601 * \brief When parsing the Pixel Data of an encapsulated file, read
2602 * the basic offset table (when present, and BTW dump it).
2604 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2606 //// Read the Basic Offset Table Item Tag length...
2607 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2609 // When present, read the basic offset table itself.
2610 // Notes: - since the presence of this basic offset table is optional
2611 // we can't rely on it for the implementation, and we will simply
2612 // trash it's content (when present).
2613 // - still, when present, we could add some further checks on the
2614 // lengths, but we won't bother with such fuses for the time being.
2615 if ( itemLength != 0 )
2617 char *basicOffsetTableItemValue = new char[itemLength + 1];
2618 Fp->read(basicOffsetTableItemValue, itemLength);
2621 for (unsigned int i=0; i < itemLength; i += 4 )
2623 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2625 gdcmVerboseMacro( "Read one length: " <<
2626 std::hex << individualLength );
2630 delete[] basicOffsetTableItemValue;
2635 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2636 * Compute the RLE extra information and store it in \ref RLEInfo
2637 * for later pixel retrieval usage.
2639 void Document::ComputeRLEInfo()
2641 std::string ts = GetTransferSyntax();
2642 if ( !Global::GetTS()->IsRLELossless(ts) )
2647 // Encoded pixel data: for the time being we are only concerned with
2648 // Jpeg or RLE Pixel data encodings.
2649 // As stated in PS 3.5-2003, section 8.2 p44:
2650 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2651 // value representation OB is used".
2652 // Hence we expect an OB value representation. Concerning OB VR,
2653 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2654 // "For the Value Representations OB and OW, the encoding shall meet the
2655 // following specifications depending on the Data element tag:"
2657 // - the first item in the sequence of items before the encoded pixel
2658 // data stream shall be basic offset table item. The basic offset table
2659 // item value, however, is not required to be present"
2661 ReadAndSkipEncapsulatedBasicOffsetTable();
2663 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2664 // Loop on the individual frame[s] and store the information
2665 // on the RLE fragments in a RLEFramesInfo.
2666 // Note: - when only a single frame is present, this is a
2668 // - when more than one frame are present, then we are in
2669 // the case of a multi-frame image.
2671 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2673 // Parse the RLE Header and store the corresponding RLE Segment
2674 // Offset Table information on fragments of this current Frame.
2675 // Note that the fragment pixels themselves are not loaded
2676 // (but just skipped).
2677 long frameOffset = Fp->tellg();
2679 uint32_t nbRleSegments = ReadInt32();
2680 if ( nbRleSegments > 16 )
2682 // There should be at most 15 segments (refer to RLEFrame class)
2683 gdcmVerboseMacro( "Too many segments.");
2686 uint32_t rleSegmentOffsetTable[16];
2687 for( int k = 1; k <= 15; k++ )
2689 rleSegmentOffsetTable[k] = ReadInt32();
2692 // Deduce from both the RLE Header and the frameLength the
2693 // fragment length, and again store this info in a
2695 long rleSegmentLength[15];
2696 // skipping (not reading) RLE Segments
2697 if ( nbRleSegments > 1)
2699 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2701 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2702 - rleSegmentOffsetTable[k];
2703 SkipBytes(rleSegmentLength[k]);
2707 rleSegmentLength[nbRleSegments] = frameLength
2708 - rleSegmentOffsetTable[nbRleSegments];
2709 SkipBytes(rleSegmentLength[nbRleSegments]);
2711 // Store the collected info
2712 RLEFrame *newFrameInfo = new RLEFrame;
2713 newFrameInfo->NumberFragments = nbRleSegments;
2714 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2716 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2717 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2719 RLEInfo->Frames.push_back( newFrameInfo );
2722 // Make sure that at the end of the item we encounter a 'Sequence
2724 if ( !ReadTag(0xfffe, 0xe0dd) )
2726 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2731 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2732 * Compute the jpeg extra information (fragment[s] offset[s] and
2733 * length) and store it[them] in \ref JPEGInfo for later pixel
2736 void Document::ComputeJPEGFragmentInfo()
2738 // If you need to, look for comments of ComputeRLEInfo().
2739 std::string ts = GetTransferSyntax();
2740 if ( ! Global::GetTS()->IsJPEG(ts) )
2745 ReadAndSkipEncapsulatedBasicOffsetTable();
2747 // Loop on the fragments[s] and store the parsed information in a
2749 long fragmentLength;
2750 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2752 long fragmentOffset = Fp->tellg();
2754 // Store the collected info
2755 JPEGFragment *newFragment = new JPEGFragment;
2756 newFragment->Offset = fragmentOffset;
2757 newFragment->Length = fragmentLength;
2758 JPEGInfo->Fragments.push_back( newFragment );
2760 SkipBytes( fragmentLength );
2763 // Make sure that at the end of the item we encounter a 'Sequence
2765 if ( !ReadTag(0xfffe, 0xe0dd) )
2767 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2772 * \brief Walk recursively the given \ref DocEntrySet, and feed
2773 * the given hash table (\ref TagDocEntryHT) with all the
2774 * \ref DocEntry (Dicom entries) encountered.
2775 * This method does the job for \ref BuildFlatHashTable.
2776 * @param builtHT Where to collect all the \ref DocEntry encountered
2777 * when recursively walking the given set.
2778 * @param set The structure to be traversed (recursively).
2780 void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2783 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2785 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2786 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2787 i != currentHT.end();
2790 DocEntry *entry = i->second;
2791 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2793 const ListSQItem& items = seqEntry->GetSQItems();
2794 for( ListSQItem::const_iterator item = items.begin();
2795 item != items.end();
2798 BuildFlatHashTableRecurse( builtHT, *item );
2802 builtHT[entry->GetKey()] = entry;
2807 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2809 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2810 for (ListDocEntry::const_iterator i = currentList.begin();
2811 i != currentList.end();
2814 DocEntry *entry = *i;
2815 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2817 const ListSQItem& items = seqEntry->GetSQItems();
2818 for( ListSQItem::const_iterator item = items.begin();
2819 item != items.end();
2822 BuildFlatHashTableRecurse( builtHT, *item );
2826 builtHT[entry->GetKey()] = entry;
2833 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2836 * The structure used by a Document (through \ref ElementSet),
2837 * in order to hold the parsed entries of a Dicom header, is a recursive
2838 * one. This is due to the fact that the sequences (when present)
2839 * can be nested. Additionaly, the sequence items (represented in
2840 * gdcm as \ref SQItem) add an extra complexity to the data
2841 * structure. Hence, a gdcm user whishing to visit all the entries of
2842 * a Dicom header will need to dig in the gdcm internals (which
2843 * implies exposing all the internal data structures to the API).
2844 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2845 * recursively builds a temporary hash table, which holds all the
2846 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2848 * \warning Of course there is NO integrity constrain between the
2849 * returned \ref TagDocEntryHT and the \ref ElementSet used
2850 * to build it. Hence if the underlying \ref ElementSet is
2851 * altered, then it is the caller responsability to invoke
2852 * \ref BuildFlatHashTable again...
2853 * @return The flat std::map<> we juste build.
2855 TagDocEntryHT *Document::BuildFlatHashTable()
2857 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2858 BuildFlatHashTableRecurse( *FlatHT, this );
2865 * \brief Compares two documents, according to \ref DicomDir rules
2866 * \warning Does NOT work with ACR-NEMA files
2867 * \todo Find a trick to solve the pb (use RET fields ?)
2869 * @return true if 'smaller'
2871 bool Document::operator<(Document &document)
2874 std::string s1 = GetEntry(0x0010,0x0010);
2875 std::string s2 = document.GetEntry(0x0010,0x0010);
2887 s1 = GetEntry(0x0010,0x0020);
2888 s2 = document.GetEntry(0x0010,0x0020);
2899 // Study Instance UID
2900 s1 = GetEntry(0x0020,0x000d);
2901 s2 = document.GetEntry(0x0020,0x000d);
2912 // Serie Instance UID
2913 s1 = GetEntry(0x0020,0x000e);
2914 s2 = document.GetEntry(0x0020,0x000e);
2931 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2932 * @param filetype Type of the File to be written
2934 int Document::ComputeGroup0002Length( FileType filetype )
2939 int groupLength = 0;
2940 bool found0002 = false;
2942 // for each zero-level Tag in the DCM Header
2946 entry = GetNextEntry();
2949 gr = entry->GetGroup();
2955 el = entry->GetElement();
2956 vr = entry->GetVR();
2958 if (filetype == ExplicitVR)
2960 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2962 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2965 groupLength += 2 + 2 + 4 + entry->GetLength();
2967 else if (found0002 )
2970 entry = GetNextEntry();
2975 } // end namespace gdcm
2977 //-----------------------------------------------------------------------------