1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/20 11:26:17 $
7 Version: $Revision: 1.202 $
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__) || defined(__MINGW32__)
42 #ifdef CMAKE_HAVE_NETINET_IN_H
43 #include <netinet/in.h>
49 //-----------------------------------------------------------------------------
50 // Refer to Document::CheckSwap()
51 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
53 // Refer to Document::SetMaxSizeLoadEntry()
54 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
55 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
57 //-----------------------------------------------------------------------------
58 // Constructor / Destructor
62 * @param filename file to be opened for parsing
64 Document::Document( std::string const &filename ) : ElementSet(-1)
69 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
79 Group0002Parsed = false;
81 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
82 // Fp->seekg( 0, std::ios::beg);
84 Fp->seekg(0, std::ios::end);
85 long lgt = Fp->tellg();
87 Fp->seekg( 0, std::ios::beg);
90 long beg = Fp->tellg();
93 ParseDES( this, beg, lgt, false); // Loading is done during parsing
95 Fp->seekg( 0, std::ios::beg);
97 // Load 'non string' values
99 std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);
100 if( PhotometricInterpretation == "PALETTE COLOR " )
102 LoadEntryBinArea(0x0028,0x1200); // gray LUT
103 /// FIXME FIXME FIXME
104 /// The tags refered by the three following lines used to be CORRECTLY
105 /// defined as having an US Value Representation in the public
106 /// dictionary. BUT the semantics implied by the three following
107 /// lines state that the corresponding tag contents are in fact
108 /// the ones of a BinEntry.
109 /// In order to fix things "Quick and Dirty" the dictionary was
110 /// altered on PURPOSE but now contains a WRONG value.
111 /// In order to fix things and restore the dictionary to its
112 /// correct value, one needs to decided of the semantics by deciding
113 /// whether the following tags are either:
114 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
115 /// also used as BinEntry, which requires the proper conversion,
116 /// - OW, and hence loaded as BinEntry, but afterwards also used
117 /// as ValEntry, which requires the proper conversion.
118 LoadEntryBinArea(0x0028,0x1201); // R LUT
119 LoadEntryBinArea(0x0028,0x1202); // G LUT
120 LoadEntryBinArea(0x0028,0x1203); // B LUT
122 // Segmented Red Palette Color LUT Data
123 LoadEntryBinArea(0x0028,0x1221);
124 // Segmented Green Palette Color LUT Data
125 LoadEntryBinArea(0x0028,0x1222);
126 // Segmented Blue Palette Color LUT Data
127 LoadEntryBinArea(0x0028,0x1223);
129 //FIXME later : how to use it?
130 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
134 // --------------------------------------------------------------
135 // Specific code to allow gdcm to read ACR-LibIDO formated images
136 // Note: ACR-LibIDO is an extension of the ACR standard that was
137 // used at CREATIS. For the time being (say a couple years)
138 // we keep this kludge to allow a smooth move to gdcm for
139 // CREATIS developpers (sorry folks).
141 // if recognition code tells us we deal with a LibIDO image
142 // we switch lineNumber and columnNumber
145 RecCode = GetEntry(0x0008, 0x0010); // recognition code (RET)
146 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
147 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
148 // with "little-endian strings"
150 Filetype = ACR_LIBIDO;
151 std::string rows = GetEntry(0x0028, 0x0010);
152 std::string columns = GetEntry(0x0028, 0x0011);
153 SetEntry(columns, 0x0028, 0x0010);
154 SetEntry(rows , 0x0028, 0x0011);
156 // ----------------- End of ACR-LibIDO kludge ------------------
160 * \brief This default constructor doesn't parse the file. You should
161 * then invoke \ref Document::SetFileName and then the parsing.
163 Document::Document() : ElementSet(-1)
170 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
173 Filetype = ExplicitVR;
174 Group0002Parsed = false;
178 * \brief Canonical destructor.
180 Document::~Document ()
191 //-----------------------------------------------------------------------------
195 * \brief Prints The Dict Entries of THE public Dicom Dictionary
198 void Document::PrintPubDict(std::ostream &os)
200 RefPubDict->SetPrintLevel(PrintLevel);
201 RefPubDict->Print(os);
205 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
208 void Document::PrintShaDict(std::ostream &os)
210 RefShaDict->SetPrintLevel(PrintLevel);
211 RefShaDict->Print(os);
214 //-----------------------------------------------------------------------------
217 * \brief Get the public dictionary used
219 Dict *Document::GetPubDict()
225 * \brief Get the shadow dictionary used
227 Dict *Document::GetShaDict()
233 * \brief Set the shadow dictionary used
234 * @param dict dictionary to use in shadow
236 bool Document::SetShaDict(Dict *dict)
243 * \brief Set the shadow dictionary used
244 * @param dictName name of the dictionary to use in shadow
246 bool Document::SetShaDict(DictKey const &dictName)
248 RefShaDict = Global::GetDicts()->GetDict(dictName);
253 * \brief This predicate, based on hopefully reasonable heuristics,
254 * decides whether or not the current Document was properly parsed
255 * and contains the mandatory information for being considered as
256 * a well formed and usable Dicom/Acr File.
257 * @return true when Document is the one of a reasonable Dicom/Acr file,
260 bool Document::IsReadable()
262 if( Filetype == Unknown)
264 gdcmVerboseMacro( "Wrong filetype");
270 gdcmVerboseMacro( "No tag in internal hash table.");
278 * \brief Accessor to the Transfer Syntax (when present) of the
279 * current document (it internally handles reading the
280 * value from disk when only parsing occured).
281 * @return The encountered Transfer Syntax of the current document.
283 std::string Document::GetTransferSyntax()
285 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
291 // The entry might be present but not loaded (parsing and loading
292 // happen at different stages): try loading and proceed with check...
293 LoadDocEntrySafe(entry);
294 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
296 std::string transfer = valEntry->GetValue();
297 // The actual transfer (as read from disk) might be padded. We
298 // first need to remove the potential padding. We can make the
299 // weak assumption that padding was not executed with digits...
300 if ( transfer.length() == 0 )
302 // for brain damaged headers
305 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
307 transfer.erase(transfer.length()-1, 1);
315 * \brief Predicate for dicom version 3 file.
316 * @return True when the file is a dicom version 3.
318 bool Document::IsDicomV3()
320 // Checking if Transfer Syntax exists is enough
321 // Anyway, it's to late check if the 'Preamble' was found ...
322 // And ... would it be a rich idea to check ?
323 // (some 'no Preamble' DICOM images exist !)
324 return GetDocEntry(0x0002, 0x0010) != NULL;
328 * \brief returns the File Type
329 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
330 * @return the FileType code
332 FileType Document::GetFileType()
338 * \brief Tries to open the file \ref Document::Filename and
339 * checks the preamble when existing.
340 * @return The FILE pointer on success.
342 std::ifstream *Document::OpenFile()
345 HasDCMPreamble = false;
346 if (Filename.length() == 0)
353 gdcmVerboseMacro( "File already open: " << Filename.c_str());
356 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
359 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
366 Fp->read((char*)&zero, (size_t)2);
373 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
375 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
376 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
377 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
378 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
381 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
382 gdcmVerboseMacro( msg.c_str() );
387 Fp->seekg(126L, std::ios::cur);
389 Fp->read(dicm, (size_t)4);
395 if( memcmp(dicm, "DICM", 4) == 0 )
397 HasDCMPreamble = true;
402 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
408 * \brief closes the file
409 * @return TRUE if the close was successfull
411 bool Document::CloseFile()
420 return true; //FIXME how do we detect a non-closed ifstream ?
424 * \brief Writes in a file all the Header Entries (Dicom Elements)
425 * @param fp file pointer on an already open file (actually: Output File Stream)
426 * @param filetype Type of the File to be written
427 * (ACR-NEMA, ExplicitVR, ImplicitVR)
428 * \return Always true.
430 void Document::WriteContent(std::ofstream *fp, FileType filetype)
432 /// \todo move the following lines (and a lot of others, to be written)
433 /// to a future function CheckAndCorrectHeader
434 /// (necessary if user wants to write a DICOM V3 file
435 /// starting from an ACR-NEMA (V2) Header
437 if ( filetype == ImplicitVR || filetype == ExplicitVR )
439 // writing Dicom File Preamble
440 char filePreamble[128];
441 memset(filePreamble, 0, 128);
442 fp->write(filePreamble, 128);
443 fp->write("DICM", 4);
447 * \todo rewrite later, if really usefull
448 * - 'Group Length' element is optional in DICOM
449 * - but un-updated odd groups lengthes can causes pb
452 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
453 * UpdateGroupLength(false,filetype);
454 * if ( filetype == ACR)
455 * UpdateGroupLength(true,ACR);
458 ElementSet::WriteContent(fp, filetype); // This one is recursive
462 * \brief Modifies the value of a given Doc Entry (Dicom Element)
463 * when it exists. Create it with the given value when unexistant.
464 * @param value (string) Value to be set
465 * @param group Group number of the Entry
466 * @param elem Element number of the Entry
467 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
468 * \return pointer to the modified/created Header Entry (NULL when creation
471 ValEntry *Document::ReplaceOrCreate(std::string const &value,
476 ValEntry *valEntry = 0;
477 DocEntry *currentEntry = GetDocEntry( group, elem);
481 valEntry = dynamic_cast< ValEntry* >(currentEntry);
485 if( valEntry->GetVR()!=vr )
488 // if currentEntry doesn't correspond to the requested valEntry
491 if (!RemoveEntry(currentEntry))
493 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
500 // Create a new valEntry if necessary
503 valEntry = NewValEntry(group, elem, vr);
505 if ( !AddEntry(valEntry))
507 gdcmVerboseMacro("AddEntry failed although this is a creation.");
514 // Set the binEntry value
515 SetEntry(value, valEntry);
520 * \brief Modifies the value of a given Header Entry (Dicom Element)
521 * when it exists. Create it with the given value when unexistant.
522 * A copy of the binArea is made to be kept in the Document.
523 * @param binArea (binary) value to be set
524 * @param group Group number of the Entry
525 * @param elem Element number of the Entry
526 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
527 * \return pointer to the modified/created Header Entry (NULL when creation
530 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
536 BinEntry *binEntry = 0;
537 DocEntry *currentEntry = GetDocEntry( group, elem);
539 // Verify the currentEntry
542 binEntry = dynamic_cast< BinEntry* >(currentEntry);
546 if( binEntry->GetVR()!=vr )
549 // if currentEntry doesn't correspond to the requested valEntry
552 if (!RemoveEntry(currentEntry))
554 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
561 // Create a new binEntry if necessary
564 binEntry = NewBinEntry(group, elem, vr);
566 if ( !AddEntry(binEntry))
568 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
575 // Set the binEntry value
577 if (lgth>0 && binArea)
579 tmpArea = new uint8_t[lgth];
580 memcpy(tmpArea,binArea,lgth);
586 if (!SetEntry(tmpArea,lgth,binEntry))
598 * \brief Modifies the value of a given Header Entry (Dicom Element)
599 * when it exists. Create it when unexistant.
600 * @param group Group number of the Entry
601 * @param elem Element number of the Entry
602 * \return pointer to the modified/created SeqEntry (NULL when creation
605 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
607 SeqEntry *seqEntry = 0;
608 DocEntry *currentEntry = GetDocEntry( group, elem);
610 // Verify the currentEntry
613 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
617 if( seqEntry->GetVR()!="SQ" )
620 // if currentEntry doesn't correspond to the requested valEntry
623 if (!RemoveEntry(currentEntry))
625 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
631 // Create a new seqEntry if necessary
634 seqEntry = NewSeqEntry(group, elem);
636 if ( !AddEntry(seqEntry))
638 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
648 * \brief Set a new value if the invoked element exists
649 * Seems to be useless !!!
650 * @param value new element value
651 * @param group group number of the Entry
652 * @param elem element number of the Entry
655 bool Document::ReplaceIfExist(std::string const &value,
656 uint16_t group, uint16_t elem )
658 SetEntry(value, group, elem);
663 //-----------------------------------------------------------------------------
667 * \brief Checks if a given Dicom Element exists within the H table
668 * @param group Group number of the searched Dicom Element
669 * @param elem Element number of the searched Dicom Element
670 * @return true is found
672 bool Document::CheckIfEntryExist(uint16_t group, uint16_t elem )
674 const std::string &key = DictEntry::TranslateToKey(group, elem );
675 return TagHT.count(key) != 0;
680 * \brief Searches within Header Entries (Dicom Elements) parsed with
681 * the public and private dictionaries
682 * for the element value representation of a given tag.
683 * @param group Group number of the searched tag.
684 * @param elem Element number of the searched tag.
685 * @return Corresponding element value representation when it exists,
686 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
688 std::string Document::GetEntry(uint16_t group, uint16_t elem)
690 TagKey key = DictEntry::TranslateToKey(group, elem);
691 if ( !TagHT.count(key))
696 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
700 * \brief Searches within Header Entries (Dicom Elements) parsed with
701 * the public and private dictionaries
702 * for the element value representation of a given tag..
703 * Obtaining the VR (Value Representation) might be needed by caller
704 * to convert the string typed content to caller's native type
705 * (think of C++ vs Python). The VR is actually of a higher level
706 * of semantics than just the native C++ type.
707 * @param group Group number of the searched tag.
708 * @param elem Element number of the searched tag.
709 * @return Corresponding element value representation when it exists,
710 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
712 std::string Document::GetEntryVR(uint16_t group, uint16_t elem)
714 DocEntry *element = GetDocEntry(group, elem);
719 return element->GetVR();
723 * \brief Searches within Header Entries (Dicom Elements) parsed with
724 * the public and private dictionaries
725 * for the value length of a given tag..
726 * @param group Group number of the searched tag.
727 * @param elem Element number of the searched tag.
728 * @return Corresponding element length; -2 if not found
730 int Document::GetEntryLength(uint16_t group, uint16_t elem)
732 DocEntry *element = GetDocEntry(group, elem);
735 return -2; //magic number
737 return element->GetLength();
741 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
742 * through it's (group, element) and modifies it's content with
744 * @param content new value (string) to substitute with
745 * @param group group number of the Dicom Element to modify
746 * @param elem element number of the Dicom Element to modify
748 bool Document::SetEntry(std::string const& content,
749 uint16_t group, uint16_t elem)
751 ValEntry *entry = GetValEntry(group, elem);
754 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
757 return SetEntry(content,entry);
761 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
762 * through it's (group, element) and modifies it's content with
764 * @param content new value (void* -> uint8_t*) to substitute with
765 * @param lgth new value length
766 * @param group group number of the Dicom Element to modify
767 * @param elem element number of the Dicom Element to modify
769 bool Document::SetEntry(uint8_t*content, int lgth,
770 uint16_t group, uint16_t elem)
772 BinEntry *entry = GetBinEntry(group, elem);
775 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
779 return SetEntry(content,lgth,entry);
783 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
784 * and modifies it's content with the given value.
785 * @param content new value (string) to substitute with
786 * @param entry Entry to be modified
788 bool Document::SetEntry(std::string const &content, ValEntry *entry)
792 entry->SetValue(content);
799 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
800 * and modifies it's content with the given value.
801 * @param content new value (void* -> uint8_t*) to substitute with
802 * @param entry Entry to be modified
803 * @param lgth new value length
805 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
809 // Hope Binary field length is *never* wrong
810 /*if(lgth%2) // Non even length are padded with a space (020H).
813 //content = content + '\0'; // fing a trick to enlarge a binary field?
816 entry->SetBinArea(content);
817 entry->SetLength(lgth);
818 entry->SetValue(GDCM_BINLOADED);
825 * \brief Gets (from Header) a 'non string' element value
826 * (LoadElementValues has already be executed)
827 * @param group group number of the Entry
828 * @param elem element number of the Entry
829 * @return Pointer to the 'non string' area
831 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
833 DocEntry *entry = GetDocEntry(group, elem);
836 gdcmVerboseMacro( "No entry");
839 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
841 return binEntry->GetBinArea();
848 * \brief Loads (from disk) the element content
849 * when a string is not suitable
850 * @param group group number of the Entry
851 * @param elem element number of the Entry
853 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
855 // Search the corresponding DocEntry
856 DocEntry *docElement = GetDocEntry(group, elem);
860 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
864 LoadEntryBinArea(binElement);
868 * \brief Loads (from disk) the element content
869 * when a string is not suitable
870 * @param elem Entry whose binArea is going to be loaded
872 void Document::LoadEntryBinArea(BinEntry *elem)
874 if(elem->GetBinArea())
881 size_t o =(size_t)elem->GetOffset();
882 Fp->seekg(o, std::ios::beg);
884 size_t l = elem->GetLength();
885 uint8_t *a = new uint8_t[l];
888 gdcmVerboseMacro( "Cannot allocate BinEntry content");
892 /// \todo check the result
893 Fp->read((char*)a, l);
894 if( Fp->fail() || Fp->eof())
907 * \brief Sets a 'non string' value to a given Dicom Element
908 * @param area area containing the 'non string' value
909 * @param group Group number of the searched Dicom Element
910 * @param elem Element number of the searched Dicom Element
913 /*bool Document::SetEntryBinArea(uint8_t *area,
914 uint16_t group, uint16_t elem)
916 DocEntry *currentEntry = GetDocEntry(group, elem);
922 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
924 binEntry->SetBinArea( area );
932 * \brief retrieves a Dicom Element using (group, element)
933 * @param group Group number of the searched Dicom Element
934 * @param elem Element number of the searched Dicom Element
937 DocEntry *Document::GetDocEntry(uint16_t group, uint16_t elem)
939 TagKey key = DictEntry::TranslateToKey(group, elem);
940 if ( !TagHT.count(key))
944 return TagHT.find(key)->second;
948 * \brief Same as \ref Document::GetDocEntry except it only
949 * returns a result when the corresponding entry is of type
951 * @param group Group number of the searched Dicom Element
952 * @param elem Element number of the searched Dicom Element
953 * @return When present, the corresponding ValEntry.
955 ValEntry *Document::GetValEntry(uint16_t group, uint16_t elem)
957 DocEntry *currentEntry = GetDocEntry(group, elem);
962 if ( ValEntry *entry = dynamic_cast<ValEntry*>(currentEntry) )
966 gdcmVerboseMacro( "Unfound ValEntry.");
972 * \brief Same as \ref Document::GetDocEntry except it only
973 * returns a result when the corresponding entry is of type
975 * @param group Group number of the searched Dicom Element
976 * @param elem Element number of the searched Dicom Element
977 * @return When present, the corresponding BinEntry.
979 BinEntry *Document::GetBinEntry(uint16_t group, uint16_t elem)
981 DocEntry *currentEntry = GetDocEntry(group, elem);
986 if ( BinEntry *entry = dynamic_cast<BinEntry*>(currentEntry) )
990 gdcmVerboseMacro( "Unfound BinEntry.");
996 * \brief Same as \ref Document::GetDocEntry except it only
997 * returns a result when the corresponding entry is of type
999 * @param group Group number of the searched Dicom Element
1000 * @param elem Element number of the searched Dicom Element
1001 * @return When present, the corresponding SeqEntry.
1003 SeqEntry *Document::GetSeqEntry(uint16_t group, uint16_t elem)
1005 DocEntry *currentEntry = GetDocEntry(group, elem);
1006 if ( !currentEntry )
1010 if ( SeqEntry *entry = dynamic_cast<SeqEntry*>(currentEntry) )
1014 gdcmVerboseMacro( "Unfound SeqEntry.");
1021 * \brief Loads the element while preserving the current
1022 * underlying file position indicator as opposed to
1023 * LoadDocEntry that modifies it.
1024 * @param entry Header Entry whose value will be loaded.
1027 void Document::LoadDocEntrySafe(DocEntry *entry)
1031 long PositionOnEntry = Fp->tellg();
1032 LoadDocEntry(entry);
1033 Fp->seekg(PositionOnEntry, std::ios::beg);
1038 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1040 * @return The properly swaped 32 bits integer.
1042 uint32_t Document::SwapLong(uint32_t a)
1049 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1050 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1053 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1056 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1059 gdcmErrorMacro( "Unset swap code:" << SwapCode );
1066 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1068 * @return The properly unswaped 32 bits integer.
1070 uint32_t Document::UnswapLong(uint32_t a)
1076 * \brief Swaps the bytes so they agree with the processor order
1077 * @return The properly swaped 16 bits integer.
1079 uint16_t Document::SwapShort(uint16_t a)
1081 if ( SwapCode == 4321 || SwapCode == 2143 )
1083 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1089 * \brief Unswaps the bytes so they agree with the processor order
1090 * @return The properly unswaped 16 bits integer.
1092 uint16_t Document::UnswapShort(uint16_t a)
1094 return SwapShort(a);
1097 //-----------------------------------------------------------------------------
1101 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1102 * @return length of the parsed set.
1104 void Document::ParseDES(DocEntrySet *set, long offset,
1105 long l_max, bool delim_mode)
1107 DocEntry *newDocEntry = 0;
1108 ValEntry *newValEntry;
1109 BinEntry *newBinEntry;
1110 SeqEntry *newSeqEntry;
1116 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1122 newDocEntry = ReadNextDocEntry( );
1129 vr = newDocEntry->GetVR();
1130 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1131 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1132 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1134 if ( newValEntry || newBinEntry )
1138 if ( Filetype == ExplicitVR && ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1140 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1141 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
1142 << "|" << newDocEntry->GetElement()
1143 << " : Neither Valentry, nor BinEntry."
1144 "Probably unknown VR.");
1147 //////////////////// BinEntry or UNKOWN VR:
1148 // When "this" is a Document the Key is simply of the
1149 // form ( group, elem )...
1150 if ( dynamic_cast< Document* > ( set ) )
1152 newBinEntry->SetKey( newBinEntry->GetKey() );
1154 // but when "this" is a SQItem, we are inserting this new
1155 // valEntry in a sequence item, and the key has the
1156 // generalized form (refer to \ref BaseTagKey):
1157 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1159 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1160 + newBinEntry->GetKey() );
1163 LoadDocEntry( newBinEntry );
1164 if( !set->AddEntry( newBinEntry ) )
1166 //Expect big troubles if here
1167 //delete newBinEntry;
1173 /////////////////////// ValEntry
1174 // When "set" is a Document, then we are at the top of the
1175 // hierarchy and the Key is simply of the form ( group, elem )...
1176 if ( dynamic_cast< Document* > ( set ) )
1178 newValEntry->SetKey( newValEntry->GetKey() );
1180 // ...but when "set" is a SQItem, we are inserting this new
1181 // valEntry in a sequence item. Hence the key has the
1182 // generalized form (refer to \ref BaseTagKey):
1183 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1185 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1186 + newValEntry->GetKey() );
1189 LoadDocEntry( newValEntry );
1190 bool delimitor=newValEntry->IsItemDelimitor();
1191 if( !set->AddEntry( newValEntry ) )
1193 // If here expect big troubles
1194 //delete newValEntry; //otherwise mem leak
1204 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1212 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1213 && ( newDocEntry->GetElement() == 0x0010 ) )
1215 std::string ts = GetTransferSyntax();
1216 if ( Global::GetTS()->IsRLELossless(ts) )
1218 long positionOnEntry = Fp->tellg();
1219 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1221 Fp->seekg( positionOnEntry, std::ios::beg );
1223 else if ( Global::GetTS()->IsJPEG(ts) )
1225 long positionOnEntry = Fp->tellg();
1226 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1227 ComputeJPEGFragmentInfo();
1228 Fp->seekg( positionOnEntry, std::ios::beg );
1232 // Just to make sure we are at the beginning of next entry.
1233 SkipToNextDocEntry(newDocEntry);
1238 unsigned long l = newDocEntry->GetReadLength();
1239 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1241 if ( l == 0xffffffff )
1250 // no other way to create it ...
1251 newSeqEntry->SetDelimitorMode( delim_mode );
1253 // At the top of the hierarchy, stands a Document. When "set"
1254 // is a Document, then we are building the first depth level.
1255 // Hence the SeqEntry we are building simply has a depth
1257 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1260 newSeqEntry->SetDepthLevel( 1 );
1261 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1263 // But when "set" is already a SQItem, we are building a nested
1264 // sequence, and hence the depth level of the new SeqEntry
1265 // we are building, is one level deeper:
1266 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1268 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1269 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1270 + newSeqEntry->GetKey() );
1274 { // Don't try to parse zero-length sequences
1275 ParseSQ( newSeqEntry,
1276 newDocEntry->GetOffset(),
1279 set->AddEntry( newSeqEntry );
1280 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1292 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1293 * @return parsed length for this level
1295 void Document::ParseSQ( SeqEntry *seqEntry,
1296 long offset, long l_max, bool delim_mode)
1298 int SQItemNumber = 0;
1300 long offsetStartCurrentSQItem = offset;
1304 // the first time, we read the fff0,e000 of the first SQItem
1305 DocEntry *newDocEntry = ReadNextDocEntry();
1309 // FIXME Should warn user
1314 if ( newDocEntry->IsSequenceDelimitor() )
1316 seqEntry->SetDelimitationItem( newDocEntry );
1320 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1325 // create the current SQItem
1326 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1327 std::ostringstream newBase;
1328 newBase << seqEntry->GetKey()
1332 itemSQ->SetBaseTagKey( newBase.str() );
1333 unsigned int l = newDocEntry->GetReadLength();
1335 if ( l == 0xffffffff )
1344 // when we're here, element fffe,e000 is already passed.
1345 // it's lost for the SQItem we're going to process !!
1347 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1348 //delete newDocEntry; // FIXME well ... it's too late to use it !
1350 // Let's try :------------
1351 // remove fff0,e000, created out of the SQItem
1353 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1354 // fill up the current SQItem, starting at the beginning of fff0,e000
1355 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1356 offsetStartCurrentSQItem = Fp->tellg();
1357 // end try -----------------
1359 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1361 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1369 * \brief Loads the element content if its length doesn't exceed
1370 * the value specified with Document::SetMaxSizeLoadEntry()
1371 * @param entry Header Entry (Dicom Element) to be dealt with
1373 void Document::LoadDocEntry(DocEntry *entry)
1375 uint16_t group = entry->GetGroup();
1376 std::string vr = entry->GetVR();
1377 uint32_t length = entry->GetLength();
1379 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1381 // A SeQuence "contains" a set of Elements.
1382 // (fffe e000) tells us an Element is beginning
1383 // (fffe e00d) tells us an Element just ended
1384 // (fffe e0dd) tells us the current SeQuence just ended
1385 if( group == 0xfffe )
1387 // NO more value field for SQ !
1391 // When the length is zero things are easy:
1394 ((ValEntry *)entry)->SetValue("");
1398 // The elements whose length is bigger than the specified upper bound
1399 // are not loaded. Instead we leave a short notice of the offset of
1400 // the element content and it's length.
1402 std::ostringstream s;
1403 if (length > MaxSizeLoadEntry)
1405 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1407 //s << "gdcm::NotLoaded (BinEntry)";
1408 s << GDCM_NOTLOADED;
1409 s << " Address:" << (long)entry->GetOffset();
1410 s << " Length:" << entry->GetLength();
1411 s << " x(" << std::hex << entry->GetLength() << ")";
1412 binEntryPtr->SetValue(s.str());
1414 // Be carefull : a BinEntry IS_A ValEntry ...
1415 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1417 // s << "gdcm::NotLoaded. (ValEntry)";
1418 s << GDCM_NOTLOADED;
1419 s << " Address:" << (long)entry->GetOffset();
1420 s << " Length:" << entry->GetLength();
1421 s << " x(" << std::hex << entry->GetLength() << ")";
1422 valEntryPtr->SetValue(s.str());
1427 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1428 << "nor a ValEntry ?! Should never print that !" );
1431 // to be sure we are at the end of the value ...
1432 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1437 // When we find a BinEntry not very much can be done :
1438 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1440 s << GDCM_BINLOADED;
1441 binEntryPtr->SetValue(s.str());
1442 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1446 /// \todo Any compacter code suggested (?)
1447 if ( IsDocEntryAnInteger(entry) )
1451 // When short integer(s) are expected, read and convert the following
1452 // n *two characters properly i.e. consider them as short integers as
1453 // opposed to strings.
1454 // Elements with Value Multiplicity > 1
1455 // contain a set of integers (not a single one)
1456 if (vr == "US" || vr == "SS")
1459 NewInt = ReadInt16();
1463 for (int i=1; i < nbInt; i++)
1466 NewInt = ReadInt16();
1471 // See above comment on multiple integers (mutatis mutandis).
1472 else if (vr == "UL" || vr == "SL")
1475 NewInt = ReadInt32();
1479 for (int i=1; i < nbInt; i++)
1482 NewInt = ReadInt32();
1487 #ifdef GDCM_NO_ANSI_STRING_STREAM
1488 s << std::ends; // to avoid oddities on Solaris
1489 #endif //GDCM_NO_ANSI_STRING_STREAM
1491 ((ValEntry *)entry)->SetValue(s.str());
1495 // FIXME: We need an additional byte for storing \0 that is not on disk
1496 char *str = new char[length+1];
1497 Fp->read(str, (size_t)length);
1498 str[length] = '\0'; //this is only useful when length is odd
1499 // Special DicomString call to properly handle \0 and even length
1500 std::string newValue;
1503 newValue = Util::DicomString(str, length+1);
1504 gdcmVerboseMacro("Warning: bad length: " << length <<
1505 ",For string :" << newValue.c_str());
1506 // Since we change the length of string update it length
1507 //entry->SetReadLength(length+1);
1511 newValue = Util::DicomString(str, length);
1515 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1517 if ( Fp->fail() || Fp->eof())
1519 gdcmVerboseMacro("Unread element value");
1520 valEntry->SetValue(GDCM_UNREAD);
1526 // Because of correspondance with the VR dic
1527 valEntry->SetValue(newValue);
1531 valEntry->SetValue(newValue);
1536 gdcmErrorMacro( "Should have a ValEntry, here !");
1542 * \brief Find the value Length of the passed Header Entry
1543 * @param entry Header Entry whose length of the value shall be loaded.
1545 void Document::FindDocEntryLength( DocEntry *entry )
1546 throw ( FormatError )
1548 std::string vr = entry->GetVR();
1551 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1553 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1555 // The following reserved two bytes (see PS 3.5-2003, section
1556 // "7.1.2 Data element structure with explicit vr", p 27) must be
1557 // skipped before proceeding on reading the length on 4 bytes.
1558 Fp->seekg( 2L, std::ios::cur);
1559 uint32_t length32 = ReadInt32();
1561 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1566 lengthOB = FindDocEntryLengthOBOrOW();
1568 catch ( FormatUnexpected )
1570 // Computing the length failed (this happens with broken
1571 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1572 // chance to get the pixels by deciding the element goes
1573 // until the end of the file. Hence we artificially fix the
1574 // the length and proceed.
1575 long currentPosition = Fp->tellg();
1576 Fp->seekg(0L,std::ios::end);
1578 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1579 Fp->seekg(currentPosition, std::ios::beg);
1581 entry->SetReadLength(lengthUntilEOF);
1582 entry->SetLength(lengthUntilEOF);
1585 entry->SetReadLength(lengthOB);
1586 entry->SetLength(lengthOB);
1589 FixDocEntryFoundLength(entry, length32);
1593 // Length is encoded on 2 bytes.
1594 length16 = ReadInt16();
1596 // FIXME : This heuristic supposes that the first group following
1597 // group 0002 *has* and element 0000.
1598 // BUT ... Element 0000 is optionnal :-(
1601 // Fixed using : HandleOutOfGroup0002()
1602 // (first hereafter strategy ...)
1604 // We can tell the current file is encoded in big endian (like
1605 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1606 // and it's value is the one of the encoding of a big endian file.
1607 // In order to deal with such big endian encoded files, we have
1608 // (at least) two strategies:
1609 // * when we load the "Transfer Syntax" tag with value of big endian
1610 // encoding, we raise the proper flags. Then we wait for the end
1611 // of the META group (0x0002) among which is "Transfer Syntax",
1612 // before switching the swap code to big endian. We have to postpone
1613 // the switching of the swap code since the META group is fully encoded
1614 // in little endian, and big endian coding only starts at the next
1615 // group. The corresponding code can be hard to analyse and adds
1616 // many additional unnecessary tests for regular tags.
1617 // * the second strategy consists in waiting for trouble, that shall
1618 // appear when we find the first group with big endian encoding. This
1619 // is easy to detect since the length of a "Group Length" tag (the
1620 // ones with zero as element number) has to be of 4 (0x0004). When we
1621 // encounter 1024 (0x0400) chances are the encoding changed and we
1622 // found a group with big endian encoding.
1623 //---> Unfortunately, element 0000 is optional.
1624 //---> This will not work when missing!
1625 // We shall use this second strategy. In order to make sure that we
1626 // can interpret the presence of an apparently big endian encoded
1627 // length of a "Group Length" without committing a big mistake, we
1628 // add an additional check: we look in the already parsed elements
1629 // for the presence of a "Transfer Syntax" whose value has to be "big
1630 // endian encoding". When this is the case, chances are we have got our
1631 // hands on a big endian encoded file: we switch the swap code to
1632 // big endian and proceed...
1634 // if ( element == 0x0000 && length16 == 0x0400 )
1636 // std::string ts = GetTransferSyntax();
1637 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1638 // != TS::ExplicitVRBigEndian )
1640 // throw FormatError( "Document::FindDocEntryLength()",
1641 // " not explicit VR." );
1645 // SwitchByteSwapCode();
1647 // // Restore the unproperly loaded values i.e. the group, the element
1648 // // and the dictionary entry depending on them.
1649 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1650 // uint16_t correctElem = SwapShort( entry->GetElement() );
1651 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1654 // // This correct tag is not in the dictionary. Create a new one.
1655 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1657 // // FIXME this can create a memory leaks on the old entry that be
1658 // // left unreferenced.
1659 // entry->SetDictEntry( newTag );
1662 // 0xffff means that we deal with 'No Length' Sequence
1663 // or 'No Length' SQItem
1664 if ( length16 == 0xffff)
1668 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1673 // Either implicit VR or a non DICOM conformal (see note below) explicit
1674 // VR that ommited the VR of (at least) this element. Farts happen.
1675 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1676 // on Data elements "Implicit and Explicit VR Data Elements shall
1677 // not coexist in a Data Set and Data Sets nested within it".]
1678 // Length is on 4 bytes.
1680 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1681 // even if Transfer Syntax is 'Implicit VR ...'
1683 FixDocEntryFoundLength( entry, ReadInt32() );
1689 * \brief Find the Value Representation of the current Dicom Element.
1690 * @return Value Representation of the current Entry
1692 std::string Document::FindDocEntryVR()
1694 if ( Filetype != ExplicitVR )
1695 return GDCM_UNKNOWN;
1697 long positionOnEntry = Fp->tellg();
1698 // Warning: we believe this is explicit VR (Value Representation) because
1699 // we used a heuristic that found "UL" in the first tag. Alas this
1700 // doesn't guarantee that all the tags will be in explicit VR. In some
1701 // cases (see e-film filtered files) one finds implicit VR tags mixed
1702 // within an explicit VR file. Hence we make sure the present tag
1703 // is in explicit VR and try to fix things if it happens not to be
1707 Fp->read (vr, (size_t)2);
1710 if( !CheckDocEntryVR(vr) )
1712 Fp->seekg(positionOnEntry, std::ios::beg);
1713 return GDCM_UNKNOWN;
1719 * \brief Check the correspondance between the VR of the header entry
1720 * and the taken VR. If they are different, the header entry is
1721 * updated with the new VR.
1722 * @param vr Dicom Value Representation
1723 * @return false if the VR is incorrect of if the VR isn't referenced
1724 * otherwise, it returns true
1726 bool Document::CheckDocEntryVR(VRKey vr)
1728 // CLEANME searching the dicom_vr at each occurence is expensive.
1729 // PostPone this test in an optional integrity check at the end
1730 // of parsing or only in debug mode.
1731 if ( !Global::GetVR()->IsValidVR(vr) )
1738 * \brief Get the transformed value of the header entry. The VR value
1739 * is used to define the transformation to operate on the value
1740 * \warning NOT end user intended method !
1741 * @param entry entry to tranform
1742 * @return Transformed entry value
1744 std::string Document::GetDocEntryValue(DocEntry *entry)
1746 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1748 std::string val = ((ValEntry *)entry)->GetValue();
1749 std::string vr = entry->GetVR();
1750 uint32_t length = entry->GetLength();
1751 std::ostringstream s;
1754 // When short integer(s) are expected, read and convert the following
1755 // n * 2 bytes properly i.e. as a multivaluated strings
1756 // (each single value is separated fromthe next one by '\'
1757 // as usual for standard multivaluated filels
1758 // Elements with Value Multiplicity > 1
1759 // contain a set of short integers (not a single one)
1761 if( vr == "US" || vr == "SS" )
1766 for (int i=0; i < nbInt; i++)
1772 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1773 newInt16 = SwapShort( newInt16 );
1778 // When integer(s) are expected, read and convert the following
1779 // n * 4 bytes properly i.e. as a multivaluated strings
1780 // (each single value is separated fromthe next one by '\'
1781 // as usual for standard multivaluated filels
1782 // Elements with Value Multiplicity > 1
1783 // contain a set of integers (not a single one)
1784 else if( vr == "UL" || vr == "SL" )
1789 for (int i=0; i < nbInt; i++)
1795 newInt32 = ( val[4*i+0] & 0xFF )
1796 + (( val[4*i+1] & 0xFF ) << 8 )
1797 + (( val[4*i+2] & 0xFF ) << 16 )
1798 + (( val[4*i+3] & 0xFF ) << 24 );
1799 newInt32 = SwapLong( newInt32 );
1803 #ifdef GDCM_NO_ANSI_STRING_STREAM
1804 s << std::ends; // to avoid oddities on Solaris
1805 #endif //GDCM_NO_ANSI_STRING_STREAM
1809 return ((ValEntry *)entry)->GetValue();
1813 * \brief Get the reverse transformed value of the header entry. The VR
1814 * value is used to define the reverse transformation to operate on
1816 * \warning NOT end user intended method !
1817 * @param entry Entry to reverse transform
1818 * @return Reverse transformed entry value
1820 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1822 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1824 std::string vr = entry->GetVR();
1825 std::vector<std::string> tokens;
1826 std::ostringstream s;
1828 if ( vr == "US" || vr == "SS" )
1832 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1833 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1834 for (unsigned int i=0; i<tokens.size(); i++)
1836 newInt16 = atoi(tokens[i].c_str());
1837 s << ( newInt16 & 0xFF )
1838 << (( newInt16 >> 8 ) & 0xFF );
1842 if ( vr == "UL" || vr == "SL")
1846 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1847 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1848 for (unsigned int i=0; i<tokens.size();i++)
1850 newInt32 = atoi(tokens[i].c_str());
1851 s << (char)( newInt32 & 0xFF )
1852 << (char)(( newInt32 >> 8 ) & 0xFF )
1853 << (char)(( newInt32 >> 16 ) & 0xFF )
1854 << (char)(( newInt32 >> 24 ) & 0xFF );
1859 #ifdef GDCM_NO_ANSI_STRING_STREAM
1860 s << std::ends; // to avoid oddities on Solaris
1861 #endif //GDCM_NO_ANSI_STRING_STREAM
1865 return ((ValEntry *)entry)->GetValue();
1869 * \brief Skip a given Header Entry
1870 * \warning NOT end user intended method !
1871 * @param entry entry to skip
1873 void Document::SkipDocEntry(DocEntry *entry)
1875 SkipBytes(entry->GetLength());
1879 * \brief Skips to the begining of the next Header Entry
1880 * \warning NOT end user intended method !
1881 * @param currentDocEntry entry to skip
1883 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1885 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1886 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1887 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1891 * \brief When the length of an element value is obviously wrong (because
1892 * the parser went Jabberwocky) one can hope improving things by
1893 * applying some heuristics.
1894 * @param entry entry to check
1895 * @param foundLength first assumption about length
1897 void Document::FixDocEntryFoundLength(DocEntry *entry,
1898 uint32_t foundLength)
1900 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1901 if ( foundLength == 0xffffffff)
1906 uint16_t gr = entry->GetGroup();
1907 uint16_t elem = entry->GetElement();
1909 if ( foundLength % 2)
1911 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1912 << " in x(" << std::hex << gr << "," << elem <<")");
1915 //////// Fix for some naughty General Electric images.
1916 // Allthough not recent many such GE corrupted images are still present
1917 // on Creatis hard disks. Hence this fix shall remain when such images
1918 // are no longer in use (we are talking a few years, here)...
1919 // Note: XMedCom probably uses such a trick since it is able to read
1920 // those pesky GE images ...
1921 if ( foundLength == 13)
1923 // Only happens for this length !
1924 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1927 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1931 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1932 // Occurence of such images is quite low (unless one leaves close to a
1933 // 'Leonardo' source. Hence, one might consider commenting out the
1934 // following fix on efficiency reasons.
1935 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1938 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1941 else if ( entry->GetVR() == "SQ" )
1943 foundLength = 0; // ReadLength is unchanged
1946 //////// We encountered a 'delimiter' element i.e. a tag of the form
1947 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1948 // taken into account.
1949 else if( gr == 0xfffe )
1951 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1952 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1953 // causes extra troubles...
1954 if( entry->GetElement() != 0x0000 )
1960 entry->SetLength(foundLength);
1964 * \brief Apply some heuristics to predict whether the considered
1965 * element value contains/represents an integer or not.
1966 * @param entry The element value on which to apply the predicate.
1967 * @return The result of the heuristical predicate.
1969 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1971 uint16_t elem = entry->GetElement();
1972 uint16_t group = entry->GetGroup();
1973 const std::string &vr = entry->GetVR();
1974 uint32_t length = entry->GetLength();
1976 // When we have some semantics on the element we just read, and if we
1977 // a priori know we are dealing with an integer, then we shall be
1978 // able to swap it's element value properly.
1979 if ( elem == 0 ) // This is the group length of the group
1987 // Allthough this should never happen, still some images have a
1988 // corrupted group length [e.g. have a glance at offset x(8336) of
1989 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1990 // Since for dicom compliant and well behaved headers, the present
1991 // test is useless (and might even look a bit paranoid), when we
1992 // encounter such an ill-formed image, we simply display a warning
1993 // message and proceed on parsing (while crossing fingers).
1994 long filePosition = Fp->tellg();
1995 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1996 << std::hex << group << " , " << elem
1997 << ") -before- position x(" << filePosition << ")"
1998 << "lgt : " << length );
2002 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2010 * \brief Find the Length till the next sequence delimiter
2011 * \warning NOT end user intended method !
2015 uint32_t Document::FindDocEntryLengthOBOrOW()
2016 throw( FormatUnexpected )
2018 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2019 long positionOnEntry = Fp->tellg();
2020 bool foundSequenceDelimiter = false;
2021 uint32_t totalLength = 0;
2023 while ( !foundSequenceDelimiter )
2029 group = ReadInt16();
2032 catch ( FormatError )
2034 throw FormatError("Unexpected end of file encountered during ",
2035 "Document::FindDocEntryLengthOBOrOW()");
2038 // We have to decount the group and element we just read
2041 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2043 long filePosition = Fp->tellg();
2044 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
2045 << std::hex << group << " , " << elem
2046 << ") -before- position x(" << filePosition << ")" );
2048 Fp->seekg(positionOnEntry, std::ios::beg);
2049 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
2052 if ( elem == 0xe0dd )
2054 foundSequenceDelimiter = true;
2057 uint32_t itemLength = ReadInt32();
2058 // We add 4 bytes since we just read the ItemLength with ReadInt32
2059 totalLength += itemLength + 4;
2060 SkipBytes(itemLength);
2062 if ( foundSequenceDelimiter )
2067 Fp->seekg( positionOnEntry, std::ios::beg);
2072 * \brief Reads a supposed to be 16 Bits integer
2073 * (swaps it depending on processor endianity)
2074 * @return read value
2076 uint16_t Document::ReadInt16()
2077 throw( FormatError )
2080 Fp->read ((char*)&g, (size_t)2);
2083 throw FormatError( "Document::ReadInt16()", " file error." );
2087 throw FormatError( "Document::ReadInt16()", "EOF." );
2094 * \brief Reads a supposed to be 32 Bits integer
2095 * (swaps it depending on processor endianity)
2096 * @return read value
2098 uint32_t Document::ReadInt32()
2099 throw( FormatError )
2102 Fp->read ((char*)&g, (size_t)4);
2105 throw FormatError( "Document::ReadInt32()", " file error." );
2109 throw FormatError( "Document::ReadInt32()", "EOF." );
2116 * \brief skips bytes inside the source file
2117 * \warning NOT end user intended method !
2120 void Document::SkipBytes(uint32_t nBytes)
2122 //FIXME don't dump the returned value
2123 Fp->seekg((long)nBytes, std::ios::cur);
2127 * \brief Loads all the needed Dictionaries
2128 * \warning NOT end user intended method !
2130 void Document::Initialize()
2132 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2134 RLEInfo = new RLEFramesInfo;
2135 JPEGInfo = new JPEGFragmentsInfo;
2140 * \brief Discover what the swap code is (among little endian, big endian,
2141 * bad little endian, bad big endian).
2143 * @return false when we are absolutely sure
2144 * it's neither ACR-NEMA nor DICOM
2145 * true when we hope ours assuptions are OK
2147 bool Document::CheckSwap()
2149 // The only guaranted way of finding the swap code is to find a
2150 // group tag since we know it's length has to be of four bytes i.e.
2151 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2152 // occurs when we can't find such group...
2154 uint32_t x = 4; // x : for ntohs
2155 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2161 // First, compare HostByteOrder and NetworkByteOrder in order to
2162 // determine if we shall need to swap bytes (i.e. the Endian type).
2163 if ( x == ntohs(x) )
2172 // The easiest case is the one of a 'true' DICOM header, we just have
2173 // to look for the string "DICM" inside the file preamble.
2176 char *entCur = deb + 128;
2177 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2179 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2181 // Group 0002 should always be VR, and the first element 0000
2182 // Let's be carefull (so many wrong headers ...)
2183 // and determine the value representation (VR) :
2184 // Let's skip to the first element (0002,0000) and check there if we find
2185 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2186 // in which case we (almost) know it is explicit VR.
2187 // WARNING: if it happens to be implicit VR then what we will read
2188 // is the length of the group. If this ascii representation of this
2189 // length happens to be "UL" then we shall believe it is explicit VR.
2190 // We need to skip :
2191 // * the 128 bytes of File Preamble (often padded with zeroes),
2192 // * the 4 bytes of "DICM" string,
2193 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2194 // i.e. a total of 136 bytes.
2197 // group 0x0002 *is always* Explicit VR Sometimes ,
2198 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2199 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2201 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2202 memcmp(entCur, "OB", (size_t)2) == 0 ||
2203 memcmp(entCur, "UI", (size_t)2) == 0 ||
2204 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2205 // when Write DCM *adds*
2207 // Use Document::dicom_vr to test all the possibilities
2208 // instead of just checking for UL, OB and UI !? group 0000
2210 Filetype = ExplicitVR;
2211 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2215 Filetype = ImplicitVR;
2216 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2217 << "Looks like a bugged Header!");
2223 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2228 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2231 // Position the file position indicator at first tag
2232 // (i.e. after the file preamble and the "DICM" string).
2233 Fp->seekg(0, std::ios::beg);
2234 Fp->seekg ( 132L, std::ios::beg);
2238 // Alas, this is not a DicomV3 file and whatever happens there is no file
2239 // preamble. We can reset the file position indicator to where the data
2240 // is (i.e. the beginning of the file).
2241 gdcmVerboseMacro( "Not a DICOM Version3 file");
2242 Fp->seekg(0, std::ios::beg);
2244 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2245 // By clean we mean that the length of the first tag is written down.
2246 // If this is the case and since the length of the first group HAS to be
2247 // four (bytes), then determining the proper swap code is straightforward.
2250 // We assume the array of char we are considering contains the binary
2251 // representation of a 32 bits integer. Hence the following dirty
2253 s32 = *((uint32_t *)(entCur));
2274 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2275 // It is time for despaired wild guesses.
2276 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2277 // i.e. the 'group length' element is not present :
2279 // check the supposed-to-be 'group number'
2280 // in ( 0x0001 .. 0x0008 )
2281 // to determine ' SwapCode' value .
2282 // Only 0 or 4321 will be possible
2283 // (no oportunity to check for the formerly well known
2284 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2285 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2286 // the file IS NOT ACR-NEMA nor DICOM V3
2287 // Find a trick to tell it the caller...
2289 s16 = *((uint16_t *)(deb));
2316 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2324 * \brief Change the Byte Swap code.
2326 void Document::SwitchByteSwapCode()
2328 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2329 if ( SwapCode == 1234 )
2333 else if ( SwapCode == 4321 )
2337 else if ( SwapCode == 3412 )
2341 else if ( SwapCode == 2143 )
2348 * \brief during parsing, Header Elements too long are not loaded in memory
2351 void Document::SetMaxSizeLoadEntry(long newSize)
2357 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2359 MaxSizeLoadEntry = 0xffffffff;
2362 MaxSizeLoadEntry = newSize;
2367 * \brief Header Elements too long will not be printed
2368 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2371 void Document::SetMaxSizePrintEntry(long newSize)
2377 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2379 MaxSizePrintEntry = 0xffffffff;
2382 MaxSizePrintEntry = newSize;
2388 * \brief Handle broken private tag from Philips NTSCAN
2389 * where the endianess is being switch to BigEndian for no
2393 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2395 // Endian reversion. Some files contain groups of tags with reversed endianess.
2396 static int reversedEndian = 0;
2397 // try to fix endian switching in the middle of headers
2398 if ((group == 0xfeff) && (elem == 0x00e0))
2400 // start endian swap mark for group found
2402 SwitchByteSwapCode();
2407 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2409 // end of reversed endian group
2411 SwitchByteSwapCode();
2416 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2417 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2419 std::string Document::GetTransferSyntaxName()
2421 // use the TS (TS : Transfer Syntax)
2422 std::string transferSyntax = GetEntry(0x0002,0x0010);
2424 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2426 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2427 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2428 return "Uncompressed ACR-NEMA";
2430 if ( transferSyntax == GDCM_UNFOUND )
2432 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2433 return "Uncompressed ACR-NEMA";
2436 // we do it only when we need it
2437 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2439 // Global::GetTS() is a global static you shall never try to delete it!
2444 * \brief Group 0002 is always coded Little Endian
2445 * whatever Transfer Syntax is
2448 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2450 // Endian reversion. Some files contain groups of tags with reversed endianess.
2451 if ( !Group0002Parsed && group != 0x0002)
2453 Group0002Parsed = true;
2454 // we just came out of group 0002
2455 // if Transfer syntax is Big Endian we have to change CheckSwap
2457 std::string ts = GetTransferSyntax();
2458 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2460 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2464 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2466 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2468 Filetype = ImplicitVR;
2471 // FIXME Strangely, this works with
2472 //'Implicit VR Transfer Syntax (GE Private)
2473 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2475 gdcmVerboseMacro("Transfer Syntax Name = ["
2476 << GetTransferSyntaxName() << "]" );
2477 SwitchByteSwapCode();
2478 group = SwapShort(group);
2479 elem = SwapShort(elem);
2485 * \brief Read the next tag but WITHOUT loading it's value
2486 * (read the 'Group Number', the 'Element Number',
2487 * gets the Dict Entry
2488 * gets the VR, gets the length, gets the offset value)
2489 * @return On succes the newly created DocEntry, NULL on failure.
2491 DocEntry *Document::ReadNextDocEntry()
2498 group = ReadInt16();
2501 catch ( FormatError e )
2503 // We reached the EOF (or an error occured) therefore
2504 // header parsing has to be considered as finished.
2509 // Sometimes file contains groups of tags with reversed endianess.
2510 HandleBrokenEndian(group, elem);
2512 // In 'true DICOM' files Group 0002 is always little endian
2513 if ( HasDCMPreamble )
2514 HandleOutOfGroup0002(group, elem);
2516 std::string vr = FindDocEntryVR();
2517 std::string realVR = vr;
2519 if( vr == GDCM_UNKNOWN)
2521 DictEntry *dictEntry = GetDictEntry(group,elem);
2523 realVR = dictEntry->GetVR();
2527 if( Global::GetVR()->IsVROfSequence(realVR) )
2528 newEntry = NewSeqEntry(group, elem);
2529 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2530 newEntry = NewValEntry(group, elem,vr);
2532 newEntry = NewBinEntry(group, elem,vr);
2534 if( vr == GDCM_UNKNOWN )
2536 if( Filetype == ExplicitVR )
2538 // We thought this was explicit VR, but we end up with an
2539 // implicit VR tag. Let's backtrack.
2540 if ( newEntry->GetGroup() != 0xfffe )
2543 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2544 newEntry->GetGroup(), newEntry->GetElement());
2545 gdcmVerboseMacro( msg.c_str() );
2548 newEntry->SetImplicitVR();
2553 FindDocEntryLength(newEntry);
2555 catch ( FormatError e )
2563 newEntry->SetOffset(Fp->tellg());
2570 * \brief Generate a free TagKey i.e. a TagKey that is not present
2571 * in the TagHt dictionary.
2572 * @param group The generated tag must belong to this group.
2573 * @return The element of tag with given group which is fee.
2575 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2577 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2579 TagKey key = DictEntry::TranslateToKey(group, elem);
2580 if (TagHT.count(key) == 0)
2589 * \brief Assuming the internal file pointer \ref Document::Fp
2590 * is placed at the beginning of a tag check whether this
2591 * tag is (TestGroup, TestElement).
2592 * \warning On success the internal file pointer \ref Document::Fp
2593 * is modified to point after the tag.
2594 * On failure (i.e. when the tag wasn't the expected tag
2595 * (TestGroup, TestElement) the internal file pointer
2596 * \ref Document::Fp is restored to it's original position.
2597 * @param testGroup The expected group of the tag.
2598 * @param testElement The expected Element of the tag.
2599 * @return True on success, false otherwise.
2601 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2603 long positionOnEntry = Fp->tellg();
2604 long currentPosition = Fp->tellg(); // On debugging purposes
2606 //// Read the Item Tag group and element, and make
2607 // sure they are what we expected:
2608 uint16_t itemTagGroup;
2609 uint16_t itemTagElement;
2612 itemTagGroup = ReadInt16();
2613 itemTagElement = ReadInt16();
2615 catch ( FormatError e )
2617 //std::cerr << e << std::endl;
2620 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2622 gdcmVerboseMacro( "Wrong Item Tag found:"
2623 << " We should have found tag ("
2624 << std::hex << testGroup << "," << testElement << ")" << std::endl
2625 << " but instead we encountered tag ("
2626 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2627 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2629 Fp->seekg(positionOnEntry, std::ios::beg);
2637 * \brief Assuming the internal file pointer \ref Document::Fp
2638 * is placed at the beginning of a tag (TestGroup, TestElement),
2639 * read the length associated to the Tag.
2640 * \warning On success the internal file pointer \ref Document::Fp
2641 * is modified to point after the tag and it's length.
2642 * On failure (i.e. when the tag wasn't the expected tag
2643 * (TestGroup, TestElement) the internal file pointer
2644 * \ref Document::Fp is restored to it's original position.
2645 * @param testGroup The expected group of the tag.
2646 * @param testElement The expected Element of the tag.
2647 * @return On success returns the length associated to the tag. On failure
2650 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2653 if ( !ReadTag(testGroup, testElement) )
2658 //// Then read the associated Item Length
2659 long currentPosition = Fp->tellg();
2660 uint32_t itemLength = ReadInt32();
2662 gdcmVerboseMacro( "Basic Item Length is: "
2663 << itemLength << std::endl
2664 << " at address: " << std::hex << (unsigned int)currentPosition);
2670 * \brief When parsing the Pixel Data of an encapsulated file, read
2671 * the basic offset table (when present, and BTW dump it).
2673 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2675 //// Read the Basic Offset Table Item Tag length...
2676 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2678 // When present, read the basic offset table itself.
2679 // Notes: - since the presence of this basic offset table is optional
2680 // we can't rely on it for the implementation, and we will simply
2681 // trash it's content (when present).
2682 // - still, when present, we could add some further checks on the
2683 // lengths, but we won't bother with such fuses for the time being.
2684 if ( itemLength != 0 )
2686 char *basicOffsetTableItemValue = new char[itemLength + 1];
2687 Fp->read(basicOffsetTableItemValue, itemLength);
2690 for (unsigned int i=0; i < itemLength; i += 4 )
2692 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2694 gdcmVerboseMacro( "Read one length: " <<
2695 std::hex << individualLength );
2699 delete[] basicOffsetTableItemValue;
2704 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2705 * Compute the RLE extra information and store it in \ref RLEInfo
2706 * for later pixel retrieval usage.
2708 void Document::ComputeRLEInfo()
2710 std::string ts = GetTransferSyntax();
2711 if ( !Global::GetTS()->IsRLELossless(ts) )
2716 // Encoded pixel data: for the time being we are only concerned with
2717 // Jpeg or RLE Pixel data encodings.
2718 // As stated in PS 3.5-2003, section 8.2 p44:
2719 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2720 // value representation OB is used".
2721 // Hence we expect an OB value representation. Concerning OB VR,
2722 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2723 // "For the Value Representations OB and OW, the encoding shall meet the
2724 // following specifications depending on the Data element tag:"
2726 // - the first item in the sequence of items before the encoded pixel
2727 // data stream shall be basic offset table item. The basic offset table
2728 // item value, however, is not required to be present"
2730 ReadAndSkipEncapsulatedBasicOffsetTable();
2732 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2733 // Loop on the individual frame[s] and store the information
2734 // on the RLE fragments in a RLEFramesInfo.
2735 // Note: - when only a single frame is present, this is a
2737 // - when more than one frame are present, then we are in
2738 // the case of a multi-frame image.
2740 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2742 // Parse the RLE Header and store the corresponding RLE Segment
2743 // Offset Table information on fragments of this current Frame.
2744 // Note that the fragment pixels themselves are not loaded
2745 // (but just skipped).
2746 long frameOffset = Fp->tellg();
2748 uint32_t nbRleSegments = ReadInt32();
2749 if ( nbRleSegments > 16 )
2751 // There should be at most 15 segments (refer to RLEFrame class)
2752 gdcmVerboseMacro( "Too many segments.");
2755 uint32_t rleSegmentOffsetTable[16];
2756 for( int k = 1; k <= 15; k++ )
2758 rleSegmentOffsetTable[k] = ReadInt32();
2761 // Deduce from both the RLE Header and the frameLength the
2762 // fragment length, and again store this info in a
2764 long rleSegmentLength[15];
2765 // skipping (not reading) RLE Segments
2766 if ( nbRleSegments > 1)
2768 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2770 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2771 - rleSegmentOffsetTable[k];
2772 SkipBytes(rleSegmentLength[k]);
2776 rleSegmentLength[nbRleSegments] = frameLength
2777 - rleSegmentOffsetTable[nbRleSegments];
2778 SkipBytes(rleSegmentLength[nbRleSegments]);
2780 // Store the collected info
2781 RLEFrame *newFrameInfo = new RLEFrame;
2782 newFrameInfo->NumberFragments = nbRleSegments;
2783 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2785 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2786 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2788 RLEInfo->Frames.push_back( newFrameInfo );
2791 // Make sure that at the end of the item we encounter a 'Sequence
2793 if ( !ReadTag(0xfffe, 0xe0dd) )
2795 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2800 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2801 * Compute the jpeg extra information (fragment[s] offset[s] and
2802 * length) and store it[them] in \ref JPEGInfo for later pixel
2805 void Document::ComputeJPEGFragmentInfo()
2807 // If you need to, look for comments of ComputeRLEInfo().
2808 std::string ts = GetTransferSyntax();
2809 if ( ! Global::GetTS()->IsJPEG(ts) )
2814 ReadAndSkipEncapsulatedBasicOffsetTable();
2816 // Loop on the fragments[s] and store the parsed information in a
2818 long fragmentLength;
2819 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2821 long fragmentOffset = Fp->tellg();
2823 // Store the collected info
2824 JPEGFragment *newFragment = new JPEGFragment;
2825 newFragment->Offset = fragmentOffset;
2826 newFragment->Length = fragmentLength;
2827 JPEGInfo->Fragments.push_back( newFragment );
2829 SkipBytes( fragmentLength );
2832 // Make sure that at the end of the item we encounter a 'Sequence
2834 if ( !ReadTag(0xfffe, 0xe0dd) )
2836 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2841 * \brief Walk recursively the given \ref DocEntrySet, and feed
2842 * the given hash table (\ref TagDocEntryHT) with all the
2843 * \ref DocEntry (Dicom entries) encountered.
2844 * This method does the job for \ref BuildFlatHashTable.
2845 * @param builtHT Where to collect all the \ref DocEntry encountered
2846 * when recursively walking the given set.
2847 * @param set The structure to be traversed (recursively).
2849 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2852 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2854 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2855 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2856 i != currentHT.end();
2859 DocEntry *entry = i->second;
2860 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2862 const ListSQItem& items = seqEntry->GetSQItems();
2863 for( ListSQItem::const_iterator item = items.begin();
2864 item != items.end();
2867 BuildFlatHashTableRecurse( builtHT, *item );
2871 builtHT[entry->GetKey()] = entry;
2876 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2878 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2879 for (ListDocEntry::const_iterator i = currentList.begin();
2880 i != currentList.end();
2883 DocEntry *entry = *i;
2884 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2886 const ListSQItem& items = seqEntry->GetSQItems();
2887 for( ListSQItem::const_iterator item = items.begin();
2888 item != items.end();
2891 BuildFlatHashTableRecurse( builtHT, *item );
2895 builtHT[entry->GetKey()] = entry;
2902 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2905 * The structure used by a Document (through \ref ElementSet),
2906 * in order to hold the parsed entries of a Dicom header, is a recursive
2907 * one. This is due to the fact that the sequences (when present)
2908 * can be nested. Additionaly, the sequence items (represented in
2909 * gdcm as \ref SQItem) add an extra complexity to the data
2910 * structure. Hence, a gdcm user whishing to visit all the entries of
2911 * a Dicom header will need to dig in the gdcm internals (which
2912 * implies exposing all the internal data structures to the API).
2913 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2914 * recursively builds a temporary hash table, which holds all the
2915 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2917 * \warning Of course there is NO integrity constrain between the
2918 * returned \ref TagDocEntryHT and the \ref ElementSet used
2919 * to build it. Hence if the underlying \ref ElementSet is
2920 * altered, then it is the caller responsability to invoke
2921 * \ref BuildFlatHashTable again...
2922 * @return The flat std::map<> we juste build.
2924 /*TagDocEntryHT *Document::BuildFlatHashTable()
2926 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2927 BuildFlatHashTableRecurse( *FlatHT, this );
2934 * \brief Compares two documents, according to \ref DicomDir rules
2935 * \warning Does NOT work with ACR-NEMA files
2936 * \todo Find a trick to solve the pb (use RET fields ?)
2938 * @return true if 'smaller'
2940 bool Document::operator<(Document &document)
2943 std::string s1 = GetEntry(0x0010,0x0010);
2944 std::string s2 = document.GetEntry(0x0010,0x0010);
2956 s1 = GetEntry(0x0010,0x0020);
2957 s2 = document.GetEntry(0x0010,0x0020);
2968 // Study Instance UID
2969 s1 = GetEntry(0x0020,0x000d);
2970 s2 = document.GetEntry(0x0020,0x000d);
2981 // Serie Instance UID
2982 s1 = GetEntry(0x0020,0x000e);
2983 s2 = document.GetEntry(0x0020,0x000e);
3000 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
3001 * @param filetype Type of the File to be written
3003 int Document::ComputeGroup0002Length( FileType filetype )
3008 int groupLength = 0;
3009 bool found0002 = false;
3011 // for each zero-level Tag in the DCM Header
3012 DocEntry *entry = GetFirstEntry();
3015 gr = entry->GetGroup();
3021 el = entry->GetElement();
3022 vr = entry->GetVR();
3024 if (filetype == ExplicitVR)
3026 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
3028 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
3031 groupLength += 2 + 2 + 4 + entry->GetLength();
3033 else if (found0002 )
3036 entry = GetNextEntry();
3041 } // end namespace gdcm
3043 //-----------------------------------------------------------------------------