1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/11/21 09:46:26 $
7 Version: $Revision: 1.329 $
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 //-----------------------------------------------------------------------------
80 * \brief Loader. use SetLoadMode(), SetFileName() before !
81 * @return false if file cannot be open or no swap info was found,
82 * or no tag was found.
84 bool Document::Load( )
86 if ( GetFileName() == "" )
88 gdcmWarningMacro( "Use SetFileName, before !" );
91 return DoTheLoadingDocumentJob( );
94 #ifndef GDCM_LEGACY_REMOVE
95 bool Document::Load( std::string const &fileName )
98 return DoTheLoadingDocumentJob( );
103 * \brief Performs the Loading Job (internal use only)
104 * @return false if file cannot be open or no swap info was found,
105 * or no tag was found.
107 bool Document::DoTheLoadingDocumentJob( )
109 if ( ! IsDocumentModified ) // Nothing to do !
117 // warning already performed in OpenFile()
122 Group0002Parsed = false;
124 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
126 Fp->seekg(0, std::ios::end);
127 long lgt = Fp->tellg(); // total length of the file
129 Fp->seekg(0, std::ios::beg);
131 // CheckSwap returns a boolean
132 // (false if no swap info of any kind was found)
135 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
136 << Filename.c_str());
141 long beg = Fp->tellg(); // just after DICOM preamble (if any)
143 lgt -= beg; // remaining length to parse
146 // Loading is done during parsing
147 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
151 gdcmErrorMacro( "No tag in internal hash table for: "
152 << Filename.c_str());
156 IsDocumentAlreadyLoaded = true;
158 Fp->seekg( 0, std::ios::beg);
160 // Load 'non string' values
162 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
163 if ( PhotometricInterpretation == "PALETTE COLOR " )
166 // Probabely this line should be outside the 'if'
167 // Try to find an image sample holding a 'gray LUT'
168 LoadEntryBinArea(0x0028,0x1200); // gray LUT
171 /// --> FIXME : The difference between BinEntry and DataEntry
172 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
173 /// --> Old comment restored on purpose.
174 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
175 /// --> had absolutely no meaning.
176 /// --> The whole comment will be removed when the stuff is cleaned !
178 /// The tags refered by the three following lines used to be CORRECTLY
179 /// defined as having an US Value Representation in the public
180 /// dictionary. BUT the semantics implied by the three following
181 /// lines state that the corresponding tag contents are in fact
182 /// the ones of a BinEntry.
183 /// In order to fix things "Quick and Dirty" the dictionary was
184 /// altered on PURPOSE but now contains a WRONG value.
185 /// In order to fix things and restore the dictionary to its
186 /// correct value, one needs to decide of the semantics by deciding
187 /// whether the following tags are either :
188 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
189 /// also used as BinEntry, which requires the proper conversion,
190 /// - OW, and hence loaded as BinEntry, but afterwards also used
191 /// as ValEntry, which requires the proper conversion.
193 // --> OB (byte aray) or OW (short int aray)
194 // The actual VR has to be deduced from other entries.
195 // Our way of loading them may fail in some cases :
196 // We must or not SwapByte depending on other field values.
198 LoadEntryBinArea(0x0028,0x1201); // R LUT
199 LoadEntryBinArea(0x0028,0x1202); // G LUT
200 LoadEntryBinArea(0x0028,0x1203); // B LUT
202 // Segmented Red Palette Color LUT Data
203 LoadEntryBinArea(0x0028,0x1221);
204 // Segmented Green Palette Color LUT Data
205 LoadEntryBinArea(0x0028,0x1222);
206 // Segmented Blue Palette Color LUT Data
207 LoadEntryBinArea(0x0028,0x1223);
210 //FIXME later : how to use it?
211 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
214 SQItem *sqi= modLutSeq->GetFirstSQItem();
217 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
218 if ( dataEntry != 0 )
220 if ( dataEntry->GetLength() != 0 )
222 // FIXME : CTX dependent means : contexted dependant.
223 // see upper comment.
224 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
230 // Force Loading some more elements if user asked to.
233 for (ListElements::iterator it = UserForceLoadList.begin();
234 it != UserForceLoadList.end();
237 gdcmDebugMacro( "Force Load " << std::hex
238 << (*it).Group << "|" <<(*it).Elem );
240 d = GetDocEntry( (*it).Group, (*it).Elem);
244 gdcmWarningMacro( "You asked toForce Load " << std::hex
245 << (*it).Group <<"|"<< (*it).Elem
246 << " that doesn't exist" );
250 LoadDocEntry(d, true);
255 // ----------------------------
256 // Specific code to allow gdcm to read ACR-LibIDO formated images
257 // Note: ACR-LibIDO is an extension of the ACR standard that was
258 // used at CREATIS. For the time being (say a couple of years)
259 // we keep this kludge to allow CREATIS users
260 // reading their old images.
262 // if recognition code tells us we deal with a LibIDO image
263 // we switch lineNumber and columnNumber
266 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
267 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
268 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
269 // with "little-endian strings"
271 Filetype = ACR_LIBIDO;
272 std::string rows = GetEntryString(0x0028, 0x0010);
273 std::string columns = GetEntryString(0x0028, 0x0011);
274 SetEntryString(columns, 0x0028, 0x0010);
275 SetEntryString(rows , 0x0028, 0x0011);
277 // --- End of ACR-LibIDO kludge ---
283 * \brief Adds a new element we want to load anyway
284 * @param group Group number of the target tag.
285 * @param elem Element number of the target tag.
287 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
292 UserForceLoadList.push_back(el);
295 * \brief Get the public dictionary used
297 Dict *Document::GetPubDict()
303 * \brief Get the shadow dictionary used
305 Dict *Document::GetShaDict()
311 * \brief Set the shadow dictionary used
312 * @param dict dictionary to use in shadow
314 bool Document::SetShaDict(Dict *dict)
321 * \brief Set the shadow dictionary used
322 * @param dictName name of the dictionary to use in shadow
324 bool Document::SetShaDict(DictKey const &dictName)
326 RefShaDict = Global::GetDicts()->GetDict(dictName);
331 * \brief This predicate tells us whether or not the current Document
332 * was properly parsed and contains at least *one* Dicom Element
333 * (and nothing more, sorry).
334 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
337 bool Document::IsParsable()
339 if ( Filetype == Unknown )
341 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
347 gdcmWarningMacro( "No tag in internal hash table.");
354 * \brief This predicate tells us whether or not the current Document
355 * was properly parsed and contains at least *one* Dicom Element
356 * (and nothing more, sorry).
357 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
360 bool Document::IsReadable()
366 * \brief Predicate for dicom version 3 file.
367 * @return True when the file is a dicom version 3.
369 bool Document::IsDicomV3()
371 // Checking if Transfer Syntax exists is enough
372 // Anyway, it's too late check if the 'Preamble' was found ...
373 // And ... would it be a rich idea to check ?
374 // (some 'no Preamble' DICOM images exist !)
375 return GetDocEntry(0x0002, 0x0010) != NULL;
379 * \brief Predicate for Papyrus file
380 * Dedicated to whomsoever it may concern
381 * @return True when the file is a Papyrus file.
383 bool Document::IsPapyrus()
385 // check for Papyrus private Sequence
386 DocEntry *e = GetDocEntry(0x0041, 0x1050);
389 // check if it's actually a Sequence
390 if ( !dynamic_cast<SeqEntry*>(e) )
396 * \brief returns the File Type
397 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
398 * @return the FileType code
400 FileType Document::GetFileType()
406 * \brief Accessor to the Transfer Syntax (when present) of the
407 * current document (it internally handles reading the
408 * value from disk when only parsing occured).
409 * @return The encountered Transfer Syntax of the current document, if DICOM.
410 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
412 std::string Document::GetTransferSyntax()
414 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
420 // The entry might be present but not loaded (parsing and loading
421 // happen at different stages): try loading and proceed with check...
422 LoadDocEntrySafe(entry);
423 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
425 std::string transfer = dataEntry->GetString();
426 // The actual transfer (as read from disk) might be padded. We
427 // first need to remove the potential padding. We can make the
428 // weak assumption that padding was not executed with digits...
429 if ( transfer.length() == 0 )
431 // for brain damaged headers
432 gdcmWarningMacro( "Transfer Syntax has length = 0.");
435 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
437 transfer.erase(transfer.length()-1, 1);
438 if ( transfer.length() == 0 )
440 // for brain damaged headers
441 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
451 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
452 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
454 std::string Document::GetTransferSyntaxName()
456 // use the TS (TS : Transfer Syntax)
457 std::string transferSyntax = GetEntryString(0x0002,0x0010);
459 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
461 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
462 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
463 return "Uncompressed ACR-NEMA";
465 if ( transferSyntax == GDCM_UNFOUND )
467 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
468 return "Uncompressed ACR-NEMA";
471 // we do it only when we need it
472 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
474 // Global::GetTS() is a global static you shall never try to delete it!
478 // --------------- Swap Code ------------------
480 * \brief Swaps the bytes so they agree with the processor order
481 * @return The properly swaped 16 bits integer.
483 uint16_t Document::SwapShort(uint16_t a)
485 if ( SwapCode == 4321 || SwapCode == 2143 )
487 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
489 a = ( a << 8 ) | ( a >> 8 );
495 * \brief Swaps back the bytes of 4-byte long integer accordingly to
497 * @return The properly swaped 32 bits integer.
499 uint32_t Document::SwapLong(uint32_t a)
506 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
507 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
509 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
510 ((a>>8) & 0x0000ff00) | (a>>24) );
513 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
514 a=( (a<<16) | (a>>16) );
517 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
520 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
527 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
529 * @return The properly swaped 64 bits double.
531 double Document::SwapDouble(double a)
535 // There were no 'double' at ACR-NEMA time.
536 // We just have to deal with 'straight Little Endian' and
537 // 'straight Big Endian'
542 char *beg = (char *)&a;
545 for (unsigned int i = 0; i<7; i++)
556 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
563 // -----------------File I/O ---------------
565 * \brief Tries to open the file \ref Document::Filename and
566 * checks the preamble when existing.
567 * @return The FILE pointer on success.
569 std::ifstream *Document::OpenFile()
571 HasDCMPreamble = false;
572 if (Filename.length() == 0)
579 gdcmDebugMacro( "File already open: " << Filename.c_str());
583 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
586 // Don't user gdcmErrorMacro :
587 // a spurious message will appear when you use, for instance
588 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
589 // to create outputFileName.
591 // FIXME : if the upper comment is still usefull
592 // --> the constructor is not so good ...
594 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
598 //exit(1); // No function is allowed to leave the application instead
599 // of warning the caller
603 Fp->read((char*)&zero, (size_t)2);
610 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
612 // FIXME : We cannot be sure the preable is only zeroes..
613 // (see ACUSON-24-YBR_FULL-RLE.dcm )
615 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
616 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
617 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
618 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
620 std::string msg = Util::Format(
621 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
622 // FIXME : is it a Warning message, or a Debug message?
623 gdcmWarningMacro( msg.c_str() );
628 Fp->seekg(126L, std::ios::cur);
629 char dicm[4]; // = {' ',' ',' ',' '};
630 Fp->read(dicm, (size_t)4);
636 if ( memcmp(dicm, "DICM", 4) == 0 )
638 HasDCMPreamble = true;
642 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
644 // Don't user Warning nor Error, not to polute the output
645 // while directory recursive parsing ...
646 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
647 << Filename.c_str());
652 * \brief closes the file
653 * @return TRUE if the close was successfull
655 bool Document::CloseFile()
667 * \brief Writes in a file all the Entries (Dicom Elements)
668 * @param fp file pointer on an already open file (actually: Output File Stream)
669 * @param filetype Type of the File to be written
670 * (ACR-NEMA, ExplicitVR, ImplicitVR)
672 void Document::WriteContent(std::ofstream *fp, FileType filetype)
674 // Skip if user wants to write an ACR-NEMA file
676 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
679 // writing Dicom File Preamble
680 char filePreamble[128];
681 memset(filePreamble, 0, 128);
682 fp->write(filePreamble, 128);
683 fp->write("DICM", 4);
687 * \todo rewrite later, if really usefull
688 * - 'Group Length' element is optional in DICOM
689 * - but un-updated odd groups lengthes can causes pb
692 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
693 * UpdateGroupLength(false,filetype);
694 * if ( filetype == ACR)
695 * UpdateGroupLength(true,ACR);
697 * --> Computing group length for groups with embeded Sequences
698 * --> was too much tricky / we were [in a hurry / too lazy]
699 * --> We don't write the element 0x0000 (group length)
702 ElementSet::WriteContent(fp, filetype); // This one is recursive
705 // -----------------------------------------
708 * \brief Loads (from disk) the element content
709 * when a string is not suitable
710 * @param group group number of the Entry
711 * @param elem element number of the Entry
713 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
715 // Search the corresponding DocEntry
716 DocEntry *docEntry = GetDocEntry(group, elem);
719 gdcmDebugMacro(std::hex << group << "|" << elem
720 << " doesn't exist" );
723 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
726 gdcmWarningMacro(std::hex << group << "|" << elem
727 << " is NOT a DataEntry");
730 LoadEntryBinArea(dataEntry);
734 * \brief Loads (from disk) the element content
735 * when a string is not suitable
736 * @param entry Entry whose binArea is going to be loaded
738 void Document::LoadEntryBinArea(DataEntry *entry)
740 if( entry->GetBinArea() )
747 size_t o =(size_t)entry->GetOffset();
748 Fp->seekg(o, std::ios::beg);
750 size_t l = entry->GetLength();
751 uint8_t *data = new uint8_t[l];
754 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
755 << std::hex << entry->GetGroup()
756 << "|" << entry->GetElement() );
761 Fp->read((char*)data, l);
762 if ( Fp->fail() || Fp->eof() )
765 entry->SetState(DataEntry::STATE_UNREAD);
769 // Swap the data content if necessary
771 unsigned short vrLgth =
772 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
774 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
775 // if( entry->GetVR() == "OW" )
786 uint16_t *data16 = (uint16_t *)data;
787 for(i=0;i<l/vrLgth;i++)
788 data16[i] = SwapShort(data16[i]);
793 uint32_t *data32 = (uint32_t *)data;
794 for(i=0;i<l/vrLgth;i++)
795 data32[i] = SwapLong(data32[i]);
800 double *data64 = (double *)data;
801 for(i=0;i<l/vrLgth;i++)
802 data64[i] = SwapDouble(data64[i]);
807 entry->SetBinArea(data);
814 * \brief Loads the element while preserving the current
815 * underlying file position indicator as opposed to
816 * LoadDocEntry that modifies it.
817 * @param entry DocEntry whose value will be loaded.
819 void Document::LoadDocEntrySafe(DocEntry *entry)
823 long PositionOnEntry = Fp->tellg();
825 Fp->seekg(PositionOnEntry, std::ios::beg);
830 * \brief Compares two documents, according to \ref DicomDir rules
831 * \warning Does NOT work with ACR-NEMA files
832 * \todo Find a trick to solve the pb (use RET fields ?)
833 * @param document to compare with current one
834 * @return true if 'smaller'
836 bool Document::operator<(Document &document)
839 std::string s1 = GetEntryString(0x0010,0x0010);
840 std::string s2 = document.GetEntryString(0x0010,0x0010);
852 s1 = GetEntryString(0x0010,0x0020);
853 s2 = document.GetEntryString(0x0010,0x0020);
864 // Study Instance UID
865 s1 = GetEntryString(0x0020,0x000d);
866 s2 = document.GetEntryString(0x0020,0x000d);
877 // Serie Instance UID
878 s1 = GetEntryString(0x0020,0x000e);
879 s2 = document.GetEntryString(0x0020,0x000e);
894 //-----------------------------------------------------------------------------
897 * \brief Reads a supposed to be 16 Bits integer
898 * (swaps it depending on processor endianness)
901 uint16_t Document::ReadInt16()
905 Fp->read ((char*)&g, (size_t)2);
908 throw FormatError( "Document::ReadInt16()", " file error." );
912 throw FormatError( "Document::ReadInt16()", "EOF." );
919 * \brief Reads a supposed to be 32 Bits integer
920 * (swaps it depending on processor endianness)
923 uint32_t Document::ReadInt32()
927 Fp->read ((char*)&g, (size_t)4);
930 throw FormatError( "Document::ReadInt32()", " file error." );
934 throw FormatError( "Document::ReadInt32()", "EOF." );
941 * \brief skips bytes inside the source file
944 void Document::SkipBytes(uint32_t nBytes)
946 //FIXME don't dump the returned value
947 Fp->seekg((long)nBytes, std::ios::cur);
951 * \brief Re-computes the length of the Dicom group 0002.
953 int Document::ComputeGroup0002Length( )
959 bool found0002 = false;
961 // for each zero-level Tag in the DCM Header
962 DocEntry *entry = GetFirstEntry();
965 gr = entry->GetGroup();
971 if ( entry->GetElement() != 0x0000 )
975 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
976 // (no SQ, OW, UT in group 0x0002;)
979 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
983 groupLength += 2 + 2 + 4 + entry->GetLength();
989 entry = GetNextEntry();
994 //-----------------------------------------------------------------------------
997 * \brief Loads all the needed Dictionaries
999 void Document::Initialize()
1001 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1007 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1008 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1009 * @param offset start of parsing
1010 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1011 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1013 void Document::ParseDES(DocEntrySet *set, long offset,
1014 long l_max, bool delim_mode)
1016 DocEntry *newDocEntry;
1017 DataEntry *newDataEntry;
1018 SeqEntry *newSeqEntry;
1020 bool used; // will be set to false when something wrong happens to an Entry.
1021 // (Entry will then be deleted)
1022 bool delim_mode_intern = delim_mode;
1024 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1025 << " at offset " << std::hex << offset );
1028 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1033 newDocEntry = ReadNextDocEntry( );
1035 // Uncoment this cerr line to be able to 'follow' the DocEntries
1036 // when something *very* strange happens
1037 if( Debug::GetDebugFlag() )
1038 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1045 // an Item Starter found elsewhere but the first position
1046 // of a SeqEntry means previous entry was a Sequence
1047 // but we didn't get it (private Sequence + Implicit VR)
1048 // we have to backtrack.
1049 if ( !first && newDocEntry->IsItemStarter() )
1051 // Debug message within the method !
1052 newDocEntry = Backtrack(newDocEntry);
1056 PreviousDocEntry = newDocEntry;
1060 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1064 //////////////////////////// DataEntry
1066 vr = newDocEntry->GetVR();
1068 if ( !set->AddEntry( newDataEntry ) )
1070 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1071 << newDataEntry->GetKey()
1073 << newDataEntry->GetOffset() << " )" );
1078 newDataEntry->Delete();
1079 // Load only if we can add (not a duplicate key)
1080 LoadDocEntry( newDataEntry );
1083 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1085 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1087 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1089 std::string strLgrGroup = newDataEntry->GetString();
1091 if ( newDataEntry->IsUnfound() )
1093 lgrGroup = atoi(strLgrGroup.c_str());
1094 Fp->seekg(lgrGroup, std::ios::cur);
1095 //used = false; // never used
1096 RemoveEntry( newDocEntry ); // Remove and delete
1097 // bcc 5.5 is right "assigned a value that's never used"
1105 bool delimitor = newDataEntry->IsItemDelimitor();
1108 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1111 newDocEntry->Delete();
1115 // Just to make sure we are at the beginning of next entry.
1116 SkipToNextDocEntry(newDocEntry);
1120 /////////////////////// SeqEntry : VR = "SQ"
1122 unsigned long l = newDocEntry->GetReadLength();
1123 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1125 if ( l == 0xffffffff )
1127 delim_mode_intern = true;
1131 delim_mode_intern = false;
1135 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1137 // User asked to skip SeQuences *only* if they belong to Shadow Group
1138 if ( newDocEntry->GetGroup()%2 != 0 )
1140 Fp->seekg( l, std::ios::cur);
1141 newDocEntry->Delete(); // Delete, not in the set
1145 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1147 // User asked to skip *any* SeQuence
1148 Fp->seekg( l, std::ios::cur);
1149 newDocEntry->Delete(); // Delete, not in the set
1152 // delay the dynamic cast as late as possible
1153 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1155 // no other way to create the Delimitor ...
1156 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1158 // At the top of the hierarchy, stands a Document. When "set"
1159 // is a Document, then we are building the first depth level.
1160 // Hence the SeqEntry we are building simply has a depth
1162 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1164 newSeqEntry->SetDepthLevel( 1 );
1166 // But when "set" is already a SQItem, we are building a nested
1167 // sequence, and hence the depth level of the new SeqEntry
1168 // we are building, is one level deeper:
1170 // time waste hunting
1171 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1173 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1177 { // Don't try to parse zero-length sequences
1179 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1180 << " at offset " << std::hex
1181 << newDocEntry->GetOffset() );
1183 ParseSQ( newSeqEntry,
1184 newDocEntry->GetOffset(),
1185 l, delim_mode_intern);
1187 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1190 if ( !set->AddEntry( newSeqEntry ) )
1192 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1193 << newSeqEntry->GetKey()
1195 << newSeqEntry->GetOffset() << " )" );
1200 newDocEntry->Delete();
1203 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1206 newDocEntry->Delete();
1209 } // end SeqEntry : VR = "SQ"
1213 newDocEntry->Delete();
1217 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1221 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1222 * @return parsed length for this level
1224 void Document::ParseSQ( SeqEntry *seqEntry,
1225 long offset, long l_max, bool delim_mode)
1227 int SQItemNumber = 0;
1229 long offsetStartCurrentSQItem = offset;
1233 // the first time, we read the fff0,e000 of the first SQItem
1234 DocEntry *newDocEntry = ReadNextDocEntry();
1238 gdcmWarningMacro("in ParseSQ : should never get here!");
1243 if ( newDocEntry->IsSequenceDelimitor() )
1245 seqEntry->SetDelimitationItem( newDocEntry );
1246 newDocEntry->Delete();
1250 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1252 newDocEntry->Delete();
1255 // create the current SQItem
1256 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1257 unsigned int l = newDocEntry->GetReadLength();
1259 if ( l == 0xffffffff )
1268 // remove fff0,e000, created out of the SQItem
1269 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1270 // fill up the current SQItem, starting at the beginning of fff0,e000
1272 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1274 offsetStartCurrentSQItem = Fp->tellg();
1276 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1278 newDocEntry->Delete();
1280 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1288 * \brief When a private Sequence + Implicit VR is encountered
1289 * we cannot guess it's a Sequence till we find the first
1290 * Item Starter. We then backtrack to do the job.
1291 * @param docEntry Item Starter that warned us
1293 DocEntry *Document::Backtrack(DocEntry *docEntry)
1295 // delete the Item Starter, built erroneously out of any Sequence
1296 // it's not yet in the HTable/chained list
1299 // Get all info we can from PreviousDocEntry
1300 uint16_t group = PreviousDocEntry->GetGroup();
1301 uint16_t elem = PreviousDocEntry->GetElement();
1302 uint32_t lgt = PreviousDocEntry->GetLength();
1303 long offset = PreviousDocEntry->GetOffset();
1305 gdcmDebugMacro( "Backtrack :" << std::hex << group
1307 << " at offset " << offset );
1308 RemoveEntry( PreviousDocEntry );
1310 // forge the Seq Entry
1311 DocEntry *newEntry = NewSeqEntry(group, elem);
1312 newEntry->SetLength(lgt);
1313 newEntry->SetOffset(offset);
1315 // Move back to the beginning of the Sequence
1316 Fp->seekg( 0, std::ios::beg);
1317 Fp->seekg(offset, std::ios::cur);
1323 * \brief Loads (or not) the element content depending if its length exceeds
1324 * or not the value specified with Document::SetMaxSizeLoadEntry()
1325 * @param entry Header Entry (Dicom Element) to be dealt with
1326 * @param forceLoad whether you want to force loading of 'long' elements
1328 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1330 uint16_t group = entry->GetGroup();
1331 uint16_t elem = entry->GetElement();
1332 const VRKey &vr = entry->GetVR();
1333 uint32_t length = entry->GetLength();
1335 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1337 // A SeQuence "contains" a set of Elements.
1338 // (fffe e000) tells us an Element is beginning
1339 // (fffe e00d) tells us an Element just ended
1340 // (fffe e0dd) tells us the current SeQuence just ended
1342 // (fffe 0000) is an 'impossible' tag value,
1343 // found in MR-PHILIPS-16-Multi-Seq.dcm
1345 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1347 // NO more value field for SQ !
1351 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1357 // When the length is zero things are easy:
1360 dataEntryPtr->SetBinArea(NULL,true);
1364 // The elements whose length is bigger than the specified upper bound
1367 std::ostringstream s;
1371 if (length > MaxSizeLoadEntry)
1373 dataEntryPtr->SetBinArea(NULL,true);
1374 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1376 // to be sure we are at the end of the value ...
1377 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1383 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1387 * \brief Find the value Length of the passed Doc Entry
1388 * @param entry Header Entry whose length of the value shall be loaded.
1390 void Document::FindDocEntryLength( DocEntry *entry )
1391 throw ( FormatError )
1393 const VRKey &vr = entry->GetVR();
1396 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1398 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1401 // The following reserved two bytes (see PS 3.5-2003, section
1402 // "7.1.2 Data element structure with explicit vr", p 27) must be
1403 // skipped before proceeding on reading the length on 4 bytes.
1404 Fp->seekg( 2L, std::ios::cur);
1405 uint32_t length32 = ReadInt32();
1407 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1412 lengthOB = FindDocEntryLengthOBOrOW();
1414 catch ( FormatUnexpected )
1416 // Computing the length failed (this happens with broken
1417 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1418 // chance to get the pixels by deciding the element goes
1419 // until the end of the file. Hence we artificially fix the
1420 // the length and proceed.
1421 gdcmWarningMacro( " Computing the length failed for " <<
1422 entry->GetKey() <<" in " <<GetFileName());
1424 long currentPosition = Fp->tellg();
1425 Fp->seekg(0L,std::ios::end);
1427 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1428 Fp->seekg(currentPosition, std::ios::beg);
1430 entry->SetReadLength(lengthUntilEOF);
1431 entry->SetLength(lengthUntilEOF);
1434 entry->SetReadLength(lengthOB);
1435 entry->SetLength(lengthOB);
1438 FixDocEntryFoundLength(entry, length32);
1442 // Length is encoded on 2 bytes.
1443 length16 = ReadInt16();
1445 // 0xffff means that we deal with 'No Length' Sequence
1446 // or 'No Length' SQItem
1447 if ( length16 == 0xffff)
1451 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1456 // Either implicit VR or a non DICOM conformal (see note below) explicit
1457 // VR that ommited the VR of (at least) this element. Farts happen.
1458 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1459 // on Data elements "Implicit and Explicit VR Data Elements shall
1460 // not coexist in a Data Set and Data Sets nested within it".]
1461 // Length is on 4 bytes.
1463 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1464 // even if Transfer Syntax is 'Implicit VR ...'
1465 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1467 FixDocEntryFoundLength( entry, ReadInt32() );
1473 * \brief Find the Length till the next sequence delimiter
1476 uint32_t Document::FindDocEntryLengthOBOrOW()
1477 throw( FormatUnexpected )
1479 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1480 long positionOnEntry = Fp->tellg();
1481 bool foundSequenceDelimiter = false;
1482 uint32_t totalLength = 0;
1484 while ( !foundSequenceDelimiter )
1490 group = ReadInt16();
1493 catch ( FormatError )
1495 throw FormatError("Unexpected end of file encountered during ",
1496 "Document::FindDocEntryLengthOBOrOW()");
1498 // We have to decount the group and element we just read
1500 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1502 long filePosition = Fp->tellg();
1504 "Neither an Item tag nor a Sequence delimiter tag on :"
1505 << std::hex << group << " , " << elem
1506 << ") -before- position x(" << filePosition << ")" );
1508 Fp->seekg(positionOnEntry, std::ios::beg);
1509 throw FormatUnexpected(
1510 "Neither an Item tag nor a Sequence delimiter tag.");
1512 if ( elem == 0xe0dd )
1514 foundSequenceDelimiter = true;
1516 uint32_t itemLength = ReadInt32();
1517 // We add 4 bytes since we just read the ItemLength with ReadInt32
1518 totalLength += itemLength + 4;
1519 SkipBytes(itemLength);
1521 if ( foundSequenceDelimiter )
1526 Fp->seekg( positionOnEntry, std::ios::beg);
1531 * \brief Find the Value Representation of the current Dicom Element.
1532 * @return Value Representation of the current Entry
1534 VRKey Document::FindDocEntryVR()
1536 if ( Filetype != ExplicitVR )
1537 return GDCM_VRUNKNOWN;
1539 long positionOnEntry = Fp->tellg();
1540 // Warning: we believe this is explicit VR (Value Representation) because
1541 // we used a heuristic that found "UL" in the first tag and/or
1542 // 'Transfer Syntax' told us it is.
1543 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1544 // In some cases one finds implicit VR tags mixed within an explicit VR file.
1545 // Hence we make sure the present tag is in explicit VR and try to fix things
1546 // if it happens not to be the case.
1549 Fp->read(&(vr[0]),(size_t)2);
1551 if ( !CheckDocEntryVR(vr) )
1553 // Don't warn user with useless messages
1554 // Often, delimiters (0xfffe), are not explicit VR ...
1555 if ( CurrentGroup != 0xfffe )
1556 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1557 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1558 << ") at offset :" << positionOnEntry );
1559 Fp->seekg(positionOnEntry, std::ios::beg);
1560 return GDCM_VRUNKNOWN;
1566 * \brief Check the correspondance between the VR of the header entry
1567 * and the taken VR. If they are different, the header entry is
1568 * updated with the new VR.
1569 * @param vr Dicom Value Representation
1570 * @return false if the VR is incorrect or if the VR isn't referenced
1571 * otherwise, it returns true
1573 bool Document::CheckDocEntryVR(const VRKey &vr)
1575 return Global::GetVR()->IsValidVR(vr);
1579 * \brief Skip a given Header Entry
1580 * @param entry entry to skip
1582 void Document::SkipDocEntry(DocEntry *entry)
1584 SkipBytes(entry->GetLength());
1588 * \brief Skips to the beginning of the next Header Entry
1589 * @param currentDocEntry entry to skip
1591 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1593 int l = currentDocEntry->GetReadLength();
1594 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1595 // ... but PMS imagers happen !
1597 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1598 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1600 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1605 * \brief When the length of an element value is obviously wrong (because
1606 * the parser went Jabberwocky) one can hope improving things by
1607 * applying some heuristics.
1608 * @param entry entry to check
1609 * @param foundLength first assumption about length
1611 void Document::FixDocEntryFoundLength(DocEntry *entry,
1612 uint32_t foundLength)
1614 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1615 if ( foundLength == 0xffffffff)
1620 uint16_t gr = entry->GetGroup();
1621 uint16_t elem = entry->GetElement();
1623 if ( foundLength % 2)
1625 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1626 << " in x(" << std::hex << gr << "," << elem <<")");
1629 //////// Fix for some naughty General Electric images.
1630 // Allthough not recent many such GE corrupted images are still present
1631 // on Creatis hard disks. Hence this fix shall remain when such images
1632 // are no longer in use (we are talking a few years, here)...
1633 // Note: XMedCon probably uses such a trick since it is able to read
1634 // those pesky GE images ...
1635 if ( foundLength == 13)
1637 // Only happens for this length !
1638 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1641 entry->SetReadLength(10); // a bug is to be fixed !?
1645 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1646 // Occurence of such images is quite low (unless one leaves close to a
1647 // 'Leonardo' source. Hence, one might consider commenting out the
1648 // following fix on efficiency reasons.
1649 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1652 entry->SetReadLength(4); // a bug is to be fixed !
1655 else if ( entry->GetVR() == "SQ" )
1657 foundLength = 0; // ReadLength is unchanged
1660 //////// We encountered a 'delimiter' element i.e. a tag of the form
1661 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1662 // taken into account.
1663 else if ( gr == 0xfffe )
1665 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1666 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1667 // causes extra troubles...
1668 if ( entry->GetElement() != 0x0000 )
1674 foundLength=12; // to skip the mess that follows this bugged Tag !
1677 entry->SetLength(foundLength);
1681 * \brief Apply some heuristics to predict whether the considered
1682 * element value contains/represents an integer or not.
1683 * @param entry The element value on which to apply the predicate.
1684 * @return The result of the heuristical predicate.
1686 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1688 uint16_t elem = entry->GetElement();
1689 uint16_t group = entry->GetGroup();
1690 const VRKey &vr = entry->GetVR();
1691 uint32_t length = entry->GetLength();
1693 // When we have some semantics on the element we just read, and if we
1694 // a priori know we are dealing with an integer, then we shall be
1695 // able to swap it's element value properly.
1696 if ( elem == 0 ) // This is the group length of the group
1704 // Although this should never happen, still some images have a
1705 // corrupted group length [e.g. have a glance at offset x(8336) of
1706 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1707 // Since for dicom compliant and well behaved headers, the present
1708 // test is useless (and might even look a bit paranoid), when we
1709 // encounter such an ill-formed image, we simply display a warning
1710 // message and proceed on parsing (while crossing fingers).
1711 long filePosition = Fp->tellg();
1712 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1713 << std::hex << group << " , " << elem
1714 << ") -before- position x(" << filePosition << ")"
1715 << "lgt : " << length );
1719 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1727 * \brief Discover what the swap code is (among little endian, big endian,
1728 * bad little endian, bad big endian).
1730 * @return false when we are absolutely sure
1731 * it's neither ACR-NEMA nor DICOM
1732 * true when we hope ours assuptions are OK
1734 bool Document::CheckSwap()
1741 // First, compare HostByteOrder and NetworkByteOrder in order to
1742 // determine if we shall need to swap bytes (i.e. the Endian type).
1743 bool net2host = Util::IsCurrentProcessorBigEndian();
1745 // The easiest case is the one of a 'true' DICOM header, we just have
1746 // to look for the string "DICM" inside the file preamble.
1749 char *entCur = deb + 128;
1750 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1752 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1754 // Group 0002 should always be VR, and the first element 0000
1755 // Let's be carefull (so many wrong headers ...)
1756 // and determine the value representation (VR) :
1757 // Let's skip to the first element (0002,0000) and check there if we find
1758 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1759 // in which case we (almost) know it is explicit VR.
1760 // WARNING: if it happens to be implicit VR then what we will read
1761 // is the length of the group. If this ascii representation of this
1762 // length happens to be "UL" then we shall believe it is explicit VR.
1763 // We need to skip :
1764 // * the 128 bytes of File Preamble (often padded with zeroes),
1765 // * the 4 bytes of "DICM" string,
1766 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1767 // i.e. a total of 136 bytes.
1770 // group 0x0002 *is always* Explicit VR Sometimes ,
1771 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1772 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1774 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1775 memcmp(entCur, "OB", (size_t)2) == 0 ||
1776 memcmp(entCur, "UI", (size_t)2) == 0 ||
1777 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1778 // when Write DCM *adds*
1780 // Use Document::dicom_vr to test all the possibilities
1781 // instead of just checking for UL, OB and UI !? group 0000
1783 Filetype = ExplicitVR;
1784 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1788 Filetype = ImplicitVR;
1789 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1790 << "Looks like a bugged Header!");
1796 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1801 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1804 // Position the file position indicator at first tag
1805 // (i.e. after the file preamble and the "DICM" string).
1807 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1809 Fp->seekg ( 132L, std::ios::beg);
1811 } // ------------------------------- End of DicomV3 ----------------
1813 // Alas, this is not a DicomV3 file and whatever happens there is no file
1814 // preamble. We can reset the file position indicator to where the data
1815 // is (i.e. the beginning of the file).
1817 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1819 Fp->seekg(0, std::ios::beg);
1821 // Let's check 'No Preamble Dicom File' :
1822 // Should start with group 0x0002
1823 // and be Explicit Value Representation
1825 s16 = *((uint16_t *)(deb));
1838 if ( SwapCode != 0 )
1840 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1841 memcmp(entCur, "OB", (size_t)2) == 0 ||
1842 memcmp(entCur, "UI", (size_t)2) == 0 ||
1843 memcmp(entCur, "SH", (size_t)2) == 0 ||
1844 memcmp(entCur, "AE", (size_t)2) == 0 ||
1845 memcmp(entCur, "OB", (size_t)2) == 0 )
1847 Filetype = ExplicitVR;
1848 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1852 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1854 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1855 // By clean we mean that the length of the first group is written down.
1856 // If this is the case and since the length of the first group HAS to be
1857 // four (bytes), then determining the proper swap code is straightforward.
1860 // We assume the array of char we are considering contains the binary
1861 // representation of a 32 bits integer. Hence the following dirty
1863 s32 = *((uint32_t *)(entCur));
1883 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1884 // It is time for despaired wild guesses.
1885 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1886 // i.e. the 'group length' element is not present :
1888 // check the supposed-to-be 'group number'
1889 // in ( 0x0001 .. 0x0008 )
1890 // to determine ' SwapCode' value .
1891 // Only 0 or 4321 will be possible
1892 // (no oportunity to check for the formerly well known
1893 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1894 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1895 // the file IS NOT ACR-NEMA nor DICOM V3
1896 // Find a trick to tell it the caller...
1898 s16 = *((uint16_t *)(deb));
1925 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1933 * \brief Change the Byte Swap code.
1935 void Document::SwitchByteSwapCode()
1937 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1938 << " at: 0x" << std::hex << Fp->tellg() );
1939 if ( SwapCode == 1234 )
1943 else if ( SwapCode == 4321 )
1947 else if ( SwapCode == 3412 )
1951 else if ( SwapCode == 2143 )
1955 gdcmDebugMacro( " Into: "<< SwapCode );
1959 * \brief during parsing, Header Elements too long are not loaded in memory
1960 * @param newSize new size
1962 void Document::SetMaxSizeLoadEntry(long newSize)
1968 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1970 MaxSizeLoadEntry = 0xffffffff;
1973 MaxSizeLoadEntry = newSize;
1977 * \brief Read the next tag WITHOUT loading it's value
1978 * (read the 'Group Number', the 'Element Number',
1979 * gets the Dict Entry
1980 * gets the VR, gets the length, gets the offset value)
1981 * @return On succes : the newly created DocEntry, NULL on failure.
1983 DocEntry *Document::ReadNextDocEntry()
1987 CurrentGroup = ReadInt16();
1988 CurrentElem = ReadInt16();
1990 catch ( FormatError )
1992 // We reached the EOF (or an error occured) therefore
1993 // header parsing has to be considered as finished.
1997 // Sometimes file contains groups of tags with reversed endianess.
1998 HandleBrokenEndian(CurrentGroup, CurrentElem);
2000 // In 'true DICOM' files Group 0002 is always little endian
2001 if ( HasDCMPreamble )
2002 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2004 VRKey vr = FindDocEntryVR();
2008 if ( vr == GDCM_VRUNKNOWN )
2010 if ( CurrentElem == 0x0000 ) // Group Length
2012 realVR = "UL"; // must be UL
2014 else if (CurrentGroup%2 == 1 &&
2015 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2017 // DICOM PS 3-5 7.8.1 a) states that those
2018 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2023 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2026 realVR = dictEntry->GetVR();
2027 dictEntry->Unregister();
2031 // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2034 if ( Global::GetVR()->IsVROfSequence(realVR) )
2035 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2038 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2039 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2042 if ( vr == GDCM_VRUNKNOWN )
2044 if ( Filetype == ExplicitVR )
2046 // We thought this was explicit VR, but we end up with an
2047 // implicit VR tag. Let's backtrack.
2048 if ( newEntry->GetGroup() != 0xfffe )
2051 int offset = Fp->tellg();
2053 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2054 newEntry->GetGroup(), newEntry->GetElement(), offset );
2055 gdcmWarningMacro( msg.c_str() );
2058 newEntry->SetImplicitVR();
2063 FindDocEntryLength(newEntry);
2065 catch ( FormatError )
2072 newEntry->SetOffset(Fp->tellg());
2078 * \brief Handle broken private tag from Philips NTSCAN
2079 * where the endianess is being switched to BigEndian
2080 * for no apparent reason
2083 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2085 // Endian reversion.
2086 // Some files contain groups of tags with reversed endianess.
2087 static int reversedEndian = 0;
2088 // try to fix endian switching in the middle of headers
2089 if ((group == 0xfeff) && (elem == 0x00e0))
2091 // start endian swap mark for group found
2092 gdcmDebugMacro( "Start endian swap mark found." );
2094 SwitchByteSwapCode();
2099 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2101 // end of reversed endian group
2102 gdcmDebugMacro( "End of reversed endian." );
2104 SwitchByteSwapCode();
2106 else if (group == 0xfeff && elem == 0xdde0)
2108 // reversed Sequence Terminator found
2109 // probabely a bug in the header !
2110 // Do what you want, it breaks !
2112 //SwitchByteSwapCode();
2113 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2118 else if (group == 0xfffe && elem == 0xe0dd)
2120 gdcmDebugMacro( "Straight Sequence Terminator." );
2125 * \brief Group 0002 is always coded Little Endian
2126 * whatever Transfer Syntax is
2129 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2131 // Endian reversion.
2132 // Some files contain groups of tags with reversed endianess.
2133 if ( !Group0002Parsed && group != 0x0002)
2135 Group0002Parsed = true;
2136 // we just came out of group 0002
2137 // if Transfer Syntax is Big Endian we have to change CheckSwap
2139 std::string ts = GetTransferSyntax();
2140 if ( ts == GDCM_UNKNOWN )
2142 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2145 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2147 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2152 // Group 0002 is always 'Explicit ...'
2153 // even when Transfer Syntax says 'Implicit ..."
2155 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2156 TS::ImplicitVRLittleEndian )
2158 Filetype = ImplicitVR;
2161 // FIXME Strangely, this works with
2162 //'Implicit VR BigEndian Transfer Syntax (GE Private)
2164 // --> Probabely normal, since we considered we never have
2165 // to trust manufacturers.
2166 // (we find very often 'Implicit VR' tag,
2167 // even when Transfer Syntax tells us it's Explicit ...
2168 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2169 TS::ExplicitVRBigEndian )
2171 gdcmDebugMacro("Transfer Syntax Name = ["
2172 << GetTransferSyntaxName() << "]" );
2173 SwitchByteSwapCode();
2174 group = SwapShort(group);
2175 elem = SwapShort(elem);
2180 //-----------------------------------------------------------------------------
2183 //-----------------------------------------------------------------------------
2184 } // end namespace gdcm