1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/02/02 18:13:57 $
7 Version: $Revision: 1.221 $
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 "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
35 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
39 #ifdef CMAKE_HAVE_NETINET_IN_H
40 #include <netinet/in.h>
45 //-----------------------------------------------------------------------------
46 // Refer to Document::CheckSwap()
47 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
49 // Refer to Document::SetMaxSizeLoadEntry()
50 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
51 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
53 //-----------------------------------------------------------------------------
54 // Constructor / Destructor
55 // Constructors and destructors are protected to avoid user to invoke directly
58 * @param filename 'Document' (File or DicomDir) to be opened for parsing
60 Document::Document( std::string const &filename )
63 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
73 Group0002Parsed = false;
75 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
76 // Fp->seekg( 0, std::ios::beg);
78 Fp->seekg(0, std::ios::end);
79 long lgt = Fp->tellg();
81 Fp->seekg(0, std::ios::beg);
84 long beg = Fp->tellg();
87 ParseDES( this, beg, lgt, false); // Loading is done during parsing
89 Fp->seekg( 0, std::ios::beg);
91 // Load 'non string' values
93 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
94 if( PhotometricInterpretation == "PALETTE COLOR " )
96 LoadEntryBinArea(0x0028,0x1200); // gray LUT
98 /// The tags refered by the three following lines used to be CORRECTLY
99 /// defined as having an US Value Representation in the public
100 /// dictionary. BUT the semantics implied by the three following
101 /// lines state that the corresponding tag contents are in fact
102 /// the ones of a BinEntry.
103 /// In order to fix things "Quick and Dirty" the dictionary was
104 /// altered on PURPOSE but now contains a WRONG value.
105 /// In order to fix things and restore the dictionary to its
106 /// correct value, one needs to decided of the semantics by deciding
107 /// whether the following tags are either:
108 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
109 /// also used as BinEntry, which requires the proper conversion,
110 /// - OW, and hence loaded as BinEntry, but afterwards also used
111 /// as ValEntry, which requires the proper conversion.
112 LoadEntryBinArea(0x0028,0x1201); // R LUT
113 LoadEntryBinArea(0x0028,0x1202); // G LUT
114 LoadEntryBinArea(0x0028,0x1203); // B LUT
116 // Segmented Red Palette Color LUT Data
117 LoadEntryBinArea(0x0028,0x1221);
118 // Segmented Green Palette Color LUT Data
119 LoadEntryBinArea(0x0028,0x1222);
120 // Segmented Blue Palette Color LUT Data
121 LoadEntryBinArea(0x0028,0x1223);
123 //FIXME later : how to use it?
124 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
128 // ----------------------------
129 // Specific code to allow gdcm to read ACR-LibIDO formated images
130 // Note: ACR-LibIDO is an extension of the ACR standard that was
131 // used at CREATIS. For the time being (say a couple years)
132 // we keep this kludge to allow a smooth move to gdcm for
133 // CREATIS developpers (sorry folks).
135 // if recognition code tells us we deal with a LibIDO image
136 // we switch lineNumber and columnNumber
139 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
140 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
141 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
142 // with "little-endian strings"
144 Filetype = ACR_LIBIDO;
145 std::string rows = GetEntryValue(0x0028, 0x0010);
146 std::string columns = GetEntryValue(0x0028, 0x0011);
147 SetValEntry(columns, 0x0028, 0x0010);
148 SetValEntry(rows , 0x0028, 0x0011);
150 // --- End of ACR-LibIDO kludge ---
154 * \brief This default constructor doesn't parse the file. You should
155 * then invoke \ref Document::SetFileName and then the parsing.
162 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
165 Filetype = ExplicitVR;
166 Group0002Parsed = false;
170 * \brief Canonical destructor.
172 Document::~Document ()
178 //-----------------------------------------------------------------------------
181 * \brief Get the public dictionary used
183 Dict *Document::GetPubDict()
189 * \brief Get the shadow dictionary used
191 Dict *Document::GetShaDict()
197 * \brief Set the shadow dictionary used
198 * @param dict dictionary to use in shadow
200 bool Document::SetShaDict(Dict *dict)
207 * \brief Set the shadow dictionary used
208 * @param dictName name of the dictionary to use in shadow
210 bool Document::SetShaDict(DictKey const &dictName)
212 RefShaDict = Global::GetDicts()->GetDict(dictName);
217 * \brief This predicate, based on hopefully reasonable heuristics,
218 * decides whether or not the current Document was properly parsed
219 * and contains the mandatory information for being considered as
220 * a well formed and usable Dicom/Acr File.
221 * @return true when Document is the one of a reasonable Dicom/Acr file,
224 bool Document::IsReadable()
226 if( Filetype == Unknown)
228 gdcmVerboseMacro( "Wrong filetype");
234 gdcmVerboseMacro( "No tag in internal hash table.");
242 * \brief Predicate for dicom version 3 file.
243 * @return True when the file is a dicom version 3.
245 bool Document::IsDicomV3()
247 // Checking if Transfer Syntax exists is enough
248 // Anyway, it's to late check if the 'Preamble' was found ...
249 // And ... would it be a rich idea to check ?
250 // (some 'no Preamble' DICOM images exist !)
251 return GetDocEntry(0x0002, 0x0010) != NULL;
255 * \brief Predicate for Papyrus file
256 * Dedicated to whomsoever it may concern
257 * @return True when the file is a Papyrus file.
259 bool Document::IsPapyrus()
261 // check for Papyrus private Sequence
262 DocEntry *e = GetDocEntry(0x0041, 0x1050);
265 // check if it's actually a Sequence
266 if ( !dynamic_cast<SeqEntry*>(e) )
272 * \brief returns the File Type
273 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
274 * @return the FileType code
276 FileType Document::GetFileType()
282 * \brief Accessor to the Transfer Syntax (when present) of the
283 * current document (it internally handles reading the
284 * value from disk when only parsing occured).
285 * @return The encountered Transfer Syntax of the current document.
287 std::string Document::GetTransferSyntax()
289 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
295 // The entry might be present but not loaded (parsing and loading
296 // happen at different stages): try loading and proceed with check...
297 LoadDocEntrySafe(entry);
298 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
300 std::string transfer = valEntry->GetValue();
301 // The actual transfer (as read from disk) might be padded. We
302 // first need to remove the potential padding. We can make the
303 // weak assumption that padding was not executed with digits...
304 if ( transfer.length() == 0 )
306 // for brain damaged headers
309 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
311 transfer.erase(transfer.length()-1, 1);
319 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
320 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
322 std::string Document::GetTransferSyntaxName()
324 // use the TS (TS : Transfer Syntax)
325 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
327 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
329 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
330 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
331 return "Uncompressed ACR-NEMA";
333 if ( transferSyntax == GDCM_UNFOUND )
335 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
336 return "Uncompressed ACR-NEMA";
339 // we do it only when we need it
340 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
342 // Global::GetTS() is a global static you shall never try to delete it!
346 // --------------- Swap Code ------------------
348 * \brief Swaps the bytes so they agree with the processor order
349 * @return The properly swaped 16 bits integer.
351 uint16_t Document::SwapShort(uint16_t a)
353 if ( SwapCode == 4321 || SwapCode == 2143 )
355 a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
361 * \brief Swaps back the bytes of 4-byte long integer accordingly to
363 * @return The properly swaped 32 bits integer.
365 uint32_t Document::SwapLong(uint32_t a)
372 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
373 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
376 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
379 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
382 gdcmErrorMacro( "Unset swap code:" << SwapCode );
389 // -----------------File I/O ---------------
391 * \brief Tries to open the file \ref Document::Filename and
392 * checks the preamble when existing.
393 * @return The FILE pointer on success.
395 std::ifstream *Document::OpenFile()
397 HasDCMPreamble = false;
398 if (Filename.length() == 0)
405 gdcmVerboseMacro( "File already open: " << Filename.c_str());
409 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
412 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
419 Fp->read((char*)&zero, (size_t)2);
426 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
428 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
429 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
430 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
431 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
434 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
435 gdcmVerboseMacro( msg.c_str() );
440 Fp->seekg(126L, std::ios::cur);
442 Fp->read(dicm, (size_t)4);
448 if( memcmp(dicm, "DICM", 4) == 0 )
450 HasDCMPreamble = true;
455 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
461 * \brief closes the file
462 * @return TRUE if the close was successfull
464 bool Document::CloseFile()
472 return true; //FIXME how do we detect a non-closed ifstream ?
476 * \brief Writes in a file all the Header Entries (Dicom Elements)
477 * @param fp file pointer on an already open file (actually: Output File Stream)
478 * @param filetype Type of the File to be written
479 * (ACR-NEMA, ExplicitVR, ImplicitVR)
480 * @return Always true.
482 void Document::WriteContent(std::ofstream *fp, FileType filetype)
484 // \TODO move the following lines (and a lot of others, to be written)
485 // to a future function CheckAndCorrectHeader
487 // (necessary if user wants to write a DICOM V3 file
488 // starting from an ACR-NEMA (V2) Header
490 if ( filetype == ImplicitVR || filetype == ExplicitVR )
492 // writing Dicom File Preamble
493 char filePreamble[128];
494 memset(filePreamble, 0, 128);
495 fp->write(filePreamble, 128);
496 fp->write("DICM", 4);
500 * \todo rewrite later, if really usefull
501 * - 'Group Length' element is optional in DICOM
502 * - but un-updated odd groups lengthes can causes pb
505 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
506 * UpdateGroupLength(false,filetype);
507 * if ( filetype == ACR)
508 * UpdateGroupLength(true,ACR);
511 ElementSet::WriteContent(fp, filetype); // This one is recursive
514 // -----------------------------------------
517 * \brief Loads (from disk) the element content
518 * when a string is not suitable
519 * @param group group number of the Entry
520 * @param elem element number of the Entry
522 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
524 // Search the corresponding DocEntry
525 DocEntry *docElement = GetDocEntry(group, elem);
529 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
533 LoadEntryBinArea(binElement);
537 * \brief Loads (from disk) the element content
538 * when a string is not suitable
539 * @param elem Entry whose binArea is going to be loaded
541 void Document::LoadEntryBinArea(BinEntry *elem)
543 if(elem->GetBinArea())
550 size_t o =(size_t)elem->GetOffset();
551 Fp->seekg(o, std::ios::beg);
553 size_t l = elem->GetLength();
554 uint8_t *a = new uint8_t[l];
557 gdcmVerboseMacro( "Cannot allocate BinEntry content");
561 /// \todo check the result
562 Fp->read((char*)a, l);
563 if( Fp->fail() || Fp->eof())
576 * \brief Loads the element while preserving the current
577 * underlying file position indicator as opposed to
578 * LoadDocEntry that modifies it.
579 * @param entry Header Entry whose value will be loaded.
582 void Document::LoadDocEntrySafe(DocEntry *entry)
586 long PositionOnEntry = Fp->tellg();
588 Fp->seekg(PositionOnEntry, std::ios::beg);
593 * \brief Compares two documents, according to \ref DicomDir rules
594 * \warning Does NOT work with ACR-NEMA files
595 * \todo Find a trick to solve the pb (use RET fields ?)
597 * @return true if 'smaller'
599 bool Document::operator<(Document &document)
602 std::string s1 = GetEntryValue(0x0010,0x0010);
603 std::string s2 = document.GetEntryValue(0x0010,0x0010);
615 s1 = GetEntryValue(0x0010,0x0020);
616 s2 = document.GetEntryValue(0x0010,0x0020);
627 // Study Instance UID
628 s1 = GetEntryValue(0x0020,0x000d);
629 s2 = document.GetEntryValue(0x0020,0x000d);
640 // Serie Instance UID
641 s1 = GetEntryValue(0x0020,0x000e);
642 s2 = document.GetEntryValue(0x0020,0x000e);
657 //-----------------------------------------------------------------------------
660 * \brief Reads a supposed to be 16 Bits integer
661 * (swaps it depending on processor endianity)
664 uint16_t Document::ReadInt16()
668 Fp->read ((char*)&g, (size_t)2);
671 throw FormatError( "Document::ReadInt16()", " file error." );
675 throw FormatError( "Document::ReadInt16()", "EOF." );
682 * \brief Reads a supposed to be 32 Bits integer
683 * (swaps it depending on processor endianity)
686 uint32_t Document::ReadInt32()
690 Fp->read ((char*)&g, (size_t)4);
693 throw FormatError( "Document::ReadInt32()", " file error." );
697 throw FormatError( "Document::ReadInt32()", "EOF." );
704 * \brief skips bytes inside the source file
705 * \warning NOT end user intended method !
708 void Document::SkipBytes(uint32_t nBytes)
710 //FIXME don't dump the returned value
711 Fp->seekg((long)nBytes, std::ios::cur);
715 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
716 * @param filetype Type of the File to be written
718 int Document::ComputeGroup0002Length( FileType filetype )
724 bool found0002 = false;
726 // for each zero-level Tag in the DCM Header
727 DocEntry *entry = GetFirstEntry();
730 gr = entry->GetGroup();
736 if( entry->GetElement() != 0x0000 )
740 if( filetype == ExplicitVR )
742 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
744 // explicit VR AND OB, OW, SQ : 4 more bytes
748 groupLength += 2 + 2 + 4 + entry->GetLength();
754 entry = GetNextEntry();
759 //-----------------------------------------------------------------------------
762 * \brief Loads all the needed Dictionaries
763 * \warning NOT end user intended method !
765 void Document::Initialize()
767 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
773 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
774 * @return length of the parsed set.
776 void Document::ParseDES(DocEntrySet *set, long offset,
777 long l_max, bool delim_mode)
779 DocEntry *newDocEntry = 0;
780 ValEntry *newValEntry;
781 BinEntry *newBinEntry;
782 SeqEntry *newSeqEntry;
788 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
794 newDocEntry = ReadNextDocEntry( );
801 vr = newDocEntry->GetVR();
802 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
803 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
804 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
806 if ( newValEntry || newBinEntry )
810 if ( Filetype == ExplicitVR &&
811 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
813 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
814 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
815 << "|" << newDocEntry->GetElement()
816 << " : Neither Valentry, nor BinEntry."
817 "Probably unknown VR.");
820 //////////////////// BinEntry or UNKOWN VR:
821 // When "this" is a Document the Key is simply of the
822 // form ( group, elem )...
823 if ( dynamic_cast< Document* > ( set ) )
825 newBinEntry->SetKey( newBinEntry->GetKey() );
827 // but when "this" is a SQItem, we are inserting this new
828 // valEntry in a sequence item, and the key has the
829 // generalized form (refer to \ref BaseTagKey):
830 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
832 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
833 + newBinEntry->GetKey() );
836 LoadDocEntry( newBinEntry );
837 if( !set->AddEntry( newBinEntry ) )
839 //Expect big troubles if here
840 //delete newBinEntry;
846 /////////////////////// ValEntry
847 // When "set" is a Document, then we are at the top of the
848 // hierarchy and the Key is simply of the form ( group, elem )...
849 if ( dynamic_cast< Document* > ( set ) )
851 newValEntry->SetKey( newValEntry->GetKey() );
853 // ...but when "set" is a SQItem, we are inserting this new
854 // valEntry in a sequence item. Hence the key has the
855 // generalized form (refer to \ref BaseTagKey):
856 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
858 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
859 + newValEntry->GetKey() );
862 LoadDocEntry( newValEntry );
863 bool delimitor=newValEntry->IsItemDelimitor();
864 if( !set->AddEntry( newValEntry ) )
866 // If here expect big troubles
867 //delete newValEntry; //otherwise mem leak
877 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
885 // Just to make sure we are at the beginning of next entry.
886 SkipToNextDocEntry(newDocEntry);
891 unsigned long l = newDocEntry->GetReadLength();
892 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
894 if ( l == 0xffffffff )
903 // no other way to create it ...
904 newSeqEntry->SetDelimitorMode( delim_mode );
906 // At the top of the hierarchy, stands a Document. When "set"
907 // is a Document, then we are building the first depth level.
908 // Hence the SeqEntry we are building simply has a depth
910 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
913 newSeqEntry->SetDepthLevel( 1 );
914 newSeqEntry->SetKey( newSeqEntry->GetKey() );
916 // But when "set" is already a SQItem, we are building a nested
917 // sequence, and hence the depth level of the new SeqEntry
918 // we are building, is one level deeper:
919 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
921 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
922 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
923 + newSeqEntry->GetKey() );
927 { // Don't try to parse zero-length sequences
928 ParseSQ( newSeqEntry,
929 newDocEntry->GetOffset(),
932 if( !set->AddEntry( newSeqEntry ) )
936 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
950 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
951 * @return parsed length for this level
953 void Document::ParseSQ( SeqEntry *seqEntry,
954 long offset, long l_max, bool delim_mode)
956 int SQItemNumber = 0;
958 long offsetStartCurrentSQItem = offset;
962 // the first time, we read the fff0,e000 of the first SQItem
963 DocEntry *newDocEntry = ReadNextDocEntry();
967 // FIXME Should warn user
972 if ( newDocEntry->IsSequenceDelimitor() )
974 seqEntry->SetDelimitationItem( newDocEntry );
978 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
983 // create the current SQItem
984 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
985 std::ostringstream newBase;
986 newBase << seqEntry->GetKey()
990 itemSQ->SetBaseTagKey( newBase.str() );
991 unsigned int l = newDocEntry->GetReadLength();
993 if ( l == 0xffffffff )
1002 // when we're here, element fffe,e000 is already passed.
1003 // it's lost for the SQItem we're going to process !!
1005 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1006 //delete newDocEntry; // FIXME well ... it's too late to use it !
1008 // Let's try :------------
1009 // remove fff0,e000, created out of the SQItem
1011 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1012 // fill up the current SQItem, starting at the beginning of fff0,e000
1013 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1014 offsetStartCurrentSQItem = Fp->tellg();
1015 // end try -----------------
1017 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1019 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1027 * \brief Loads the element content if its length doesn't exceed
1028 * the value specified with Document::SetMaxSizeLoadEntry()
1029 * @param entry Header Entry (Dicom Element) to be dealt with
1031 void Document::LoadDocEntry(DocEntry *entry)
1033 uint16_t group = entry->GetGroup();
1034 std::string vr = entry->GetVR();
1035 uint32_t length = entry->GetLength();
1037 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1039 // A SeQuence "contains" a set of Elements.
1040 // (fffe e000) tells us an Element is beginning
1041 // (fffe e00d) tells us an Element just ended
1042 // (fffe e0dd) tells us the current SeQuence just ended
1043 if( group == 0xfffe )
1045 // NO more value field for SQ !
1049 // When the length is zero things are easy:
1052 ((ValEntry *)entry)->SetValue("");
1056 // The elements whose length is bigger than the specified upper bound
1057 // are not loaded. Instead we leave a short notice of the offset of
1058 // the element content and it's length.
1060 std::ostringstream s;
1061 if (length > MaxSizeLoadEntry)
1063 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1065 //s << "gdcm::NotLoaded (BinEntry)";
1066 s << GDCM_NOTLOADED;
1067 s << " Address:" << (long)entry->GetOffset();
1068 s << " Length:" << entry->GetLength();
1069 s << " x(" << std::hex << entry->GetLength() << ")";
1070 binEntryPtr->SetValue(s.str());
1072 // Be carefull : a BinEntry IS_A ValEntry ...
1073 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1075 // s << "gdcm::NotLoaded. (ValEntry)";
1076 s << GDCM_NOTLOADED;
1077 s << " Address:" << (long)entry->GetOffset();
1078 s << " Length:" << entry->GetLength();
1079 s << " x(" << std::hex << entry->GetLength() << ")";
1080 valEntryPtr->SetValue(s.str());
1085 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1086 << "nor a ValEntry ?! Should never print that !" );
1089 // to be sure we are at the end of the value ...
1090 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1095 // When we find a BinEntry not very much can be done :
1096 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1098 s << GDCM_BINLOADED;
1099 binEntryPtr->SetValue(s.str());
1100 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1104 /// \todo Any compacter code suggested (?)
1105 if ( IsDocEntryAnInteger(entry) )
1109 // When short integer(s) are expected, read and convert the following
1110 // n *two characters properly i.e. consider them as short integers as
1111 // opposed to strings.
1112 // Elements with Value Multiplicity > 1
1113 // contain a set of integers (not a single one)
1114 if (vr == "US" || vr == "SS")
1117 NewInt = ReadInt16();
1121 for (int i=1; i < nbInt; i++)
1124 NewInt = ReadInt16();
1129 // See above comment on multiple integers (mutatis mutandis).
1130 else if (vr == "UL" || vr == "SL")
1133 NewInt = ReadInt32();
1137 for (int i=1; i < nbInt; i++)
1140 NewInt = ReadInt32();
1145 #ifdef GDCM_NO_ANSI_STRING_STREAM
1146 s << std::ends; // to avoid oddities on Solaris
1147 #endif //GDCM_NO_ANSI_STRING_STREAM
1149 ((ValEntry *)entry)->SetValue(s.str());
1153 // FIXME: We need an additional byte for storing \0 that is not on disk
1154 char *str = new char[length+1];
1155 Fp->read(str, (size_t)length);
1156 str[length] = '\0'; //this is only useful when length is odd
1157 // Special DicomString call to properly handle \0 and even length
1158 std::string newValue;
1161 newValue = Util::DicomString(str, length+1);
1162 gdcmVerboseMacro("Warning: bad length: " << length <<
1163 ",For string :" << newValue.c_str());
1164 // Since we change the length of string update it length
1165 //entry->SetReadLength(length+1);
1169 newValue = Util::DicomString(str, length);
1173 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1175 if ( Fp->fail() || Fp->eof())
1177 gdcmVerboseMacro("Unread element value");
1178 valEntry->SetValue(GDCM_UNREAD);
1184 // Because of correspondance with the VR dic
1185 valEntry->SetValue(newValue);
1189 valEntry->SetValue(newValue);
1194 gdcmErrorMacro( "Should have a ValEntry, here !");
1199 * \brief Find the value Length of the passed Header Entry
1200 * @param entry Header Entry whose length of the value shall be loaded.
1202 void Document::FindDocEntryLength( DocEntry *entry )
1203 throw ( FormatError )
1205 std::string vr = entry->GetVR();
1208 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1210 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1212 // The following reserved two bytes (see PS 3.5-2003, section
1213 // "7.1.2 Data element structure with explicit vr", p 27) must be
1214 // skipped before proceeding on reading the length on 4 bytes.
1215 Fp->seekg( 2L, std::ios::cur);
1216 uint32_t length32 = ReadInt32();
1218 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1223 lengthOB = FindDocEntryLengthOBOrOW();
1225 catch ( FormatUnexpected )
1227 // Computing the length failed (this happens with broken
1228 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1229 // chance to get the pixels by deciding the element goes
1230 // until the end of the file. Hence we artificially fix the
1231 // the length and proceed.
1232 long currentPosition = Fp->tellg();
1233 Fp->seekg(0L,std::ios::end);
1235 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1236 Fp->seekg(currentPosition, std::ios::beg);
1238 entry->SetReadLength(lengthUntilEOF);
1239 entry->SetLength(lengthUntilEOF);
1242 entry->SetReadLength(lengthOB);
1243 entry->SetLength(lengthOB);
1246 FixDocEntryFoundLength(entry, length32);
1250 // Length is encoded on 2 bytes.
1251 length16 = ReadInt16();
1253 // FIXME : This heuristic supposes that the first group following
1254 // group 0002 *has* and element 0000.
1255 // BUT ... Element 0000 is optionnal :-(
1258 // Fixed using : HandleOutOfGroup0002()
1259 // (first hereafter strategy ...)
1261 // We can tell the current file is encoded in big endian (like
1262 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1263 // and it's value is the one of the encoding of a big endian file.
1264 // In order to deal with such big endian encoded files, we have
1265 // (at least) two strategies:
1266 // * when we load the "Transfer Syntax" tag with value of big endian
1267 // encoding, we raise the proper flags. Then we wait for the end
1268 // of the META group (0x0002) among which is "Transfer Syntax",
1269 // before switching the swap code to big endian. We have to postpone
1270 // the switching of the swap code since the META group is fully encoded
1271 // in little endian, and big endian coding only starts at the next
1272 // group. The corresponding code can be hard to analyse and adds
1273 // many additional unnecessary tests for regular tags.
1274 // * the second strategy consists in waiting for trouble, that shall
1275 // appear when we find the first group with big endian encoding. This
1276 // is easy to detect since the length of a "Group Length" tag (the
1277 // ones with zero as element number) has to be of 4 (0x0004). When we
1278 // encounter 1024 (0x0400) chances are the encoding changed and we
1279 // found a group with big endian encoding.
1280 //---> Unfortunately, element 0000 is optional.
1281 //---> This will not work when missing!
1282 // We shall use this second strategy. In order to make sure that we
1283 // can interpret the presence of an apparently big endian encoded
1284 // length of a "Group Length" without committing a big mistake, we
1285 // add an additional check: we look in the already parsed elements
1286 // for the presence of a "Transfer Syntax" whose value has to be "big
1287 // endian encoding". When this is the case, chances are we have got our
1288 // hands on a big endian encoded file: we switch the swap code to
1289 // big endian and proceed...
1291 // if ( element == 0x0000 && length16 == 0x0400 )
1293 // std::string ts = GetTransferSyntax();
1294 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1295 // != TS::ExplicitVRBigEndian )
1297 // throw FormatError( "Document::FindDocEntryLength()",
1298 // " not explicit VR." );
1302 // SwitchByteSwapCode();
1304 // // Restore the unproperly loaded values i.e. the group, the element
1305 // // and the dictionary entry depending on them.
1306 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1307 // uint16_t correctElem = SwapShort( entry->GetElement() );
1308 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1311 // // This correct tag is not in the dictionary. Create a new one.
1312 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1314 // // FIXME this can create a memory leaks on the old entry that be
1315 // // left unreferenced.
1316 // entry->SetDictEntry( newTag );
1319 // 0xffff means that we deal with 'No Length' Sequence
1320 // or 'No Length' SQItem
1321 if ( length16 == 0xffff)
1325 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1330 // Either implicit VR or a non DICOM conformal (see note below) explicit
1331 // VR that ommited the VR of (at least) this element. Farts happen.
1332 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1333 // on Data elements "Implicit and Explicit VR Data Elements shall
1334 // not coexist in a Data Set and Data Sets nested within it".]
1335 // Length is on 4 bytes.
1337 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1338 // even if Transfer Syntax is 'Implicit VR ...'
1340 FixDocEntryFoundLength( entry, ReadInt32() );
1346 * \brief Find the Length till the next sequence delimiter
1347 * \warning NOT end user intended method !
1350 uint32_t Document::FindDocEntryLengthOBOrOW()
1351 throw( FormatUnexpected )
1353 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1354 long positionOnEntry = Fp->tellg();
1355 bool foundSequenceDelimiter = false;
1356 uint32_t totalLength = 0;
1358 while ( !foundSequenceDelimiter )
1364 group = ReadInt16();
1367 catch ( FormatError )
1369 throw FormatError("Unexpected end of file encountered during ",
1370 "Document::FindDocEntryLengthOBOrOW()");
1372 // We have to decount the group and element we just read
1374 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1376 long filePosition = Fp->tellg();
1377 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1378 << std::hex << group << " , " << elem
1379 << ") -before- position x(" << filePosition << ")" );
1381 Fp->seekg(positionOnEntry, std::ios::beg);
1382 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1384 if ( elem == 0xe0dd )
1386 foundSequenceDelimiter = true;
1388 uint32_t itemLength = ReadInt32();
1389 // We add 4 bytes since we just read the ItemLength with ReadInt32
1390 totalLength += itemLength + 4;
1391 SkipBytes(itemLength);
1393 if ( foundSequenceDelimiter )
1398 Fp->seekg( positionOnEntry, std::ios::beg);
1403 * \brief Find the Value Representation of the current Dicom Element.
1404 * @return Value Representation of the current Entry
1406 std::string Document::FindDocEntryVR()
1408 if ( Filetype != ExplicitVR )
1409 return GDCM_UNKNOWN;
1411 long positionOnEntry = Fp->tellg();
1412 // Warning: we believe this is explicit VR (Value Representation) because
1413 // we used a heuristic that found "UL" in the first tag. Alas this
1414 // doesn't guarantee that all the tags will be in explicit VR. In some
1415 // cases (see e-film filtered files) one finds implicit VR tags mixed
1416 // within an explicit VR file. Hence we make sure the present tag
1417 // is in explicit VR and try to fix things if it happens not to be
1421 Fp->read (vr, (size_t)2);
1424 if( !CheckDocEntryVR(vr) )
1426 Fp->seekg(positionOnEntry, std::ios::beg);
1427 return GDCM_UNKNOWN;
1433 * \brief Check the correspondance between the VR of the header entry
1434 * and the taken VR. If they are different, the header entry is
1435 * updated with the new VR.
1436 * @param vr Dicom Value Representation
1437 * @return false if the VR is incorrect of if the VR isn't referenced
1438 * otherwise, it returns true
1440 bool Document::CheckDocEntryVR(VRKey vr)
1442 if ( !Global::GetVR()->IsValidVR(vr) )
1449 * \brief Get the transformed value of the header entry. The VR value
1450 * is used to define the transformation to operate on the value
1451 * \warning NOT end user intended method !
1452 * @param entry entry to tranform
1453 * @return Transformed entry value
1455 std::string Document::GetDocEntryValue(DocEntry *entry)
1457 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1459 std::string val = ((ValEntry *)entry)->GetValue();
1460 std::string vr = entry->GetVR();
1461 uint32_t length = entry->GetLength();
1462 std::ostringstream s;
1465 // When short integer(s) are expected, read and convert the following
1466 // n * 2 bytes properly i.e. as a multivaluated strings
1467 // (each single value is separated fromthe next one by '\'
1468 // as usual for standard multivaluated filels
1469 // Elements with Value Multiplicity > 1
1470 // contain a set of short integers (not a single one)
1472 if( vr == "US" || vr == "SS" )
1477 for (int i=0; i < nbInt; i++)
1483 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1484 newInt16 = SwapShort( newInt16 );
1489 // When integer(s) are expected, read and convert the following
1490 // n * 4 bytes properly i.e. as a multivaluated strings
1491 // (each single value is separated fromthe next one by '\'
1492 // as usual for standard multivaluated filels
1493 // Elements with Value Multiplicity > 1
1494 // contain a set of integers (not a single one)
1495 else if( vr == "UL" || vr == "SL" )
1500 for (int i=0; i < nbInt; i++)
1506 newInt32 = ( val[4*i+0] & 0xFF )
1507 + (( val[4*i+1] & 0xFF ) << 8 )
1508 + (( val[4*i+2] & 0xFF ) << 16 )
1509 + (( val[4*i+3] & 0xFF ) << 24 );
1510 newInt32 = SwapLong( newInt32 );
1514 #ifdef GDCM_NO_ANSI_STRING_STREAM
1515 s << std::ends; // to avoid oddities on Solaris
1516 #endif //GDCM_NO_ANSI_STRING_STREAM
1519 return ((ValEntry *)entry)->GetValue();
1523 * \brief Get the reverse transformed value of the header entry. The VR
1524 * value is used to define the reverse transformation to operate on
1526 * \warning NOT end user intended method !
1527 * @param entry Entry to reverse transform
1528 * @return Reverse transformed entry value
1530 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1532 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1534 std::string vr = entry->GetVR();
1535 std::vector<std::string> tokens;
1536 std::ostringstream s;
1538 if ( vr == "US" || vr == "SS" )
1542 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1543 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1544 for (unsigned int i=0; i<tokens.size(); i++)
1546 newInt16 = atoi(tokens[i].c_str());
1547 s << ( newInt16 & 0xFF )
1548 << (( newInt16 >> 8 ) & 0xFF );
1552 if ( vr == "UL" || vr == "SL")
1556 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1557 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1558 for (unsigned int i=0; i<tokens.size();i++)
1560 newInt32 = atoi(tokens[i].c_str());
1561 s << (char)( newInt32 & 0xFF )
1562 << (char)(( newInt32 >> 8 ) & 0xFF )
1563 << (char)(( newInt32 >> 16 ) & 0xFF )
1564 << (char)(( newInt32 >> 24 ) & 0xFF );
1569 #ifdef GDCM_NO_ANSI_STRING_STREAM
1570 s << std::ends; // to avoid oddities on Solaris
1571 #endif //GDCM_NO_ANSI_STRING_STREAM
1575 return ((ValEntry *)entry)->GetValue();
1579 * \brief Skip a given Header Entry
1580 * \warning NOT end user intended method !
1581 * @param entry entry to skip
1583 void Document::SkipDocEntry(DocEntry *entry)
1585 SkipBytes(entry->GetLength());
1589 * \brief Skips to the beginning of the next Header Entry
1590 * \warning NOT end user intended method !
1591 * @param currentDocEntry entry to skip
1593 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1595 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1596 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1597 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1601 * \brief When the length of an element value is obviously wrong (because
1602 * the parser went Jabberwocky) one can hope improving things by
1603 * applying some heuristics.
1604 * @param entry entry to check
1605 * @param foundLength first assumption about length
1607 void Document::FixDocEntryFoundLength(DocEntry *entry,
1608 uint32_t foundLength)
1610 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1611 if ( foundLength == 0xffffffff)
1616 uint16_t gr = entry->GetGroup();
1617 uint16_t elem = entry->GetElement();
1619 if ( foundLength % 2)
1621 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1622 << " in x(" << std::hex << gr << "," << elem <<")");
1625 //////// Fix for some naughty General Electric images.
1626 // Allthough not recent many such GE corrupted images are still present
1627 // on Creatis hard disks. Hence this fix shall remain when such images
1628 // are no longer in use (we are talking a few years, here)...
1629 // Note: XMedCom probably uses such a trick since it is able to read
1630 // those pesky GE images ...
1631 if ( foundLength == 13)
1633 // Only happens for this length !
1634 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1637 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1641 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1642 // Occurence of such images is quite low (unless one leaves close to a
1643 // 'Leonardo' source. Hence, one might consider commenting out the
1644 // following fix on efficiency reasons.
1645 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1648 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1651 else if ( entry->GetVR() == "SQ" )
1653 foundLength = 0; // ReadLength is unchanged
1656 //////// We encountered a 'delimiter' element i.e. a tag of the form
1657 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1658 // taken into account.
1659 else if( gr == 0xfffe )
1661 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1662 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1663 // causes extra troubles...
1664 if( entry->GetElement() != 0x0000 )
1669 entry->SetLength(foundLength);
1673 * \brief Apply some heuristics to predict whether the considered
1674 * element value contains/represents an integer or not.
1675 * @param entry The element value on which to apply the predicate.
1676 * @return The result of the heuristical predicate.
1678 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1680 uint16_t elem = entry->GetElement();
1681 uint16_t group = entry->GetGroup();
1682 const std::string &vr = entry->GetVR();
1683 uint32_t length = entry->GetLength();
1685 // When we have some semantics on the element we just read, and if we
1686 // a priori know we are dealing with an integer, then we shall be
1687 // able to swap it's element value properly.
1688 if ( elem == 0 ) // This is the group length of the group
1696 // Allthough this should never happen, still some images have a
1697 // corrupted group length [e.g. have a glance at offset x(8336) of
1698 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1699 // Since for dicom compliant and well behaved headers, the present
1700 // test is useless (and might even look a bit paranoid), when we
1701 // encounter such an ill-formed image, we simply display a warning
1702 // message and proceed on parsing (while crossing fingers).
1703 long filePosition = Fp->tellg();
1704 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1705 << std::hex << group << " , " << elem
1706 << ") -before- position x(" << filePosition << ")"
1707 << "lgt : " << length );
1711 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1719 * \brief Discover what the swap code is (among little endian, big endian,
1720 * bad little endian, bad big endian).
1722 * @return false when we are absolutely sure
1723 * it's neither ACR-NEMA nor DICOM
1724 * true when we hope ours assuptions are OK
1726 bool Document::CheckSwap()
1728 // The only guaranted way of finding the swap code is to find a
1729 // group tag since we know it's length has to be of four bytes i.e.
1730 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1731 // occurs when we can't find such group...
1733 uint32_t x = 4; // x : for ntohs
1734 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1740 // First, compare HostByteOrder and NetworkByteOrder in order to
1741 // determine if we shall need to swap bytes (i.e. the Endian type).
1742 if ( x == ntohs(x) )
1751 // The easiest case is the one of a 'true' DICOM header, we just have
1752 // to look for the string "DICM" inside the file preamble.
1755 char *entCur = deb + 128;
1756 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1758 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1760 // Group 0002 should always be VR, and the first element 0000
1761 // Let's be carefull (so many wrong headers ...)
1762 // and determine the value representation (VR) :
1763 // Let's skip to the first element (0002,0000) and check there if we find
1764 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1765 // in which case we (almost) know it is explicit VR.
1766 // WARNING: if it happens to be implicit VR then what we will read
1767 // is the length of the group. If this ascii representation of this
1768 // length happens to be "UL" then we shall believe it is explicit VR.
1769 // We need to skip :
1770 // * the 128 bytes of File Preamble (often padded with zeroes),
1771 // * the 4 bytes of "DICM" string,
1772 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1773 // i.e. a total of 136 bytes.
1776 // group 0x0002 *is always* Explicit VR Sometimes ,
1777 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1778 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1780 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1781 memcmp(entCur, "OB", (size_t)2) == 0 ||
1782 memcmp(entCur, "UI", (size_t)2) == 0 ||
1783 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1784 // when Write DCM *adds*
1786 // Use Document::dicom_vr to test all the possibilities
1787 // instead of just checking for UL, OB and UI !? group 0000
1789 Filetype = ExplicitVR;
1790 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
1794 Filetype = ImplicitVR;
1795 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
1796 << "Looks like a bugged Header!");
1802 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
1807 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
1810 // Position the file position indicator at first tag
1811 // (i.e. after the file preamble and the "DICM" string).
1812 Fp->seekg(0, std::ios::beg);
1813 Fp->seekg ( 132L, std::ios::beg);
1817 // Alas, this is not a DicomV3 file and whatever happens there is no file
1818 // preamble. We can reset the file position indicator to where the data
1819 // is (i.e. the beginning of the file).
1820 gdcmVerboseMacro( "Not a DICOM Version3 file");
1821 Fp->seekg(0, std::ios::beg);
1823 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1824 // By clean we mean that the length of the first tag is written down.
1825 // If this is the case and since the length of the first group HAS to be
1826 // four (bytes), then determining the proper swap code is straightforward.
1829 // We assume the array of char we are considering contains the binary
1830 // representation of a 32 bits integer. Hence the following dirty
1832 s32 = *((uint32_t *)(entCur));
1853 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1854 // It is time for despaired wild guesses.
1855 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1856 // i.e. the 'group length' element is not present :
1858 // check the supposed-to-be 'group number'
1859 // in ( 0x0001 .. 0x0008 )
1860 // to determine ' SwapCode' value .
1861 // Only 0 or 4321 will be possible
1862 // (no oportunity to check for the formerly well known
1863 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1864 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1865 // the file IS NOT ACR-NEMA nor DICOM V3
1866 // Find a trick to tell it the caller...
1868 s16 = *((uint16_t *)(deb));
1895 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1903 * \brief Change the Byte Swap code.
1905 void Document::SwitchByteSwapCode()
1907 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
1908 if ( SwapCode == 1234 )
1912 else if ( SwapCode == 4321 )
1916 else if ( SwapCode == 3412 )
1920 else if ( SwapCode == 2143 )
1927 * \brief during parsing, Header Elements too long are not loaded in memory
1930 void Document::SetMaxSizeLoadEntry(long newSize)
1936 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1938 MaxSizeLoadEntry = 0xffffffff;
1941 MaxSizeLoadEntry = newSize;
1945 * \brief Header Elements too long will not be printed
1946 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
1949 void Document::SetMaxSizePrintEntry(long newSize)
1955 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1957 MaxSizePrintEntry = 0xffffffff;
1960 MaxSizePrintEntry = newSize;
1965 * \brief Read the next tag but WITHOUT loading it's value
1966 * (read the 'Group Number', the 'Element Number',
1967 * gets the Dict Entry
1968 * gets the VR, gets the length, gets the offset value)
1969 * @return On succes the newly created DocEntry, NULL on failure.
1971 DocEntry *Document::ReadNextDocEntry()
1978 group = ReadInt16();
1981 catch ( FormatError e )
1983 // We reached the EOF (or an error occured) therefore
1984 // header parsing has to be considered as finished.
1988 // Sometimes file contains groups of tags with reversed endianess.
1989 HandleBrokenEndian(group, elem);
1991 // In 'true DICOM' files Group 0002 is always little endian
1992 if ( HasDCMPreamble )
1993 HandleOutOfGroup0002(group, elem);
1995 std::string vr = FindDocEntryVR();
1996 std::string realVR = vr;
1998 if( vr == GDCM_UNKNOWN)
2000 DictEntry *dictEntry = GetDictEntry(group,elem);
2002 realVR = dictEntry->GetVR();
2006 if( Global::GetVR()->IsVROfSequence(realVR) )
2007 newEntry = NewSeqEntry(group, elem);
2008 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2009 newEntry = NewValEntry(group, elem,vr);
2011 newEntry = NewBinEntry(group, elem,vr);
2013 if( vr == GDCM_UNKNOWN )
2015 if( Filetype == ExplicitVR )
2017 // We thought this was explicit VR, but we end up with an
2018 // implicit VR tag. Let's backtrack.
2019 if ( newEntry->GetGroup() != 0xfffe )
2022 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2023 newEntry->GetGroup(), newEntry->GetElement());
2024 gdcmVerboseMacro( msg.c_str() );
2027 newEntry->SetImplicitVR();
2032 FindDocEntryLength(newEntry);
2034 catch ( FormatError e )
2042 newEntry->SetOffset(Fp->tellg());
2048 * \brief Handle broken private tag from Philips NTSCAN
2049 * where the endianess is being switch to BigEndian for no
2053 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2055 // Endian reversion. Some files contain groups of tags with reversed endianess.
2056 static int reversedEndian = 0;
2057 // try to fix endian switching in the middle of headers
2058 if ((group == 0xfeff) && (elem == 0x00e0))
2060 // start endian swap mark for group found
2062 SwitchByteSwapCode();
2067 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2069 // end of reversed endian group
2071 SwitchByteSwapCode();
2076 * \brief Group 0002 is always coded Little Endian
2077 * whatever Transfer Syntax is
2080 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2082 // Endian reversion. Some files contain groups of tags with reversed endianess.
2083 if ( !Group0002Parsed && group != 0x0002)
2085 Group0002Parsed = true;
2086 // we just came out of group 0002
2087 // if Transfer syntax is Big Endian we have to change CheckSwap
2089 std::string ts = GetTransferSyntax();
2090 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2092 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2096 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2098 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2100 Filetype = ImplicitVR;
2103 // FIXME Strangely, this works with
2104 //'Implicit VR Transfer Syntax (GE Private)
2105 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2107 gdcmVerboseMacro("Transfer Syntax Name = ["
2108 << GetTransferSyntaxName() << "]" );
2109 SwitchByteSwapCode();
2110 group = SwapShort(group);
2111 elem = SwapShort(elem);
2116 //-----------------------------------------------------------------------------
2119 //-----------------------------------------------------------------------------
2120 } // end namespace gdcm