1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/02/02 10:02:17 $
7 Version: $Revision: 1.219 $
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 ) & 0x0ff00 ) | (( 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);
592 //-----------------------------------------------------------------------------
595 * \brief Reads a supposed to be 16 Bits integer
596 * (swaps it depending on processor endianity)
599 uint16_t Document::ReadInt16()
603 Fp->read ((char*)&g, (size_t)2);
606 throw FormatError( "Document::ReadInt16()", " file error." );
610 throw FormatError( "Document::ReadInt16()", "EOF." );
617 * \brief Reads a supposed to be 32 Bits integer
618 * (swaps it depending on processor endianity)
621 uint32_t Document::ReadInt32()
625 Fp->read ((char*)&g, (size_t)4);
628 throw FormatError( "Document::ReadInt32()", " file error." );
632 throw FormatError( "Document::ReadInt32()", "EOF." );
639 * \brief skips bytes inside the source file
640 * \warning NOT end user intended method !
643 void Document::SkipBytes(uint32_t nBytes)
645 //FIXME don't dump the returned value
646 Fp->seekg((long)nBytes, std::ios::cur);
650 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
651 * @param filetype Type of the File to be written
653 int Document::ComputeGroup0002Length( FileType filetype )
659 bool found0002 = false;
661 // for each zero-level Tag in the DCM Header
662 DocEntry *entry = GetFirstEntry();
665 gr = entry->GetGroup();
671 if( entry->GetElement() != 0x0000 )
675 if( filetype == ExplicitVR )
677 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
679 // explicit VR AND OB, OW, SQ : 4 more bytes
683 groupLength += 2 + 2 + 4 + entry->GetLength();
689 entry = GetNextEntry();
694 //-----------------------------------------------------------------------------
697 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
698 * @return length of the parsed set.
700 void Document::ParseDES(DocEntrySet *set, long offset,
701 long l_max, bool delim_mode)
703 DocEntry *newDocEntry = 0;
704 ValEntry *newValEntry;
705 BinEntry *newBinEntry;
706 SeqEntry *newSeqEntry;
712 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
718 newDocEntry = ReadNextDocEntry( );
725 vr = newDocEntry->GetVR();
726 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
727 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
728 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
730 if ( newValEntry || newBinEntry )
734 if ( Filetype == ExplicitVR &&
735 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
737 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
738 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
739 << "|" << newDocEntry->GetElement()
740 << " : Neither Valentry, nor BinEntry."
741 "Probably unknown VR.");
744 //////////////////// BinEntry or UNKOWN VR:
745 // When "this" is a Document the Key is simply of the
746 // form ( group, elem )...
747 if ( dynamic_cast< Document* > ( set ) )
749 newBinEntry->SetKey( newBinEntry->GetKey() );
751 // but when "this" is a SQItem, we are inserting this new
752 // valEntry in a sequence item, and the key has the
753 // generalized form (refer to \ref BaseTagKey):
754 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
756 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
757 + newBinEntry->GetKey() );
760 LoadDocEntry( newBinEntry );
761 if( !set->AddEntry( newBinEntry ) )
763 //Expect big troubles if here
764 //delete newBinEntry;
770 /////////////////////// ValEntry
771 // When "set" is a Document, then we are at the top of the
772 // hierarchy and the Key is simply of the form ( group, elem )...
773 if ( dynamic_cast< Document* > ( set ) )
775 newValEntry->SetKey( newValEntry->GetKey() );
777 // ...but when "set" is a SQItem, we are inserting this new
778 // valEntry in a sequence item. Hence the key has the
779 // generalized form (refer to \ref BaseTagKey):
780 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
782 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
783 + newValEntry->GetKey() );
786 LoadDocEntry( newValEntry );
787 bool delimitor=newValEntry->IsItemDelimitor();
788 if( !set->AddEntry( newValEntry ) )
790 // If here expect big troubles
791 //delete newValEntry; //otherwise mem leak
801 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
809 // Just to make sure we are at the beginning of next entry.
810 SkipToNextDocEntry(newDocEntry);
815 unsigned long l = newDocEntry->GetReadLength();
816 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
818 if ( l == 0xffffffff )
827 // no other way to create it ...
828 newSeqEntry->SetDelimitorMode( delim_mode );
830 // At the top of the hierarchy, stands a Document. When "set"
831 // is a Document, then we are building the first depth level.
832 // Hence the SeqEntry we are building simply has a depth
834 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
837 newSeqEntry->SetDepthLevel( 1 );
838 newSeqEntry->SetKey( newSeqEntry->GetKey() );
840 // But when "set" is already a SQItem, we are building a nested
841 // sequence, and hence the depth level of the new SeqEntry
842 // we are building, is one level deeper:
843 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
845 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
846 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
847 + newSeqEntry->GetKey() );
851 { // Don't try to parse zero-length sequences
852 ParseSQ( newSeqEntry,
853 newDocEntry->GetOffset(),
856 if( !set->AddEntry( newSeqEntry ) )
860 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
874 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
875 * @return parsed length for this level
877 void Document::ParseSQ( SeqEntry *seqEntry,
878 long offset, long l_max, bool delim_mode)
880 int SQItemNumber = 0;
882 long offsetStartCurrentSQItem = offset;
886 // the first time, we read the fff0,e000 of the first SQItem
887 DocEntry *newDocEntry = ReadNextDocEntry();
891 // FIXME Should warn user
896 if ( newDocEntry->IsSequenceDelimitor() )
898 seqEntry->SetDelimitationItem( newDocEntry );
902 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
907 // create the current SQItem
908 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
909 std::ostringstream newBase;
910 newBase << seqEntry->GetKey()
914 itemSQ->SetBaseTagKey( newBase.str() );
915 unsigned int l = newDocEntry->GetReadLength();
917 if ( l == 0xffffffff )
926 // when we're here, element fffe,e000 is already passed.
927 // it's lost for the SQItem we're going to process !!
929 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
930 //delete newDocEntry; // FIXME well ... it's too late to use it !
932 // Let's try :------------
933 // remove fff0,e000, created out of the SQItem
935 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
936 // fill up the current SQItem, starting at the beginning of fff0,e000
937 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
938 offsetStartCurrentSQItem = Fp->tellg();
939 // end try -----------------
941 seqEntry->AddSQItem( itemSQ, SQItemNumber );
943 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
951 * \brief Loads the element content if its length doesn't exceed
952 * the value specified with Document::SetMaxSizeLoadEntry()
953 * @param entry Header Entry (Dicom Element) to be dealt with
955 void Document::LoadDocEntry(DocEntry *entry)
957 uint16_t group = entry->GetGroup();
958 std::string vr = entry->GetVR();
959 uint32_t length = entry->GetLength();
961 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
963 // A SeQuence "contains" a set of Elements.
964 // (fffe e000) tells us an Element is beginning
965 // (fffe e00d) tells us an Element just ended
966 // (fffe e0dd) tells us the current SeQuence just ended
967 if( group == 0xfffe )
969 // NO more value field for SQ !
973 // When the length is zero things are easy:
976 ((ValEntry *)entry)->SetValue("");
980 // The elements whose length is bigger than the specified upper bound
981 // are not loaded. Instead we leave a short notice of the offset of
982 // the element content and it's length.
984 std::ostringstream s;
985 if (length > MaxSizeLoadEntry)
987 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
989 //s << "gdcm::NotLoaded (BinEntry)";
991 s << " Address:" << (long)entry->GetOffset();
992 s << " Length:" << entry->GetLength();
993 s << " x(" << std::hex << entry->GetLength() << ")";
994 binEntryPtr->SetValue(s.str());
996 // Be carefull : a BinEntry IS_A ValEntry ...
997 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
999 // s << "gdcm::NotLoaded. (ValEntry)";
1000 s << GDCM_NOTLOADED;
1001 s << " Address:" << (long)entry->GetOffset();
1002 s << " Length:" << entry->GetLength();
1003 s << " x(" << std::hex << entry->GetLength() << ")";
1004 valEntryPtr->SetValue(s.str());
1009 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1010 << "nor a ValEntry ?! Should never print that !" );
1013 // to be sure we are at the end of the value ...
1014 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1019 // When we find a BinEntry not very much can be done :
1020 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1022 s << GDCM_BINLOADED;
1023 binEntryPtr->SetValue(s.str());
1024 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1028 /// \todo Any compacter code suggested (?)
1029 if ( IsDocEntryAnInteger(entry) )
1033 // When short integer(s) are expected, read and convert the following
1034 // n *two characters properly i.e. consider them as short integers as
1035 // opposed to strings.
1036 // Elements with Value Multiplicity > 1
1037 // contain a set of integers (not a single one)
1038 if (vr == "US" || vr == "SS")
1041 NewInt = ReadInt16();
1045 for (int i=1; i < nbInt; i++)
1048 NewInt = ReadInt16();
1053 // See above comment on multiple integers (mutatis mutandis).
1054 else if (vr == "UL" || vr == "SL")
1057 NewInt = ReadInt32();
1061 for (int i=1; i < nbInt; i++)
1064 NewInt = ReadInt32();
1069 #ifdef GDCM_NO_ANSI_STRING_STREAM
1070 s << std::ends; // to avoid oddities on Solaris
1071 #endif //GDCM_NO_ANSI_STRING_STREAM
1073 ((ValEntry *)entry)->SetValue(s.str());
1077 // FIXME: We need an additional byte for storing \0 that is not on disk
1078 char *str = new char[length+1];
1079 Fp->read(str, (size_t)length);
1080 str[length] = '\0'; //this is only useful when length is odd
1081 // Special DicomString call to properly handle \0 and even length
1082 std::string newValue;
1085 newValue = Util::DicomString(str, length+1);
1086 gdcmVerboseMacro("Warning: bad length: " << length <<
1087 ",For string :" << newValue.c_str());
1088 // Since we change the length of string update it length
1089 //entry->SetReadLength(length+1);
1093 newValue = Util::DicomString(str, length);
1097 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1099 if ( Fp->fail() || Fp->eof())
1101 gdcmVerboseMacro("Unread element value");
1102 valEntry->SetValue(GDCM_UNREAD);
1108 // Because of correspondance with the VR dic
1109 valEntry->SetValue(newValue);
1113 valEntry->SetValue(newValue);
1118 gdcmErrorMacro( "Should have a ValEntry, here !");
1123 * \brief Find the value Length of the passed Header Entry
1124 * @param entry Header Entry whose length of the value shall be loaded.
1126 void Document::FindDocEntryLength( DocEntry *entry )
1127 throw ( FormatError )
1129 std::string vr = entry->GetVR();
1132 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1134 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1136 // The following reserved two bytes (see PS 3.5-2003, section
1137 // "7.1.2 Data element structure with explicit vr", p 27) must be
1138 // skipped before proceeding on reading the length on 4 bytes.
1139 Fp->seekg( 2L, std::ios::cur);
1140 uint32_t length32 = ReadInt32();
1142 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1147 lengthOB = FindDocEntryLengthOBOrOW();
1149 catch ( FormatUnexpected )
1151 // Computing the length failed (this happens with broken
1152 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1153 // chance to get the pixels by deciding the element goes
1154 // until the end of the file. Hence we artificially fix the
1155 // the length and proceed.
1156 long currentPosition = Fp->tellg();
1157 Fp->seekg(0L,std::ios::end);
1159 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1160 Fp->seekg(currentPosition, std::ios::beg);
1162 entry->SetReadLength(lengthUntilEOF);
1163 entry->SetLength(lengthUntilEOF);
1166 entry->SetReadLength(lengthOB);
1167 entry->SetLength(lengthOB);
1170 FixDocEntryFoundLength(entry, length32);
1174 // Length is encoded on 2 bytes.
1175 length16 = ReadInt16();
1177 // FIXME : This heuristic supposes that the first group following
1178 // group 0002 *has* and element 0000.
1179 // BUT ... Element 0000 is optionnal :-(
1182 // Fixed using : HandleOutOfGroup0002()
1183 // (first hereafter strategy ...)
1185 // We can tell the current file is encoded in big endian (like
1186 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1187 // and it's value is the one of the encoding of a big endian file.
1188 // In order to deal with such big endian encoded files, we have
1189 // (at least) two strategies:
1190 // * when we load the "Transfer Syntax" tag with value of big endian
1191 // encoding, we raise the proper flags. Then we wait for the end
1192 // of the META group (0x0002) among which is "Transfer Syntax",
1193 // before switching the swap code to big endian. We have to postpone
1194 // the switching of the swap code since the META group is fully encoded
1195 // in little endian, and big endian coding only starts at the next
1196 // group. The corresponding code can be hard to analyse and adds
1197 // many additional unnecessary tests for regular tags.
1198 // * the second strategy consists in waiting for trouble, that shall
1199 // appear when we find the first group with big endian encoding. This
1200 // is easy to detect since the length of a "Group Length" tag (the
1201 // ones with zero as element number) has to be of 4 (0x0004). When we
1202 // encounter 1024 (0x0400) chances are the encoding changed and we
1203 // found a group with big endian encoding.
1204 //---> Unfortunately, element 0000 is optional.
1205 //---> This will not work when missing!
1206 // We shall use this second strategy. In order to make sure that we
1207 // can interpret the presence of an apparently big endian encoded
1208 // length of a "Group Length" without committing a big mistake, we
1209 // add an additional check: we look in the already parsed elements
1210 // for the presence of a "Transfer Syntax" whose value has to be "big
1211 // endian encoding". When this is the case, chances are we have got our
1212 // hands on a big endian encoded file: we switch the swap code to
1213 // big endian and proceed...
1215 // if ( element == 0x0000 && length16 == 0x0400 )
1217 // std::string ts = GetTransferSyntax();
1218 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1219 // != TS::ExplicitVRBigEndian )
1221 // throw FormatError( "Document::FindDocEntryLength()",
1222 // " not explicit VR." );
1226 // SwitchByteSwapCode();
1228 // // Restore the unproperly loaded values i.e. the group, the element
1229 // // and the dictionary entry depending on them.
1230 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1231 // uint16_t correctElem = SwapShort( entry->GetElement() );
1232 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1235 // // This correct tag is not in the dictionary. Create a new one.
1236 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1238 // // FIXME this can create a memory leaks on the old entry that be
1239 // // left unreferenced.
1240 // entry->SetDictEntry( newTag );
1243 // 0xffff means that we deal with 'No Length' Sequence
1244 // or 'No Length' SQItem
1245 if ( length16 == 0xffff)
1249 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1254 // Either implicit VR or a non DICOM conformal (see note below) explicit
1255 // VR that ommited the VR of (at least) this element. Farts happen.
1256 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1257 // on Data elements "Implicit and Explicit VR Data Elements shall
1258 // not coexist in a Data Set and Data Sets nested within it".]
1259 // Length is on 4 bytes.
1261 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1262 // even if Transfer Syntax is 'Implicit VR ...'
1264 FixDocEntryFoundLength( entry, ReadInt32() );
1270 * \brief Find the Length till the next sequence delimiter
1271 * \warning NOT end user intended method !
1274 uint32_t Document::FindDocEntryLengthOBOrOW()
1275 throw( FormatUnexpected )
1277 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1278 long positionOnEntry = Fp->tellg();
1279 bool foundSequenceDelimiter = false;
1280 uint32_t totalLength = 0;
1282 while ( !foundSequenceDelimiter )
1288 group = ReadInt16();
1291 catch ( FormatError )
1293 throw FormatError("Unexpected end of file encountered during ",
1294 "Document::FindDocEntryLengthOBOrOW()");
1296 // We have to decount the group and element we just read
1298 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1300 long filePosition = Fp->tellg();
1301 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1302 << std::hex << group << " , " << elem
1303 << ") -before- position x(" << filePosition << ")" );
1305 Fp->seekg(positionOnEntry, std::ios::beg);
1306 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1308 if ( elem == 0xe0dd )
1310 foundSequenceDelimiter = true;
1312 uint32_t itemLength = ReadInt32();
1313 // We add 4 bytes since we just read the ItemLength with ReadInt32
1314 totalLength += itemLength + 4;
1315 SkipBytes(itemLength);
1317 if ( foundSequenceDelimiter )
1322 Fp->seekg( positionOnEntry, std::ios::beg);
1327 * \brief Find the Value Representation of the current Dicom Element.
1328 * @return Value Representation of the current Entry
1330 std::string Document::FindDocEntryVR()
1332 if ( Filetype != ExplicitVR )
1333 return GDCM_UNKNOWN;
1335 long positionOnEntry = Fp->tellg();
1336 // Warning: we believe this is explicit VR (Value Representation) because
1337 // we used a heuristic that found "UL" in the first tag. Alas this
1338 // doesn't guarantee that all the tags will be in explicit VR. In some
1339 // cases (see e-film filtered files) one finds implicit VR tags mixed
1340 // within an explicit VR file. Hence we make sure the present tag
1341 // is in explicit VR and try to fix things if it happens not to be
1345 Fp->read (vr, (size_t)2);
1348 if( !CheckDocEntryVR(vr) )
1350 Fp->seekg(positionOnEntry, std::ios::beg);
1351 return GDCM_UNKNOWN;
1357 * \brief Check the correspondance between the VR of the header entry
1358 * and the taken VR. If they are different, the header entry is
1359 * updated with the new VR.
1360 * @param vr Dicom Value Representation
1361 * @return false if the VR is incorrect of if the VR isn't referenced
1362 * otherwise, it returns true
1364 bool Document::CheckDocEntryVR(VRKey vr)
1366 // CLEANME searching the dicom_vr at each occurence is expensive.
1367 // PostPone this test in an optional integrity check at the end
1368 // of parsing or only in debug mode.
1369 if ( !Global::GetVR()->IsValidVR(vr) )
1376 * \brief Get the transformed value of the header entry. The VR value
1377 * is used to define the transformation to operate on the value
1378 * \warning NOT end user intended method !
1379 * @param entry entry to tranform
1380 * @return Transformed entry value
1382 std::string Document::GetDocEntryValue(DocEntry *entry)
1384 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1386 std::string val = ((ValEntry *)entry)->GetValue();
1387 std::string vr = entry->GetVR();
1388 uint32_t length = entry->GetLength();
1389 std::ostringstream s;
1392 // When short integer(s) are expected, read and convert the following
1393 // n * 2 bytes properly i.e. as a multivaluated strings
1394 // (each single value is separated fromthe next one by '\'
1395 // as usual for standard multivaluated filels
1396 // Elements with Value Multiplicity > 1
1397 // contain a set of short integers (not a single one)
1399 if( vr == "US" || vr == "SS" )
1404 for (int i=0; i < nbInt; i++)
1410 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1411 newInt16 = SwapShort( newInt16 );
1416 // When integer(s) are expected, read and convert the following
1417 // n * 4 bytes properly i.e. as a multivaluated strings
1418 // (each single value is separated fromthe next one by '\'
1419 // as usual for standard multivaluated filels
1420 // Elements with Value Multiplicity > 1
1421 // contain a set of integers (not a single one)
1422 else if( vr == "UL" || vr == "SL" )
1427 for (int i=0; i < nbInt; i++)
1433 newInt32 = ( val[4*i+0] & 0xFF )
1434 + (( val[4*i+1] & 0xFF ) << 8 )
1435 + (( val[4*i+2] & 0xFF ) << 16 )
1436 + (( val[4*i+3] & 0xFF ) << 24 );
1437 newInt32 = SwapLong( newInt32 );
1441 #ifdef GDCM_NO_ANSI_STRING_STREAM
1442 s << std::ends; // to avoid oddities on Solaris
1443 #endif //GDCM_NO_ANSI_STRING_STREAM
1446 return ((ValEntry *)entry)->GetValue();
1450 * \brief Get the reverse transformed value of the header entry. The VR
1451 * value is used to define the reverse transformation to operate on
1453 * \warning NOT end user intended method !
1454 * @param entry Entry to reverse transform
1455 * @return Reverse transformed entry value
1457 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1459 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1461 std::string vr = entry->GetVR();
1462 std::vector<std::string> tokens;
1463 std::ostringstream s;
1465 if ( vr == "US" || vr == "SS" )
1469 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1470 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1471 for (unsigned int i=0; i<tokens.size(); i++)
1473 newInt16 = atoi(tokens[i].c_str());
1474 s << ( newInt16 & 0xFF )
1475 << (( newInt16 >> 8 ) & 0xFF );
1479 if ( vr == "UL" || vr == "SL")
1483 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1484 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1485 for (unsigned int i=0; i<tokens.size();i++)
1487 newInt32 = atoi(tokens[i].c_str());
1488 s << (char)( newInt32 & 0xFF )
1489 << (char)(( newInt32 >> 8 ) & 0xFF )
1490 << (char)(( newInt32 >> 16 ) & 0xFF )
1491 << (char)(( newInt32 >> 24 ) & 0xFF );
1496 #ifdef GDCM_NO_ANSI_STRING_STREAM
1497 s << std::ends; // to avoid oddities on Solaris
1498 #endif //GDCM_NO_ANSI_STRING_STREAM
1502 return ((ValEntry *)entry)->GetValue();
1506 * \brief Skip a given Header Entry
1507 * \warning NOT end user intended method !
1508 * @param entry entry to skip
1510 void Document::SkipDocEntry(DocEntry *entry)
1512 SkipBytes(entry->GetLength());
1516 * \brief Skips to the beginning of the next Header Entry
1517 * \warning NOT end user intended method !
1518 * @param currentDocEntry entry to skip
1520 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1522 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1523 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1524 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1528 * \brief When the length of an element value is obviously wrong (because
1529 * the parser went Jabberwocky) one can hope improving things by
1530 * applying some heuristics.
1531 * @param entry entry to check
1532 * @param foundLength first assumption about length
1534 void Document::FixDocEntryFoundLength(DocEntry *entry,
1535 uint32_t foundLength)
1537 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1538 if ( foundLength == 0xffffffff)
1543 uint16_t gr = entry->GetGroup();
1544 uint16_t elem = entry->GetElement();
1546 if ( foundLength % 2)
1548 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1549 << " in x(" << std::hex << gr << "," << elem <<")");
1552 //////// Fix for some naughty General Electric images.
1553 // Allthough not recent many such GE corrupted images are still present
1554 // on Creatis hard disks. Hence this fix shall remain when such images
1555 // are no longer in use (we are talking a few years, here)...
1556 // Note: XMedCom probably uses such a trick since it is able to read
1557 // those pesky GE images ...
1558 if ( foundLength == 13)
1560 // Only happens for this length !
1561 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1564 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1568 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1569 // Occurence of such images is quite low (unless one leaves close to a
1570 // 'Leonardo' source. Hence, one might consider commenting out the
1571 // following fix on efficiency reasons.
1572 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1575 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1578 else if ( entry->GetVR() == "SQ" )
1580 foundLength = 0; // ReadLength is unchanged
1583 //////// We encountered a 'delimiter' element i.e. a tag of the form
1584 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1585 // taken into account.
1586 else if( gr == 0xfffe )
1588 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1589 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1590 // causes extra troubles...
1591 if( entry->GetElement() != 0x0000 )
1596 entry->SetLength(foundLength);
1600 * \brief Apply some heuristics to predict whether the considered
1601 * element value contains/represents an integer or not.
1602 * @param entry The element value on which to apply the predicate.
1603 * @return The result of the heuristical predicate.
1605 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1607 uint16_t elem = entry->GetElement();
1608 uint16_t group = entry->GetGroup();
1609 const std::string &vr = entry->GetVR();
1610 uint32_t length = entry->GetLength();
1612 // When we have some semantics on the element we just read, and if we
1613 // a priori know we are dealing with an integer, then we shall be
1614 // able to swap it's element value properly.
1615 if ( elem == 0 ) // This is the group length of the group
1623 // Allthough this should never happen, still some images have a
1624 // corrupted group length [e.g. have a glance at offset x(8336) of
1625 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1626 // Since for dicom compliant and well behaved headers, the present
1627 // test is useless (and might even look a bit paranoid), when we
1628 // encounter such an ill-formed image, we simply display a warning
1629 // message and proceed on parsing (while crossing fingers).
1630 long filePosition = Fp->tellg();
1631 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1632 << std::hex << group << " , " << elem
1633 << ") -before- position x(" << filePosition << ")"
1634 << "lgt : " << length );
1638 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1646 * \brief Loads all the needed Dictionaries
1647 * \warning NOT end user intended method !
1649 void Document::Initialize()
1651 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1657 * \brief Discover what the swap code is (among little endian, big endian,
1658 * bad little endian, bad big endian).
1660 * @return false when we are absolutely sure
1661 * it's neither ACR-NEMA nor DICOM
1662 * true when we hope ours assuptions are OK
1664 bool Document::CheckSwap()
1666 // The only guaranted way of finding the swap code is to find a
1667 // group tag since we know it's length has to be of four bytes i.e.
1668 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1669 // occurs when we can't find such group...
1671 uint32_t x = 4; // x : for ntohs
1672 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1678 // First, compare HostByteOrder and NetworkByteOrder in order to
1679 // determine if we shall need to swap bytes (i.e. the Endian type).
1680 if ( x == ntohs(x) )
1689 // The easiest case is the one of a 'true' DICOM header, we just have
1690 // to look for the string "DICM" inside the file preamble.
1693 char *entCur = deb + 128;
1694 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1696 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1698 // Group 0002 should always be VR, and the first element 0000
1699 // Let's be carefull (so many wrong headers ...)
1700 // and determine the value representation (VR) :
1701 // Let's skip to the first element (0002,0000) and check there if we find
1702 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1703 // in which case we (almost) know it is explicit VR.
1704 // WARNING: if it happens to be implicit VR then what we will read
1705 // is the length of the group. If this ascii representation of this
1706 // length happens to be "UL" then we shall believe it is explicit VR.
1707 // We need to skip :
1708 // * the 128 bytes of File Preamble (often padded with zeroes),
1709 // * the 4 bytes of "DICM" string,
1710 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1711 // i.e. a total of 136 bytes.
1714 // group 0x0002 *is always* Explicit VR Sometimes ,
1715 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1716 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1718 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1719 memcmp(entCur, "OB", (size_t)2) == 0 ||
1720 memcmp(entCur, "UI", (size_t)2) == 0 ||
1721 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1722 // when Write DCM *adds*
1724 // Use Document::dicom_vr to test all the possibilities
1725 // instead of just checking for UL, OB and UI !? group 0000
1727 Filetype = ExplicitVR;
1728 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
1732 Filetype = ImplicitVR;
1733 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
1734 << "Looks like a bugged Header!");
1740 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
1745 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
1748 // Position the file position indicator at first tag
1749 // (i.e. after the file preamble and the "DICM" string).
1750 Fp->seekg(0, std::ios::beg);
1751 Fp->seekg ( 132L, std::ios::beg);
1755 // Alas, this is not a DicomV3 file and whatever happens there is no file
1756 // preamble. We can reset the file position indicator to where the data
1757 // is (i.e. the beginning of the file).
1758 gdcmVerboseMacro( "Not a DICOM Version3 file");
1759 Fp->seekg(0, std::ios::beg);
1761 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1762 // By clean we mean that the length of the first tag is written down.
1763 // If this is the case and since the length of the first group HAS to be
1764 // four (bytes), then determining the proper swap code is straightforward.
1767 // We assume the array of char we are considering contains the binary
1768 // representation of a 32 bits integer. Hence the following dirty
1770 s32 = *((uint32_t *)(entCur));
1791 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1792 // It is time for despaired wild guesses.
1793 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1794 // i.e. the 'group length' element is not present :
1796 // check the supposed-to-be 'group number'
1797 // in ( 0x0001 .. 0x0008 )
1798 // to determine ' SwapCode' value .
1799 // Only 0 or 4321 will be possible
1800 // (no oportunity to check for the formerly well known
1801 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1802 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1803 // the file IS NOT ACR-NEMA nor DICOM V3
1804 // Find a trick to tell it the caller...
1806 s16 = *((uint16_t *)(deb));
1833 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1841 * \brief Change the Byte Swap code.
1843 void Document::SwitchByteSwapCode()
1845 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
1846 if ( SwapCode == 1234 )
1850 else if ( SwapCode == 4321 )
1854 else if ( SwapCode == 3412 )
1858 else if ( SwapCode == 2143 )
1865 * \brief during parsing, Header Elements too long are not loaded in memory
1868 void Document::SetMaxSizeLoadEntry(long newSize)
1874 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1876 MaxSizeLoadEntry = 0xffffffff;
1879 MaxSizeLoadEntry = newSize;
1883 * \brief Header Elements too long will not be printed
1884 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
1887 void Document::SetMaxSizePrintEntry(long newSize)
1893 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1895 MaxSizePrintEntry = 0xffffffff;
1898 MaxSizePrintEntry = newSize;
1903 * \brief Read the next tag but WITHOUT loading it's value
1904 * (read the 'Group Number', the 'Element Number',
1905 * gets the Dict Entry
1906 * gets the VR, gets the length, gets the offset value)
1907 * @return On succes the newly created DocEntry, NULL on failure.
1909 DocEntry *Document::ReadNextDocEntry()
1916 group = ReadInt16();
1919 catch ( FormatError e )
1921 // We reached the EOF (or an error occured) therefore
1922 // header parsing has to be considered as finished.
1926 // Sometimes file contains groups of tags with reversed endianess.
1927 HandleBrokenEndian(group, elem);
1929 // In 'true DICOM' files Group 0002 is always little endian
1930 if ( HasDCMPreamble )
1931 HandleOutOfGroup0002(group, elem);
1933 std::string vr = FindDocEntryVR();
1934 std::string realVR = vr;
1936 if( vr == GDCM_UNKNOWN)
1938 DictEntry *dictEntry = GetDictEntry(group,elem);
1940 realVR = dictEntry->GetVR();
1944 if( Global::GetVR()->IsVROfSequence(realVR) )
1945 newEntry = NewSeqEntry(group, elem);
1946 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1947 newEntry = NewValEntry(group, elem,vr);
1949 newEntry = NewBinEntry(group, elem,vr);
1951 if( vr == GDCM_UNKNOWN )
1953 if( Filetype == ExplicitVR )
1955 // We thought this was explicit VR, but we end up with an
1956 // implicit VR tag. Let's backtrack.
1957 if ( newEntry->GetGroup() != 0xfffe )
1960 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
1961 newEntry->GetGroup(), newEntry->GetElement());
1962 gdcmVerboseMacro( msg.c_str() );
1965 newEntry->SetImplicitVR();
1970 FindDocEntryLength(newEntry);
1972 catch ( FormatError e )
1980 newEntry->SetOffset(Fp->tellg());
1986 * \brief Handle broken private tag from Philips NTSCAN
1987 * where the endianess is being switch to BigEndian for no
1991 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
1993 // Endian reversion. Some files contain groups of tags with reversed endianess.
1994 static int reversedEndian = 0;
1995 // try to fix endian switching in the middle of headers
1996 if ((group == 0xfeff) && (elem == 0x00e0))
1998 // start endian swap mark for group found
2000 SwitchByteSwapCode();
2005 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2007 // end of reversed endian group
2009 SwitchByteSwapCode();
2014 * \brief Group 0002 is always coded Little Endian
2015 * whatever Transfer Syntax is
2018 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2020 // Endian reversion. Some files contain groups of tags with reversed endianess.
2021 if ( !Group0002Parsed && group != 0x0002)
2023 Group0002Parsed = true;
2024 // we just came out of group 0002
2025 // if Transfer syntax is Big Endian we have to change CheckSwap
2027 std::string ts = GetTransferSyntax();
2028 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2030 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2034 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2036 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2038 Filetype = ImplicitVR;
2041 // FIXME Strangely, this works with
2042 //'Implicit VR Transfer Syntax (GE Private)
2043 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2045 gdcmVerboseMacro("Transfer Syntax Name = ["
2046 << GetTransferSyntaxName() << "]" );
2047 SwitchByteSwapCode();
2048 group = SwapShort(group);
2049 elem = SwapShort(elem);
2055 * \brief Compares two documents, according to \ref DicomDir rules
2056 * \warning Does NOT work with ACR-NEMA files
2057 * \todo Find a trick to solve the pb (use RET fields ?)
2059 * @return true if 'smaller'
2061 bool Document::operator<(Document &document)
2064 std::string s1 = GetEntryValue(0x0010,0x0010);
2065 std::string s2 = document.GetEntryValue(0x0010,0x0010);
2077 s1 = GetEntryValue(0x0010,0x0020);
2078 s2 = document.GetEntryValue(0x0010,0x0020);
2089 // Study Instance UID
2090 s1 = GetEntryValue(0x0020,0x000d);
2091 s2 = document.GetEntryValue(0x0020,0x000d);
2102 // Serie Instance UID
2103 s1 = GetEntryValue(0x0020,0x000e);
2104 s2 = document.GetEntryValue(0x0020,0x000e);
2119 //-----------------------------------------------------------------------------
2122 * \brief Prints The Dict Entries of THE public Dicom Dictionary
2123 * @param os ostream to print to
2126 void Document::PrintPubDict(std::ostream &os)
2128 RefPubDict->SetPrintLevel(PrintLevel);
2129 RefPubDict->Print(os);
2133 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
2134 * @param os ostream to print to
2137 void Document::PrintShaDict(std::ostream &os)
2139 RefShaDict->SetPrintLevel(PrintLevel);
2140 RefShaDict->Print(os);
2143 //-----------------------------------------------------------------------------
2144 } // end namespace gdcm