1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/15 03:49:49 $
7 Version: $Revision: 1.191 $
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);
85 long beg = Fp->tellg();
88 ParseDES( this, beg, lgt, false); // Loading is done during parsing
90 Fp->seekg( 0, std::ios::beg);
92 // Load 'non string' values
94 std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);
95 if( PhotometricInterpretation == "PALETTE COLOR " )
97 LoadEntryBinArea(0x0028,0x1200); // gray LUT
99 /// The tags refered by the three following lines used to be CORRECTLY
100 /// defined as having an US Value Representation in the public
101 /// dictionnary. BUT the semantics implied by the three following
102 /// lines state that the corresponding tag contents are in fact
103 /// the ones of a BinEntry.
104 /// In order to fix things "Quick and Dirty" the dictionnary was
105 /// altered on PURPOSE but now contains a WRONG value.
106 /// In order to fix things and restore the dictionary to its
107 /// correct value, one needs to decided of the semantics by deciding
108 /// wether the following tags are either:
109 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
110 /// also used as BinEntry, which requires the proper conversion,
111 /// - OW, and hence loaded as BinEntry, but afterwards also used
112 /// as ValEntry, which requires the proper conversion.
113 LoadEntryBinArea(0x0028,0x1201); // R LUT
114 LoadEntryBinArea(0x0028,0x1202); // G LUT
115 LoadEntryBinArea(0x0028,0x1203); // B LUT
117 // Segmented Red Palette Color LUT Data
118 LoadEntryBinArea(0x0028,0x1221);
119 // Segmented Green Palette Color LUT Data
120 LoadEntryBinArea(0x0028,0x1222);
121 // Segmented Blue Palette Color LUT Data
122 LoadEntryBinArea(0x0028,0x1223);
124 //FIXME later : how to use it?
125 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
129 // --------------------------------------------------------------
130 // Specific code to allow gdcm to read ACR-LibIDO formated images
131 // Note: ACR-LibIDO is an extension of the ACR standard that was
132 // used at CREATIS. For the time being (say a couple years)
133 // we keep this kludge to allow a smooth move to gdcm for
134 // CREATIS developpers (sorry folks).
136 // if recognition code tells us we deal with a LibIDO image
137 // we switch lineNumber and columnNumber
140 RecCode = GetEntry(0x0008, 0x0010); // recognition code
141 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
142 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
143 // with "little-endian strings"
145 Filetype = ACR_LIBIDO;
146 std::string rows = GetEntry(0x0028, 0x0010);
147 std::string columns = GetEntry(0x0028, 0x0011);
148 SetEntry(columns, 0x0028, 0x0010);
149 SetEntry(rows , 0x0028, 0x0011);
151 // ----------------- End of ACR-LibIDO kludge ------------------
155 * \brief This default constructor doesn't parse the file. You should
156 * then invoke \ref Document::SetFileName and then the parsing.
158 Document::Document() : ElementSet(-1)
162 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
165 Filetype = ExplicitVR;
166 Group0002Parsed = false;
170 * \brief Canonical destructor.
172 Document::~Document ()
181 //-----------------------------------------------------------------------------
185 * \brief Prints The Dict Entries of THE public Dicom Dictionary
188 void Document::PrintPubDict(std::ostream &os)
190 RefPubDict->SetPrintLevel(PrintLevel);
191 RefPubDict->Print(os);
195 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
198 void Document::PrintShaDict(std::ostream &os)
200 RefShaDict->SetPrintLevel(PrintLevel);
201 RefShaDict->Print(os);
204 //-----------------------------------------------------------------------------
207 * \brief Get the public dictionary used
209 Dict *Document::GetPubDict()
215 * \brief Get the shadow dictionary used
217 Dict *Document::GetShaDict()
223 * \brief Set the shadow dictionary used
224 * @param dict dictionary to use in shadow
226 bool Document::SetShaDict(Dict *dict)
233 * \brief Set the shadow dictionary used
234 * @param dictName name of the dictionary to use in shadow
236 bool Document::SetShaDict(DictKey const &dictName)
238 RefShaDict = Global::GetDicts()->GetDict(dictName);
243 * \brief This predicate, based on hopefully reasonable heuristics,
244 * decides whether or not the current Document was properly parsed
245 * and contains the mandatory information for being considered as
246 * a well formed and usable Dicom/Acr File.
247 * @return true when Document is the one of a reasonable Dicom/Acr file,
250 bool Document::IsReadable()
252 if( Filetype == Unknown)
254 gdcmVerboseMacro( "Wrong filetype");
260 gdcmVerboseMacro( "No tags in internal hash table.");
268 * \brief Accessor to the Transfer Syntax (when present) of the
269 * current document (it internally handles reading the
270 * value from disk when only parsing occured).
271 * @return The encountered Transfer Syntax of the current document.
273 std::string Document::GetTransferSyntax()
275 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
281 // The entry might be present but not loaded (parsing and loading
282 // happen at different stages): try loading and proceed with check...
283 LoadDocEntrySafe(entry);
284 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
286 std::string transfer = valEntry->GetValue();
287 // The actual transfer (as read from disk) might be padded. We
288 // first need to remove the potential padding. We can make the
289 // weak assumption that padding was not executed with digits...
290 if ( transfer.length() == 0 )
292 // for brain damaged headers
295 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
297 transfer.erase(transfer.length()-1, 1);
305 * \brief Predicate for dicom version 3 file.
306 * @return True when the file is a dicom version 3.
308 bool Document::IsDicomV3()
310 // Checking if Transfer Syntax exists is enough
311 // Anyway, it's to late check if the 'Preamble' was found ...
312 // And ... would it be a rich idea to check ?
313 // (some 'no Preamble' DICOM images exist !)
314 return GetDocEntry(0x0002, 0x0010) != NULL;
318 * \brief returns the File Type
319 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
320 * @return the FileType code
322 FileType Document::GetFileType()
328 * \brief Tries to open the file \ref Document::Filename and
329 * checks the preamble when existing.
330 * @return The FILE pointer on success.
332 std::ifstream *Document::OpenFile()
335 HasDCMPreamble = false;
336 if (Filename.length() == 0)
343 gdcmVerboseMacro( "File already open: " << Filename.c_str());
346 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
349 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
356 Fp->read((char*)&zero, (size_t)2);
363 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
365 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
366 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
367 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
368 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
371 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
372 gdcmVerboseMacro( msg.c_str() );
377 Fp->seekg(126L, std::ios::cur);
379 Fp->read(dicm, (size_t)4);
385 if( memcmp(dicm, "DICM", 4) == 0 )
387 HasDCMPreamble = true;
392 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
398 * \brief closes the file
399 * @return TRUE if the close was successfull
401 bool Document::CloseFile()
410 return true; //FIXME how do we detect a non-close ifstream ?
414 * \brief Writes in a file all the Header Entries (Dicom Elements)
415 * @param fp file pointer on an already open file
416 * @param filetype Type of the File to be written
417 * (ACR-NEMA, ExplicitVR, ImplicitVR)
418 * \return Always true.
420 void Document::WriteContent(std::ofstream *fp, FileType filetype)
422 /// \todo move the following lines (and a lot of others, to be written)
423 /// to a future function CheckAndCorrectHeader
424 /// (necessary if user wants to write a DICOM V3 file
425 /// starting from an ACR-NEMA (V2) Header
427 if ( filetype == ImplicitVR || filetype == ExplicitVR )
429 // writing Dicom File Preamble
430 char filePreamble[128];
431 memset(filePreamble, 0, 128);
432 fp->write(filePreamble, 128);
433 fp->write("DICM", 4);
437 * \todo rewrite later, if really usefull
438 * - 'Group Length' element is optional in DICOM
439 * - but un-updated odd groups lengthes can causes pb
442 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
443 * UpdateGroupLength(false,filetype);
444 * if ( filetype == ACR)
445 * UpdateGroupLength(true,ACR);
448 ElementSet::WriteContent(fp, filetype); // This one is recursive
452 * \brief Modifies the value of a given Doc Entry (Dicom Element)
453 * when it exists. Create it with the given value when unexistant.
454 * @param value (string) Value to be set
455 * @param group Group number of the Entry
456 * @param elem Element number of the Entry
457 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
458 * \return pointer to the modified/created Header Entry (NULL when creation
461 ValEntry *Document::ReplaceOrCreate(std::string const &value,
466 ValEntry *valEntry = 0;
467 DocEntry *currentEntry = GetDocEntry( group, elem);
471 valEntry = dynamic_cast< ValEntry* >(currentEntry);
475 if( valEntry->GetVR()!=vr )
478 // if currentEntry doesn't correspond to the requested valEntry
481 if (!RemoveEntry(currentEntry))
483 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
490 // Create a new valEntry if necessary
493 valEntry = NewValEntry(group, elem, vr);
495 if ( !AddEntry(valEntry))
497 gdcmVerboseMacro("AddEntry failed although this is a creation.");
504 // Set the binEntry value
505 SetEntry(value, valEntry);
510 * \brief Modifies the value of a given Header Entry (Dicom Element)
511 * when it exists. Create it with the given value when unexistant.
512 * A copy of the binArea is made to be kept in the Document.
513 * @param binArea (binary) value to be set
514 * @param Group Group number of the Entry
515 * @param Elem Element number of the Entry
516 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
517 * \return pointer to the modified/created Header Entry (NULL when creation
520 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
526 BinEntry *binEntry = 0;
527 DocEntry *currentEntry = GetDocEntry( group, elem);
529 // Verify the currentEntry
532 binEntry = dynamic_cast< BinEntry* >(currentEntry);
536 if( binEntry->GetVR()!=vr )
539 // if currentEntry doesn't correspond to the requested valEntry
542 if (!RemoveEntry(currentEntry))
544 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
551 // Create a new binEntry if necessary
554 binEntry = NewBinEntry(group, elem, vr);
556 if ( !AddEntry(binEntry))
558 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
565 // Set the binEntry value
567 if (lgth>0 && binArea)
569 tmpArea = new uint8_t[lgth];
570 memcpy(tmpArea,binArea,lgth);
576 if (!SetEntry(tmpArea,lgth,binEntry))
588 * \brief Modifies the value of a given Header Entry (Dicom Element)
589 * when it exists. Create it when unexistant.
590 * @param Group Group number of the Entry
591 * @param Elem Element number of the Entry
592 * \return pointer to the modified/created SeqEntry (NULL when creation
595 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
597 SeqEntry *seqEntry = 0;
598 DocEntry *currentEntry = GetDocEntry( group, elem);
600 // Verify the currentEntry
603 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
607 if( seqEntry->GetVR()!="SQ" )
610 // if currentEntry doesn't correspond to the requested valEntry
613 if (!RemoveEntry(currentEntry))
615 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
622 // Create a new seqEntry if necessary
625 seqEntry = NewSeqEntry(group, elem);
627 if ( !AddEntry(seqEntry))
629 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
640 * \brief Set a new value if the invoked element exists
641 * Seems to be useless !!!
642 * @param value new element value
643 * @param group group number of the Entry
644 * @param elem element number of the Entry
647 bool Document::ReplaceIfExist(std::string const &value,
648 uint16_t group, uint16_t elem )
650 SetEntry(value, group, elem);
655 //-----------------------------------------------------------------------------
659 * \brief Checks if a given Dicom Element exists within the H table
660 * @param group Group number of the searched Dicom Element
661 * @param element Element number of the searched Dicom Element
662 * @return true is found
664 bool Document::CheckIfEntryExist(uint16_t group, uint16_t element )
666 const std::string &key = DictEntry::TranslateToKey(group, element );
667 return TagHT.count(key) != 0;
672 * \brief Searches within Header Entries (Dicom Elements) parsed with
673 * the public and private dictionaries
674 * for the element value representation of a given tag.
675 * @param group Group number of the searched tag.
676 * @param element Element number of the searched tag.
677 * @return Corresponding element value representation when it exists,
678 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
680 std::string Document::GetEntry(uint16_t group, uint16_t element)
682 TagKey key = DictEntry::TranslateToKey(group, element);
683 if ( !TagHT.count(key))
688 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
692 * \brief Searches within Header Entries (Dicom Elements) parsed with
693 * the public and private dictionaries
694 * for the element value representation of a given tag..
696 * Obtaining the VR (Value Representation) might be needed by caller
697 * to convert the string typed content to caller's native type
698 * (think of C++ vs Python). The VR is actually of a higher level
699 * of semantics than just the native C++ type.
700 * @param group Group number of the searched tag.
701 * @param element Element number of the searched tag.
702 * @return Corresponding element value representation when it exists,
703 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
705 std::string Document::GetEntryVR(uint16_t group, uint16_t element)
707 DocEntry *elem = GetDocEntry(group, element);
712 return elem->GetVR();
716 * \brief Searches within Header Entries (Dicom Elements) parsed with
717 * the public and private dictionaries
718 * for the value length of a given tag..
719 * @param group Group number of the searched tag.
720 * @param element Element number of the searched tag.
721 * @return Corresponding element length; -2 if not found
723 int Document::GetEntryLength(uint16_t group, uint16_t element)
725 DocEntry *elem = GetDocEntry(group, element);
728 return -2; //magic number
730 return elem->GetLength();
734 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
735 * through it's (group, element) and modifies it's content with
737 * @param content new value (string) to substitute with
738 * @param group group number of the Dicom Element to modify
739 * @param element element number of the Dicom Element to modify
741 bool Document::SetEntry(std::string const& content,
742 uint16_t group, uint16_t element)
744 ValEntry *entry = GetValEntry(group, element);
747 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
750 return SetEntry(content,entry);
754 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
755 * through it's (group, element) and modifies it's content with
757 * @param content new value (void* -> uint8_t*) to substitute with
758 * @param lgth new value length
759 * @param group group number of the Dicom Element to modify
760 * @param element element number of the Dicom Element to modify
762 bool Document::SetEntry(uint8_t*content, int lgth,
763 uint16_t group, uint16_t element)
765 BinEntry *entry = GetBinEntry(group, element);
768 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
772 return SetEntry(content,lgth,entry);
776 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
777 * and modifies it's content with the given value.
778 * @param content new value (string) to substitute with
779 * @param entry Entry to be modified
781 bool Document::SetEntry(std::string const &content,ValEntry *entry)
785 entry->SetValue(content);
792 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
793 * and modifies it's content with the given value.
794 * @param content new value (void* -> uint8_t*) to substitute with
795 * @param entry Entry to be modified
796 * @param lgth new value length
798 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
802 // Hope Binary field length is *never* wrong
803 /*if(lgth%2) // Non even length are padded with a space (020H).
806 //content = content + '\0'; // fing a trick to enlarge a binary field?
809 entry->SetBinArea(content);
810 entry->SetLength(lgth);
811 entry->SetValue(GDCM_BINLOADED);
818 * \brief Gets (from Header) a 'non string' element value
819 * (LoadElementValues has already be executed)
820 * @param group group number of the Entry
821 * @param elem element number of the Entry
822 * @return Pointer to the 'non string' area
824 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
826 DocEntry *entry = GetDocEntry(group, elem);
829 gdcmVerboseMacro( "No entry");
832 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
834 return binEntry->GetBinArea();
841 * \brief Loads (from disk) the element content
842 * when a string is not suitable
843 * @param group group number of the Entry
844 * @param elem element number of the Entry
846 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
848 // Search the corresponding DocEntry
849 DocEntry *docElement = GetDocEntry(group, elem);
853 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
857 LoadEntryBinArea(binElement);
861 * \brief Loads (from disk) the element content
862 * when a string is not suitable
863 * @param element Entry whose binArea is going to be loaded
865 void Document::LoadEntryBinArea(BinEntry *element)
867 if(element->GetBinArea())
874 size_t o =(size_t)element->GetOffset();
875 Fp->seekg(o, std::ios::beg);
877 size_t l = element->GetLength();
878 uint8_t *a = new uint8_t[l];
881 gdcmVerboseMacro( "Cannot allocate a");
885 /// \todo check the result
886 Fp->read((char*)a, l);
887 if( Fp->fail() || Fp->eof())
893 element->SetBinArea(a);
900 * \brief Sets a 'non string' value to a given Dicom Element
901 * @param area area containing the 'non string' value
902 * @param group Group number of the searched Dicom Element
903 * @param element Element number of the searched Dicom Element
906 /*bool Document::SetEntryBinArea(uint8_t *area,
907 uint16_t group, uint16_t element)
909 DocEntry *currentEntry = GetDocEntry(group, element);
915 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
917 binEntry->SetBinArea( area );
925 * \brief retrieves a Dicom Element (the first one) using (group, element)
926 * \warning (group, element) IS NOT an identifier inside the Dicom Header
927 * if you think it's NOT UNIQUE, check the count number
928 * and use iterators to retrieve ALL the Dicoms Elements within
929 * a given couple (group, element)
930 * @param group Group number of the searched Dicom Element
931 * @param element Element number of the searched Dicom Element
934 DocEntry *Document::GetDocEntry(uint16_t group, uint16_t element)
936 TagKey key = DictEntry::TranslateToKey(group, element);
937 if ( !TagHT.count(key))
941 return TagHT.find(key)->second;
945 * \brief Same as \ref Document::GetDocEntry except it only
946 * returns a result when the corresponding entry is of type
948 * @return When present, the corresponding ValEntry.
950 ValEntry *Document::GetValEntry(uint16_t group, uint16_t element)
952 DocEntry *currentEntry = GetDocEntry(group, element);
957 if ( ValEntry *entry = dynamic_cast<ValEntry*>(currentEntry) )
961 gdcmVerboseMacro( "Unfound ValEntry.");
967 * \brief Same as \ref Document::GetDocEntry except it only
968 * returns a result when the corresponding entry is of type
970 * @return When present, the corresponding BinEntry.
972 BinEntry *Document::GetBinEntry(uint16_t group, uint16_t element)
974 DocEntry *currentEntry = GetDocEntry(group, element);
979 if ( BinEntry *entry = dynamic_cast<BinEntry*>(currentEntry) )
983 gdcmVerboseMacro( "Unfound BinEntry.");
989 * \brief Loads the element while preserving the current
990 * underlying file position indicator as opposed to
991 * to LoadDocEntry that modifies it.
992 * @param entry Header Entry whose value will be loaded.
995 void Document::LoadDocEntrySafe(DocEntry *entry)
999 long PositionOnEntry = Fp->tellg();
1000 LoadDocEntry(entry);
1001 Fp->seekg(PositionOnEntry, std::ios::beg);
1006 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1008 * @return The properly swaped 32 bits integer.
1010 uint32_t Document::SwapLong(uint32_t a)
1017 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1018 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1021 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1024 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1027 gdcmErrorMacro( "Unset swap code:" << SwapCode );
1034 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1036 * @return The properly unswaped 32 bits integer.
1038 uint32_t Document::UnswapLong(uint32_t a)
1044 * \brief Swaps the bytes so they agree with the processor order
1045 * @return The properly swaped 16 bits integer.
1047 uint16_t Document::SwapShort(uint16_t a)
1049 if ( SwapCode == 4321 || SwapCode == 2143 )
1051 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1057 * \brief Unswaps the bytes so they agree with the processor order
1058 * @return The properly unswaped 16 bits integer.
1060 uint16_t Document::UnswapShort(uint16_t a)
1062 return SwapShort(a);
1065 //-----------------------------------------------------------------------------
1069 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1070 * @return length of the parsed set.
1072 void Document::ParseDES(DocEntrySet *set, long offset,
1073 long l_max, bool delim_mode)
1075 DocEntry *newDocEntry = 0;
1076 ValEntry *newValEntry;
1077 BinEntry *newBinEntry;
1078 SeqEntry *newSeqEntry;
1084 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1090 newDocEntry = ReadNextDocEntry( );
1096 vr = newDocEntry->GetVR();
1097 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1098 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1099 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1101 if ( newValEntry || newBinEntry )
1105 if ( ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1107 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1108 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
1109 << "|" << newDocEntry->GetElement()
1110 << " : Neither Valentry, nor BinEntry."
1111 "Probably unknown VR.");
1114 //////////////////// BinEntry or UNKOWN VR:
1115 // When "this" is a Document the Key is simply of the
1116 // form ( group, elem )...
1117 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1120 newBinEntry->SetKey( newBinEntry->GetKey() );
1122 // but when "this" is a SQItem, we are inserting this new
1123 // valEntry in a sequence item, and the kay has the
1124 // generalized form (refer to \ref BaseTagKey):
1125 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1127 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1128 + newBinEntry->GetKey() );
1131 LoadDocEntry( newBinEntry );
1132 if( !set->AddEntry( newBinEntry ) )
1134 //Expect big troubles if here
1135 //delete newBinEntry;
1141 /////////////////////// ValEntry
1142 // When "set" is a Document, then we are at the top of the
1143 // hierarchy and the Key is simply of the form ( group, elem )...
1144 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1147 newValEntry->SetKey( newValEntry->GetKey() );
1149 // ...but when "set" is a SQItem, we are inserting this new
1150 // valEntry in a sequence item. Hence the key has the
1151 // generalized form (refer to \ref BaseTagKey):
1152 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1154 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1155 + newValEntry->GetKey() );
1158 LoadDocEntry( newValEntry );
1159 bool delimitor=newValEntry->IsItemDelimitor();
1160 if( !set->AddEntry( newValEntry ) )
1162 // If here expect big troubles
1163 //delete newValEntry; //otherwise mem leak
1173 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1181 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1182 && ( newDocEntry->GetElement() == 0x0010 ) )
1184 std::string ts = GetTransferSyntax();
1185 if ( Global::GetTS()->IsRLELossless(ts) )
1187 long positionOnEntry = Fp->tellg();
1188 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1190 Fp->seekg( positionOnEntry, std::ios::beg );
1192 else if ( Global::GetTS()->IsJPEG(ts) )
1194 long positionOnEntry = Fp->tellg();
1195 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1196 ComputeJPEGFragmentInfo();
1197 Fp->seekg( positionOnEntry, std::ios::beg );
1201 // Just to make sure we are at the beginning of next entry.
1202 SkipToNextDocEntry(newDocEntry);
1207 unsigned long l = newDocEntry->GetReadLength();
1208 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1210 if ( l == 0xffffffff )
1219 // no other way to create it ...
1220 newSeqEntry->SetDelimitorMode( delim_mode );
1222 // At the top of the hierarchy, stands a Document. When "set"
1223 // is a Document, then we are building the first depth level.
1224 // Hence the SeqEntry we are building simply has a depth
1226 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1229 newSeqEntry->SetDepthLevel( 1 );
1230 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1232 // But when "set" is already a SQItem, we are building a nested
1233 // sequence, and hence the depth level of the new SeqEntry
1234 // we are building, is one level deeper:
1235 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1237 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1238 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1239 + newSeqEntry->GetKey() );
1243 { // Don't try to parse zero-length sequences
1244 ParseSQ( newSeqEntry,
1245 newDocEntry->GetOffset(),
1248 set->AddEntry( newSeqEntry );
1249 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1261 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1262 * @return parsed length for this level
1264 void Document::ParseSQ( SeqEntry *seqEntry,
1265 long offset, long l_max, bool delim_mode)
1267 int SQItemNumber = 0;
1272 DocEntry *newDocEntry = ReadNextDocEntry();
1275 // FIXME Should warn user
1280 if ( newDocEntry->IsSequenceDelimitor() )
1282 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1286 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1292 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1293 std::ostringstream newBase;
1294 newBase << seqEntry->GetKey()
1298 itemSQ->SetBaseTagKey( newBase.str() );
1299 unsigned int l = newDocEntry->GetReadLength();
1301 if ( l == 0xffffffff )
1310 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1311 delete newDocEntry; // FIXME Why deleting fffe 000e ?!?
1313 seqEntry->AddEntry( itemSQ, SQItemNumber );
1315 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1323 * \brief Loads the element content if its length doesn't exceed
1324 * the value specified with Document::SetMaxSizeLoadEntry()
1325 * @param entry Header Entry (Dicom Element) to be dealt with
1327 void Document::LoadDocEntry(DocEntry *entry)
1329 uint16_t group = entry->GetGroup();
1330 std::string vr = entry->GetVR();
1331 uint32_t length = entry->GetLength();
1333 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1335 // A SeQuence "contains" a set of Elements.
1336 // (fffe e000) tells us an Element is beginning
1337 // (fffe e00d) tells us an Element just ended
1338 // (fffe e0dd) tells us the current SeQuence just ended
1339 if( group == 0xfffe )
1341 // NO more value field for SQ !
1345 // When the length is zero things are easy:
1348 ((ValEntry *)entry)->SetValue("");
1352 // The elements whose length is bigger than the specified upper bound
1353 // are not loaded. Instead we leave a short notice of the offset of
1354 // the element content and it's length.
1356 std::ostringstream s;
1357 if (length > MaxSizeLoadEntry)
1359 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1361 //s << "gdcm::NotLoaded (BinEntry)";
1362 s << GDCM_NOTLOADED;
1363 s << " Address:" << (long)entry->GetOffset();
1364 s << " Length:" << entry->GetLength();
1365 s << " x(" << std::hex << entry->GetLength() << ")";
1366 binEntryPtr->SetValue(s.str());
1368 // Be carefull : a BinEntry IS_A ValEntry ...
1369 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1371 // s << "gdcm::NotLoaded. (ValEntry)";
1372 s << GDCM_NOTLOADED;
1373 s << " Address:" << (long)entry->GetOffset();
1374 s << " Length:" << entry->GetLength();
1375 s << " x(" << std::hex << entry->GetLength() << ")";
1376 valEntryPtr->SetValue(s.str());
1381 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1382 << "nor a ValEntry ?! Should never print that !" );
1385 // to be sure we are at the end of the value ...
1386 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1391 // When we find a BinEntry not very much can be done :
1392 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1394 s << GDCM_BINLOADED;
1395 binEntryPtr->SetValue(s.str());
1396 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1400 /// \todo Any compacter code suggested (?)
1401 if ( IsDocEntryAnInteger(entry) )
1405 // When short integer(s) are expected, read and convert the following
1406 // n *two characters properly i.e. consider them as short integers as
1407 // opposed to strings.
1408 // Elements with Value Multiplicity > 1
1409 // contain a set of integers (not a single one)
1410 if (vr == "US" || vr == "SS")
1413 NewInt = ReadInt16();
1417 for (int i=1; i < nbInt; i++)
1420 NewInt = ReadInt16();
1425 // See above comment on multiple integers (mutatis mutandis).
1426 else if (vr == "UL" || vr == "SL")
1429 NewInt = ReadInt32();
1433 for (int i=1; i < nbInt; i++)
1436 NewInt = ReadInt32();
1441 #ifdef GDCM_NO_ANSI_STRING_STREAM
1442 s << std::ends; // to avoid oddities on Solaris
1443 #endif //GDCM_NO_ANSI_STRING_STREAM
1445 ((ValEntry *)entry)->SetValue(s.str());
1449 // FIXME: We need an additional byte for storing \0 that is not on disk
1450 char *str = new char[length+1];
1451 Fp->read(str, (size_t)length);
1452 str[length] = '\0'; //this is only useful when length is odd
1453 // Special DicomString call to properly handle \0 and even length
1454 std::string newValue;
1457 newValue = Util::DicomString(str, length+1);
1458 gdcmVerboseMacro("Warning: bad length: " << length <<
1459 ",For string :" << newValue.c_str());
1460 // Since we change the length of string update it length
1461 //entry->SetReadLength(length+1);
1465 newValue = Util::DicomString(str, length);
1469 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1471 if ( Fp->fail() || Fp->eof())
1473 gdcmVerboseMacro("Unread element value");
1474 valEntry->SetValue(GDCM_UNREAD);
1480 // Because of correspondance with the VR dic
1481 valEntry->SetValue(newValue);
1485 valEntry->SetValue(newValue);
1490 gdcmErrorMacro( "Should have a ValEntry, here !");
1496 * \brief Find the value Length of the passed Header Entry
1497 * @param entry Header Entry whose length of the value shall be loaded.
1499 void Document::FindDocEntryLength( DocEntry *entry )
1500 throw ( FormatError )
1502 std::string vr = entry->GetVR();
1505 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1507 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1509 // The following reserved two bytes (see PS 3.5-2003, section
1510 // "7.1.2 Data element structure with explicit vr", p 27) must be
1511 // skipped before proceeding on reading the length on 4 bytes.
1512 Fp->seekg( 2L, std::ios::cur);
1513 uint32_t length32 = ReadInt32();
1515 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1520 lengthOB = FindDocEntryLengthOBOrOW();
1522 catch ( FormatUnexpected )
1524 // Computing the length failed (this happens with broken
1525 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1526 // chance to get the pixels by deciding the element goes
1527 // until the end of the file. Hence we artificially fix the
1528 // the length and proceed.
1529 long currentPosition = Fp->tellg();
1530 Fp->seekg(0L,std::ios::end);
1532 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1533 Fp->seekg(currentPosition, std::ios::beg);
1535 entry->SetReadLength(lengthUntilEOF);
1536 entry->SetLength(lengthUntilEOF);
1539 entry->SetReadLength(lengthOB);
1540 entry->SetLength(lengthOB);
1543 FixDocEntryFoundLength(entry, length32);
1547 // Length is encoded on 2 bytes.
1548 length16 = ReadInt16();
1550 // FIXME : This heuristic supposes that the first group following
1551 // group 0002 *has* and element 0000.
1552 // BUT ... Element 0000 is optionnal :-(
1555 // Fixed using : HandleOutOfGroup0002()
1556 // (first hereafter strategy ...)
1558 // We can tell the current file is encoded in big endian (like
1559 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1560 // and it's value is the one of the encoding of a big endian file.
1561 // In order to deal with such big endian encoded files, we have
1562 // (at least) two strategies:
1563 // * when we load the "Transfer Syntax" tag with value of big endian
1564 // encoding, we raise the proper flags. Then we wait for the end
1565 // of the META group (0x0002) among which is "Transfer Syntax",
1566 // before switching the swap code to big endian. We have to postpone
1567 // the switching of the swap code since the META group is fully encoded
1568 // in little endian, and big endian coding only starts at the next
1569 // group. The corresponding code can be hard to analyse and adds
1570 // many additional unnecessary tests for regular tags.
1571 // * the second strategy consists in waiting for trouble, that shall
1572 // appear when we find the first group with big endian encoding. This
1573 // is easy to detect since the length of a "Group Length" tag (the
1574 // ones with zero as element number) has to be of 4 (0x0004). When we
1575 // encounter 1024 (0x0400) chances are the encoding changed and we
1576 // found a group with big endian encoding.
1577 //---> Unfortunately, element 0000 is optional.
1578 //---> This will not work when missing!
1579 // We shall use this second strategy. In order to make sure that we
1580 // can interpret the presence of an apparently big endian encoded
1581 // length of a "Group Length" without committing a big mistake, we
1582 // add an additional check: we look in the already parsed elements
1583 // for the presence of a "Transfer Syntax" whose value has to be "big
1584 // endian encoding". When this is the case, chances are we have got our
1585 // hands on a big endian encoded file: we switch the swap code to
1586 // big endian and proceed...
1589 // if ( element == 0x0000 && length16 == 0x0400 )
1591 // std::string ts = GetTransferSyntax();
1592 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1593 // != TS::ExplicitVRBigEndian )
1595 // throw FormatError( "Document::FindDocEntryLength()",
1596 // " not explicit VR." );
1600 // SwitchByteSwapCode();
1602 // Restore the unproperly loaded values i.e. the group, the element
1603 // and the dictionary entry depending on them.
1604 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1605 // uint16_t correctElem = SwapShort( entry->GetElement() );
1606 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem ); if ( !newTag )
1608 // This correct tag is not in the dictionary. Create a new one.
1609 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1611 // FIXME this can create a memory leaks on the old entry that be
1612 // left unreferenced.
1613 // entry->SetDictEntry( newTag );
1617 // 0xffff means that we deal with 'No Length' Sequence
1618 // or 'No Length' SQItem
1619 if ( length16 == 0xffff)
1623 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1628 // Either implicit VR or a non DICOM conformal (see note below) explicit
1629 // VR that ommited the VR of (at least) this element. Farts happen.
1630 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1631 // on Data elements "Implicit and Explicit VR Data Elements shall
1632 // not coexist in a Data Set and Data Sets nested within it".]
1633 // Length is on 4 bytes.
1635 FixDocEntryFoundLength( entry, ReadInt32() );
1641 * \brief Find the Value Representation of the current Dicom Element.
1642 * @return Value Representation of the current Entry
1644 std::string Document::FindDocEntryVR()
1646 if ( Filetype != ExplicitVR )
1647 return GDCM_UNKNOWN;
1649 long positionOnEntry = Fp->tellg();
1650 // Warning: we believe this is explicit VR (Value Representation) because
1651 // we used a heuristic that found "UL" in the first tag. Alas this
1652 // doesn't guarantee that all the tags will be in explicit VR. In some
1653 // cases (see e-film filtered files) one finds implicit VR tags mixed
1654 // within an explicit VR file. Hence we make sure the present tag
1655 // is in explicit VR and try to fix things if it happens not to be
1659 Fp->read (vr, (size_t)2);
1662 if( !CheckDocEntryVR(vr) )
1664 Fp->seekg(positionOnEntry, std::ios::beg);
1665 return GDCM_UNKNOWN;
1671 * \brief Check the correspondance between the VR of the header entry
1672 * and the taken VR. If they are different, the header entry is
1673 * updated with the new VR.
1674 * @param vr Dicom Value Representation
1675 * @return false if the VR is incorrect of if the VR isn't referenced
1676 * otherwise, it returns true
1678 bool Document::CheckDocEntryVR(VRKey vr)
1680 // CLEANME searching the dicom_vr at each occurence is expensive.
1681 // PostPone this test in an optional integrity check at the end
1682 // of parsing or only in debug mode.
1683 if ( !Global::GetVR()->IsValidVR(vr) )
1690 * \brief Get the transformed value of the header entry. The VR value
1691 * is used to define the transformation to operate on the value
1692 * \warning NOT end user intended method !
1693 * @param entry entry to tranform
1694 * @return Transformed entry value
1696 std::string Document::GetDocEntryValue(DocEntry *entry)
1698 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1700 std::string val = ((ValEntry *)entry)->GetValue();
1701 std::string vr = entry->GetVR();
1702 uint32_t length = entry->GetLength();
1703 std::ostringstream s;
1706 // When short integer(s) are expected, read and convert the following
1707 // n * 2 bytes properly i.e. as a multivaluated strings
1708 // (each single value is separated fromthe next one by '\'
1709 // as usual for standard multivaluated filels
1710 // Elements with Value Multiplicity > 1
1711 // contain a set of short integers (not a single one)
1713 if( vr == "US" || vr == "SS" )
1718 for (int i=0; i < nbInt; i++)
1724 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1725 newInt16 = SwapShort( newInt16 );
1730 // When integer(s) are expected, read and convert the following
1731 // n * 4 bytes properly i.e. as a multivaluated strings
1732 // (each single value is separated fromthe next one by '\'
1733 // as usual for standard multivaluated filels
1734 // Elements with Value Multiplicity > 1
1735 // contain a set of integers (not a single one)
1736 else if( vr == "UL" || vr == "SL" )
1741 for (int i=0; i < nbInt; i++)
1747 newInt32 = ( val[4*i+0] & 0xFF )
1748 + (( val[4*i+1] & 0xFF ) << 8 )
1749 + (( val[4*i+2] & 0xFF ) << 16 )
1750 + (( val[4*i+3] & 0xFF ) << 24 );
1751 newInt32 = SwapLong( newInt32 );
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 Get the reverse transformed value of the header entry. The VR
1766 * value is used to define the reverse transformation to operate on
1768 * \warning NOT end user intended method !
1769 * @param entry Entry to reverse transform
1770 * @return Reverse transformed entry value
1772 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1774 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1776 std::string vr = entry->GetVR();
1777 std::vector<std::string> tokens;
1778 std::ostringstream s;
1780 if ( vr == "US" || vr == "SS" )
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 newInt16 = atoi(tokens[i].c_str());
1789 s << ( newInt16 & 0xFF )
1790 << (( newInt16 >> 8 ) & 0xFF );
1794 if ( vr == "UL" || vr == "SL")
1798 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1799 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1800 for (unsigned int i=0; i<tokens.size();i++)
1802 newInt32 = atoi(tokens[i].c_str());
1803 s << (char)( newInt32 & 0xFF )
1804 << (char)(( newInt32 >> 8 ) & 0xFF )
1805 << (char)(( newInt32 >> 16 ) & 0xFF )
1806 << (char)(( newInt32 >> 24 ) & 0xFF );
1811 #ifdef GDCM_NO_ANSI_STRING_STREAM
1812 s << std::ends; // to avoid oddities on Solaris
1813 #endif //GDCM_NO_ANSI_STRING_STREAM
1817 return ((ValEntry *)entry)->GetValue();
1821 * \brief Skip a given Header Entry
1822 * \warning NOT end user intended method !
1823 * @param entry entry to skip
1825 void Document::SkipDocEntry(DocEntry *entry)
1827 SkipBytes(entry->GetLength());
1831 * \brief Skips to the begining of the next Header Entry
1832 * \warning NOT end user intended method !
1833 * @param currentDocEntry entry to skip
1835 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1837 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1838 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1842 * \brief When the length of an element value is obviously wrong (because
1843 * the parser went Jabberwocky) one can hope improving things by
1844 * applying some heuristics.
1845 * @param entry entry to check
1846 * @param foundLength first assumption about length
1848 void Document::FixDocEntryFoundLength(DocEntry *entry,
1849 uint32_t foundLength)
1851 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1852 if ( foundLength == 0xffffffff)
1857 uint16_t gr = entry->GetGroup();
1858 uint16_t elem = entry->GetElement();
1860 if ( foundLength % 2)
1862 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1863 << " in x(" << std::hex << gr << "," << elem <<")");
1866 //////// Fix for some naughty General Electric images.
1867 // Allthough not recent many such GE corrupted images are still present
1868 // on Creatis hard disks. Hence this fix shall remain when such images
1869 // are no longer in use (we are talking a few years, here)...
1870 // Note: XMedCom probably uses such a trick since it is able to read
1871 // those pesky GE images ...
1872 if ( foundLength == 13)
1874 // Only happens for this length !
1875 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1878 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1882 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1883 // Occurence of such images is quite low (unless one leaves close to a
1884 // 'Leonardo' source. Hence, one might consider commenting out the
1885 // following fix on efficiency reasons.
1886 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1889 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1892 else if ( entry->GetVR() == "SQ" )
1894 foundLength = 0; // ReadLength is unchanged
1897 //////// We encountered a 'delimiter' element i.e. a tag of the form
1898 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1899 // taken into account.
1900 else if( gr == 0xfffe )
1902 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1903 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1904 // causes extra troubles...
1905 if( entry->GetElement() != 0x0000 )
1911 entry->SetLength(foundLength);
1915 * \brief Apply some heuristics to predict whether the considered
1916 * element value contains/represents an integer or not.
1917 * @param entry The element value on which to apply the predicate.
1918 * @return The result of the heuristical predicate.
1920 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1922 uint16_t elem = entry->GetElement();
1923 uint16_t group = entry->GetGroup();
1924 const std::string &vr = entry->GetVR();
1925 uint32_t length = entry->GetLength();
1927 // When we have some semantics on the element we just read, and if we
1928 // a priori know we are dealing with an integer, then we shall be
1929 // able to swap it's element value properly.
1930 if ( elem == 0 ) // This is the group length of the group
1938 // Allthough this should never happen, still some images have a
1939 // corrupted group length [e.g. have a glance at offset x(8336) of
1940 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1941 // Since for dicom compliant and well behaved headers, the present
1942 // test is useless (and might even look a bit paranoid), when we
1943 // encounter such an ill-formed image, we simply display a warning
1944 // message and proceed on parsing (while crossing fingers).
1945 long filePosition = Fp->tellg();
1946 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1947 << std::hex << group << " , " << elem
1948 << ") -before- position x(" << filePosition << ")"
1949 << "lgt : " << length );
1953 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1961 * \brief Find the Length till the next sequence delimiter
1962 * \warning NOT end user intended method !
1966 uint32_t Document::FindDocEntryLengthOBOrOW()
1967 throw( FormatUnexpected )
1969 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1970 long positionOnEntry = Fp->tellg();
1971 bool foundSequenceDelimiter = false;
1972 uint32_t totalLength = 0;
1974 while ( !foundSequenceDelimiter )
1980 group = ReadInt16();
1983 catch ( FormatError )
1985 throw FormatError("Unexpected end of file encountered during ",
1986 "Document::FindDocEntryLengthOBOrOW()");
1989 // We have to decount the group and element we just read
1992 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1994 long filePosition = Fp->tellg();
1995 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1996 << std::hex << group << " , " << elem
1997 << ") -before- position x(" << filePosition << ")" );
1999 Fp->seekg(positionOnEntry, std::ios::beg);
2000 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
2003 if ( elem == 0xe0dd )
2005 foundSequenceDelimiter = true;
2008 uint32_t itemLength = ReadInt32();
2009 // We add 4 bytes since we just read the ItemLength with ReadInt32
2010 totalLength += itemLength + 4;
2011 SkipBytes(itemLength);
2013 if ( foundSequenceDelimiter )
2018 Fp->seekg( positionOnEntry, std::ios::beg);
2023 * \brief Reads a supposed to be 16 Bits integer
2024 * (swaps it depending on processor endianity)
2025 * @return read value
2027 uint16_t Document::ReadInt16()
2028 throw( FormatError )
2031 Fp->read ((char*)&g, (size_t)2);
2034 throw FormatError( "Document::ReadInt16()", " file error." );
2038 throw FormatError( "Document::ReadInt16()", "EOF." );
2045 * \brief Reads a supposed to be 32 Bits integer
2046 * (swaps it depending on processor endianity)
2047 * @return read value
2049 uint32_t Document::ReadInt32()
2050 throw( FormatError )
2053 Fp->read ((char*)&g, (size_t)4);
2056 throw FormatError( "Document::ReadInt32()", " file error." );
2060 throw FormatError( "Document::ReadInt32()", "EOF." );
2067 * \brief skips bytes inside the source file
2068 * \warning NOT end user intended method !
2071 void Document::SkipBytes(uint32_t nBytes)
2073 //FIXME don't dump the returned value
2074 Fp->seekg((long)nBytes, std::ios::cur);
2078 * \brief Loads all the needed Dictionaries
2079 * \warning NOT end user intended method !
2081 void Document::Initialise()
2083 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2085 RLEInfo = new RLEFramesInfo;
2086 JPEGInfo = new JPEGFragmentsInfo;
2091 * \brief Discover what the swap code is (among little endian, big endian,
2092 * bad little endian, bad big endian).
2094 * @return false when we are absolutely sure
2095 * it's neither ACR-NEMA nor DICOM
2096 * true when we hope ours assuptions are OK
2098 bool Document::CheckSwap()
2100 // The only guaranted way of finding the swap code is to find a
2101 // group tag since we know it's length has to be of four bytes i.e.
2102 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2103 // occurs when we can't find such group...
2105 uint32_t x = 4; // x : for ntohs
2106 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2112 // First, compare HostByteOrder and NetworkByteOrder in order to
2113 // determine if we shall need to swap bytes (i.e. the Endian type).
2114 if ( x == ntohs(x) )
2123 // The easiest case is the one of a 'true' DICOM header, we just have
2124 // to look for the string "DICM" inside the file preamble.
2127 char *entCur = deb + 128;
2128 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2130 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2132 // Group 0002 should always be VR, and the first element 0000
2133 // Let's be carefull (so many wrong headers ...)
2134 // and determine the value representation (VR) :
2135 // Let's skip to the first element (0002,0000) and check there if we find
2136 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2137 // in which case we (almost) know it is explicit VR.
2138 // WARNING: if it happens to be implicit VR then what we will read
2139 // is the length of the group. If this ascii representation of this
2140 // length happens to be "UL" then we shall believe it is explicit VR.
2141 // We need to skip :
2142 // * the 128 bytes of File Preamble (often padded with zeroes),
2143 // * the 4 bytes of "DICM" string,
2144 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2145 // i.e. a total of 136 bytes.
2148 // group 0x0002 *is always* Explicit VR Sometimes ,
2149 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2150 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2152 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2153 memcmp(entCur, "OB", (size_t)2) == 0 ||
2154 memcmp(entCur, "UI", (size_t)2) == 0 ||
2155 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2156 // when Write DCM *adds*
2158 // Use Document::dicom_vr to test all the possibilities
2159 // instead of just checking for UL, OB and UI !? group 0000
2161 Filetype = ExplicitVR;
2162 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2166 Filetype = ImplicitVR;
2167 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2168 << "Looks like a bugged Header!");
2174 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2179 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2182 // Position the file position indicator at first tag
2183 // (i.e. after the file preamble and the "DICM" string).
2184 Fp->seekg(0, std::ios::beg);
2185 Fp->seekg ( 132L, std::ios::beg);
2189 // Alas, this is not a DicomV3 file and whatever happens there is no file
2190 // preamble. We can reset the file position indicator to where the data
2191 // is (i.e. the beginning of the file).
2192 gdcmVerboseMacro( "Not a DICOM Version3 file");
2193 Fp->seekg(0, std::ios::beg);
2195 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2196 // By clean we mean that the length of the first tag is written down.
2197 // If this is the case and since the length of the first group HAS to be
2198 // four (bytes), then determining the proper swap code is straightforward.
2201 // We assume the array of char we are considering contains the binary
2202 // representation of a 32 bits integer. Hence the following dirty
2204 s32 = *((uint32_t *)(entCur));
2225 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2226 // It is time for despaired wild guesses.
2227 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2228 // i.e. the 'group length' element is not present :
2230 // check the supposed-to-be 'group number'
2231 // in ( 0x0001 .. 0x0008 )
2232 // to determine ' SwapCode' value .
2233 // Only 0 or 4321 will be possible
2234 // (no oportunity to check for the formerly well known
2235 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2236 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2237 // the file IS NOT ACR-NEMA nor DICOM V3
2238 // Find a trick to tell it the caller...
2240 s16 = *((uint16_t *)(deb));
2267 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2277 * \brief Change the Byte Swap code.
2279 void Document::SwitchByteSwapCode()
2281 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2282 if ( SwapCode == 1234 )
2286 else if ( SwapCode == 4321 )
2290 else if ( SwapCode == 3412 )
2294 else if ( SwapCode == 2143 )
2301 * \brief during parsing, Header Elements too long are not loaded in memory
2304 void Document::SetMaxSizeLoadEntry(long newSize)
2310 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2312 MaxSizeLoadEntry = 0xffffffff;
2315 MaxSizeLoadEntry = newSize;
2320 * \brief Header Elements too long will not be printed
2321 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2324 void Document::SetMaxSizePrintEntry(long newSize)
2326 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2331 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2333 MaxSizePrintEntry = 0xffffffff;
2336 MaxSizePrintEntry = newSize;
2342 * \brief Handle broken private tag from Philips NTSCAN
2343 * where the endianess is being switch to BigEndian for no
2347 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2349 // Endian reversion. Some files contain groups of tags with reversed endianess.
2350 static int reversedEndian = 0;
2351 // try to fix endian switching in the middle of headers
2352 if ((group == 0xfeff) && (elem == 0x00e0))
2354 // start endian swap mark for group found
2356 SwitchByteSwapCode();
2361 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2363 // end of reversed endian group
2365 SwitchByteSwapCode();
2370 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2372 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2374 std::string Document::GetTransferSyntaxName()
2376 // use the TS (TS : Transfer Syntax)
2377 std::string transferSyntax = GetEntry(0x0002,0x0010);
2379 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2381 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2382 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2383 return "Uncompressed ACR-NEMA";
2385 if ( transferSyntax == GDCM_UNFOUND )
2387 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2388 return "Uncompressed ACR-NEMA";
2391 // we do it only when we need it
2392 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2394 // Global::GetTS() is a global static you shall never try to delete it!
2399 * \brief Group 0002 is always coded Little Endian
2400 * whatever Transfer Syntax is
2403 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2405 // Endian reversion. Some files contain groups of tags with reversed endianess.
2406 if ( !Group0002Parsed && group != 0x0002)
2408 Group0002Parsed = true;
2409 // we just came out of group 0002
2410 // if Transfer syntax is Big Endian we have to change CheckSwap
2412 std::string ts = GetTransferSyntax();
2413 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2415 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2419 // FIXME Strangely, this works with
2420 //'Implicit VR Transfer Syntax (GE Private)
2421 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2423 gdcmVerboseMacro("Transfer Syntax Name = ["
2424 << GetTransferSyntaxName() << "]" );
2425 SwitchByteSwapCode();
2426 group = SwapShort(group);
2427 elem = SwapShort(elem);
2433 * \brief Read the next tag but WITHOUT loading it's value
2434 * (read the 'Group Number', the 'Element Number',
2435 * gets the Dict Entry
2436 * gets the VR, gets the length, gets the offset value)
2437 * @return On succes the newly created DocEntry, NULL on failure.
2439 DocEntry *Document::ReadNextDocEntry()
2446 group = ReadInt16();
2449 catch ( FormatError e )
2451 // We reached the EOF (or an error occured) therefore
2452 // header parsing has to be considered as finished.
2457 // Sometimes file contains groups of tags with reversed endianess.
2458 HandleBrokenEndian(group, elem);
2460 // In 'true DICOM' files Group 0002 is always little endian
2461 if ( HasDCMPreamble )
2462 HandleOutOfGroup0002(group, elem);
2464 std::string vr = FindDocEntryVR();
2465 std::string realVR = vr;
2467 if( vr == GDCM_UNKNOWN)
2469 DictEntry *dictEntry = GetDictEntry(group,elem);
2471 realVR = dictEntry->GetVR();
2475 if( Global::GetVR()->IsVROfSequence(realVR) )
2476 newEntry = NewSeqEntry(group, elem);
2477 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2478 newEntry = NewValEntry(group, elem,vr);
2480 newEntry = NewBinEntry(group, elem,vr);
2482 if( vr == GDCM_UNKNOWN )
2484 if( Filetype == ExplicitVR )
2486 // We thought this was explicit VR, but we end up with an
2487 // implicit VR tag. Let's backtrack.
2488 if ( newEntry->GetGroup() != 0xfffe )
2491 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2492 newEntry->GetGroup(), newEntry->GetElement());
2493 gdcmVerboseMacro( msg.c_str() );
2496 newEntry->SetImplicitVR();
2501 FindDocEntryLength(newEntry);
2503 catch ( FormatError e )
2511 newEntry->SetOffset(Fp->tellg());
2518 * \brief Generate a free TagKey i.e. a TagKey that is not present
2519 * in the TagHt dictionary.
2520 * @param group The generated tag must belong to this group.
2521 * @return The element of tag with given group which is fee.
2523 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2525 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2527 TagKey key = DictEntry::TranslateToKey(group, elem);
2528 if (TagHT.count(key) == 0)
2537 * \brief Assuming the internal file pointer \ref Document::Fp
2538 * is placed at the beginning of a tag check whether this
2539 * tag is (TestGroup, TestElement).
2540 * \warning On success the internal file pointer \ref Document::Fp
2541 * is modified to point after the tag.
2542 * On failure (i.e. when the tag wasn't the expected tag
2543 * (TestGroup, TestElement) the internal file pointer
2544 * \ref Document::Fp is restored to it's original position.
2545 * @param testGroup The expected group of the tag.
2546 * @param testElement The expected Element of the tag.
2547 * @return True on success, false otherwise.
2549 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2551 long positionOnEntry = Fp->tellg();
2552 long currentPosition = Fp->tellg(); // On debugging purposes
2554 //// Read the Item Tag group and element, and make
2555 // sure they are what we expected:
2556 uint16_t itemTagGroup;
2557 uint16_t itemTagElement;
2560 itemTagGroup = ReadInt16();
2561 itemTagElement = ReadInt16();
2563 catch ( FormatError e )
2565 //std::cerr << e << std::endl;
2568 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2570 gdcmVerboseMacro( "Wrong Item Tag found:"
2571 << " We should have found tag ("
2572 << std::hex << testGroup << "," << testElement << ")" << std::endl
2573 << " but instead we encountered tag ("
2574 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2575 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2577 Fp->seekg(positionOnEntry, std::ios::beg);
2585 * \brief Assuming the internal file pointer \ref Document::Fp
2586 * is placed at the beginning of a tag (TestGroup, TestElement),
2587 * read the length associated to the Tag.
2588 * \warning On success the internal file pointer \ref Document::Fp
2589 * is modified to point after the tag and it's length.
2590 * On failure (i.e. when the tag wasn't the expected tag
2591 * (TestGroup, TestElement) the internal file pointer
2592 * \ref Document::Fp is restored to it's original position.
2593 * @param testGroup The expected group of the tag.
2594 * @param testElement The expected Element of the tag.
2595 * @return On success returns the length associated to the tag. On failure
2598 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2600 long positionOnEntry = Fp->tellg();
2601 (void)positionOnEntry;
2603 if ( !ReadTag(testGroup, testElement) )
2608 //// Then read the associated Item Length
2609 long currentPosition = Fp->tellg();
2610 uint32_t itemLength = ReadInt32();
2612 gdcmVerboseMacro( "Basic Item Length is: "
2613 << itemLength << std::endl
2614 << " at address: " << std::hex << (unsigned int)currentPosition);
2620 * \brief When parsing the Pixel Data of an encapsulated file, read
2621 * the basic offset table (when present, and BTW dump it).
2623 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2625 //// Read the Basic Offset Table Item Tag length...
2626 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2628 // When present, read the basic offset table itself.
2629 // Notes: - since the presence of this basic offset table is optional
2630 // we can't rely on it for the implementation, and we will simply
2631 // trash it's content (when present).
2632 // - still, when present, we could add some further checks on the
2633 // lengths, but we won't bother with such fuses for the time being.
2634 if ( itemLength != 0 )
2636 char *basicOffsetTableItemValue = new char[itemLength + 1];
2637 Fp->read(basicOffsetTableItemValue, itemLength);
2640 for (unsigned int i=0; i < itemLength; i += 4 )
2642 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2644 gdcmVerboseMacro( "Read one length: " <<
2645 std::hex << individualLength );
2649 delete[] basicOffsetTableItemValue;
2654 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2655 * Compute the RLE extra information and store it in \ref RLEInfo
2656 * for later pixel retrieval usage.
2658 void Document::ComputeRLEInfo()
2660 std::string ts = GetTransferSyntax();
2661 if ( !Global::GetTS()->IsRLELossless(ts) )
2666 // Encoded pixel data: for the time being we are only concerned with
2667 // Jpeg or RLE Pixel data encodings.
2668 // As stated in PS 3.5-2003, section 8.2 p44:
2669 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2670 // value representation OB is used".
2671 // Hence we expect an OB value representation. Concerning OB VR,
2672 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2673 // "For the Value Representations OB and OW, the encoding shall meet the
2674 // following specifications depending on the Data element tag:"
2676 // - the first item in the sequence of items before the encoded pixel
2677 // data stream shall be basic offset table item. The basic offset table
2678 // item value, however, is not required to be present"
2680 ReadAndSkipEncapsulatedBasicOffsetTable();
2682 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2683 // Loop on the individual frame[s] and store the information
2684 // on the RLE fragments in a RLEFramesInfo.
2685 // Note: - when only a single frame is present, this is a
2687 // - when more than one frame are present, then we are in
2688 // the case of a multi-frame image.
2690 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2692 // Parse the RLE Header and store the corresponding RLE Segment
2693 // Offset Table information on fragments of this current Frame.
2694 // Note that the fragment pixels themselves are not loaded
2695 // (but just skipped).
2696 long frameOffset = Fp->tellg();
2698 uint32_t nbRleSegments = ReadInt32();
2699 if ( nbRleSegments > 16 )
2701 // There should be at most 15 segments (refer to RLEFrame class)
2702 gdcmVerboseMacro( "Too many segments.");
2705 uint32_t rleSegmentOffsetTable[16];
2706 for( int k = 1; k <= 15; k++ )
2708 rleSegmentOffsetTable[k] = ReadInt32();
2711 // Deduce from both the RLE Header and the frameLength the
2712 // fragment length, and again store this info in a
2714 long rleSegmentLength[15];
2715 // skipping (not reading) RLE Segments
2716 if ( nbRleSegments > 1)
2718 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2720 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2721 - rleSegmentOffsetTable[k];
2722 SkipBytes(rleSegmentLength[k]);
2726 rleSegmentLength[nbRleSegments] = frameLength
2727 - rleSegmentOffsetTable[nbRleSegments];
2728 SkipBytes(rleSegmentLength[nbRleSegments]);
2730 // Store the collected info
2731 RLEFrame *newFrameInfo = new RLEFrame;
2732 newFrameInfo->NumberFragments = nbRleSegments;
2733 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2735 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2736 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2738 RLEInfo->Frames.push_back( newFrameInfo );
2741 // Make sure that at the end of the item we encounter a 'Sequence
2743 if ( !ReadTag(0xfffe, 0xe0dd) )
2745 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2750 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2751 * Compute the jpeg extra information (fragment[s] offset[s] and
2752 * length) and store it[them] in \ref JPEGInfo for later pixel
2755 void Document::ComputeJPEGFragmentInfo()
2757 // If you need to, look for comments of ComputeRLEInfo().
2758 std::string ts = GetTransferSyntax();
2759 if ( ! Global::GetTS()->IsJPEG(ts) )
2764 ReadAndSkipEncapsulatedBasicOffsetTable();
2766 // Loop on the fragments[s] and store the parsed information in a
2768 long fragmentLength;
2769 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2771 long fragmentOffset = Fp->tellg();
2773 // Store the collected info
2774 JPEGFragment *newFragment = new JPEGFragment;
2775 newFragment->Offset = fragmentOffset;
2776 newFragment->Length = fragmentLength;
2777 JPEGInfo->Fragments.push_back( newFragment );
2779 SkipBytes( fragmentLength );
2782 // Make sure that at the end of the item we encounter a 'Sequence
2784 if ( !ReadTag(0xfffe, 0xe0dd) )
2786 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2791 * \brief Walk recursively the given \ref DocEntrySet, and feed
2792 * the given hash table (\ref TagDocEntryHT) with all the
2793 * \ref DocEntry (Dicom entries) encountered.
2794 * This method does the job for \ref BuildFlatHashTable.
2795 * @param builtHT Where to collect all the \ref DocEntry encountered
2796 * when recursively walking the given set.
2797 * @param set The structure to be traversed (recursively).
2799 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2802 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2804 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2805 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2806 i != currentHT.end();
2809 DocEntry *entry = i->second;
2810 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2812 const ListSQItem& items = seqEntry->GetSQItems();
2813 for( ListSQItem::const_iterator item = items.begin();
2814 item != items.end();
2817 BuildFlatHashTableRecurse( builtHT, *item );
2821 builtHT[entry->GetKey()] = entry;
2826 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2828 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2829 for (ListDocEntry::const_iterator i = currentList.begin();
2830 i != currentList.end();
2833 DocEntry *entry = *i;
2834 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2836 const ListSQItem& items = seqEntry->GetSQItems();
2837 for( ListSQItem::const_iterator item = items.begin();
2838 item != items.end();
2841 BuildFlatHashTableRecurse( builtHT, *item );
2845 builtHT[entry->GetKey()] = entry;
2852 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2855 * The structure used by a Document (through \ref ElementSet),
2856 * in order to hold the parsed entries of a Dicom header, is a recursive
2857 * one. This is due to the fact that the sequences (when present)
2858 * can be nested. Additionaly, the sequence items (represented in
2859 * gdcm as \ref SQItem) add an extra complexity to the data
2860 * structure. Hence, a gdcm user whishing to visit all the entries of
2861 * a Dicom header will need to dig in the gdcm internals (which
2862 * implies exposing all the internal data structures to the API).
2863 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2864 * recursively builds a temporary hash table, which holds all the
2865 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2867 * \warning Of course there is NO integrity constrain between the
2868 * returned \ref TagDocEntryHT and the \ref ElementSet used
2869 * to build it. Hence if the underlying \ref ElementSet is
2870 * altered, then it is the caller responsability to invoke
2871 * \ref BuildFlatHashTable again...
2872 * @return The flat std::map<> we juste build.
2874 /*TagDocEntryHT *Document::BuildFlatHashTable()
2876 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2877 BuildFlatHashTableRecurse( *FlatHT, this );
2884 * \brief Compares two documents, according to \ref DicomDir rules
2885 * \warning Does NOT work with ACR-NEMA files
2886 * \todo Find a trick to solve the pb (use RET fields ?)
2888 * @return true if 'smaller'
2890 bool Document::operator<(Document &document)
2893 std::string s1 = GetEntry(0x0010,0x0010);
2894 std::string s2 = document.GetEntry(0x0010,0x0010);
2906 s1 = GetEntry(0x0010,0x0020);
2907 s2 = document.GetEntry(0x0010,0x0020);
2918 // Study Instance UID
2919 s1 = GetEntry(0x0020,0x000d);
2920 s2 = document.GetEntry(0x0020,0x000d);
2931 // Serie Instance UID
2932 s1 = GetEntry(0x0020,0x000e);
2933 s2 = document.GetEntry(0x0020,0x000e);
2950 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2951 * @param filetype Type of the File to be written
2953 int Document::ComputeGroup0002Length( FileType filetype )
2958 int groupLength = 0;
2959 bool found0002 = false;
2961 // for each zero-level Tag in the DCM Header
2965 entry = GetNextEntry();
2968 gr = entry->GetGroup();
2974 el = entry->GetElement();
2975 vr = entry->GetVR();
2977 if (filetype == ExplicitVR)
2979 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2981 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2984 groupLength += 2 + 2 + 4 + entry->GetLength();
2986 else if (found0002 )
2989 entry = GetNextEntry();
2994 } // end namespace gdcm
2996 //-----------------------------------------------------------------------------