1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/10/21 07:38:58 $
7 Version: $Revision: 1.302 $
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 "gdcmSeqEntry.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmDebug.h"
25 #include "gdcmDictSet.h"
26 #include "gdcmDocEntrySet.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
33 #include <ctype.h> // for isdigit
34 #include <stdlib.h> // for atoi
38 //-----------------------------------------------------------------------------
40 // Refer to Document::SetMaxSizeLoadEntry()
41 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
43 //-----------------------------------------------------------------------------
44 // Constructor / Destructor
45 // Constructors and destructors are protected to avoid user to invoke directly
48 * \brief This default constructor neither loads nor parses the file.
49 * You should then invoke \ref Document::Load.
57 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
60 Filetype = ExplicitVR;
61 // Load will set it to true if sucessfull
62 Group0002Parsed = false;
63 IsDocumentAlreadyLoaded = false;
64 IsDocumentModified = true;
65 LoadMode = LD_ALL; // default : load everything, later
70 * \brief Canonical destructor.
72 Document::~Document ()
77 //-----------------------------------------------------------------------------
81 * \brief Loader. use SetLoadMode(), SetFileName() before !
82 * @return false if file cannot be open or no swap info was found,
83 * or no tag was found.
85 bool Document::Load( )
87 if ( GetFileName() == "" )
89 gdcmWarningMacro( "Use SetFileName, before !" );
92 return DoTheLoadingDocumentJob( );
95 * \brief Loader. (DEPRECATED : not to break the API)
96 * @param fileName 'Document' (File or DicomDir) to be open for parsing
97 * @return false if file cannot be open or no swap info was found,
98 * or no tag was found.
100 bool Document::Load( std::string const &fileName )
103 return DoTheLoadingDocumentJob( );
107 * \brief Performs the Loading Job (internal use only)
108 * @return false if file cannot be open or no swap info was found,
109 * or no tag was found.
111 bool Document::DoTheLoadingDocumentJob( )
113 if ( ! IsDocumentModified ) // Nothing to do !
121 // warning already performed in OpenFile()
122 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
123 // << Filename.c_str() );
128 Group0002Parsed = false;
130 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
132 Fp->seekg(0, std::ios::end);
133 long lgt = Fp->tellg(); // total length of the file
135 Fp->seekg(0, std::ios::beg);
137 // CheckSwap returns a boolean
138 // (false if no swap info of any kind was found)
141 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
142 << Filename.c_str());
147 long beg = Fp->tellg(); // just after DICOM preamble (if any)
149 lgt -= beg; // remaining length to parse
152 // Loading is done during parsing
153 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
157 gdcmWarningMacro( "No tag in internal hash table for: "
158 << Filename.c_str());
162 IsDocumentAlreadyLoaded = true;
164 Fp->seekg( 0, std::ios::beg);
166 // Load 'non string' values
168 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
169 if ( PhotometricInterpretation == "PALETTE COLOR " )
172 // Probabely this line should be outside the 'if'
173 // Try to find an image sample holding a 'gray LUT'
174 LoadEntryBinArea(0x0028,0x1200); // gray LUT
177 /// The tags refered by the three following lines used to be CORRECTLY
178 /// defined as having an US Value Representation in the public
179 /// dictionary. BUT the semantics implied by the three following
180 /// lines state that the corresponding tag contents are in fact
181 /// the ones of a DataEntry.
182 /// In order to fix things "Quick and Dirty" the dictionary was
183 /// altered on PURPOSE but now contains a WRONG value.
184 /// In order to fix things and restore the dictionary to its
185 /// correct value, one needs to decided of the semantics by deciding
186 /// whether the following tags are either :
187 /// - multivaluated US, and hence loaded as DataEntry, but afterwards
188 /// also used as DataEntry, which requires the proper conversion,
189 /// - OW, and hence loaded as DataEntry, but afterwards also used
190 /// as DataEntry, which requires the proper conversion.
191 LoadEntryBinArea(0x0028,0x1201); // R LUT
192 LoadEntryBinArea(0x0028,0x1202); // G LUT
193 LoadEntryBinArea(0x0028,0x1203); // B LUT
195 // Segmented Red Palette Color LUT Data
196 LoadEntryBinArea(0x0028,0x1221);
197 // Segmented Green Palette Color LUT Data
198 LoadEntryBinArea(0x0028,0x1222);
199 // Segmented Blue Palette Color LUT Data
200 LoadEntryBinArea(0x0028,0x1223);
203 //FIXME later : how to use it?
204 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
207 SQItem *sqi= modLutSeq->GetFirstSQItem();
210 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
211 if ( dataEntry != 0 )
213 if ( dataEntry->GetLength() != 0 )
215 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
221 // Force Loading some more elements if user asked to.
224 for (ListElements::iterator it = UserForceLoadList.begin();
225 it != UserForceLoadList.end();
228 gdcmWarningMacro( "Force Load " << std::hex
229 << (*it).Group << "|" <<(*it).Elem );
231 d = GetDocEntry( (*it).Group, (*it).Elem);
235 gdcmWarningMacro( "You asked toForce Load " << std::hex
236 << (*it).Group <<"|"<< (*it).Elem
237 << " that doesn't exist" );
241 LoadDocEntry(d, true);
246 // ----------------------------
247 // Specific code to allow gdcm to read ACR-LibIDO formated images
248 // Note: ACR-LibIDO is an extension of the ACR standard that was
249 // used at CREATIS. For the time being (say a couple of years)
250 // we keep this kludge to allow CREATIS users
251 // reading their old images.
253 // if recognition code tells us we deal with a LibIDO image
254 // we switch lineNumber and columnNumber
257 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
258 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
259 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
260 // with "little-endian strings"
262 Filetype = ACR_LIBIDO;
263 std::string rows = GetEntryString(0x0028, 0x0010);
264 std::string columns = GetEntryString(0x0028, 0x0011);
265 SetEntryString(columns, 0x0028, 0x0010);
266 SetEntryString(rows , 0x0028, 0x0011);
268 // --- End of ACR-LibIDO kludge ---
274 * \brief Adds a new element we want to load anyway
275 * @param group Group number of the target tag.
276 * @param elem Element number of the target tag.
278 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
283 UserForceLoadList.push_back(el);
286 * \brief Get the public dictionary used
288 Dict *Document::GetPubDict()
294 * \brief Get the shadow dictionary used
296 Dict *Document::GetShaDict()
302 * \brief Set the shadow dictionary used
303 * @param dict dictionary to use in shadow
305 bool Document::SetShaDict(Dict *dict)
312 * \brief Set the shadow dictionary used
313 * @param dictName name of the dictionary to use in shadow
315 bool Document::SetShaDict(DictKey const &dictName)
317 RefShaDict = Global::GetDicts()->GetDict(dictName);
322 * \brief This predicate tells us whether or not the current Document
323 * was properly parsed and contains at least *one* Dicom Element
324 * (and nothing more, sorry).
325 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
328 bool Document::IsReadable()
330 if ( Filetype == Unknown )
332 gdcmWarningMacro( "Wrong filetype");
338 gdcmWarningMacro( "No tag in internal hash table.");
346 * \brief Predicate for dicom version 3 file.
347 * @return True when the file is a dicom version 3.
349 bool Document::IsDicomV3()
351 // Checking if Transfer Syntax exists is enough
352 // Anyway, it's too late check if the 'Preamble' was found ...
353 // And ... would it be a rich idea to check ?
354 // (some 'no Preamble' DICOM images exist !)
355 return GetDocEntry(0x0002, 0x0010) != NULL;
359 * \brief Predicate for Papyrus file
360 * Dedicated to whomsoever it may concern
361 * @return True when the file is a Papyrus file.
363 bool Document::IsPapyrus()
365 // check for Papyrus private Sequence
366 DocEntry *e = GetDocEntry(0x0041, 0x1050);
369 // check if it's actually a Sequence
370 if ( !dynamic_cast<SeqEntry*>(e) )
376 * \brief returns the File Type
377 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
378 * @return the FileType code
380 FileType Document::GetFileType()
386 * \brief Accessor to the Transfer Syntax (when present) of the
387 * current document (it internally handles reading the
388 * value from disk when only parsing occured).
389 * @return The encountered Transfer Syntax of the current document.
391 std::string Document::GetTransferSyntax()
393 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
399 // The entry might be present but not loaded (parsing and loading
400 // happen at different stages): try loading and proceed with check...
401 LoadDocEntrySafe(entry);
402 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
404 std::string transfer = dataEntry->GetString();
405 // The actual transfer (as read from disk) might be padded. We
406 // first need to remove the potential padding. We can make the
407 // weak assumption that padding was not executed with digits...
408 if ( transfer.length() == 0 )
410 // for brain damaged headers
413 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
415 transfer.erase(transfer.length()-1, 1);
416 if ( transfer.length() == 0 )
418 // for brain damaged headers
428 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
429 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
431 std::string Document::GetTransferSyntaxName()
433 // use the TS (TS : Transfer Syntax)
434 std::string transferSyntax = GetEntryString(0x0002,0x0010);
436 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
438 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
439 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
440 return "Uncompressed ACR-NEMA";
442 if ( transferSyntax == GDCM_UNFOUND )
444 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
445 return "Uncompressed ACR-NEMA";
448 // we do it only when we need it
449 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
451 // Global::GetTS() is a global static you shall never try to delete it!
455 // --------------- Swap Code ------------------
457 * \brief Swaps the bytes so they agree with the processor order
458 * @return The properly swaped 16 bits integer.
460 uint16_t Document::SwapShort(uint16_t a)
462 if ( SwapCode == 4321 || SwapCode == 2143 )
464 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
466 a = ( a << 8 ) | ( a >> 8 );
472 * \brief Swaps back the bytes of 4-byte long integer accordingly to
474 * @return The properly swaped 32 bits integer.
476 uint32_t Document::SwapLong(uint32_t a)
483 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
484 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
486 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
487 ((a>>8) & 0x0000ff00) | (a>>24) );
490 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
491 a=( (a<<16) | (a>>16) );
494 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
497 gdcmErrorMacro( "Unset swap code:" << SwapCode );
504 // -----------------File I/O ---------------
506 * \brief Tries to open the file \ref Document::Filename and
507 * checks the preamble when existing.
508 * @return The FILE pointer on success.
510 std::ifstream *Document::OpenFile()
512 HasDCMPreamble = false;
513 if (Filename.length() == 0)
520 gdcmWarningMacro( "File already open: " << Filename.c_str());
524 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
527 // Don't user gdcmErrorMacro :
528 // a spurious message will appear when you use, for instance
529 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
530 // to create outputFileName.
531 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
535 //exit(1); // No function is allowed to leave the application instead
536 // of warning the caller
540 Fp->read((char*)&zero, (size_t)2);
547 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
549 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
550 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
551 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
552 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
554 std::string msg = Util::Format(
555 "ACR/DICOM starting at the beginning of the file:(%04x)\n", zero);
556 gdcmWarningMacro( msg.c_str() );
561 Fp->seekg(126L, std::ios::cur);
562 char dicm[4]; // = {' ',' ',' ',' '};
563 Fp->read(dicm, (size_t)4);
569 if ( memcmp(dicm, "DICM", 4) == 0 )
571 HasDCMPreamble = true;
575 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
577 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
578 << Filename.c_str());
583 * \brief closes the file
584 * @return TRUE if the close was successfull
586 bool Document::CloseFile()
598 * \brief Writes in a file all the Entries (Dicom Elements)
599 * @param fp file pointer on an already open file (actually: Output File Stream)
600 * @param filetype Type of the File to be written
601 * (ACR-NEMA, ExplicitVR, ImplicitVR)
603 void Document::WriteContent(std::ofstream *fp, FileType filetype)
605 // Skip if user wants to write an ACR-NEMA file
607 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
610 // writing Dicom File Preamble
611 char filePreamble[128];
612 memset(filePreamble, 0, 128);
613 fp->write(filePreamble, 128);
614 fp->write("DICM", 4);
618 * \todo rewrite later, if really usefull
619 * - 'Group Length' element is optional in DICOM
620 * - but un-updated odd groups lengthes can causes pb
623 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
624 * UpdateGroupLength(false,filetype);
625 * if ( filetype == ACR)
626 * UpdateGroupLength(true,ACR);
629 ElementSet::WriteContent(fp, filetype); // This one is recursive
632 // -----------------------------------------
635 * \brief Loads (from disk) the element content
636 * when a string is not suitable
637 * @param group group number of the Entry
638 * @param elem element number of the Entry
640 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
642 // Search the corresponding DocEntry
643 DocEntry *docEntry = GetDocEntry(group, elem);
646 gdcmWarningMacro(std::hex << group << "|" << elem
647 << "doesn't exist" );
650 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
653 gdcmWarningMacro(std::hex << group << "|" << elem
654 << "is NOT a DataEntry");
657 LoadEntryBinArea(dataEntry);
661 * \brief Loads (from disk) the element content
662 * when a string is not suitable
663 * @param entry Entry whose binArea is going to be loaded
665 void Document::LoadEntryBinArea(DataEntry *entry)
667 if( entry->GetBinArea() )
674 size_t o =(size_t)entry->GetOffset();
675 Fp->seekg(o, std::ios::beg);
677 size_t l = entry->GetLength();
678 uint8_t *data = new uint8_t[l];
681 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
682 << std::hex << entry->GetGroup()
683 << "|" << entry->GetElement() );
688 Fp->read((char*)data, l);
689 if ( Fp->fail() || Fp->eof() )
692 entry->SetState(DataEntry::STATE_UNREAD);
696 // Swap the data content if necessary
698 unsigned short vrLgth =
699 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
700 if( entry->GetVR() == "OW" )
707 uint16_t *data16 = (uint16_t *)data;
708 for(i=0;i<l/vrLgth;i++)
709 data16[i] = SwapShort(data16[i]);
714 uint32_t *data32 = (uint32_t *)data;
715 for(i=0;i<l/vrLgth;i++)
716 data32[i] = SwapLong(data32[i]);
721 gdcmWarningMacro("Can't swap 64 bits datas");
722 /* uint64_t *data64 = (uint64_t *)data;
723 for(i=0;i<l/vrLgth;i++)
724 data64[i] = SwapLongLong(data64[i]);*/
729 entry->SetBinArea(data);
736 * \brief Loads the element while preserving the current
737 * underlying file position indicator as opposed to
738 * LoadDocEntry that modifies it.
739 * @param entry DocEntry whose value will be loaded.
741 void Document::LoadDocEntrySafe(DocEntry *entry)
745 long PositionOnEntry = Fp->tellg();
747 Fp->seekg(PositionOnEntry, std::ios::beg);
752 * \brief Compares two documents, according to \ref DicomDir rules
753 * \warning Does NOT work with ACR-NEMA files
754 * \todo Find a trick to solve the pb (use RET fields ?)
755 * @param document to compare with current one
756 * @return true if 'smaller'
758 bool Document::operator<(Document &document)
761 std::string s1 = GetEntryString(0x0010,0x0010);
762 std::string s2 = document.GetEntryString(0x0010,0x0010);
774 s1 = GetEntryString(0x0010,0x0020);
775 s2 = document.GetEntryString(0x0010,0x0020);
786 // Study Instance UID
787 s1 = GetEntryString(0x0020,0x000d);
788 s2 = document.GetEntryString(0x0020,0x000d);
799 // Serie Instance UID
800 s1 = GetEntryString(0x0020,0x000e);
801 s2 = document.GetEntryString(0x0020,0x000e);
816 //-----------------------------------------------------------------------------
819 * \brief Reads a supposed to be 16 Bits integer
820 * (swaps it depending on processor endianness)
823 uint16_t Document::ReadInt16()
827 Fp->read ((char*)&g, (size_t)2);
830 throw FormatError( "Document::ReadInt16()", " file error." );
834 throw FormatError( "Document::ReadInt16()", "EOF." );
841 * \brief Reads a supposed to be 32 Bits integer
842 * (swaps it depending on processor endianness)
845 uint32_t Document::ReadInt32()
849 Fp->read ((char*)&g, (size_t)4);
852 throw FormatError( "Document::ReadInt32()", " file error." );
856 throw FormatError( "Document::ReadInt32()", "EOF." );
863 * \brief skips bytes inside the source file
864 * \warning NOT end user intended method !
867 void Document::SkipBytes(uint32_t nBytes)
869 //FIXME don't dump the returned value
870 Fp->seekg((long)nBytes, std::ios::cur);
874 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
876 int Document::ComputeGroup0002Length( )
882 bool found0002 = false;
884 // for each zero-level Tag in the DCM Header
885 DocEntry *entry = GetFirstEntry();
888 gr = entry->GetGroup();
894 if ( entry->GetElement() != 0x0000 )
898 // FIXME : group 0x0002 is *always* Explicit VR!
900 //if ( filetype == ExplicitVR )
902 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
903 // (no SQ, OW, UT in group 0x0002;)
906 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
910 groupLength += 2 + 2 + 4 + entry->GetLength();
916 entry = GetNextEntry();
921 //-----------------------------------------------------------------------------
924 * \brief Loads all the needed Dictionaries
925 * \warning NOT end user intended method !
927 void Document::Initialize()
929 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
935 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
936 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
937 * @param offset start of parsing
938 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
939 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
941 void Document::ParseDES(DocEntrySet *set, long offset,
942 long l_max, bool delim_mode)
944 DocEntry *newDocEntry;
945 DataEntry *newDataEntry;
946 SeqEntry *newSeqEntry;
948 bool used; // will be set to false when something wrong happens to an Entry.
949 // (Entry will then be deleted)
950 bool delim_mode_intern = delim_mode;
952 gdcmWarningMacro( "Enter in ParseDES, delim-mode " << delim_mode
953 << " at offset " << std::hex << offset );
956 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
961 newDocEntry = ReadNextDocEntry( );
964 // Private tag, in IMplicit VR are defaulted as a DataEntry,
965 // Very often they are only composed of Printable characters,
966 // and could be defaulted as a DataEntry.
967 // It's too late to do the Job
968 // (we should check the value, but we know it after LoadDocEntry ...)
970 // Uncoment this printf line to be able to 'follow' the DocEntries
971 // when something *very* strange happens
973 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
974 // newDocEntry->GetElement(),
975 // newDocEntry->GetVR().c_str() );
982 // an Item Starter found elsewhere but the first position
983 // of a SeqEntry means previous entry was a Sequence
984 // but we didn't get it (private Sequence + Implicit VR)
985 // we have to backtrack.
986 if ( !first && newDocEntry->IsItemStarter() )
988 newDocEntry = Backtrack(newDocEntry);
992 PreviousDocEntry = newDocEntry;
996 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1000 //////////////////////////// DataEntry
1001 vr = newDocEntry->GetVR();
1002 if ( Filetype == ExplicitVR &&
1003 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1005 ////// No DataEntry: should mean UNKOWN VR
1006 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
1007 << "|" << newDocEntry->GetElement()
1008 << " : No DataEntry."
1009 "Probably unknown VR.");
1012 if ( !set->AddEntry( newDataEntry ) )
1014 gdcmWarningMacro( "in ParseDES : cannot add a DataEntry "
1015 << newDataEntry->GetKey()
1017 << newDataEntry->GetOffset() << " )" );
1022 // Load only if we can add (not a duplicate key)
1023 LoadDocEntry( newDataEntry );
1026 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1028 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1030 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1032 std::string strLgrGroup = newDataEntry->GetString();
1034 if ( newDataEntry->IsUnfound() )
1036 lgrGroup = atoi(strLgrGroup.c_str());
1037 Fp->seekg(lgrGroup, std::ios::cur);
1038 //used = false; // never used
1039 RemoveEntry( newDocEntry ); // Remove and delete
1040 // bcc 5.5 is right "assigned a value that's never used"
1048 bool delimitor = newDataEntry->IsItemDelimitor();
1051 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1058 // Just to make sure we are at the beginning of next entry.
1059 SkipToNextDocEntry(newDocEntry);
1063 /////////////////////// SeqEntry : VR = "SQ"
1065 unsigned long l = newDocEntry->GetReadLength();
1066 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1068 if ( l == 0xffffffff )
1070 delim_mode_intern = true;
1074 delim_mode_intern = false;
1078 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1080 // User asked to skip SeQuences *only* if they belong to Shadow Group
1081 if ( newDocEntry->GetGroup()%2 != 0 )
1083 Fp->seekg( l, std::ios::cur);
1084 delete newDocEntry; // Delete, not in the set
1088 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1090 // User asked to skip *any* SeQuence
1091 Fp->seekg( l, std::ios::cur);
1092 delete newDocEntry; // Delete, not in the set
1095 // delay the dynamic cast as late as possible
1096 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1098 // no other way to create the Delimitor ...
1099 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1101 // At the top of the hierarchy, stands a Document. When "set"
1102 // is a Document, then we are building the first depth level.
1103 // Hence the SeqEntry we are building simply has a depth
1105 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1107 newSeqEntry->SetDepthLevel( 1 );
1109 // But when "set" is already a SQItem, we are building a nested
1110 // sequence, and hence the depth level of the new SeqEntry
1111 // we are building, is one level deeper:
1113 // time waste hunting
1114 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1116 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1120 { // Don't try to parse zero-length sequences
1122 gdcmWarningMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1123 << " at offset " << std::hex
1124 << newDocEntry->GetOffset() );
1126 ParseSQ( newSeqEntry,
1127 newDocEntry->GetOffset(),
1128 l, delim_mode_intern);
1130 gdcmWarningMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1133 if ( !set->AddEntry( newSeqEntry ) )
1135 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1136 << newSeqEntry->GetKey()
1138 << newSeqEntry->GetOffset() << " )" );
1142 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1148 } // end SeqEntry : VR = "SQ"
1156 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1160 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1161 * @return parsed length for this level
1163 void Document::ParseSQ( SeqEntry *seqEntry,
1164 long offset, long l_max, bool delim_mode)
1166 int SQItemNumber = 0;
1168 long offsetStartCurrentSQItem = offset;
1172 // the first time, we read the fff0,e000 of the first SQItem
1173 DocEntry *newDocEntry = ReadNextDocEntry();
1177 // FIXME Should warn user
1178 gdcmWarningMacro("in ParseSQ : should never get here!");
1183 if ( newDocEntry->IsSequenceDelimitor() )
1185 seqEntry->SetDelimitationItem( newDocEntry );
1189 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1194 // create the current SQItem
1195 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1196 unsigned int l = newDocEntry->GetReadLength();
1198 if ( l == 0xffffffff )
1207 // Let's try :------------
1208 // remove fff0,e000, created out of the SQItem
1210 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1211 // fill up the current SQItem, starting at the beginning of fff0,e000
1213 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1215 offsetStartCurrentSQItem = Fp->tellg();
1216 // end try -----------------
1218 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1220 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1228 * \brief When a private Sequence + Implicit VR is encountered
1229 * we cannot guess it's a Sequence till we find the first
1230 * Item Starter. We then backtrack to do the job.
1231 * @param docEntry Item Starter that warned us
1233 DocEntry *Document::Backtrack(DocEntry *docEntry)
1235 // delete the Item Starter, built erroneously out of any Sequence
1236 // it's not yet in the HTable/chained list
1239 // Get all info we can from PreviousDocEntry
1240 uint16_t group = PreviousDocEntry->GetGroup();
1241 uint16_t elem = PreviousDocEntry->GetElement();
1242 uint32_t lgt = PreviousDocEntry->GetLength();
1243 long offset = PreviousDocEntry->GetOffset();
1245 gdcmWarningMacro( "Backtrack :" << std::hex << group
1247 << " at offset " << offset );
1248 RemoveEntry( PreviousDocEntry );
1250 // forge the Seq Entry
1251 DocEntry *newEntry = NewSeqEntry(group, elem);
1252 newEntry->SetLength(lgt);
1253 newEntry->SetOffset(offset);
1255 // Move back to the beginning of the Sequence
1256 Fp->seekg( 0, std::ios::beg);
1257 Fp->seekg(offset, std::ios::cur);
1263 * \brief Loads (or not) the element content depending if its length exceeds
1264 * or not the value specified with Document::SetMaxSizeLoadEntry()
1265 * @param entry Header Entry (Dicom Element) to be dealt with
1266 * @param forceLoad whether you want to force loading of 'long' elements
1268 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1270 uint16_t group = entry->GetGroup();
1271 uint16_t elem = entry->GetElement();
1272 const VRKey &vr = entry->GetVR();
1273 uint32_t length = entry->GetLength();
1275 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1277 // A SeQuence "contains" a set of Elements.
1278 // (fffe e000) tells us an Element is beginning
1279 // (fffe e00d) tells us an Element just ended
1280 // (fffe e0dd) tells us the current SeQuence just ended
1282 // (fffe 0000) is an 'impossible' tag value,
1283 // found in MR-PHILIPS-16-Multi-Seq.dcm
1285 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1287 // NO more value field for SQ !
1291 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1297 // When the length is zero things are easy:
1300 dataEntryPtr->SetBinArea(NULL,true);
1304 // The elements whose length is bigger than the specified upper bound
1305 // are not loaded. Instead we leave a short notice on the offset of
1306 // the element content and it's length.
1308 std::ostringstream s;
1312 if (length > MaxSizeLoadEntry)
1314 dataEntryPtr->SetBinArea(NULL,true);
1315 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1317 // to be sure we are at the end of the value ...
1318 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1324 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1328 * \brief Find the value Length of the passed Doc Entry
1329 * @param entry Header Entry whose length of the value shall be loaded.
1331 void Document::FindDocEntryLength( DocEntry *entry )
1332 throw ( FormatError )
1334 const VRKey &vr = entry->GetVR();
1337 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1339 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1342 // The following reserved two bytes (see PS 3.5-2003, section
1343 // "7.1.2 Data element structure with explicit vr", p 27) must be
1344 // skipped before proceeding on reading the length on 4 bytes.
1345 Fp->seekg( 2L, std::ios::cur);
1346 uint32_t length32 = ReadInt32();
1348 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1353 lengthOB = FindDocEntryLengthOBOrOW();
1355 catch ( FormatUnexpected )
1357 // Computing the length failed (this happens with broken
1358 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1359 // chance to get the pixels by deciding the element goes
1360 // until the end of the file. Hence we artificially fix the
1361 // the length and proceed.
1362 gdcmWarningMacro( " Computing the length failed for " <<
1363 entry->GetKey() <<" in " <<GetFileName());
1365 long currentPosition = Fp->tellg();
1366 Fp->seekg(0L,std::ios::end);
1368 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1369 Fp->seekg(currentPosition, std::ios::beg);
1371 entry->SetReadLength(lengthUntilEOF);
1372 entry->SetLength(lengthUntilEOF);
1375 entry->SetReadLength(lengthOB);
1376 entry->SetLength(lengthOB);
1379 FixDocEntryFoundLength(entry, length32);
1383 // Length is encoded on 2 bytes.
1384 length16 = ReadInt16();
1386 // 0xffff means that we deal with 'No Length' Sequence
1387 // or 'No Length' SQItem
1388 if ( length16 == 0xffff)
1392 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1397 // Either implicit VR or a non DICOM conformal (see note below) explicit
1398 // VR that ommited the VR of (at least) this element. Farts happen.
1399 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1400 // on Data elements "Implicit and Explicit VR Data Elements shall
1401 // not coexist in a Data Set and Data Sets nested within it".]
1402 // Length is on 4 bytes.
1404 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1405 // even if Transfer Syntax is 'Implicit VR ...'
1407 FixDocEntryFoundLength( entry, ReadInt32() );
1413 * \brief Find the Length till the next sequence delimiter
1414 * \warning NOT end user intended method !
1417 uint32_t Document::FindDocEntryLengthOBOrOW()
1418 throw( FormatUnexpected )
1420 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1421 long positionOnEntry = Fp->tellg();
1422 bool foundSequenceDelimiter = false;
1423 uint32_t totalLength = 0;
1425 while ( !foundSequenceDelimiter )
1431 group = ReadInt16();
1434 catch ( FormatError )
1436 throw FormatError("Unexpected end of file encountered during ",
1437 "Document::FindDocEntryLengthOBOrOW()");
1439 // We have to decount the group and element we just read
1441 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1443 long filePosition = Fp->tellg();
1445 "Neither an Item tag nor a Sequence delimiter tag on :"
1446 << std::hex << group << " , " << elem
1447 << ") -before- position x(" << filePosition << ")" );
1449 Fp->seekg(positionOnEntry, std::ios::beg);
1450 throw FormatUnexpected(
1451 "Neither an Item tag nor a Sequence delimiter tag.");
1453 if ( elem == 0xe0dd )
1455 foundSequenceDelimiter = true;
1457 uint32_t itemLength = ReadInt32();
1458 // We add 4 bytes since we just read the ItemLength with ReadInt32
1459 totalLength += itemLength + 4;
1460 SkipBytes(itemLength);
1462 if ( foundSequenceDelimiter )
1467 Fp->seekg( positionOnEntry, std::ios::beg);
1472 * \brief Find the Value Representation of the current Dicom Element.
1473 * @return Value Representation of the current Entry
1475 VRKey Document::FindDocEntryVR()
1477 if ( Filetype != ExplicitVR )
1478 return GDCM_VRUNKNOWN;
1480 long positionOnEntry = Fp->tellg();
1481 // Warning: we believe this is explicit VR (Value Representation) because
1482 // we used a heuristic that found "UL" in the first tag. Alas this
1483 // doesn't guarantee that all the tags will be in explicit VR. In some
1484 // cases (see e-film filtered files) one finds implicit VR tags mixed
1485 // within an explicit VR file. Hence we make sure the present tag
1486 // is in explicit VR and try to fix things if it happens not to be
1490 Fp->read(&(vr[0]),(size_t)2);
1492 gdcmDebugMacro( "--> VR: " << vr )
1493 if ( !CheckDocEntryVR(vr) )
1495 gdcmWarningMacro( "Unknown VR '" << vr << "'" )
1496 Fp->seekg(positionOnEntry, std::ios::beg);
1497 return GDCM_VRUNKNOWN;
1503 * \brief Check the correspondance between the VR of the header entry
1504 * and the taken VR. If they are different, the header entry is
1505 * updated with the new VR.
1506 * @param vr Dicom Value Representation
1507 * @return false if the VR is incorrect or if the VR isn't referenced
1508 * otherwise, it returns true
1510 bool Document::CheckDocEntryVR(const VRKey &vr)
1512 return Global::GetVR()->IsValidVR(vr);
1516 * \brief Skip a given Header Entry
1517 * \warning NOT end user intended method !
1518 * @param entry entry to skip
1520 void Document::SkipDocEntry(DocEntry *entry)
1522 SkipBytes(entry->GetLength());
1526 * \brief Skips to the beginning of the next Header Entry
1527 * \warning NOT end user intended method !
1528 * @param currentDocEntry entry to skip
1530 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1532 int l = currentDocEntry->GetReadLength();
1533 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1534 // ... but PMS imagers happen !
1536 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1537 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1539 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1544 * \brief When the length of an element value is obviously wrong (because
1545 * the parser went Jabberwocky) one can hope improving things by
1546 * applying some heuristics.
1547 * @param entry entry to check
1548 * @param foundLength first assumption about length
1550 void Document::FixDocEntryFoundLength(DocEntry *entry,
1551 uint32_t foundLength)
1553 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1554 if ( foundLength == 0xffffffff)
1559 uint16_t gr = entry->GetGroup();
1560 uint16_t elem = entry->GetElement();
1562 if ( foundLength % 2)
1564 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1565 << " in x(" << std::hex << gr << "," << elem <<")");
1568 //////// Fix for some naughty General Electric images.
1569 // Allthough not recent many such GE corrupted images are still present
1570 // on Creatis hard disks. Hence this fix shall remain when such images
1571 // are no longer in use (we are talking a few years, here)...
1572 // Note: XMedCon probably uses such a trick since it is able to read
1573 // those pesky GE images ...
1574 if ( foundLength == 13)
1576 // Only happens for this length !
1577 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1580 entry->SetReadLength(10); // a bug is to be fixed !?
1584 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1585 // Occurence of such images is quite low (unless one leaves close to a
1586 // 'Leonardo' source. Hence, one might consider commenting out the
1587 // following fix on efficiency reasons.
1588 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1591 entry->SetReadLength(4); // a bug is to be fixed !
1594 else if ( entry->GetVR() == "SQ" )
1596 foundLength = 0; // ReadLength is unchanged
1599 //////// We encountered a 'delimiter' element i.e. a tag of the form
1600 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1601 // taken into account.
1602 else if ( gr == 0xfffe )
1604 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1605 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1606 // causes extra troubles...
1607 if ( entry->GetElement() != 0x0000 )
1613 foundLength=12; // to skip the mess that follows this bugged Tag !
1616 entry->SetLength(foundLength);
1620 * \brief Apply some heuristics to predict whether the considered
1621 * element value contains/represents an integer or not.
1622 * @param entry The element value on which to apply the predicate.
1623 * @return The result of the heuristical predicate.
1625 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1627 uint16_t elem = entry->GetElement();
1628 uint16_t group = entry->GetGroup();
1629 const VRKey &vr = entry->GetVR();
1630 uint32_t length = entry->GetLength();
1632 // When we have some semantics on the element we just read, and if we
1633 // a priori know we are dealing with an integer, then we shall be
1634 // able to swap it's element value properly.
1635 if ( elem == 0 ) // This is the group length of the group
1643 // Although this should never happen, still some images have a
1644 // corrupted group length [e.g. have a glance at offset x(8336) of
1645 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1646 // Since for dicom compliant and well behaved headers, the present
1647 // test is useless (and might even look a bit paranoid), when we
1648 // encounter such an ill-formed image, we simply display a warning
1649 // message and proceed on parsing (while crossing fingers).
1650 long filePosition = Fp->tellg();
1651 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1652 << std::hex << group << " , " << elem
1653 << ") -before- position x(" << filePosition << ")"
1654 << "lgt : " << length );
1658 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1666 * \brief Discover what the swap code is (among little endian, big endian,
1667 * bad little endian, bad big endian).
1669 * @return false when we are absolutely sure
1670 * it's neither ACR-NEMA nor DICOM
1671 * true when we hope ours assuptions are OK
1673 bool Document::CheckSwap()
1680 // First, compare HostByteOrder and NetworkByteOrder in order to
1681 // determine if we shall need to swap bytes (i.e. the Endian type).
1682 bool net2host = Util::IsCurrentProcessorBigEndian();
1684 // The easiest case is the one of a 'true' DICOM header, we just have
1685 // to look for the string "DICM" inside the file preamble.
1688 char *entCur = deb + 128;
1689 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1691 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1693 // Group 0002 should always be VR, and the first element 0000
1694 // Let's be carefull (so many wrong headers ...)
1695 // and determine the value representation (VR) :
1696 // Let's skip to the first element (0002,0000) and check there if we find
1697 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1698 // in which case we (almost) know it is explicit VR.
1699 // WARNING: if it happens to be implicit VR then what we will read
1700 // is the length of the group. If this ascii representation of this
1701 // length happens to be "UL" then we shall believe it is explicit VR.
1702 // We need to skip :
1703 // * the 128 bytes of File Preamble (often padded with zeroes),
1704 // * the 4 bytes of "DICM" string,
1705 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1706 // i.e. a total of 136 bytes.
1709 // group 0x0002 *is always* Explicit VR Sometimes ,
1710 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1711 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1713 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1714 memcmp(entCur, "OB", (size_t)2) == 0 ||
1715 memcmp(entCur, "UI", (size_t)2) == 0 ||
1716 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1717 // when Write DCM *adds*
1719 // Use Document::dicom_vr to test all the possibilities
1720 // instead of just checking for UL, OB and UI !? group 0000
1722 Filetype = ExplicitVR;
1723 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1727 Filetype = ImplicitVR;
1728 gdcmErrorMacro( "Group 0002 :Not an explicit Value Representation;"
1729 << "Looks like a bugged Header!");
1735 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder");
1740 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder");
1743 // Position the file position indicator at first tag
1744 // (i.e. after the file preamble and the "DICM" string).
1746 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1748 Fp->seekg ( 132L, std::ios::beg);
1750 } // ------------------------------- End of DicomV3 ----------------
1752 // Alas, this is not a DicomV3 file and whatever happens there is no file
1753 // preamble. We can reset the file position indicator to where the data
1754 // is (i.e. the beginning of the file).
1756 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1758 Fp->seekg(0, std::ios::beg);
1760 // Let's check 'No Preamble Dicom File' :
1761 // Should start with group 0x0002
1762 // and be Explicit Value Representation
1764 s16 = *((uint16_t *)(deb));
1777 if ( SwapCode != 0 )
1779 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1780 memcmp(entCur, "OB", (size_t)2) == 0 ||
1781 memcmp(entCur, "UI", (size_t)2) == 0 ||
1782 memcmp(entCur, "SH", (size_t)2) == 0 ||
1783 memcmp(entCur, "AE", (size_t)2) == 0 ||
1784 memcmp(entCur, "OB", (size_t)2) == 0 )
1786 Filetype = ExplicitVR;
1787 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1791 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1793 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1794 // By clean we mean that the length of the first group is written down.
1795 // If this is the case and since the length of the first group HAS to be
1796 // four (bytes), then determining the proper swap code is straightforward.
1799 // We assume the array of char we are considering contains the binary
1800 // representation of a 32 bits integer. Hence the following dirty
1802 s32 = *((uint32_t *)(entCur));
1822 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1823 // It is time for despaired wild guesses.
1824 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1825 // i.e. the 'group length' element is not present :
1827 // check the supposed-to-be 'group number'
1828 // in ( 0x0001 .. 0x0008 )
1829 // to determine ' SwapCode' value .
1830 // Only 0 or 4321 will be possible
1831 // (no oportunity to check for the formerly well known
1832 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1833 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1834 // the file IS NOT ACR-NEMA nor DICOM V3
1835 // Find a trick to tell it the caller...
1837 s16 = *((uint16_t *)(deb));
1864 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1872 * \brief Change the Byte Swap code.
1874 void Document::SwitchByteSwapCode()
1876 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1877 << " at: 0x" << std::hex << Fp->tellg() );
1878 if ( SwapCode == 1234 )
1882 else if ( SwapCode == 4321 )
1886 else if ( SwapCode == 3412 )
1890 else if ( SwapCode == 2143 )
1894 gdcmDebugMacro( " Into: "<< SwapCode );
1898 * \brief during parsing, Header Elements too long are not loaded in memory
1899 * @param newSize new size
1901 void Document::SetMaxSizeLoadEntry(long newSize)
1907 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1909 MaxSizeLoadEntry = 0xffffffff;
1912 MaxSizeLoadEntry = newSize;
1916 * \brief Read the next tag WITHOUT loading it's value
1917 * (read the 'Group Number', the 'Element Number',
1918 * gets the Dict Entry
1919 * gets the VR, gets the length, gets the offset value)
1920 * @return On succes : the newly created DocEntry, NULL on failure.
1922 DocEntry *Document::ReadNextDocEntry()
1929 group = ReadInt16();
1932 catch ( FormatError )
1934 // We reached the EOF (or an error occured) therefore
1935 // header parsing has to be considered as finished.
1939 // Sometimes file contains groups of tags with reversed endianess.
1940 HandleBrokenEndian(group, elem);
1942 // In 'true DICOM' files Group 0002 is always little endian
1943 if ( HasDCMPreamble )
1944 HandleOutOfGroup0002(group, elem);
1946 VRKey vr = FindDocEntryVR();
1950 if ( vr == GDCM_VRUNKNOWN )
1952 if ( elem == 0x0000 ) // Group Length
1954 realVR = "UL"; // must be UL
1956 else if (group%2 == 1 && (elem >= 0x0010 && elem <=0x00ff ))
1958 // DICOM PS 3-5 7.8.1 a) states that those
1959 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
1964 DictEntry *dictEntry = GetDictEntry(group,elem);
1967 realVR = dictEntry->GetVR();
1968 dictEntry->Unregister();
1972 gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
1975 if ( Global::GetVR()->IsVROfSequence(realVR) )
1976 newEntry = NewSeqEntry(group, elem);
1979 newEntry = NewDataEntry(group, elem, realVR);
1980 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
1983 if ( vr == GDCM_VRUNKNOWN )
1985 if ( Filetype == ExplicitVR )
1987 // We thought this was explicit VR, but we end up with an
1988 // implicit VR tag. Let's backtrack.
1989 if ( newEntry->GetGroup() != 0xfffe )
1992 int offset = Fp->tellg();
1994 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
1995 newEntry->GetGroup(), newEntry->GetElement(), offset );
1996 gdcmWarningMacro( msg.c_str() );
1999 newEntry->SetImplicitVR();
2004 FindDocEntryLength(newEntry);
2006 catch ( FormatError )
2013 newEntry->SetOffset(Fp->tellg());
2019 * \brief Handle broken private tag from Philips NTSCAN
2020 * where the endianess is being switched to BigEndian
2021 * for no apparent reason
2024 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2026 // Endian reversion.
2027 // Some files contain groups of tags with reversed endianess.
2028 static int reversedEndian = 0;
2029 // try to fix endian switching in the middle of headers
2030 if ((group == 0xfeff) && (elem == 0x00e0))
2032 // start endian swap mark for group found
2034 SwitchByteSwapCode();
2039 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2041 // end of reversed endian group
2043 SwitchByteSwapCode();
2045 else if (group == 0xfeff && elem == 0xdde0)
2047 // reversed Sequence Terminator found
2048 // probabely a bug in the header !
2049 // Do what you want, it breaks !
2051 //SwitchByteSwapCode();
2052 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2057 else if (group == 0xfffe && elem == 0xe0dd)
2059 gdcmWarningMacro( "Straight Sequence Terminator." );
2064 * \brief Group 0002 is always coded Little Endian
2065 * whatever Transfer Syntax is
2068 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2070 // Endian reversion.
2071 // Some files contain groups of tags with reversed endianess.
2072 if ( !Group0002Parsed && group != 0x0002)
2074 Group0002Parsed = true;
2075 // we just came out of group 0002
2076 // if Transfer syntax is Big Endian we have to change CheckSwap
2078 std::string ts = GetTransferSyntax();
2079 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2081 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2085 // Group 0002 is always 'Explicit ...'
2086 // even when Transfer Syntax says 'Implicit ..."
2088 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2089 TS::ImplicitVRLittleEndian )
2091 Filetype = ImplicitVR;
2094 // FIXME Strangely, this works with
2095 //'Implicit VR BigEndian Transfer Syntax (GE Private)
2097 // --> Probabely normal, since we considered we never have
2098 // to trust manufacturers.
2099 // (we find very often 'Implicit VR' tag,
2100 // even when Transfer Syntax tells us it's Explicit ...
2101 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2102 TS::ExplicitVRBigEndian )
2104 gdcmWarningMacro("Transfer Syntax Name = ["
2105 << GetTransferSyntaxName() << "]" );
2106 SwitchByteSwapCode();
2107 group = SwapShort(group);
2108 elem = SwapShort(elem);
2113 //-----------------------------------------------------------------------------
2116 //-----------------------------------------------------------------------------
2117 } // end namespace gdcm