1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/25 15:44:23 $
7 Version: $Revision: 1.210 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmRLEFramesInfo.h"
29 #include "gdcmJPEGFragmentsInfo.h"
30 #include "gdcmDocEntrySet.h"
31 #include "gdcmSQItem.h"
37 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
41 #ifdef CMAKE_HAVE_NETINET_IN_H
42 #include <netinet/in.h>
48 //-----------------------------------------------------------------------------
49 // Refer to Document::CheckSwap()
50 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
52 // Refer to Document::SetMaxSizeLoadEntry()
53 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
54 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
56 //-----------------------------------------------------------------------------
57 // Constructor / Destructor
61 * @param filename 'Document' (File or DicomDir) to be opened for parsing
63 Document::Document( std::string const &filename ) : ElementSet(-1)
68 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
78 Group0002Parsed = false;
80 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
81 // Fp->seekg( 0, std::ios::beg);
83 Fp->seekg(0, std::ios::end);
84 long lgt = Fp->tellg();
86 Fp->seekg( 0, std::ios::beg);
89 long beg = Fp->tellg();
92 ParseDES( this, beg, lgt, false); // Loading is done during parsing
94 Fp->seekg( 0, std::ios::beg);
96 // Load 'non string' values
98 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
99 if( PhotometricInterpretation == "PALETTE COLOR " )
101 LoadEntryBinArea(0x0028,0x1200); // gray LUT
102 /// FIXME FIXME FIXME
103 /// The tags refered by the three following lines used to be CORRECTLY
104 /// defined as having an US Value Representation in the public
105 /// dictionary. BUT the semantics implied by the three following
106 /// lines state that the corresponding tag contents are in fact
107 /// the ones of a BinEntry.
108 /// In order to fix things "Quick and Dirty" the dictionary was
109 /// altered on PURPOSE but now contains a WRONG value.
110 /// In order to fix things and restore the dictionary to its
111 /// correct value, one needs to decided of the semantics by deciding
112 /// whether the following tags are either:
113 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
114 /// also used as BinEntry, which requires the proper conversion,
115 /// - OW, and hence loaded as BinEntry, but afterwards also used
116 /// as ValEntry, which requires the proper conversion.
117 LoadEntryBinArea(0x0028,0x1201); // R LUT
118 LoadEntryBinArea(0x0028,0x1202); // G LUT
119 LoadEntryBinArea(0x0028,0x1203); // B LUT
121 // Segmented Red Palette Color LUT Data
122 LoadEntryBinArea(0x0028,0x1221);
123 // Segmented Green Palette Color LUT Data
124 LoadEntryBinArea(0x0028,0x1222);
125 // Segmented Blue Palette Color LUT Data
126 LoadEntryBinArea(0x0028,0x1223);
128 //FIXME later : how to use it?
129 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
133 // --------------------------------------------------------------
134 // Specific code to allow gdcm to read ACR-LibIDO formated images
135 // Note: ACR-LibIDO is an extension of the ACR standard that was
136 // used at CREATIS. For the time being (say a couple years)
137 // we keep this kludge to allow a smooth move to gdcm for
138 // CREATIS developpers (sorry folks).
140 // if recognition code tells us we deal with a LibIDO image
141 // we switch lineNumber and columnNumber
144 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
145 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
146 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
147 // with "little-endian strings"
149 Filetype = ACR_LIBIDO;
150 std::string rows = GetEntryValue(0x0028, 0x0010);
151 std::string columns = GetEntryValue(0x0028, 0x0011);
152 SetValEntry(columns, 0x0028, 0x0010);
153 SetValEntry(rows , 0x0028, 0x0011);
155 // ----------------- End of ACR-LibIDO kludge ------------------
159 * \brief This default constructor doesn't parse the file. You should
160 * then invoke \ref Document::SetFileName and then the parsing.
162 Document::Document() : ElementSet(-1)
169 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
172 Filetype = ExplicitVR;
173 Group0002Parsed = false;
177 * \brief Canonical destructor.
179 Document::~Document ()
190 //-----------------------------------------------------------------------------
194 * \brief Prints The Dict Entries of THE public Dicom Dictionary
197 void Document::PrintPubDict(std::ostream &os)
199 RefPubDict->SetPrintLevel(PrintLevel);
200 RefPubDict->Print(os);
204 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
207 void Document::PrintShaDict(std::ostream &os)
209 RefShaDict->SetPrintLevel(PrintLevel);
210 RefShaDict->Print(os);
213 //-----------------------------------------------------------------------------
216 * \brief Get the public dictionary used
218 Dict *Document::GetPubDict()
224 * \brief Get the shadow dictionary used
226 Dict *Document::GetShaDict()
232 * \brief Set the shadow dictionary used
233 * @param dict dictionary to use in shadow
235 bool Document::SetShaDict(Dict *dict)
242 * \brief Set the shadow dictionary used
243 * @param dictName name of the dictionary to use in shadow
245 bool Document::SetShaDict(DictKey const &dictName)
247 RefShaDict = Global::GetDicts()->GetDict(dictName);
252 * \brief This predicate, based on hopefully reasonable heuristics,
253 * decides whether or not the current Document was properly parsed
254 * and contains the mandatory information for being considered as
255 * a well formed and usable Dicom/Acr File.
256 * @return true when Document is the one of a reasonable Dicom/Acr file,
259 bool Document::IsReadable()
261 if( Filetype == Unknown)
263 gdcmVerboseMacro( "Wrong filetype");
269 gdcmVerboseMacro( "No tag in internal hash table.");
277 * \brief Accessor to the Transfer Syntax (when present) of the
278 * current document (it internally handles reading the
279 * value from disk when only parsing occured).
280 * @return The encountered Transfer Syntax of the current document.
282 std::string Document::GetTransferSyntax()
284 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
290 // The entry might be present but not loaded (parsing and loading
291 // happen at different stages): try loading and proceed with check...
292 LoadDocEntrySafe(entry);
293 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
295 std::string transfer = valEntry->GetValue();
296 // The actual transfer (as read from disk) might be padded. We
297 // first need to remove the potential padding. We can make the
298 // weak assumption that padding was not executed with digits...
299 if ( transfer.length() == 0 )
301 // for brain damaged headers
304 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
306 transfer.erase(transfer.length()-1, 1);
314 * \brief Predicate for dicom version 3 file.
315 * @return True when the file is a dicom version 3.
317 bool Document::IsDicomV3()
319 // Checking if Transfer Syntax exists is enough
320 // Anyway, it's to late check if the 'Preamble' was found ...
321 // And ... would it be a rich idea to check ?
322 // (some 'no Preamble' DICOM images exist !)
323 return GetDocEntry(0x0002, 0x0010) != NULL;
327 * \brief Predicate for Papyrus file
328 * Dedicated to whomsoever it may concern
329 * @return True when the file is a Papyrus file.
331 bool Document::IsPapyrus()
333 // check for Papyrus private Sequence
334 DocEntry *e = GetDocEntry(0x0041, 0x1050);
337 // check if it's actually a Sequence
338 if ( !dynamic_cast<SeqEntry*>(e) )
344 * \brief returns the File Type
345 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
346 * @return the FileType code
348 FileType Document::GetFileType()
354 * \brief Tries to open the file \ref Document::Filename and
355 * checks the preamble when existing.
356 * @return The FILE pointer on success.
358 std::ifstream *Document::OpenFile()
361 HasDCMPreamble = false;
362 if (Filename.length() == 0)
369 gdcmVerboseMacro( "File already open: " << Filename.c_str());
372 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
375 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
382 Fp->read((char*)&zero, (size_t)2);
389 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
391 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
392 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
393 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
394 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
397 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
398 gdcmVerboseMacro( msg.c_str() );
403 Fp->seekg(126L, std::ios::cur);
405 Fp->read(dicm, (size_t)4);
411 if( memcmp(dicm, "DICM", 4) == 0 )
413 HasDCMPreamble = true;
418 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
424 * \brief closes the file
425 * @return TRUE if the close was successfull
427 bool Document::CloseFile()
436 return true; //FIXME how do we detect a non-closed ifstream ?
440 * \brief Writes in a file all the Header Entries (Dicom Elements)
441 * @param fp file pointer on an already open file (actually: Output File Stream)
442 * @param filetype Type of the File to be written
443 * (ACR-NEMA, ExplicitVR, ImplicitVR)
444 * \return Always true.
446 void Document::WriteContent(std::ofstream *fp, FileType filetype)
448 /// \todo move the following lines (and a lot of others, to be written)
449 /// to a future function CheckAndCorrectHeader
450 /// (necessary if user wants to write a DICOM V3 file
451 /// starting from an ACR-NEMA (V2) Header
453 if ( filetype == ImplicitVR || filetype == ExplicitVR )
455 // writing Dicom File Preamble
456 char filePreamble[128];
457 memset(filePreamble, 0, 128);
458 fp->write(filePreamble, 128);
459 fp->write("DICM", 4);
463 * \todo rewrite later, if really usefull
464 * - 'Group Length' element is optional in DICOM
465 * - but un-updated odd groups lengthes can causes pb
468 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
469 * UpdateGroupLength(false,filetype);
470 * if ( filetype == ACR)
471 * UpdateGroupLength(true,ACR);
474 ElementSet::WriteContent(fp, filetype); // This one is recursive
477 //-----------------------------------------------------------------------------
480 * \brief Loads (from disk) the element content
481 * when a string is not suitable
482 * @param group group number of the Entry
483 * @param elem element number of the Entry
485 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
487 // Search the corresponding DocEntry
488 DocEntry *docElement = GetDocEntry(group, elem);
492 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
496 LoadEntryBinArea(binElement);
500 * \brief Loads (from disk) the element content
501 * when a string is not suitable
502 * @param elem Entry whose binArea is going to be loaded
504 void Document::LoadEntryBinArea(BinEntry *elem)
506 if(elem->GetBinArea())
513 size_t o =(size_t)elem->GetOffset();
514 Fp->seekg(o, std::ios::beg);
516 size_t l = elem->GetLength();
517 uint8_t *a = new uint8_t[l];
520 gdcmVerboseMacro( "Cannot allocate BinEntry content");
524 /// \todo check the result
525 Fp->read((char*)a, l);
526 if( Fp->fail() || Fp->eof())
539 * \brief Sets a 'non string' value to a given Dicom Element
540 * @param area area containing the 'non string' value
541 * @param group Group number of the searched Dicom Element
542 * @param elem Element number of the searched Dicom Element
545 /*bool Document::SetEntryBinArea(uint8_t *area,
546 uint16_t group, uint16_t elem)
548 DocEntry *currentEntry = GetDocEntry(group, elem);
554 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
556 binEntry->SetBinArea( area );
565 * \brief Loads the element while preserving the current
566 * underlying file position indicator as opposed to
567 * LoadDocEntry that modifies it.
568 * @param entry Header Entry whose value will be loaded.
571 void Document::LoadDocEntrySafe(DocEntry *entry)
575 long PositionOnEntry = Fp->tellg();
577 Fp->seekg(PositionOnEntry, std::ios::beg);
582 * \brief Swaps back the bytes of 4-byte long integer accordingly to
584 * @return The properly swaped 32 bits integer.
586 uint32_t Document::SwapLong(uint32_t a)
593 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
594 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
597 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
600 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
603 gdcmErrorMacro( "Unset swap code:" << SwapCode );
610 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
612 * @return The properly unswaped 32 bits integer.
614 uint32_t Document::UnswapLong(uint32_t a)
620 * \brief Swaps the bytes so they agree with the processor order
621 * @return The properly swaped 16 bits integer.
623 uint16_t Document::SwapShort(uint16_t a)
625 if ( SwapCode == 4321 || SwapCode == 2143 )
627 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
633 * \brief Unswaps the bytes so they agree with the processor order
634 * @return The properly unswaped 16 bits integer.
636 uint16_t Document::UnswapShort(uint16_t a)
641 //-----------------------------------------------------------------------------
645 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
646 * @return length of the parsed set.
648 void Document::ParseDES(DocEntrySet *set, long offset,
649 long l_max, bool delim_mode)
651 DocEntry *newDocEntry = 0;
652 ValEntry *newValEntry;
653 BinEntry *newBinEntry;
654 SeqEntry *newSeqEntry;
660 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
666 newDocEntry = ReadNextDocEntry( );
673 vr = newDocEntry->GetVR();
674 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
675 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
676 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
678 if ( newValEntry || newBinEntry )
682 if ( Filetype == ExplicitVR &&
683 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
685 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
686 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
687 << "|" << newDocEntry->GetElement()
688 << " : Neither Valentry, nor BinEntry."
689 "Probably unknown VR.");
692 //////////////////// BinEntry or UNKOWN VR:
693 // When "this" is a Document the Key is simply of the
694 // form ( group, elem )...
695 if ( dynamic_cast< Document* > ( set ) )
697 newBinEntry->SetKey( newBinEntry->GetKey() );
699 // but when "this" is a SQItem, we are inserting this new
700 // valEntry in a sequence item, and the key has the
701 // generalized form (refer to \ref BaseTagKey):
702 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
704 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
705 + newBinEntry->GetKey() );
708 LoadDocEntry( newBinEntry );
709 if( !set->AddEntry( newBinEntry ) )
711 //Expect big troubles if here
712 //delete newBinEntry;
718 /////////////////////// ValEntry
719 // When "set" is a Document, then we are at the top of the
720 // hierarchy and the Key is simply of the form ( group, elem )...
721 if ( dynamic_cast< Document* > ( set ) )
723 newValEntry->SetKey( newValEntry->GetKey() );
725 // ...but when "set" is a SQItem, we are inserting this new
726 // valEntry in a sequence item. Hence the key has the
727 // generalized form (refer to \ref BaseTagKey):
728 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
730 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
731 + newValEntry->GetKey() );
734 LoadDocEntry( newValEntry );
735 bool delimitor=newValEntry->IsItemDelimitor();
736 if( !set->AddEntry( newValEntry ) )
738 // If here expect big troubles
739 //delete newValEntry; //otherwise mem leak
749 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
757 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
758 && ( newDocEntry->GetElement() == 0x0010 ) )
760 std::string ts = GetTransferSyntax();
761 if ( Global::GetTS()->IsRLELossless(ts) )
763 long positionOnEntry = Fp->tellg();
764 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
766 Fp->seekg( positionOnEntry, std::ios::beg );
768 else if ( Global::GetTS()->IsJPEG(ts) )
770 long positionOnEntry = Fp->tellg();
771 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
772 ComputeJPEGFragmentInfo();
773 Fp->seekg( positionOnEntry, std::ios::beg );
777 // Just to make sure we are at the beginning of next entry.
778 SkipToNextDocEntry(newDocEntry);
783 unsigned long l = newDocEntry->GetReadLength();
784 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
786 if ( l == 0xffffffff )
795 // no other way to create it ...
796 newSeqEntry->SetDelimitorMode( delim_mode );
798 // At the top of the hierarchy, stands a Document. When "set"
799 // is a Document, then we are building the first depth level.
800 // Hence the SeqEntry we are building simply has a depth
802 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
805 newSeqEntry->SetDepthLevel( 1 );
806 newSeqEntry->SetKey( newSeqEntry->GetKey() );
808 // But when "set" is already a SQItem, we are building a nested
809 // sequence, and hence the depth level of the new SeqEntry
810 // we are building, is one level deeper:
811 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
813 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
814 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
815 + newSeqEntry->GetKey() );
819 { // Don't try to parse zero-length sequences
820 ParseSQ( newSeqEntry,
821 newDocEntry->GetOffset(),
824 if( !set->AddEntry( newSeqEntry ) )
828 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
842 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
843 * @return parsed length for this level
845 void Document::ParseSQ( SeqEntry *seqEntry,
846 long offset, long l_max, bool delim_mode)
848 int SQItemNumber = 0;
850 long offsetStartCurrentSQItem = offset;
854 // the first time, we read the fff0,e000 of the first SQItem
855 DocEntry *newDocEntry = ReadNextDocEntry();
859 // FIXME Should warn user
864 if ( newDocEntry->IsSequenceDelimitor() )
866 seqEntry->SetDelimitationItem( newDocEntry );
870 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
875 // create the current SQItem
876 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
877 std::ostringstream newBase;
878 newBase << seqEntry->GetKey()
882 itemSQ->SetBaseTagKey( newBase.str() );
883 unsigned int l = newDocEntry->GetReadLength();
885 if ( l == 0xffffffff )
894 // when we're here, element fffe,e000 is already passed.
895 // it's lost for the SQItem we're going to process !!
897 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
898 //delete newDocEntry; // FIXME well ... it's too late to use it !
900 // Let's try :------------
901 // remove fff0,e000, created out of the SQItem
903 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
904 // fill up the current SQItem, starting at the beginning of fff0,e000
905 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
906 offsetStartCurrentSQItem = Fp->tellg();
907 // end try -----------------
909 seqEntry->AddSQItem( itemSQ, SQItemNumber );
911 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
919 * \brief Loads the element content if its length doesn't exceed
920 * the value specified with Document::SetMaxSizeLoadEntry()
921 * @param entry Header Entry (Dicom Element) to be dealt with
923 void Document::LoadDocEntry(DocEntry *entry)
925 uint16_t group = entry->GetGroup();
926 std::string vr = entry->GetVR();
927 uint32_t length = entry->GetLength();
929 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
931 // A SeQuence "contains" a set of Elements.
932 // (fffe e000) tells us an Element is beginning
933 // (fffe e00d) tells us an Element just ended
934 // (fffe e0dd) tells us the current SeQuence just ended
935 if( group == 0xfffe )
937 // NO more value field for SQ !
941 // When the length is zero things are easy:
944 ((ValEntry *)entry)->SetValue("");
948 // The elements whose length is bigger than the specified upper bound
949 // are not loaded. Instead we leave a short notice of the offset of
950 // the element content and it's length.
952 std::ostringstream s;
953 if (length > MaxSizeLoadEntry)
955 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
957 //s << "gdcm::NotLoaded (BinEntry)";
959 s << " Address:" << (long)entry->GetOffset();
960 s << " Length:" << entry->GetLength();
961 s << " x(" << std::hex << entry->GetLength() << ")";
962 binEntryPtr->SetValue(s.str());
964 // Be carefull : a BinEntry IS_A ValEntry ...
965 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
967 // s << "gdcm::NotLoaded. (ValEntry)";
969 s << " Address:" << (long)entry->GetOffset();
970 s << " Length:" << entry->GetLength();
971 s << " x(" << std::hex << entry->GetLength() << ")";
972 valEntryPtr->SetValue(s.str());
977 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
978 << "nor a ValEntry ?! Should never print that !" );
981 // to be sure we are at the end of the value ...
982 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
987 // When we find a BinEntry not very much can be done :
988 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
991 binEntryPtr->SetValue(s.str());
992 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
996 /// \todo Any compacter code suggested (?)
997 if ( IsDocEntryAnInteger(entry) )
1001 // When short integer(s) are expected, read and convert the following
1002 // n *two characters properly i.e. consider them as short integers as
1003 // opposed to strings.
1004 // Elements with Value Multiplicity > 1
1005 // contain a set of integers (not a single one)
1006 if (vr == "US" || vr == "SS")
1009 NewInt = ReadInt16();
1013 for (int i=1; i < nbInt; i++)
1016 NewInt = ReadInt16();
1021 // See above comment on multiple integers (mutatis mutandis).
1022 else if (vr == "UL" || vr == "SL")
1025 NewInt = ReadInt32();
1029 for (int i=1; i < nbInt; i++)
1032 NewInt = ReadInt32();
1037 #ifdef GDCM_NO_ANSI_STRING_STREAM
1038 s << std::ends; // to avoid oddities on Solaris
1039 #endif //GDCM_NO_ANSI_STRING_STREAM
1041 ((ValEntry *)entry)->SetValue(s.str());
1045 // FIXME: We need an additional byte for storing \0 that is not on disk
1046 char *str = new char[length+1];
1047 Fp->read(str, (size_t)length);
1048 str[length] = '\0'; //this is only useful when length is odd
1049 // Special DicomString call to properly handle \0 and even length
1050 std::string newValue;
1053 newValue = Util::DicomString(str, length+1);
1054 gdcmVerboseMacro("Warning: bad length: " << length <<
1055 ",For string :" << newValue.c_str());
1056 // Since we change the length of string update it length
1057 //entry->SetReadLength(length+1);
1061 newValue = Util::DicomString(str, length);
1065 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1067 if ( Fp->fail() || Fp->eof())
1069 gdcmVerboseMacro("Unread element value");
1070 valEntry->SetValue(GDCM_UNREAD);
1076 // Because of correspondance with the VR dic
1077 valEntry->SetValue(newValue);
1081 valEntry->SetValue(newValue);
1086 gdcmErrorMacro( "Should have a ValEntry, here !");
1092 * \brief Find the value Length of the passed Header Entry
1093 * @param entry Header Entry whose length of the value shall be loaded.
1095 void Document::FindDocEntryLength( DocEntry *entry )
1096 throw ( FormatError )
1098 std::string vr = entry->GetVR();
1101 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1103 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1105 // The following reserved two bytes (see PS 3.5-2003, section
1106 // "7.1.2 Data element structure with explicit vr", p 27) must be
1107 // skipped before proceeding on reading the length on 4 bytes.
1108 Fp->seekg( 2L, std::ios::cur);
1109 uint32_t length32 = ReadInt32();
1111 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1116 lengthOB = FindDocEntryLengthOBOrOW();
1118 catch ( FormatUnexpected )
1120 // Computing the length failed (this happens with broken
1121 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1122 // chance to get the pixels by deciding the element goes
1123 // until the end of the file. Hence we artificially fix the
1124 // the length and proceed.
1125 long currentPosition = Fp->tellg();
1126 Fp->seekg(0L,std::ios::end);
1128 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1129 Fp->seekg(currentPosition, std::ios::beg);
1131 entry->SetReadLength(lengthUntilEOF);
1132 entry->SetLength(lengthUntilEOF);
1135 entry->SetReadLength(lengthOB);
1136 entry->SetLength(lengthOB);
1139 FixDocEntryFoundLength(entry, length32);
1143 // Length is encoded on 2 bytes.
1144 length16 = ReadInt16();
1146 // FIXME : This heuristic supposes that the first group following
1147 // group 0002 *has* and element 0000.
1148 // BUT ... Element 0000 is optionnal :-(
1151 // Fixed using : HandleOutOfGroup0002()
1152 // (first hereafter strategy ...)
1154 // We can tell the current file is encoded in big endian (like
1155 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1156 // and it's value is the one of the encoding of a big endian file.
1157 // In order to deal with such big endian encoded files, we have
1158 // (at least) two strategies:
1159 // * when we load the "Transfer Syntax" tag with value of big endian
1160 // encoding, we raise the proper flags. Then we wait for the end
1161 // of the META group (0x0002) among which is "Transfer Syntax",
1162 // before switching the swap code to big endian. We have to postpone
1163 // the switching of the swap code since the META group is fully encoded
1164 // in little endian, and big endian coding only starts at the next
1165 // group. The corresponding code can be hard to analyse and adds
1166 // many additional unnecessary tests for regular tags.
1167 // * the second strategy consists in waiting for trouble, that shall
1168 // appear when we find the first group with big endian encoding. This
1169 // is easy to detect since the length of a "Group Length" tag (the
1170 // ones with zero as element number) has to be of 4 (0x0004). When we
1171 // encounter 1024 (0x0400) chances are the encoding changed and we
1172 // found a group with big endian encoding.
1173 //---> Unfortunately, element 0000 is optional.
1174 //---> This will not work when missing!
1175 // We shall use this second strategy. In order to make sure that we
1176 // can interpret the presence of an apparently big endian encoded
1177 // length of a "Group Length" without committing a big mistake, we
1178 // add an additional check: we look in the already parsed elements
1179 // for the presence of a "Transfer Syntax" whose value has to be "big
1180 // endian encoding". When this is the case, chances are we have got our
1181 // hands on a big endian encoded file: we switch the swap code to
1182 // big endian and proceed...
1184 // if ( element == 0x0000 && length16 == 0x0400 )
1186 // std::string ts = GetTransferSyntax();
1187 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1188 // != TS::ExplicitVRBigEndian )
1190 // throw FormatError( "Document::FindDocEntryLength()",
1191 // " not explicit VR." );
1195 // SwitchByteSwapCode();
1197 // // Restore the unproperly loaded values i.e. the group, the element
1198 // // and the dictionary entry depending on them.
1199 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1200 // uint16_t correctElem = SwapShort( entry->GetElement() );
1201 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1204 // // This correct tag is not in the dictionary. Create a new one.
1205 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1207 // // FIXME this can create a memory leaks on the old entry that be
1208 // // left unreferenced.
1209 // entry->SetDictEntry( newTag );
1212 // 0xffff means that we deal with 'No Length' Sequence
1213 // or 'No Length' SQItem
1214 if ( length16 == 0xffff)
1218 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1223 // Either implicit VR or a non DICOM conformal (see note below) explicit
1224 // VR that ommited the VR of (at least) this element. Farts happen.
1225 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1226 // on Data elements "Implicit and Explicit VR Data Elements shall
1227 // not coexist in a Data Set and Data Sets nested within it".]
1228 // Length is on 4 bytes.
1230 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1231 // even if Transfer Syntax is 'Implicit VR ...'
1233 FixDocEntryFoundLength( entry, ReadInt32() );
1239 * \brief Find the Value Representation of the current Dicom Element.
1240 * @return Value Representation of the current Entry
1242 std::string Document::FindDocEntryVR()
1244 if ( Filetype != ExplicitVR )
1245 return GDCM_UNKNOWN;
1247 long positionOnEntry = Fp->tellg();
1248 // Warning: we believe this is explicit VR (Value Representation) because
1249 // we used a heuristic that found "UL" in the first tag. Alas this
1250 // doesn't guarantee that all the tags will be in explicit VR. In some
1251 // cases (see e-film filtered files) one finds implicit VR tags mixed
1252 // within an explicit VR file. Hence we make sure the present tag
1253 // is in explicit VR and try to fix things if it happens not to be
1257 Fp->read (vr, (size_t)2);
1260 if( !CheckDocEntryVR(vr) )
1262 Fp->seekg(positionOnEntry, std::ios::beg);
1263 return GDCM_UNKNOWN;
1269 * \brief Check the correspondance between the VR of the header entry
1270 * and the taken VR. If they are different, the header entry is
1271 * updated with the new VR.
1272 * @param vr Dicom Value Representation
1273 * @return false if the VR is incorrect of if the VR isn't referenced
1274 * otherwise, it returns true
1276 bool Document::CheckDocEntryVR(VRKey vr)
1278 // CLEANME searching the dicom_vr at each occurence is expensive.
1279 // PostPone this test in an optional integrity check at the end
1280 // of parsing or only in debug mode.
1281 if ( !Global::GetVR()->IsValidVR(vr) )
1288 * \brief Get the transformed value of the header entry. The VR value
1289 * is used to define the transformation to operate on the value
1290 * \warning NOT end user intended method !
1291 * @param entry entry to tranform
1292 * @return Transformed entry value
1294 std::string Document::GetDocEntryValue(DocEntry *entry)
1296 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1298 std::string val = ((ValEntry *)entry)->GetValue();
1299 std::string vr = entry->GetVR();
1300 uint32_t length = entry->GetLength();
1301 std::ostringstream s;
1304 // When short integer(s) are expected, read and convert the following
1305 // n * 2 bytes properly i.e. as a multivaluated strings
1306 // (each single value is separated fromthe next one by '\'
1307 // as usual for standard multivaluated filels
1308 // Elements with Value Multiplicity > 1
1309 // contain a set of short integers (not a single one)
1311 if( vr == "US" || vr == "SS" )
1316 for (int i=0; i < nbInt; i++)
1322 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1323 newInt16 = SwapShort( newInt16 );
1328 // When integer(s) are expected, read and convert the following
1329 // n * 4 bytes properly i.e. as a multivaluated strings
1330 // (each single value is separated fromthe next one by '\'
1331 // as usual for standard multivaluated filels
1332 // Elements with Value Multiplicity > 1
1333 // contain a set of integers (not a single one)
1334 else if( vr == "UL" || vr == "SL" )
1339 for (int i=0; i < nbInt; i++)
1345 newInt32 = ( val[4*i+0] & 0xFF )
1346 + (( val[4*i+1] & 0xFF ) << 8 )
1347 + (( val[4*i+2] & 0xFF ) << 16 )
1348 + (( val[4*i+3] & 0xFF ) << 24 );
1349 newInt32 = SwapLong( newInt32 );
1353 #ifdef GDCM_NO_ANSI_STRING_STREAM
1354 s << std::ends; // to avoid oddities on Solaris
1355 #endif //GDCM_NO_ANSI_STRING_STREAM
1359 return ((ValEntry *)entry)->GetValue();
1363 * \brief Get the reverse transformed value of the header entry. The VR
1364 * value is used to define the reverse transformation to operate on
1366 * \warning NOT end user intended method !
1367 * @param entry Entry to reverse transform
1368 * @return Reverse transformed entry value
1370 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1372 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1374 std::string vr = entry->GetVR();
1375 std::vector<std::string> tokens;
1376 std::ostringstream s;
1378 if ( vr == "US" || vr == "SS" )
1382 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1383 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1384 for (unsigned int i=0; i<tokens.size(); i++)
1386 newInt16 = atoi(tokens[i].c_str());
1387 s << ( newInt16 & 0xFF )
1388 << (( newInt16 >> 8 ) & 0xFF );
1392 if ( vr == "UL" || vr == "SL")
1396 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1397 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1398 for (unsigned int i=0; i<tokens.size();i++)
1400 newInt32 = atoi(tokens[i].c_str());
1401 s << (char)( newInt32 & 0xFF )
1402 << (char)(( newInt32 >> 8 ) & 0xFF )
1403 << (char)(( newInt32 >> 16 ) & 0xFF )
1404 << (char)(( newInt32 >> 24 ) & 0xFF );
1409 #ifdef GDCM_NO_ANSI_STRING_STREAM
1410 s << std::ends; // to avoid oddities on Solaris
1411 #endif //GDCM_NO_ANSI_STRING_STREAM
1415 return ((ValEntry *)entry)->GetValue();
1419 * \brief Skip a given Header Entry
1420 * \warning NOT end user intended method !
1421 * @param entry entry to skip
1423 void Document::SkipDocEntry(DocEntry *entry)
1425 SkipBytes(entry->GetLength());
1429 * \brief Skips to the begining of the next Header Entry
1430 * \warning NOT end user intended method !
1431 * @param currentDocEntry entry to skip
1433 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1435 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1436 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1437 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1441 * \brief When the length of an element value is obviously wrong (because
1442 * the parser went Jabberwocky) one can hope improving things by
1443 * applying some heuristics.
1444 * @param entry entry to check
1445 * @param foundLength first assumption about length
1447 void Document::FixDocEntryFoundLength(DocEntry *entry,
1448 uint32_t foundLength)
1450 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1451 if ( foundLength == 0xffffffff)
1456 uint16_t gr = entry->GetGroup();
1457 uint16_t elem = entry->GetElement();
1459 if ( foundLength % 2)
1461 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1462 << " in x(" << std::hex << gr << "," << elem <<")");
1465 //////// Fix for some naughty General Electric images.
1466 // Allthough not recent many such GE corrupted images are still present
1467 // on Creatis hard disks. Hence this fix shall remain when such images
1468 // are no longer in use (we are talking a few years, here)...
1469 // Note: XMedCom probably uses such a trick since it is able to read
1470 // those pesky GE images ...
1471 if ( foundLength == 13)
1473 // Only happens for this length !
1474 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1477 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1481 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1482 // Occurence of such images is quite low (unless one leaves close to a
1483 // 'Leonardo' source. Hence, one might consider commenting out the
1484 // following fix on efficiency reasons.
1485 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1488 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1491 else if ( entry->GetVR() == "SQ" )
1493 foundLength = 0; // ReadLength is unchanged
1496 //////// We encountered a 'delimiter' element i.e. a tag of the form
1497 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1498 // taken into account.
1499 else if( gr == 0xfffe )
1501 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1502 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1503 // causes extra troubles...
1504 if( entry->GetElement() != 0x0000 )
1510 entry->SetLength(foundLength);
1514 * \brief Apply some heuristics to predict whether the considered
1515 * element value contains/represents an integer or not.
1516 * @param entry The element value on which to apply the predicate.
1517 * @return The result of the heuristical predicate.
1519 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1521 uint16_t elem = entry->GetElement();
1522 uint16_t group = entry->GetGroup();
1523 const std::string &vr = entry->GetVR();
1524 uint32_t length = entry->GetLength();
1526 // When we have some semantics on the element we just read, and if we
1527 // a priori know we are dealing with an integer, then we shall be
1528 // able to swap it's element value properly.
1529 if ( elem == 0 ) // This is the group length of the group
1537 // Allthough this should never happen, still some images have a
1538 // corrupted group length [e.g. have a glance at offset x(8336) of
1539 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1540 // Since for dicom compliant and well behaved headers, the present
1541 // test is useless (and might even look a bit paranoid), when we
1542 // encounter such an ill-formed image, we simply display a warning
1543 // message and proceed on parsing (while crossing fingers).
1544 long filePosition = Fp->tellg();
1545 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1546 << std::hex << group << " , " << elem
1547 << ") -before- position x(" << filePosition << ")"
1548 << "lgt : " << length );
1552 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1560 * \brief Find the Length till the next sequence delimiter
1561 * \warning NOT end user intended method !
1565 uint32_t Document::FindDocEntryLengthOBOrOW()
1566 throw( FormatUnexpected )
1568 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1569 long positionOnEntry = Fp->tellg();
1570 bool foundSequenceDelimiter = false;
1571 uint32_t totalLength = 0;
1573 while ( !foundSequenceDelimiter )
1579 group = ReadInt16();
1582 catch ( FormatError )
1584 throw FormatError("Unexpected end of file encountered during ",
1585 "Document::FindDocEntryLengthOBOrOW()");
1588 // We have to decount the group and element we just read
1591 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1593 long filePosition = Fp->tellg();
1594 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1595 << std::hex << group << " , " << elem
1596 << ") -before- position x(" << filePosition << ")" );
1598 Fp->seekg(positionOnEntry, std::ios::beg);
1599 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1602 if ( elem == 0xe0dd )
1604 foundSequenceDelimiter = true;
1607 uint32_t itemLength = ReadInt32();
1608 // We add 4 bytes since we just read the ItemLength with ReadInt32
1609 totalLength += itemLength + 4;
1610 SkipBytes(itemLength);
1612 if ( foundSequenceDelimiter )
1617 Fp->seekg( positionOnEntry, std::ios::beg);
1622 * \brief Reads a supposed to be 16 Bits integer
1623 * (swaps it depending on processor endianity)
1624 * @return read value
1626 uint16_t Document::ReadInt16()
1627 throw( FormatError )
1630 Fp->read ((char*)&g, (size_t)2);
1633 throw FormatError( "Document::ReadInt16()", " file error." );
1637 throw FormatError( "Document::ReadInt16()", "EOF." );
1644 * \brief Reads a supposed to be 32 Bits integer
1645 * (swaps it depending on processor endianity)
1646 * @return read value
1648 uint32_t Document::ReadInt32()
1649 throw( FormatError )
1652 Fp->read ((char*)&g, (size_t)4);
1655 throw FormatError( "Document::ReadInt32()", " file error." );
1659 throw FormatError( "Document::ReadInt32()", "EOF." );
1666 * \brief skips bytes inside the source file
1667 * \warning NOT end user intended method !
1670 void Document::SkipBytes(uint32_t nBytes)
1672 //FIXME don't dump the returned value
1673 Fp->seekg((long)nBytes, std::ios::cur);
1677 * \brief Loads all the needed Dictionaries
1678 * \warning NOT end user intended method !
1680 void Document::Initialize()
1682 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1684 RLEInfo = new RLEFramesInfo;
1685 JPEGInfo = new JPEGFragmentsInfo;
1690 * \brief Discover what the swap code is (among little endian, big endian,
1691 * bad little endian, bad big endian).
1693 * @return false when we are absolutely sure
1694 * it's neither ACR-NEMA nor DICOM
1695 * true when we hope ours assuptions are OK
1697 bool Document::CheckSwap()
1699 // The only guaranted way of finding the swap code is to find a
1700 // group tag since we know it's length has to be of four bytes i.e.
1701 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1702 // occurs when we can't find such group...
1704 uint32_t x = 4; // x : for ntohs
1705 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1711 // First, compare HostByteOrder and NetworkByteOrder in order to
1712 // determine if we shall need to swap bytes (i.e. the Endian type).
1713 if ( x == ntohs(x) )
1722 // The easiest case is the one of a 'true' DICOM header, we just have
1723 // to look for the string "DICM" inside the file preamble.
1726 char *entCur = deb + 128;
1727 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1729 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1731 // Group 0002 should always be VR, and the first element 0000
1732 // Let's be carefull (so many wrong headers ...)
1733 // and determine the value representation (VR) :
1734 // Let's skip to the first element (0002,0000) and check there if we find
1735 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1736 // in which case we (almost) know it is explicit VR.
1737 // WARNING: if it happens to be implicit VR then what we will read
1738 // is the length of the group. If this ascii representation of this
1739 // length happens to be "UL" then we shall believe it is explicit VR.
1740 // We need to skip :
1741 // * the 128 bytes of File Preamble (often padded with zeroes),
1742 // * the 4 bytes of "DICM" string,
1743 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1744 // i.e. a total of 136 bytes.
1747 // group 0x0002 *is always* Explicit VR Sometimes ,
1748 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1749 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1751 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1752 memcmp(entCur, "OB", (size_t)2) == 0 ||
1753 memcmp(entCur, "UI", (size_t)2) == 0 ||
1754 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1755 // when Write DCM *adds*
1757 // Use Document::dicom_vr to test all the possibilities
1758 // instead of just checking for UL, OB and UI !? group 0000
1760 Filetype = ExplicitVR;
1761 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
1765 Filetype = ImplicitVR;
1766 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
1767 << "Looks like a bugged Header!");
1773 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
1778 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
1781 // Position the file position indicator at first tag
1782 // (i.e. after the file preamble and the "DICM" string).
1783 Fp->seekg(0, std::ios::beg);
1784 Fp->seekg ( 132L, std::ios::beg);
1788 // Alas, this is not a DicomV3 file and whatever happens there is no file
1789 // preamble. We can reset the file position indicator to where the data
1790 // is (i.e. the beginning of the file).
1791 gdcmVerboseMacro( "Not a DICOM Version3 file");
1792 Fp->seekg(0, std::ios::beg);
1794 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1795 // By clean we mean that the length of the first tag is written down.
1796 // If this is the case and since the length of the first group HAS to be
1797 // four (bytes), then determining the proper swap code is straightforward.
1800 // We assume the array of char we are considering contains the binary
1801 // representation of a 32 bits integer. Hence the following dirty
1803 s32 = *((uint32_t *)(entCur));
1824 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1825 // It is time for despaired wild guesses.
1826 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1827 // i.e. the 'group length' element is not present :
1829 // check the supposed-to-be 'group number'
1830 // in ( 0x0001 .. 0x0008 )
1831 // to determine ' SwapCode' value .
1832 // Only 0 or 4321 will be possible
1833 // (no oportunity to check for the formerly well known
1834 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1835 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1836 // the file IS NOT ACR-NEMA nor DICOM V3
1837 // Find a trick to tell it the caller...
1839 s16 = *((uint16_t *)(deb));
1866 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1874 * \brief Change the Byte Swap code.
1876 void Document::SwitchByteSwapCode()
1878 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
1879 if ( SwapCode == 1234 )
1883 else if ( SwapCode == 4321 )
1887 else if ( SwapCode == 3412 )
1891 else if ( SwapCode == 2143 )
1898 * \brief during parsing, Header Elements too long are not loaded in memory
1901 void Document::SetMaxSizeLoadEntry(long newSize)
1907 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1909 MaxSizeLoadEntry = 0xffffffff;
1912 MaxSizeLoadEntry = newSize;
1917 * \brief Header Elements too long will not be printed
1918 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
1921 void Document::SetMaxSizePrintEntry(long newSize)
1927 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1929 MaxSizePrintEntry = 0xffffffff;
1932 MaxSizePrintEntry = newSize;
1938 * \brief Handle broken private tag from Philips NTSCAN
1939 * where the endianess is being switch to BigEndian for no
1943 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
1945 // Endian reversion. Some files contain groups of tags with reversed endianess.
1946 static int reversedEndian = 0;
1947 // try to fix endian switching in the middle of headers
1948 if ((group == 0xfeff) && (elem == 0x00e0))
1950 // start endian swap mark for group found
1952 SwitchByteSwapCode();
1957 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
1959 // end of reversed endian group
1961 SwitchByteSwapCode();
1966 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
1967 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
1969 std::string Document::GetTransferSyntaxName()
1971 // use the TS (TS : Transfer Syntax)
1972 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
1974 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
1976 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
1977 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
1978 return "Uncompressed ACR-NEMA";
1980 if ( transferSyntax == GDCM_UNFOUND )
1982 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
1983 return "Uncompressed ACR-NEMA";
1986 // we do it only when we need it
1987 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
1989 // Global::GetTS() is a global static you shall never try to delete it!
1994 * \brief Group 0002 is always coded Little Endian
1995 * whatever Transfer Syntax is
1998 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2000 // Endian reversion. Some files contain groups of tags with reversed endianess.
2001 if ( !Group0002Parsed && group != 0x0002)
2003 Group0002Parsed = true;
2004 // we just came out of group 0002
2005 // if Transfer syntax is Big Endian we have to change CheckSwap
2007 std::string ts = GetTransferSyntax();
2008 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2010 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2014 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2016 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2018 Filetype = ImplicitVR;
2021 // FIXME Strangely, this works with
2022 //'Implicit VR Transfer Syntax (GE Private)
2023 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2025 gdcmVerboseMacro("Transfer Syntax Name = ["
2026 << GetTransferSyntaxName() << "]" );
2027 SwitchByteSwapCode();
2028 group = SwapShort(group);
2029 elem = SwapShort(elem);
2035 * \brief Read the next tag but WITHOUT loading it's value
2036 * (read the 'Group Number', the 'Element Number',
2037 * gets the Dict Entry
2038 * gets the VR, gets the length, gets the offset value)
2039 * @return On succes the newly created DocEntry, NULL on failure.
2041 DocEntry *Document::ReadNextDocEntry()
2048 group = ReadInt16();
2051 catch ( FormatError e )
2053 // We reached the EOF (or an error occured) therefore
2054 // header parsing has to be considered as finished.
2059 // Sometimes file contains groups of tags with reversed endianess.
2060 HandleBrokenEndian(group, elem);
2062 // In 'true DICOM' files Group 0002 is always little endian
2063 if ( HasDCMPreamble )
2064 HandleOutOfGroup0002(group, elem);
2066 std::string vr = FindDocEntryVR();
2067 std::string realVR = vr;
2069 if( vr == GDCM_UNKNOWN)
2071 DictEntry *dictEntry = GetDictEntry(group,elem);
2073 realVR = dictEntry->GetVR();
2077 if( Global::GetVR()->IsVROfSequence(realVR) )
2078 newEntry = NewSeqEntry(group, elem);
2079 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2080 newEntry = NewValEntry(group, elem,vr);
2082 newEntry = NewBinEntry(group, elem,vr);
2084 if( vr == GDCM_UNKNOWN )
2086 if( Filetype == ExplicitVR )
2088 // We thought this was explicit VR, but we end up with an
2089 // implicit VR tag. Let's backtrack.
2090 if ( newEntry->GetGroup() != 0xfffe )
2093 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2094 newEntry->GetGroup(), newEntry->GetElement());
2095 gdcmVerboseMacro( msg.c_str() );
2098 newEntry->SetImplicitVR();
2103 FindDocEntryLength(newEntry);
2105 catch ( FormatError e )
2113 newEntry->SetOffset(Fp->tellg());
2118 //GenerateFreeTagKeyInGroup? What was it designed for ?!?
2120 * \brief Generate a free TagKey i.e. a TagKey that is not present
2121 * in the TagHt dictionary.
2122 * @param group The generated tag must belong to this group.
2123 * @return The element of tag with given group which is fee.
2125 //uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2127 // for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2129 // TagKey key = DictEntry::TranslateToKey(group, elem);
2130 // if (TagHT.count(key) == 0)
2135 // return UINT32_MAX;
2139 * \brief Assuming the internal file pointer \ref Document::Fp
2140 * is placed at the beginning of a tag check whether this
2141 * tag is (TestGroup, TestElement).
2142 * \warning On success the internal file pointer \ref Document::Fp
2143 * is modified to point after the tag.
2144 * On failure (i.e. when the tag wasn't the expected tag
2145 * (TestGroup, TestElement) the internal file pointer
2146 * \ref Document::Fp is restored to it's original position.
2147 * @param testGroup The expected group of the tag.
2148 * @param testElement The expected Element of the tag.
2149 * @return True on success, false otherwise.
2151 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2153 long positionOnEntry = Fp->tellg();
2154 long currentPosition = Fp->tellg(); // On debugging purposes
2156 //// Read the Item Tag group and element, and make
2157 // sure they are what we expected:
2158 uint16_t itemTagGroup;
2159 uint16_t itemTagElement;
2162 itemTagGroup = ReadInt16();
2163 itemTagElement = ReadInt16();
2165 catch ( FormatError e )
2167 //std::cerr << e << std::endl;
2170 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2172 gdcmVerboseMacro( "Wrong Item Tag found:"
2173 << " We should have found tag ("
2174 << std::hex << testGroup << "," << testElement << ")" << std::endl
2175 << " but instead we encountered tag ("
2176 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2177 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2179 Fp->seekg(positionOnEntry, std::ios::beg);
2187 * \brief Assuming the internal file pointer \ref Document::Fp
2188 * is placed at the beginning of a tag (TestGroup, TestElement),
2189 * read the length associated to the Tag.
2190 * \warning On success the internal file pointer \ref Document::Fp
2191 * is modified to point after the tag and it's length.
2192 * On failure (i.e. when the tag wasn't the expected tag
2193 * (TestGroup, TestElement) the internal file pointer
2194 * \ref Document::Fp is restored to it's original position.
2195 * @param testGroup The expected group of the tag.
2196 * @param testElement The expected Element of the tag.
2197 * @return On success returns the length associated to the tag. On failure
2200 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2203 if ( !ReadTag(testGroup, testElement) )
2208 //// Then read the associated Item Length
2209 long currentPosition = Fp->tellg();
2210 uint32_t itemLength = ReadInt32();
2212 gdcmVerboseMacro( "Basic Item Length is: "
2213 << itemLength << std::endl
2214 << " at address: " << std::hex << (unsigned int)currentPosition);
2220 * \brief When parsing the Pixel Data of an encapsulated file, read
2221 * the basic offset table (when present, and BTW dump it).
2223 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2225 //// Read the Basic Offset Table Item Tag length...
2226 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2228 // When present, read the basic offset table itself.
2229 // Notes: - since the presence of this basic offset table is optional
2230 // we can't rely on it for the implementation, and we will simply
2231 // trash it's content (when present).
2232 // - still, when present, we could add some further checks on the
2233 // lengths, but we won't bother with such fuses for the time being.
2234 if ( itemLength != 0 )
2236 char *basicOffsetTableItemValue = new char[itemLength + 1];
2237 Fp->read(basicOffsetTableItemValue, itemLength);
2240 for (unsigned int i=0; i < itemLength; i += 4 )
2242 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2244 gdcmVerboseMacro( "Read one length: " <<
2245 std::hex << individualLength );
2249 delete[] basicOffsetTableItemValue;
2254 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2255 * Compute the RLE extra information and store it in \ref RLEInfo
2256 * for later pixel retrieval usage.
2258 void Document::ComputeRLEInfo()
2260 std::string ts = GetTransferSyntax();
2261 if ( !Global::GetTS()->IsRLELossless(ts) )
2266 // Encoded pixel data: for the time being we are only concerned with
2267 // Jpeg or RLE Pixel data encodings.
2268 // As stated in PS 3.5-2003, section 8.2 p44:
2269 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2270 // value representation OB is used".
2271 // Hence we expect an OB value representation. Concerning OB VR,
2272 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2273 // "For the Value Representations OB and OW, the encoding shall meet the
2274 // following specifications depending on the Data element tag:"
2276 // - the first item in the sequence of items before the encoded pixel
2277 // data stream shall be basic offset table item. The basic offset table
2278 // item value, however, is not required to be present"
2280 ReadAndSkipEncapsulatedBasicOffsetTable();
2282 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2283 // Loop on the individual frame[s] and store the information
2284 // on the RLE fragments in a RLEFramesInfo.
2285 // Note: - when only a single frame is present, this is a
2287 // - when more than one frame are present, then we are in
2288 // the case of a multi-frame image.
2290 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2292 // Parse the RLE Header and store the corresponding RLE Segment
2293 // Offset Table information on fragments of this current Frame.
2294 // Note that the fragment pixels themselves are not loaded
2295 // (but just skipped).
2296 long frameOffset = Fp->tellg();
2298 uint32_t nbRleSegments = ReadInt32();
2299 if ( nbRleSegments > 16 )
2301 // There should be at most 15 segments (refer to RLEFrame class)
2302 gdcmVerboseMacro( "Too many segments.");
2305 uint32_t rleSegmentOffsetTable[16];
2306 for( int k = 1; k <= 15; k++ )
2308 rleSegmentOffsetTable[k] = ReadInt32();
2311 // Deduce from both the RLE Header and the frameLength the
2312 // fragment length, and again store this info in a
2314 long rleSegmentLength[15];
2315 // skipping (not reading) RLE Segments
2316 if ( nbRleSegments > 1)
2318 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2320 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2321 - rleSegmentOffsetTable[k];
2322 SkipBytes(rleSegmentLength[k]);
2326 rleSegmentLength[nbRleSegments] = frameLength
2327 - rleSegmentOffsetTable[nbRleSegments];
2328 SkipBytes(rleSegmentLength[nbRleSegments]);
2330 // Store the collected info
2331 RLEFrame *newFrameInfo = new RLEFrame;
2332 newFrameInfo->NumberFragments = nbRleSegments;
2333 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2335 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2336 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2338 RLEInfo->Frames.push_back( newFrameInfo );
2341 // Make sure that at the end of the item we encounter a 'Sequence
2343 if ( !ReadTag(0xfffe, 0xe0dd) )
2345 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2350 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2351 * Compute the jpeg extra information (fragment[s] offset[s] and
2352 * length) and store it[them] in \ref JPEGInfo for later pixel
2355 void Document::ComputeJPEGFragmentInfo()
2357 // If you need to, look for comments of ComputeRLEInfo().
2358 std::string ts = GetTransferSyntax();
2359 if ( ! Global::GetTS()->IsJPEG(ts) )
2364 ReadAndSkipEncapsulatedBasicOffsetTable();
2366 // Loop on the fragments[s] and store the parsed information in a
2368 long fragmentLength;
2369 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2371 long fragmentOffset = Fp->tellg();
2373 // Store the collected info
2374 JPEGFragment *newFragment = new JPEGFragment;
2375 newFragment->Offset = fragmentOffset;
2376 newFragment->Length = fragmentLength;
2377 JPEGInfo->Fragments.push_back( newFragment );
2379 SkipBytes( fragmentLength );
2382 // Make sure that at the end of the item we encounter a 'Sequence
2384 if ( !ReadTag(0xfffe, 0xe0dd) )
2386 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2391 * \brief Walk recursively the given \ref DocEntrySet, and feed
2392 * the given hash table (\ref TagDocEntryHT) with all the
2393 * \ref DocEntry (Dicom entries) encountered.
2394 * This method does the job for \ref BuildFlatHashTable.
2395 * @param builtHT Where to collect all the \ref DocEntry encountered
2396 * when recursively walking the given set.
2397 * @param set The structure to be traversed (recursively).
2399 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2402 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2404 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2405 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2406 i != currentHT.end();
2409 DocEntry *entry = i->second;
2410 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2412 const ListSQItem& items = seqEntry->GetSQItems();
2413 for( ListSQItem::const_iterator item = items.begin();
2414 item != items.end();
2417 BuildFlatHashTableRecurse( builtHT, *item );
2421 builtHT[entry->GetKey()] = entry;
2426 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2428 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2429 for (ListDocEntry::const_iterator i = currentList.begin();
2430 i != currentList.end();
2433 DocEntry *entry = *i;
2434 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2436 const ListSQItem& items = seqEntry->GetSQItems();
2437 for( ListSQItem::const_iterator item = items.begin();
2438 item != items.end();
2441 BuildFlatHashTableRecurse( builtHT, *item );
2445 builtHT[entry->GetKey()] = entry;
2452 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2455 * The structure used by a Document (through \ref ElementSet),
2456 * in order to hold the parsed entries of a Dicom header, is a recursive
2457 * one. This is due to the fact that the sequences (when present)
2458 * can be nested. Additionaly, the sequence items (represented in
2459 * gdcm as \ref SQItem) add an extra complexity to the data
2460 * structure. Hence, a gdcm user whishing to visit all the entries of
2461 * a Dicom header will need to dig in the gdcm internals (which
2462 * implies exposing all the internal data structures to the API).
2463 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2464 * recursively builds a temporary hash table, which holds all the
2465 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2467 * \warning Of course there is NO integrity constrain between the
2468 * returned \ref TagDocEntryHT and the \ref ElementSet used
2469 * to build it. Hence if the underlying \ref ElementSet is
2470 * altered, then it is the caller responsability to invoke
2471 * \ref BuildFlatHashTable again...
2472 * @return The flat std::map<> we juste build.
2474 /*TagDocEntryHT *Document::BuildFlatHashTable()
2476 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2477 BuildFlatHashTableRecurse( *FlatHT, this );
2484 * \brief Compares two documents, according to \ref DicomDir rules
2485 * \warning Does NOT work with ACR-NEMA files
2486 * \todo Find a trick to solve the pb (use RET fields ?)
2488 * @return true if 'smaller'
2490 bool Document::operator<(Document &document)
2493 std::string s1 = GetEntryValue(0x0010,0x0010);
2494 std::string s2 = document.GetEntryValue(0x0010,0x0010);
2506 s1 = GetEntryValue(0x0010,0x0020);
2507 s2 = document.GetEntryValue(0x0010,0x0020);
2518 // Study Instance UID
2519 s1 = GetEntryValue(0x0020,0x000d);
2520 s2 = document.GetEntryValue(0x0020,0x000d);
2531 // Serie Instance UID
2532 s1 = GetEntryValue(0x0020,0x000e);
2533 s2 = document.GetEntryValue(0x0020,0x000e);
2549 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2550 * @param filetype Type of the File to be written
2552 int Document::ComputeGroup0002Length( FileType filetype )
2557 int groupLength = 0;
2558 bool found0002 = false;
2560 // for each zero-level Tag in the DCM Header
2561 DocEntry *entry = GetFirstEntry();
2564 gr = entry->GetGroup();
2569 vr = entry->GetVR();
2571 if (filetype == ExplicitVR)
2573 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2575 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2578 groupLength += 2 + 2 + 4 + entry->GetLength();
2580 else if (found0002 )
2583 entry = GetNextEntry();
2588 } // end namespace gdcm
2590 //-----------------------------------------------------------------------------