1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/02/11 20:04:08 $
7 Version: $Revision: 1.229 $
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"
37 //-----------------------------------------------------------------------------
38 // Refer to Document::CheckSwap()
39 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
41 // Refer to Document::SetMaxSizeLoadEntry()
42 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
43 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
45 //-----------------------------------------------------------------------------
46 // Constructor / Destructor
47 // Constructors and destructors are protected to avoid user to invoke directly
50 * @param filename 'Document' (File or DicomDir) to be opened for parsing
52 Document::Document( std::string const &filename )
55 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
65 Group0002Parsed = false;
67 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
69 Fp->seekg(0, std::ios::end);
70 long lgt = Fp->tellg();
72 Fp->seekg(0, std::ios::beg);
75 long beg = Fp->tellg();
78 ParseDES( this, beg, lgt, false); // Loading is done during parsing
80 Fp->seekg( 0, std::ios::beg);
82 // Load 'non string' values
84 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
85 if( PhotometricInterpretation == "PALETTE COLOR " )
87 LoadEntryBinArea(0x0028,0x1200); // gray LUT
89 /// The tags refered by the three following lines used to be CORRECTLY
90 /// defined as having an US Value Representation in the public
91 /// dictionary. BUT the semantics implied by the three following
92 /// lines state that the corresponding tag contents are in fact
93 /// the ones of a BinEntry.
94 /// In order to fix things "Quick and Dirty" the dictionary was
95 /// altered on PURPOSE but now contains a WRONG value.
96 /// In order to fix things and restore the dictionary to its
97 /// correct value, one needs to decided of the semantics by deciding
98 /// whether the following tags are either:
99 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
100 /// also used as BinEntry, which requires the proper conversion,
101 /// - OW, and hence loaded as BinEntry, but afterwards also used
102 /// as ValEntry, which requires the proper conversion.
103 LoadEntryBinArea(0x0028,0x1201); // R LUT
104 LoadEntryBinArea(0x0028,0x1202); // G LUT
105 LoadEntryBinArea(0x0028,0x1203); // B LUT
107 // Segmented Red Palette Color LUT Data
108 LoadEntryBinArea(0x0028,0x1221);
109 // Segmented Green Palette Color LUT Data
110 LoadEntryBinArea(0x0028,0x1222);
111 // Segmented Blue Palette Color LUT Data
112 LoadEntryBinArea(0x0028,0x1223);
114 //FIXME later : how to use it?
115 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
119 // ----------------------------
120 // Specific code to allow gdcm to read ACR-LibIDO formated images
121 // Note: ACR-LibIDO is an extension of the ACR standard that was
122 // used at CREATIS. For the time being (say a couple years)
123 // we keep this kludge to allow a smooth move to gdcm for
124 // CREATIS developpers (sorry folks).
126 // if recognition code tells us we deal with a LibIDO image
127 // we switch lineNumber and columnNumber
130 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
131 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
132 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
133 // with "little-endian strings"
135 Filetype = ACR_LIBIDO;
136 std::string rows = GetEntryValue(0x0028, 0x0010);
137 std::string columns = GetEntryValue(0x0028, 0x0011);
138 SetValEntry(columns, 0x0028, 0x0010);
139 SetValEntry(rows , 0x0028, 0x0011);
141 // --- End of ACR-LibIDO kludge ---
145 * \brief This default constructor doesn't parse the file. You should
146 * then invoke \ref Document::SetFileName and then the parsing.
153 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
156 Filetype = ExplicitVR;
157 Group0002Parsed = false;
161 * \brief Canonical destructor.
163 Document::~Document ()
169 //-----------------------------------------------------------------------------
172 * \brief Get the public dictionary used
174 Dict *Document::GetPubDict()
180 * \brief Get the shadow dictionary used
182 Dict *Document::GetShaDict()
188 * \brief Set the shadow dictionary used
189 * @param dict dictionary to use in shadow
191 bool Document::SetShaDict(Dict *dict)
198 * \brief Set the shadow dictionary used
199 * @param dictName name of the dictionary to use in shadow
201 bool Document::SetShaDict(DictKey const &dictName)
203 RefShaDict = Global::GetDicts()->GetDict(dictName);
208 * \brief This predicate, based on hopefully reasonable heuristics,
209 * decides whether or not the current Document was properly parsed
210 * and contains the mandatory information for being considered as
211 * a well formed and usable Dicom/Acr File.
212 * @return true when Document is the one of a reasonable Dicom/Acr file,
215 bool Document::IsReadable()
217 if( Filetype == Unknown)
219 gdcmWarningMacro( "Wrong filetype");
225 gdcmWarningMacro( "No tag in internal hash table.");
233 * \brief Predicate for dicom version 3 file.
234 * @return True when the file is a dicom version 3.
236 bool Document::IsDicomV3()
238 // Checking if Transfer Syntax exists is enough
239 // Anyway, it's to late check if the 'Preamble' was found ...
240 // And ... would it be a rich idea to check ?
241 // (some 'no Preamble' DICOM images exist !)
242 return GetDocEntry(0x0002, 0x0010) != NULL;
246 * \brief Predicate for Papyrus file
247 * Dedicated to whomsoever it may concern
248 * @return True when the file is a Papyrus file.
250 bool Document::IsPapyrus()
252 // check for Papyrus private Sequence
253 DocEntry *e = GetDocEntry(0x0041, 0x1050);
256 // check if it's actually a Sequence
257 if ( !dynamic_cast<SeqEntry*>(e) )
263 * \brief returns the File Type
264 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
265 * @return the FileType code
267 FileType Document::GetFileType()
273 * \brief Accessor to the Transfer Syntax (when present) of the
274 * current document (it internally handles reading the
275 * value from disk when only parsing occured).
276 * @return The encountered Transfer Syntax of the current document.
278 std::string Document::GetTransferSyntax()
280 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
286 // The entry might be present but not loaded (parsing and loading
287 // happen at different stages): try loading and proceed with check...
288 LoadDocEntrySafe(entry);
289 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
291 std::string transfer = valEntry->GetValue();
292 // The actual transfer (as read from disk) might be padded. We
293 // first need to remove the potential padding. We can make the
294 // weak assumption that padding was not executed with digits...
295 if ( transfer.length() == 0 )
297 // for brain damaged headers
300 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
302 transfer.erase(transfer.length()-1, 1);
310 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
311 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
313 std::string Document::GetTransferSyntaxName()
315 // use the TS (TS : Transfer Syntax)
316 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
318 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
320 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
321 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
322 return "Uncompressed ACR-NEMA";
324 if ( transferSyntax == GDCM_UNFOUND )
326 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
327 return "Uncompressed ACR-NEMA";
330 // we do it only when we need it
331 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
333 // Global::GetTS() is a global static you shall never try to delete it!
337 // --------------- Swap Code ------------------
339 * \brief Swaps the bytes so they agree with the processor order
340 * @return The properly swaped 16 bits integer.
342 uint16_t Document::SwapShort(uint16_t a)
344 if ( SwapCode == 4321 || SwapCode == 2143 )
346 a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
352 * \brief Swaps back the bytes of 4-byte long integer accordingly to
354 * @return The properly swaped 32 bits integer.
356 uint32_t Document::SwapLong(uint32_t a)
363 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
364 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
367 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
370 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
373 gdcmErrorMacro( "Unset swap code:" << SwapCode );
380 // -----------------File I/O ---------------
382 * \brief Tries to open the file \ref Document::Filename and
383 * checks the preamble when existing.
384 * @return The FILE pointer on success.
386 std::ifstream *Document::OpenFile()
388 HasDCMPreamble = false;
389 if (Filename.length() == 0)
396 gdcmWarningMacro( "File already open: " << Filename.c_str());
400 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
403 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
410 Fp->read((char*)&zero, (size_t)2);
417 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
419 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
420 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
421 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
422 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
425 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
426 gdcmWarningMacro( msg.c_str() );
431 Fp->seekg(126L, std::ios::cur);
432 char dicm[4] = {' ',' ',' ',' '};
433 Fp->read(dicm, (size_t)4);
439 if( memcmp(dicm, "DICM", 4) == 0 )
441 HasDCMPreamble = true;
446 gdcmWarningMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
452 * \brief closes the file
453 * @return TRUE if the close was successfull
455 bool Document::CloseFile()
467 * \brief Writes in a file all the Header Entries (Dicom Elements)
468 * @param fp file pointer on an already open file (actually: Output File Stream)
469 * @param filetype Type of the File to be written
470 * (ACR-NEMA, ExplicitVR, ImplicitVR)
471 * @return Always true.
473 void Document::WriteContent(std::ofstream *fp, FileType filetype)
475 // \TODO move the following lines (and a lot of others, to be written)
476 // to a future function CheckAndCorrectHeader
478 // (necessary if user wants to write a DICOM V3 file
479 // starting from an ACR-NEMA (V2) Header
481 if ( filetype == ImplicitVR || filetype == ExplicitVR )
483 // writing Dicom File Preamble
484 char filePreamble[128];
485 memset(filePreamble, 0, 128);
486 fp->write(filePreamble, 128);
487 fp->write("DICM", 4);
491 * \todo rewrite later, if really usefull
492 * - 'Group Length' element is optional in DICOM
493 * - but un-updated odd groups lengthes can causes pb
496 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
497 * UpdateGroupLength(false,filetype);
498 * if ( filetype == ACR)
499 * UpdateGroupLength(true,ACR);
502 ElementSet::WriteContent(fp, filetype); // This one is recursive
505 // -----------------------------------------
508 * \brief Loads (from disk) the element content
509 * when a string is not suitable
510 * @param group group number of the Entry
511 * @param elem element number of the Entry
513 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
515 // Search the corresponding DocEntry
516 DocEntry *docElement = GetDocEntry(group, elem);
520 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
524 LoadEntryBinArea(binElement);
528 * \brief Loads (from disk) the element content
529 * when a string is not suitable
530 * @param elem Entry whose binArea is going to be loaded
532 void Document::LoadEntryBinArea(BinEntry *elem)
534 if(elem->GetBinArea())
541 size_t o =(size_t)elem->GetOffset();
542 Fp->seekg(o, std::ios::beg);
544 size_t l = elem->GetLength();
545 uint8_t *a = new uint8_t[l];
548 gdcmWarningMacro( "Cannot allocate BinEntry content");
552 Fp->read((char*)a, l);
553 if( Fp->fail() || Fp->eof())
566 * \brief Loads the element while preserving the current
567 * underlying file position indicator as opposed to
568 * LoadDocEntry that modifies it.
569 * @param entry DocEntry whose value will be loaded.
571 void Document::LoadDocEntrySafe(DocEntry *entry)
575 long PositionOnEntry = Fp->tellg();
577 Fp->seekg(PositionOnEntry, std::ios::beg);
582 * \brief Compares two documents, according to \ref DicomDir rules
583 * \warning Does NOT work with ACR-NEMA files
584 * \todo Find a trick to solve the pb (use RET fields ?)
585 * @param document to compare with current one
586 * @return true if 'smaller'
588 bool Document::operator<(Document &document)
591 std::string s1 = GetEntryValue(0x0010,0x0010);
592 std::string s2 = document.GetEntryValue(0x0010,0x0010);
604 s1 = GetEntryValue(0x0010,0x0020);
605 s2 = document.GetEntryValue(0x0010,0x0020);
616 // Study Instance UID
617 s1 = GetEntryValue(0x0020,0x000d);
618 s2 = document.GetEntryValue(0x0020,0x000d);
629 // Serie Instance UID
630 s1 = GetEntryValue(0x0020,0x000e);
631 s2 = document.GetEntryValue(0x0020,0x000e);
646 //-----------------------------------------------------------------------------
649 * \brief Reads a supposed to be 16 Bits integer
650 * (swaps it depending on processor endianness)
653 uint16_t Document::ReadInt16()
657 Fp->read ((char*)&g, (size_t)2);
660 throw FormatError( "Document::ReadInt16()", " file error." );
664 throw FormatError( "Document::ReadInt16()", "EOF." );
671 * \brief Reads a supposed to be 32 Bits integer
672 * (swaps it depending on processor endianness)
675 uint32_t Document::ReadInt32()
679 Fp->read ((char*)&g, (size_t)4);
682 throw FormatError( "Document::ReadInt32()", " file error." );
686 throw FormatError( "Document::ReadInt32()", "EOF." );
693 * \brief skips bytes inside the source file
694 * \warning NOT end user intended method !
697 void Document::SkipBytes(uint32_t nBytes)
699 //FIXME don't dump the returned value
700 Fp->seekg((long)nBytes, std::ios::cur);
704 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
705 * @param filetype Type of the File to be written
707 int Document::ComputeGroup0002Length( FileType filetype )
713 bool found0002 = false;
715 // for each zero-level Tag in the DCM Header
716 DocEntry *entry = GetFirstEntry();
719 gr = entry->GetGroup();
725 if( entry->GetElement() != 0x0000 )
729 if( filetype == ExplicitVR )
731 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
733 // explicit VR AND OB, OW, SQ : 4 more bytes
737 groupLength += 2 + 2 + 4 + entry->GetLength();
743 entry = GetNextEntry();
748 //-----------------------------------------------------------------------------
751 * \brief Loads all the needed Dictionaries
752 * \warning NOT end user intended method !
754 void Document::Initialize()
756 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
762 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
763 * @return length of the parsed set.
765 void Document::ParseDES(DocEntrySet *set, long offset,
766 long l_max, bool delim_mode)
768 DocEntry *newDocEntry = 0;
769 ValEntry *newValEntry;
770 BinEntry *newBinEntry;
771 SeqEntry *newSeqEntry;
777 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
783 newDocEntry = ReadNextDocEntry( );
790 vr = newDocEntry->GetVR();
791 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
792 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
793 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
795 if ( newValEntry || newBinEntry )
799 if ( Filetype == ExplicitVR &&
800 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
802 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
803 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
804 << "|" << newDocEntry->GetElement()
805 << " : Neither Valentry, nor BinEntry."
806 "Probably unknown VR.");
809 //////////////////// BinEntry or UNKOWN VR:
810 // When "this" is a Document the Key is simply of the
811 // form ( group, elem )...
812 if ( dynamic_cast< Document* > ( set ) )
814 newBinEntry->SetKey( newBinEntry->GetKey() );
816 // but when "this" is a SQItem, we are inserting this new
817 // valEntry in a sequence item, and the key has the
818 // generalized form (refer to \ref BaseTagKey):
819 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
821 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
822 + newBinEntry->GetKey() );
825 LoadDocEntry( newBinEntry );
826 if( !set->AddEntry( newBinEntry ) )
828 //Expect big troubles if here
829 //delete newBinEntry;
835 /////////////////////// ValEntry
836 // When "set" is a Document, then we are at the top of the
837 // hierarchy and the Key is simply of the form ( group, elem )...
838 if ( dynamic_cast< Document* > ( set ) )
840 newValEntry->SetKey( newValEntry->GetKey() );
842 // ...but when "set" is a SQItem, we are inserting this new
843 // valEntry in a sequence item. Hence the key has the
844 // generalized form (refer to \ref BaseTagKey):
845 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
847 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
848 + newValEntry->GetKey() );
851 LoadDocEntry( newValEntry );
852 bool delimitor=newValEntry->IsItemDelimitor();
853 if( !set->AddEntry( newValEntry ) )
855 // If here expect big troubles
856 //delete newValEntry; //otherwise mem leak
866 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
874 // Just to make sure we are at the beginning of next entry.
875 SkipToNextDocEntry(newDocEntry);
880 unsigned long l = newDocEntry->GetReadLength();
881 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
883 if ( l == 0xffffffff )
892 // no other way to create it ...
893 newSeqEntry->SetDelimitorMode( delim_mode );
895 // At the top of the hierarchy, stands a Document. When "set"
896 // is a Document, then we are building the first depth level.
897 // Hence the SeqEntry we are building simply has a depth
899 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
902 newSeqEntry->SetDepthLevel( 1 );
903 newSeqEntry->SetKey( newSeqEntry->GetKey() );
905 // But when "set" is already a SQItem, we are building a nested
906 // sequence, and hence the depth level of the new SeqEntry
907 // we are building, is one level deeper:
908 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
910 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
911 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
912 + newSeqEntry->GetKey() );
916 { // Don't try to parse zero-length sequences
917 ParseSQ( newSeqEntry,
918 newDocEntry->GetOffset(),
921 if( !set->AddEntry( newSeqEntry ) )
925 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
939 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
940 * @return parsed length for this level
942 void Document::ParseSQ( SeqEntry *seqEntry,
943 long offset, long l_max, bool delim_mode)
945 int SQItemNumber = 0;
947 long offsetStartCurrentSQItem = offset;
951 // the first time, we read the fff0,e000 of the first SQItem
952 DocEntry *newDocEntry = ReadNextDocEntry();
956 // FIXME Should warn user
961 if ( newDocEntry->IsSequenceDelimitor() )
963 seqEntry->SetDelimitationItem( newDocEntry );
967 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
972 // create the current SQItem
973 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
974 std::ostringstream newBase;
975 newBase << seqEntry->GetKey()
979 itemSQ->SetBaseTagKey( newBase.str() );
980 unsigned int l = newDocEntry->GetReadLength();
982 if ( l == 0xffffffff )
991 // Let's try :------------
992 // remove fff0,e000, created out of the SQItem
994 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
995 // fill up the current SQItem, starting at the beginning of fff0,e000
996 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
997 offsetStartCurrentSQItem = Fp->tellg();
998 // end try -----------------
1000 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1002 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1010 * \brief Loads the element content if its length doesn't exceed
1011 * the value specified with Document::SetMaxSizeLoadEntry()
1012 * @param entry Header Entry (Dicom Element) to be dealt with
1014 void Document::LoadDocEntry(DocEntry *entry)
1016 uint16_t group = entry->GetGroup();
1017 std::string vr = entry->GetVR();
1018 uint32_t length = entry->GetLength();
1020 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1022 // A SeQuence "contains" a set of Elements.
1023 // (fffe e000) tells us an Element is beginning
1024 // (fffe e00d) tells us an Element just ended
1025 // (fffe e0dd) tells us the current SeQuence just ended
1026 if( group == 0xfffe )
1028 // NO more value field for SQ !
1032 // When the length is zero things are easy:
1035 ((ValEntry *)entry)->SetValue("");
1039 // The elements whose length is bigger than the specified upper bound
1040 // are not loaded. Instead we leave a short notice of the offset of
1041 // the element content and it's length.
1043 std::ostringstream s;
1044 if (length > MaxSizeLoadEntry)
1046 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1048 //s << "gdcm::NotLoaded (BinEntry)";
1049 s << GDCM_NOTLOADED;
1050 s << " Address:" << (long)entry->GetOffset();
1051 s << " Length:" << entry->GetLength();
1052 s << " x(" << std::hex << entry->GetLength() << ")";
1053 binEntryPtr->SetValue(s.str());
1055 // Be carefull : a BinEntry IS_A ValEntry ...
1056 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1058 // s << "gdcm::NotLoaded. (ValEntry)";
1059 s << GDCM_NOTLOADED;
1060 s << " Address:" << (long)entry->GetOffset();
1061 s << " Length:" << entry->GetLength();
1062 s << " x(" << std::hex << entry->GetLength() << ")";
1063 valEntryPtr->SetValue(s.str());
1068 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1069 << "nor a ValEntry ?! Should never print that !" );
1072 // to be sure we are at the end of the value ...
1073 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1078 // When we find a BinEntry not very much can be done :
1079 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1081 s << GDCM_BINLOADED;
1082 binEntryPtr->SetValue(s.str());
1083 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1087 if ( IsDocEntryAnInteger(entry) )
1091 // When short integer(s) are expected, read and convert the following
1092 // n *two characters properly i.e. consider them as short integers as
1093 // opposed to strings.
1094 // Elements with Value Multiplicity > 1
1095 // contain a set of integers (not a single one)
1096 if (vr == "US" || vr == "SS")
1099 NewInt = ReadInt16();
1103 for (int i=1; i < nbInt; i++)
1106 NewInt = ReadInt16();
1111 // See above comment on multiple integers (mutatis mutandis).
1112 else if (vr == "UL" || vr == "SL")
1115 NewInt = ReadInt32();
1119 for (int i=1; i < nbInt; i++)
1122 NewInt = ReadInt32();
1127 #ifdef GDCM_NO_ANSI_STRING_STREAM
1128 s << std::ends; // to avoid oddities on Solaris
1129 #endif //GDCM_NO_ANSI_STRING_STREAM
1131 ((ValEntry *)entry)->SetValue(s.str());
1135 // FIXME: We need an additional byte for storing \0 that is not on disk
1136 char *str = new char[length+1];
1137 Fp->read(str, (size_t)length);
1138 str[length] = '\0'; //this is only useful when length is odd
1139 // Special DicomString call to properly handle \0 and even length
1140 std::string newValue;
1143 newValue = Util::DicomString(str, length+1);
1144 gdcmWarningMacro("Warning: bad length: " << length <<
1145 ",For string :" << newValue.c_str());
1146 // Since we change the length of string update it length
1147 //entry->SetReadLength(length+1);
1151 newValue = Util::DicomString(str, length);
1155 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1157 if ( Fp->fail() || Fp->eof())
1159 gdcmWarningMacro("Unread element value");
1160 valEntry->SetValue(GDCM_UNREAD);
1166 // Because of correspondance with the VR dic
1167 valEntry->SetValue(newValue);
1171 valEntry->SetValue(newValue);
1176 gdcmErrorMacro( "Should have a ValEntry, here !");
1181 * \brief Find the value Length of the passed Header Entry
1182 * @param entry Header Entry whose length of the value shall be loaded.
1184 void Document::FindDocEntryLength( DocEntry *entry )
1185 throw ( FormatError )
1187 std::string vr = entry->GetVR();
1190 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1192 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1194 // The following reserved two bytes (see PS 3.5-2003, section
1195 // "7.1.2 Data element structure with explicit vr", p 27) must be
1196 // skipped before proceeding on reading the length on 4 bytes.
1197 Fp->seekg( 2L, std::ios::cur);
1198 uint32_t length32 = ReadInt32();
1200 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1205 lengthOB = FindDocEntryLengthOBOrOW();
1207 catch ( FormatUnexpected )
1209 // Computing the length failed (this happens with broken
1210 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1211 // chance to get the pixels by deciding the element goes
1212 // until the end of the file. Hence we artificially fix the
1213 // the length and proceed.
1214 long currentPosition = Fp->tellg();
1215 Fp->seekg(0L,std::ios::end);
1217 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1218 Fp->seekg(currentPosition, std::ios::beg);
1220 entry->SetReadLength(lengthUntilEOF);
1221 entry->SetLength(lengthUntilEOF);
1224 entry->SetReadLength(lengthOB);
1225 entry->SetLength(lengthOB);
1228 FixDocEntryFoundLength(entry, length32);
1232 // Length is encoded on 2 bytes.
1233 length16 = ReadInt16();
1235 // FIXME : This heuristic supposes that the first group following
1236 // group 0002 *has* and element 0000.
1237 // BUT ... Element 0000 is optionnal :-(
1240 // Fixed using : HandleOutOfGroup0002()
1241 // (first hereafter strategy ...)
1243 // We can tell the current file is encoded in big endian (like
1244 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1245 // and it's value is the one of the encoding of a big endian file.
1246 // In order to deal with such big endian encoded files, we have
1247 // (at least) two strategies:
1248 // * when we load the "Transfer Syntax" tag with value of big endian
1249 // encoding, we raise the proper flags. Then we wait for the end
1250 // of the META group (0x0002) among which is "Transfer Syntax",
1251 // before switching the swap code to big endian. We have to postpone
1252 // the switching of the swap code since the META group is fully encoded
1253 // in little endian, and big endian coding only starts at the next
1254 // group. The corresponding code can be hard to analyse and adds
1255 // many additional unnecessary tests for regular tags.
1256 // * the second strategy consists in waiting for trouble, that shall
1257 // appear when we find the first group with big endian encoding. This
1258 // is easy to detect since the length of a "Group Length" tag (the
1259 // ones with zero as element number) has to be of 4 (0x0004). When we
1260 // encounter 1024 (0x0400) chances are the encoding changed and we
1261 // found a group with big endian encoding.
1262 //---> Unfortunately, element 0000 is optional.
1263 //---> This will not work when missing!
1264 // We shall use this second strategy. In order to make sure that we
1265 // can interpret the presence of an apparently big endian encoded
1266 // length of a "Group Length" without committing a big mistake, we
1267 // add an additional check: we look in the already parsed elements
1268 // for the presence of a "Transfer Syntax" whose value has to be "big
1269 // endian encoding". When this is the case, chances are we have got our
1270 // hands on a big endian encoded file: we switch the swap code to
1271 // big endian and proceed...
1273 // if ( element == 0x0000 && length16 == 0x0400 )
1275 // std::string ts = GetTransferSyntax();
1276 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1277 // != TS::ExplicitVRBigEndian )
1279 // throw FormatError( "Document::FindDocEntryLength()",
1280 // " not explicit VR." );
1284 // SwitchByteSwapCode();
1286 // // Restore the unproperly loaded values i.e. the group, the element
1287 // // and the dictionary entry depending on them.
1288 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1289 // uint16_t correctElem = SwapShort( entry->GetElement() );
1290 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1293 // // This correct tag is not in the dictionary. Create a new one.
1294 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1296 // // FIXME this can create a memory leaks on the old entry that be
1297 // // left unreferenced.
1298 // entry->SetDictEntry( newTag );
1301 // 0xffff means that we deal with 'No Length' Sequence
1302 // or 'No Length' SQItem
1303 if ( length16 == 0xffff)
1307 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1312 // Either implicit VR or a non DICOM conformal (see note below) explicit
1313 // VR that ommited the VR of (at least) this element. Farts happen.
1314 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1315 // on Data elements "Implicit and Explicit VR Data Elements shall
1316 // not coexist in a Data Set and Data Sets nested within it".]
1317 // Length is on 4 bytes.
1319 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1320 // even if Transfer Syntax is 'Implicit VR ...'
1322 FixDocEntryFoundLength( entry, ReadInt32() );
1328 * \brief Find the Length till the next sequence delimiter
1329 * \warning NOT end user intended method !
1332 uint32_t Document::FindDocEntryLengthOBOrOW()
1333 throw( FormatUnexpected )
1335 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1336 long positionOnEntry = Fp->tellg();
1337 bool foundSequenceDelimiter = false;
1338 uint32_t totalLength = 0;
1340 while ( !foundSequenceDelimiter )
1346 group = ReadInt16();
1349 catch ( FormatError )
1351 throw FormatError("Unexpected end of file encountered during ",
1352 "Document::FindDocEntryLengthOBOrOW()");
1354 // We have to decount the group and element we just read
1356 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1358 long filePosition = Fp->tellg();
1359 gdcmWarningMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1360 << std::hex << group << " , " << elem
1361 << ") -before- position x(" << filePosition << ")" );
1363 Fp->seekg(positionOnEntry, std::ios::beg);
1364 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1366 if ( elem == 0xe0dd )
1368 foundSequenceDelimiter = true;
1370 uint32_t itemLength = ReadInt32();
1371 // We add 4 bytes since we just read the ItemLength with ReadInt32
1372 totalLength += itemLength + 4;
1373 SkipBytes(itemLength);
1375 if ( foundSequenceDelimiter )
1380 Fp->seekg( positionOnEntry, std::ios::beg);
1385 * \brief Find the Value Representation of the current Dicom Element.
1386 * @return Value Representation of the current Entry
1388 std::string Document::FindDocEntryVR()
1390 if ( Filetype != ExplicitVR )
1391 return GDCM_UNKNOWN;
1393 long positionOnEntry = Fp->tellg();
1394 // Warning: we believe this is explicit VR (Value Representation) because
1395 // we used a heuristic that found "UL" in the first tag. Alas this
1396 // doesn't guarantee that all the tags will be in explicit VR. In some
1397 // cases (see e-film filtered files) one finds implicit VR tags mixed
1398 // within an explicit VR file. Hence we make sure the present tag
1399 // is in explicit VR and try to fix things if it happens not to be
1403 Fp->read (vr, (size_t)2);
1406 if( !CheckDocEntryVR(vr) )
1408 Fp->seekg(positionOnEntry, std::ios::beg);
1409 return GDCM_UNKNOWN;
1415 * \brief Check the correspondance between the VR of the header entry
1416 * and the taken VR. If they are different, the header entry is
1417 * updated with the new VR.
1418 * @param vr Dicom Value Representation
1419 * @return false if the VR is incorrect of if the VR isn't referenced
1420 * otherwise, it returns true
1422 bool Document::CheckDocEntryVR(VRKey vr)
1424 if ( !Global::GetVR()->IsValidVR(vr) )
1431 * \brief Get the transformed value of the header entry. The VR value
1432 * is used to define the transformation to operate on the value
1433 * \warning NOT end user intended method !
1434 * @param entry entry to tranform
1435 * @return Transformed entry value
1437 std::string Document::GetDocEntryValue(DocEntry *entry)
1439 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1441 std::string val = ((ValEntry *)entry)->GetValue();
1442 std::string vr = entry->GetVR();
1443 uint32_t length = entry->GetLength();
1444 std::ostringstream s;
1447 // When short integer(s) are expected, read and convert the following
1448 // n * 2 bytes properly i.e. as a multivaluated strings
1449 // (each single value is separated fromthe next one by '\'
1450 // as usual for standard multivaluated filels
1451 // Elements with Value Multiplicity > 1
1452 // contain a set of short integers (not a single one)
1454 if( vr == "US" || vr == "SS" )
1459 for (int i=0; i < nbInt; i++)
1465 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1466 newInt16 = SwapShort( newInt16 );
1471 // When integer(s) are expected, read and convert the following
1472 // n * 4 bytes properly i.e. as a multivaluated strings
1473 // (each single value is separated fromthe next one by '\'
1474 // as usual for standard multivaluated filels
1475 // Elements with Value Multiplicity > 1
1476 // contain a set of integers (not a single one)
1477 else if( vr == "UL" || vr == "SL" )
1482 for (int i=0; i < nbInt; i++)
1488 newInt32 = ( val[4*i+0] & 0xFF )
1489 + (( val[4*i+1] & 0xFF ) << 8 )
1490 + (( val[4*i+2] & 0xFF ) << 16 )
1491 + (( val[4*i+3] & 0xFF ) << 24 );
1492 newInt32 = SwapLong( newInt32 );
1496 #ifdef GDCM_NO_ANSI_STRING_STREAM
1497 s << std::ends; // to avoid oddities on Solaris
1498 #endif //GDCM_NO_ANSI_STRING_STREAM
1501 return ((ValEntry *)entry)->GetValue();
1505 * \brief Get the reverse transformed value of the header entry. The VR
1506 * value is used to define the reverse transformation to operate on
1508 * \warning NOT end user intended method !
1509 * @param entry Entry to reverse transform
1510 * @return Reverse transformed entry value
1512 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1514 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1516 std::string vr = entry->GetVR();
1517 std::vector<std::string> tokens;
1518 std::ostringstream s;
1520 if ( vr == "US" || vr == "SS" )
1524 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1525 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1526 for (unsigned int i=0; i<tokens.size(); i++)
1528 newInt16 = atoi(tokens[i].c_str());
1529 s << ( newInt16 & 0xFF )
1530 << (( newInt16 >> 8 ) & 0xFF );
1534 if ( vr == "UL" || vr == "SL")
1538 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1539 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1540 for (unsigned int i=0; i<tokens.size();i++)
1542 newInt32 = atoi(tokens[i].c_str());
1543 s << (char)( newInt32 & 0xFF )
1544 << (char)(( newInt32 >> 8 ) & 0xFF )
1545 << (char)(( newInt32 >> 16 ) & 0xFF )
1546 << (char)(( newInt32 >> 24 ) & 0xFF );
1551 #ifdef GDCM_NO_ANSI_STRING_STREAM
1552 s << std::ends; // to avoid oddities on Solaris
1553 #endif //GDCM_NO_ANSI_STRING_STREAM
1557 return ((ValEntry *)entry)->GetValue();
1561 * \brief Skip a given Header Entry
1562 * \warning NOT end user intended method !
1563 * @param entry entry to skip
1565 void Document::SkipDocEntry(DocEntry *entry)
1567 SkipBytes(entry->GetLength());
1571 * \brief Skips to the beginning of the next Header Entry
1572 * \warning NOT end user intended method !
1573 * @param currentDocEntry entry to skip
1575 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1577 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1578 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1579 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1583 * \brief When the length of an element value is obviously wrong (because
1584 * the parser went Jabberwocky) one can hope improving things by
1585 * applying some heuristics.
1586 * @param entry entry to check
1587 * @param foundLength first assumption about length
1589 void Document::FixDocEntryFoundLength(DocEntry *entry,
1590 uint32_t foundLength)
1592 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1593 if ( foundLength == 0xffffffff)
1598 uint16_t gr = entry->GetGroup();
1599 uint16_t elem = entry->GetElement();
1601 if ( foundLength % 2)
1603 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1604 << " in x(" << std::hex << gr << "," << elem <<")");
1607 //////// Fix for some naughty General Electric images.
1608 // Allthough not recent many such GE corrupted images are still present
1609 // on Creatis hard disks. Hence this fix shall remain when such images
1610 // are no longer in use (we are talking a few years, here)...
1611 // Note: XMedCom probably uses such a trick since it is able to read
1612 // those pesky GE images ...
1613 if ( foundLength == 13)
1615 // Only happens for this length !
1616 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1619 entry->SetReadLength(10); // a bug is to be fixed !?
1623 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1624 // Occurence of such images is quite low (unless one leaves close to a
1625 // 'Leonardo' source. Hence, one might consider commenting out the
1626 // following fix on efficiency reasons.
1627 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1630 entry->SetReadLength(4); // a bug is to be fixed !?
1633 else if ( entry->GetVR() == "SQ" )
1635 foundLength = 0; // ReadLength is unchanged
1638 //////// We encountered a 'delimiter' element i.e. a tag of the form
1639 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1640 // taken into account.
1641 else if( gr == 0xfffe )
1643 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1644 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1645 // causes extra troubles...
1646 if( entry->GetElement() != 0x0000 )
1651 entry->SetLength(foundLength);
1655 * \brief Apply some heuristics to predict whether the considered
1656 * element value contains/represents an integer or not.
1657 * @param entry The element value on which to apply the predicate.
1658 * @return The result of the heuristical predicate.
1660 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1662 uint16_t elem = entry->GetElement();
1663 uint16_t group = entry->GetGroup();
1664 const std::string &vr = entry->GetVR();
1665 uint32_t length = entry->GetLength();
1667 // When we have some semantics on the element we just read, and if we
1668 // a priori know we are dealing with an integer, then we shall be
1669 // able to swap it's element value properly.
1670 if ( elem == 0 ) // This is the group length of the group
1678 // Allthough this should never happen, still some images have a
1679 // corrupted group length [e.g. have a glance at offset x(8336) of
1680 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1681 // Since for dicom compliant and well behaved headers, the present
1682 // test is useless (and might even look a bit paranoid), when we
1683 // encounter such an ill-formed image, we simply display a warning
1684 // message and proceed on parsing (while crossing fingers).
1685 long filePosition = Fp->tellg();
1686 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1687 << std::hex << group << " , " << elem
1688 << ") -before- position x(" << filePosition << ")"
1689 << "lgt : " << length );
1693 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1701 * \brief Discover what the swap code is (among little endian, big endian,
1702 * bad little endian, bad big endian).
1704 * @return false when we are absolutely sure
1705 * it's neither ACR-NEMA nor DICOM
1706 * true when we hope ours assuptions are OK
1708 bool Document::CheckSwap()
1710 // The only guaranted way of finding the swap code is to find a
1711 // group tag since we know it's length has to be of four bytes i.e.
1712 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1713 // occurs when we can't find such group...
1720 // First, compare HostByteOrder and NetworkByteOrder in order to
1721 // determine if we shall need to swap bytes (i.e. the Endian type).
1722 bool net2host = Util::IsCurrentProcessorBigEndian();
1724 // The easiest case is the one of a 'true' DICOM header, we just have
1725 // to look for the string "DICM" inside the file preamble.
1728 char *entCur = deb + 128;
1729 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1731 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1733 // Group 0002 should always be VR, and the first element 0000
1734 // Let's be carefull (so many wrong headers ...)
1735 // and determine the value representation (VR) :
1736 // Let's skip to the first element (0002,0000) and check there if we find
1737 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1738 // in which case we (almost) know it is explicit VR.
1739 // WARNING: if it happens to be implicit VR then what we will read
1740 // is the length of the group. If this ascii representation of this
1741 // length happens to be "UL" then we shall believe it is explicit VR.
1742 // We need to skip :
1743 // * the 128 bytes of File Preamble (often padded with zeroes),
1744 // * the 4 bytes of "DICM" string,
1745 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1746 // i.e. a total of 136 bytes.
1749 // group 0x0002 *is always* Explicit VR Sometimes ,
1750 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1751 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1753 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1754 memcmp(entCur, "OB", (size_t)2) == 0 ||
1755 memcmp(entCur, "UI", (size_t)2) == 0 ||
1756 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1757 // when Write DCM *adds*
1759 // Use Document::dicom_vr to test all the possibilities
1760 // instead of just checking for UL, OB and UI !? group 0000
1762 Filetype = ExplicitVR;
1763 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1767 Filetype = ImplicitVR;
1768 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1769 << "Looks like a bugged Header!");
1775 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1780 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1783 // Position the file position indicator at first tag
1784 // (i.e. after the file preamble and the "DICM" string).
1785 Fp->seekg(0, std::ios::beg);
1786 Fp->seekg ( 132L, std::ios::beg);
1790 // Alas, this is not a DicomV3 file and whatever happens there is no file
1791 // preamble. We can reset the file position indicator to where the data
1792 // is (i.e. the beginning of the file).
1793 gdcmWarningMacro( "Not a DICOM Version3 file");
1794 Fp->seekg(0, std::ios::beg);
1796 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1797 // By clean we mean that the length of the first tag is written down.
1798 // If this is the case and since the length of the first group HAS to be
1799 // four (bytes), then determining the proper swap code is straightforward.
1802 // We assume the array of char we are considering contains the binary
1803 // representation of a 32 bits integer. Hence the following dirty
1805 s32 = *((uint32_t *)(entCur));
1826 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1827 // It is time for despaired wild guesses.
1828 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1829 // i.e. the 'group length' element is not present :
1831 // check the supposed-to-be 'group number'
1832 // in ( 0x0001 .. 0x0008 )
1833 // to determine ' SwapCode' value .
1834 // Only 0 or 4321 will be possible
1835 // (no oportunity to check for the formerly well known
1836 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1837 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1838 // the file IS NOT ACR-NEMA nor DICOM V3
1839 // Find a trick to tell it the caller...
1841 s16 = *((uint16_t *)(deb));
1868 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1876 * \brief Change the Byte Swap code.
1878 void Document::SwitchByteSwapCode()
1880 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1881 if ( SwapCode == 1234 )
1885 else if ( SwapCode == 4321 )
1889 else if ( SwapCode == 3412 )
1893 else if ( SwapCode == 2143 )
1900 * \brief during parsing, Header Elements too long are not loaded in memory
1901 * @param newSize new size
1903 void Document::SetMaxSizeLoadEntry(long newSize)
1909 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1911 MaxSizeLoadEntry = 0xffffffff;
1914 MaxSizeLoadEntry = newSize;
1918 * \brief Header Elements too long will not be printed
1919 * See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
1920 * @param newSize new size
1922 void Document::SetMaxSizePrintEntry(long newSize)
1928 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1930 MaxSizePrintEntry = 0xffffffff;
1933 MaxSizePrintEntry = newSize;
1938 * \brief Read the next tag but WITHOUT loading it's value
1939 * (read the 'Group Number', the 'Element Number',
1940 * gets the Dict Entry
1941 * gets the VR, gets the length, gets the offset value)
1942 * @return On succes the newly created DocEntry, NULL on failure.
1944 DocEntry *Document::ReadNextDocEntry()
1951 group = ReadInt16();
1954 catch ( FormatError e )
1956 // We reached the EOF (or an error occured) therefore
1957 // header parsing has to be considered as finished.
1961 // Sometimes file contains groups of tags with reversed endianess.
1962 HandleBrokenEndian(group, elem);
1964 // In 'true DICOM' files Group 0002 is always little endian
1965 if ( HasDCMPreamble )
1966 HandleOutOfGroup0002(group, elem);
1968 std::string vr = FindDocEntryVR();
1969 std::string realVR = vr;
1971 if( vr == GDCM_UNKNOWN)
1973 DictEntry *dictEntry = GetDictEntry(group,elem);
1975 realVR = dictEntry->GetVR();
1979 if( Global::GetVR()->IsVROfSequence(realVR) )
1980 newEntry = NewSeqEntry(group, elem);
1981 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1982 newEntry = NewValEntry(group, elem,vr);
1984 newEntry = NewBinEntry(group, elem,vr);
1986 if( vr == GDCM_UNKNOWN )
1988 if( Filetype == ExplicitVR )
1990 // We thought this was explicit VR, but we end up with an
1991 // implicit VR tag. Let's backtrack.
1992 if ( newEntry->GetGroup() != 0xfffe )
1995 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
1996 newEntry->GetGroup(), newEntry->GetElement());
1997 gdcmWarningMacro( msg.c_str() );
2000 newEntry->SetImplicitVR();
2005 FindDocEntryLength(newEntry);
2007 catch ( FormatError e )
2015 newEntry->SetOffset(Fp->tellg());
2021 * \brief Handle broken private tag from Philips NTSCAN
2022 * where the endianess is being switch to BigEndian for no
2026 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2028 // Endian reversion. Some files contain groups of tags with reversed endianess.
2029 static int reversedEndian = 0;
2030 // try to fix endian switching in the middle of headers
2031 if ((group == 0xfeff) && (elem == 0x00e0))
2033 // start endian swap mark for group found
2035 SwitchByteSwapCode();
2040 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2042 // end of reversed endian group
2044 SwitchByteSwapCode();
2049 * \brief Group 0002 is always coded Little Endian
2050 * whatever Transfer Syntax is
2053 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2055 // Endian reversion. Some files contain groups of tags with reversed endianess.
2056 if ( !Group0002Parsed && group != 0x0002)
2058 Group0002Parsed = true;
2059 // we just came out of group 0002
2060 // if Transfer syntax is Big Endian we have to change CheckSwap
2062 std::string ts = GetTransferSyntax();
2063 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2065 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2069 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2071 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2073 Filetype = ImplicitVR;
2076 // FIXME Strangely, this works with
2077 //'Implicit VR Transfer Syntax (GE Private)
2078 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2080 gdcmWarningMacro("Transfer Syntax Name = ["
2081 << GetTransferSyntaxName() << "]" );
2082 SwitchByteSwapCode();
2083 group = SwapShort(group);
2084 elem = SwapShort(elem);
2089 //-----------------------------------------------------------------------------
2092 //-----------------------------------------------------------------------------
2093 } // end namespace gdcm