1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2006/05/30 08:10:19 $
7 Version: $Revision: 1.349 $
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
36 #if defined(__BORLANDC__)
37 #include <mem.h> // for memset
42 //-----------------------------------------------------------------------------
44 // Refer to Document::SetMaxSizeLoadEntry()
45 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
49 // Constructors and destructors are protected to avoid user to invoke directly
52 * \brief This default constructor neither loads nor parses the file.
53 * You should then invoke \ref Document::Load.
61 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
64 Filetype = ExplicitVR;
65 // Load will set it to true if sucessfull
66 Group0002Parsed = false;
67 IsDocumentAlreadyLoaded = false;
68 IsDocumentModified = true;
69 LoadMode = LD_ALL; // default : load everything, later
74 * \brief Canonical destructor.
76 Document::~Document ()
81 //-----------------------------------------------------------------------------
84 * \brief Loader. use SetLoadMode(), SetFileName() before !
85 * @return false if file cannot be open or no swap info was found,
86 * or no tag was found.
88 bool Document::Load( )
90 if ( GetFileName() == "" )
92 gdcmWarningMacro( "Use SetFileName, before !" );
95 return DoTheLoadingDocumentJob( );
99 //#ifndef GDCM_LEGACY_REMOVE
101 * \brief Loader. (DEPRECATED : not to break the API)
102 * @param fileName 'Document' (File or DicomDir) to be open for parsing
103 * @return false if file cannot be open or no swap info was found,
104 * or no tag was found.
107 bool Document::Load( std::string const &fileName )
110 return DoTheLoadingDocumentJob( );
116 * \brief Performs the Loading Job (internal use only)
117 * @return false if file cannot be open or no swap info was found,
118 * or no tag was found.
120 bool Document::DoTheLoadingDocumentJob( )
122 if ( ! IsDocumentModified ) // Nothing to do !
130 // warning already performed in OpenFile()
135 Group0002Parsed = false;
137 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
139 // Computes the total length of the file
140 Fp->seekg(0, std::ios::end); // Once per Document !
141 long lgt = Fp->tellg(); // Once per Document !
142 Fp->seekg(0, std::ios::beg); // Once per Document !
144 // CheckSwap returns a boolean
145 // (false if no swap info of any kind was found)
148 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
149 << Filename.c_str());
154 long beg = Fp->tellg(); // just after DICOM preamble (if any)
156 lgt -= beg; // remaining length to parse
159 // Loading is done during parsing
160 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
164 gdcmErrorMacro( "No tag in internal hash table for: "
165 << Filename.c_str());
169 IsDocumentAlreadyLoaded = true;
171 //Fp->seekg(0, std::ios::beg); // Once per Document!
173 // Load 'non string' values
175 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
176 if ( PhotometricInterpretation == "PALETTE COLOR " )
179 // Probabely this line should be outside the 'if'
180 // Try to find an image sample holding a 'gray LUT'
181 LoadEntryBinArea(0x0028,0x1200); // gray LUT
184 /// --> FIXME : The difference between BinEntry and DataEntry
185 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
186 /// --> Old comment restored on purpose.
187 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
188 /// --> had absolutely no meaning.
189 /// --> The whole comment will be removed when the stuff is cleaned !
191 /// The tags refered by the three following lines used to be CORRECTLY
192 /// defined as having an US Value Representation in the public
193 /// dictionary. BUT the semantics implied by the three following
194 /// lines state that the corresponding tag contents are in fact
195 /// the ones of a BinEntry.
196 /// In order to fix things "Quick and Dirty" the dictionary was
197 /// altered on PURPOSE but now contains a WRONG value.
198 /// In order to fix things and restore the dictionary to its
199 /// correct value, one needs to decide of the semantics by deciding
200 /// whether the following tags are either :
201 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
202 /// also used as BinEntry, which requires the proper conversion,
203 /// - OW, and hence loaded as BinEntry, but afterwards also used
204 /// as ValEntry, which requires the proper conversion.
206 // --> OB (byte aray) or OW (short int aray)
207 // The actual VR has to be deduced from other entries.
208 // Our way of loading them may fail in some cases :
209 // We must or not SwapByte depending on other field values.
211 LoadEntryBinArea(0x0028,0x1201); // R LUT
212 LoadEntryBinArea(0x0028,0x1202); // G LUT
213 LoadEntryBinArea(0x0028,0x1203); // B LUT
215 // Segmented Red Palette Color LUT Data
216 LoadEntryBinArea(0x0028,0x1221);
217 // Segmented Green Palette Color LUT Data
218 LoadEntryBinArea(0x0028,0x1222);
219 // Segmented Blue Palette Color LUT Data
220 LoadEntryBinArea(0x0028,0x1223);
223 //FIXME later : how to use it?
224 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
227 SQItem *sqi= modLutSeq->GetFirstSQItem();
230 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
231 if ( dataEntry != 0 )
233 if ( dataEntry->GetLength() != 0 )
235 // FIXME : CTX dependent means : contexted dependant.
236 // see upper comment.
237 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
243 // Force Loading some more elements if user asked to.
246 for (ListElements::iterator it = UserForceLoadList.begin();
247 it != UserForceLoadList.end();
250 gdcmDebugMacro( "Force Load " << std::hex
251 << (*it).Group << "|" <<(*it).Elem );
253 d = GetDocEntry( (*it).Group, (*it).Elem);
257 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
258 << (*it).Group <<"|"<< (*it).Elem
259 << " that doesn't exist" );
263 LoadDocEntry(d, true);
268 // ----------------------------
269 // Specific code to allow gdcm to read ACR-LibIDO formated images
270 // Note: ACR-LibIDO is an extension of the ACR standard that was
271 // used at CREATIS. For the time being (say a couple of years)
272 // we keep this kludge to allow CREATIS users
273 // reading their old images.
275 // if recognition code tells us we deal with a LibIDO image
276 // we switch lineNumber and columnNumber
279 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
280 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
281 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
282 // with "little-endian strings"
284 Filetype = ACR_LIBIDO;
285 std::string rows = GetEntryString(0x0028, 0x0010);
286 std::string columns = GetEntryString(0x0028, 0x0011);
287 SetEntryString(columns, 0x0028, 0x0010);
288 SetEntryString(rows , 0x0028, 0x0011);
290 // --- End of ACR-LibIDO kludge ---
296 * \brief Adds a new element we want to load anyway
297 * @param group Group number of the target tag.
298 * @param elem Element number of the target tag.
300 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
305 UserForceLoadList.push_back(el);
308 * \brief Get the public dictionary used
310 Dict *Document::GetPubDict()
316 * \brief Get the shadow dictionary used
318 Dict *Document::GetShaDict()
324 * \brief Set the shadow dictionary used
325 * @param dict dictionary to use in shadow
327 bool Document::SetShaDict(Dict *dict)
334 * \brief Set the shadow dictionary used
335 * @param dictName name of the dictionary to use in shadow
337 bool Document::SetShaDict(DictKey const &dictName)
339 RefShaDict = Global::GetDicts()->GetDict(dictName);
344 * \brief This predicate tells us whether or not the current Document
345 * was properly parsed and contains at least *one* Dicom Element
346 * (and nothing more, sorry).
347 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
350 bool Document::IsParsable()
352 if ( Filetype == Unknown )
354 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
360 gdcmWarningMacro( "No tag in internal hash table.");
367 * \brief This predicate tells us whether or not the current Document
368 * was properly parsed and contains at least *one* Dicom Element
369 * (and nothing more, sorry).
370 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
373 bool Document::IsReadable()
379 * \brief Predicate for dicom version 3 file.
380 * @return True when the file is a dicom version 3.
382 bool Document::IsDicomV3()
384 // Checking if Transfer Syntax exists is enough
385 // Anyway, it's too late check if the 'Preamble' was found ...
386 // And ... would it be a rich idea to check ?
387 // (some 'no Preamble' DICOM images exist !)
388 return GetDocEntry(0x0002, 0x0010) != NULL;
392 * \brief Predicate for Papyrus file
393 * Dedicated to whomsoever it may concern
394 * @return True when the file is a Papyrus file.
396 bool Document::IsPapyrus()
398 // check for Papyrus private Sequence
399 DocEntry *e = GetDocEntry(0x0041, 0x1050);
402 // check if it's actually a Sequence
403 if ( !dynamic_cast<SeqEntry*>(e) )
409 * \brief returns the File Type
410 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
411 * @return the FileType code
413 FileType Document::GetFileType()
419 * \brief Accessor to the Transfer Syntax (when present) of the
420 * current document (it internally handles reading the
421 * value from disk when only parsing occured).
422 * @return The encountered Transfer Syntax of the current document, if DICOM.
423 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
425 std::string Document::GetTransferSyntax()
427 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
433 // The entry might be present but not loaded (parsing and loading
434 // happen at different stages): try loading and proceed with check...
437 // (parsing and loading happen at the very same stage!)
438 //LoadDocEntrySafe(entry); //JPRx
439 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
441 std::string transfer = dataEntry->GetString();
442 // The actual transfer (as read from disk) might be padded. We
443 // first need to remove the potential padding. We can make the
444 // weak assumption that padding was not executed with digits...
445 if ( transfer.length() == 0 )
447 // for brain damaged headers
448 gdcmWarningMacro( "Transfer Syntax has length = 0.");
451 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
453 transfer.erase(transfer.length()-1, 1);
454 if ( transfer.length() == 0 )
456 // for brain damaged headers
457 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
467 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
468 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
470 std::string Document::GetTransferSyntaxName()
472 // use the TS (TS : Transfer Syntax)
473 std::string transferSyntax = GetEntryString(0x0002,0x0010);
475 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
477 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
478 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
479 return "Uncompressed ACR-NEMA";
481 if ( transferSyntax == GDCM_UNFOUND )
483 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
484 return "Uncompressed ACR-NEMA";
487 // we do it only when we need it
488 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
490 // Global::GetTS() is a global static you shall never try to delete it!
494 // --------------- Swap Code ------------------
496 * \brief Swaps the bytes so they agree with the processor order
497 * @return The properly swaped 16 bits integer.
499 uint16_t Document::SwapShort(uint16_t a)
501 if ( SwapCode == 4321 || SwapCode == 2143 )
503 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
505 a = ( a << 8 ) | ( a >> 8 );
511 * \brief Swaps back the bytes of 4-byte long integer accordingly to
513 * @return The properly swaped 32 bits integer.
515 uint32_t Document::SwapLong(uint32_t a)
522 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
523 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
525 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
526 ((a>>8) & 0x0000ff00) | (a>>24) );
529 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
530 a=( (a<<16) | (a>>16) );
533 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
536 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
543 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
545 * @return The properly swaped 64 bits double.
547 double Document::SwapDouble(double a)
551 // There were no 'double' at ACR-NEMA time.
552 // We just have to deal with 'straight Little Endian' and
553 // 'straight Big Endian'
558 char *beg = (char *)&a;
561 for (unsigned int i = 0; i<7; i++)
572 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
579 // -----------------File I/O ---------------
581 * \brief Tries to open the file \ref Document::Filename and
582 * checks the preamble when existing.
583 * @return The FILE pointer on success.
585 std::ifstream *Document::OpenFile()
587 HasDCMPreamble = false;
588 if (Filename.length() == 0)
595 gdcmDebugMacro( "File already open: " << Filename.c_str());
599 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
602 // Don't user gdcmErrorMacro :
603 // a spurious message will appear when you use, for instance
604 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
605 // to create outputFileName.
607 // FIXME : if the upper comment is still usefull
608 // --> the constructor is not so good ...
610 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
614 //exit(1); // No function is allowed to leave the application instead
615 // of warning the caller
619 Fp->read((char*)&zero, (size_t)2);
626 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
628 // FIXME : We cannot be sure the preable is only zeroes..
629 // (see ACUSON-24-YBR_FULL-RLE.dcm )
631 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
632 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
633 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
634 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
636 std::string msg = Util::Format(
637 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
638 // FIXME : is it a Warning message, or a Debug message?
639 gdcmWarningMacro( msg.c_str() );
644 Fp->seekg(126L, std::ios::cur); // Once per Document
645 char dicm[4]; // = {' ',' ',' ',' '};
646 Fp->read(dicm, (size_t)4);
652 if ( memcmp(dicm, "DICM", 4) == 0 )
654 HasDCMPreamble = true;
658 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
660 // Don't user Warning nor Error, not to pollute the output
661 // while directory recursive parsing ...
662 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
663 << Filename.c_str());
668 * \brief closes the file
669 * @return TRUE if the close was successfull
671 bool Document::CloseFile()
683 * \brief Writes in a file all the Entries (Dicom Elements)
684 * @param fp file pointer on an already open file (actually: Output File Stream)
685 * @param filetype Type of the File to be written
686 * (ACR-NEMA, ExplicitVR, ImplicitVR)
688 void Document::WriteContent(std::ofstream *fp, FileType filetype)
690 // Skip if user wants to write an ACR-NEMA file
692 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
695 // writing Dicom File Preamble
696 char filePreamble[128];
697 memset(filePreamble, 0, 128);
698 fp->write(filePreamble, 128);
699 fp->write("DICM", 4);
702 * \todo rewrite later, if really usefull
703 * - 'Group Length' element is optional in DICOM
704 * - but un-updated odd groups lengthes can causes pb
707 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
708 * UpdateGroupLength(false,filetype);
709 * if ( filetype == ACR)
710 * UpdateGroupLength(true,ACR);
712 * --> Computing group length for groups with embeded Sequences
713 * --> was too much tricky / we were [in a hurry / too lazy]
714 * --> We don't write the element 0x0000 (group length)
717 ElementSet::WriteContent(fp, filetype); // This one is recursive
720 // -----------------------------------------
723 * \brief Loads (from disk) the element content
724 * when a string is not suitable
725 * @param group group number of the Entry
726 * @param elem element number of the Entry
728 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
730 // Search the corresponding DocEntry
731 DocEntry *docEntry = GetDocEntry(group, elem);
734 gdcmDebugMacro(std::hex << group << "|" << elem
735 << " doesn't exist" );
738 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
741 gdcmWarningMacro(std::hex << group << "|" << elem
742 << " is NOT a DataEntry");
745 LoadEntryBinArea(dataEntry);
749 * \brief Loads (from disk) the element content
750 * when a string is not suitable
751 * @param entry Entry whose binArea is going to be loaded
753 void Document::LoadEntryBinArea(DataEntry *entry)
755 if( entry->GetBinArea() )
762 //size_t o =(size_t)entry->GetOffset();
763 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
765 size_t l = entry->GetLength();
766 uint8_t *data = new uint8_t[l];
769 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
770 << std::hex << entry->GetGroup()
771 << "|" << entry->GetElement() );
776 Fp->read((char*)data, l);
777 if ( Fp->fail() || Fp->eof() )
780 entry->SetState(DataEntry::STATE_UNREAD);
784 // Swap the data content if necessary
786 unsigned short vrLgth =
787 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
789 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
790 // if( entry->GetVR() == "OW" )
801 uint16_t *data16 = (uint16_t *)data;
802 for(i=0;i<l/vrLgth;i++)
803 data16[i] = SwapShort(data16[i]);
808 uint32_t *data32 = (uint32_t *)data;
809 for(i=0;i<l/vrLgth;i++)
810 data32[i] = SwapLong(data32[i]);
815 double *data64 = (double *)data;
816 for(i=0;i<l/vrLgth;i++)
817 data64[i] = SwapDouble(data64[i]);
822 entry->SetBinArea(data);
824 if ( openFile ) // The file is left in the state (open/close) it was at entrance
829 * \brief Loads the element while preserving the current
830 * underlying file position indicator as opposed to
831 * LoadDocEntry that modifies it
832 * \note seems to be unused!.
833 * @param entry DocEntry whose value will be loaded.
835 //void Document::LoadDocEntrySafe(DocEntry *entry)
839 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
840 // LoadDocEntry(entry);
841 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
846 * \brief Compares two documents, according to \ref DicomDir rules
847 * \warning Does NOT work with ACR-NEMA files
848 * \todo Find a trick to solve the pb (use RET fields ?)
849 * @param document to compare with current one
850 * @return true if 'smaller'
852 bool Document::operator<(Document &document)
855 std::string s1 = GetEntryString(0x0010,0x0010);
856 std::string s2 = document.GetEntryString(0x0010,0x0010);
868 s1 = GetEntryString(0x0010,0x0020);
869 s2 = document.GetEntryString(0x0010,0x0020);
880 // Study Instance UID
881 s1 = GetEntryString(0x0020,0x000d);
882 s2 = document.GetEntryString(0x0020,0x000d);
893 // Serie Instance UID
894 s1 = GetEntryString(0x0020,0x000e);
895 s2 = document.GetEntryString(0x0020,0x000e);
910 //-----------------------------------------------------------------------------
913 * \brief Reads a supposed to be 16 Bits integer
914 * (swaps it depending on processor endianness)
917 uint16_t Document::ReadInt16()
921 Fp->read ((char*)&g, (size_t)2);
924 throw FormatError( "Document::ReadInt16()", " file error." );
928 throw FormatError( "Document::ReadInt16()", "EOF." );
935 * \brief Reads a supposed to be 32 Bits integer
936 * (swaps it depending on processor endianness)
939 uint32_t Document::ReadInt32()
943 Fp->read ((char*)&g, (size_t)4);
946 throw FormatError( "Document::ReadInt32()", " file error." );
950 throw FormatError( "Document::ReadInt32()", "EOF." );
957 * \brief Re-computes the length of the Dicom group 0002.
959 int Document::ComputeGroup0002Length( )
965 bool found0002 = false;
967 // for each zero-level Tag in the DCM Header
968 DocEntry *entry = GetFirstEntry();
971 gr = entry->GetGroup();
977 if ( entry->GetElement() != 0x0000 )
981 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
982 // (no SQ, OW, UT in group 0x0002;)
985 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
988 groupLength += 2 + 2 + 4 + entry->GetLength();
994 entry = GetNextEntry();
1000 * \brief CallStartMethod
1002 void Document::CallStartMethod()
1006 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1010 * \brief CallProgressMethod
1012 void Document::CallProgressMethod()
1014 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1018 * \brief CallEndMethod
1020 void Document::CallEndMethod()
1023 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1026 //-----------------------------------------------------------------------------
1029 * \brief Loads all the needed Dictionaries
1030 * \warning NOT end user intended method !
1032 void Document::Initialize()
1034 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1040 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1041 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1042 * @param offset start of parsing
1043 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1044 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1046 void Document::ParseDES(DocEntrySet *set, long offset,
1047 long l_max, bool delim_mode)
1049 DocEntry *newDocEntry;
1050 DataEntry *newDataEntry;
1051 SeqEntry *newSeqEntry;
1053 bool used; // will be set to false when something wrong happens to an Entry.
1054 // (Entry will then be deleted)
1055 bool delim_mode_intern = delim_mode;
1057 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1058 << " at offset " << std::hex << "0x(" << offset << ")" );
1062 ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1063 /// Probabely a bug in gdcm code somwhere (some memory erased ?)
1065 // Uncomment to track the bug
1067 if( Debug::GetDebugFlag() )
1068 std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1069 << std::hex << " 0x(" <<(long)(Fp->tellg()) << ")" << std::endl;
1072 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1073 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1074 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1079 newDocEntry = ReadNextDocEntry( );
1086 // Uncoment this cerr line to be able to 'follow' the DocEntries
1087 // when something *very* strange happens
1088 if( Debug::GetDebugFlag() )
1089 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1091 // an Item Starter found elsewhere but in the first position
1092 // of a SeqEntry means previous entry was a Sequence
1093 // but we didn't get it (private Sequence + Implicit VR)
1094 // we have to backtrack.
1095 if ( !first && newDocEntry->IsItemStarter() )
1097 // Debug message within the method !
1098 newDocEntry = Backtrack(newDocEntry);
1102 PreviousDocEntry = newDocEntry;
1106 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1110 //////////////////////////// DataEntry
1112 //vr = newDocEntry->GetVR(); // useless ?
1114 if ( !set->AddEntry( newDataEntry ) )
1116 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1117 << newDataEntry->GetKey()
1118 << " (at offset : 0x("
1119 << newDataEntry->GetOffset() << ") )" );
1124 newDataEntry->Delete();
1125 // Load only if we can add (not a duplicate key)
1126 LoadDocEntry( newDataEntry );
1128 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1130 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1132 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1134 std::string strLgrGroup = newDataEntry->GetString();
1137 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1139 lgrGroup = atoi(strLgrGroup.c_str());
1140 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1141 RemoveEntry( newDocEntry ); // Remove and delete
1148 bool delimitor = newDataEntry->IsItemDelimitor();
1149 bool outOfBounds = false;
1151 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1154 // 'and then', 'or else' don't exist in C++ :-(
1155 // if ( (delimitor) ||
1156 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1158 if ( delimitor || outOfBounds )
1161 newDocEntry->Delete();
1165 // Just to make sure we are at the beginning of next entry.
1166 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1170 /////////////////////// SeqEntry : VR = "SQ"
1172 unsigned long l = newDocEntry->GetReadLength();
1173 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1175 if ( l == 0xffffffff )
1177 delim_mode_intern = true;
1181 delim_mode_intern = false;
1185 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1187 // User asked to skip SeQuences *only* if they belong to Shadow Group
1188 if ( newDocEntry->GetGroup()%2 != 0 )
1190 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1191 newDocEntry->Delete(); // Delete, not in the set
1195 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1197 // User asked to skip *any* SeQuence
1198 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1199 newDocEntry->Delete(); // Delete, not in the set
1202 // delay the dynamic cast as late as possible
1203 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1205 // no other way to create the Delimitor ...
1206 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1208 // At the top of the hierarchy, stands a Document. When "set"
1209 // is a Document, then we are building the first depth level.
1210 // Hence the SeqEntry we are building simply has a depth
1212 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1214 newSeqEntry->SetDepthLevel( 1 );
1216 // But when "set" is already a SQItem, we are building a nested
1217 // sequence, and hence the depth level of the new SeqEntry
1218 // we are building, is one level deeper:
1220 // time waste hunting
1221 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1223 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1227 { // Don't try to parse zero-length sequences
1229 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1230 << " at offset 0x(" << std::hex
1231 << newDocEntry->GetOffset() << ")");
1233 ParseSQ( newSeqEntry,
1234 newDocEntry->GetOffset(),
1235 l, delim_mode_intern);
1237 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1239 if ( !set->AddEntry( newSeqEntry ) )
1241 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1242 << newSeqEntry->GetKey()
1243 << " (at offset : 0x("
1244 << newSeqEntry->GetOffset() << ") )" );
1249 newDocEntry->Delete();
1252 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1254 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1255 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1259 newDocEntry->Delete();
1262 } // end SeqEntry : VR = "SQ"
1266 newDocEntry->Delete();
1270 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1274 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1275 * @return parsed length for this level
1277 void Document::ParseSQ( SeqEntry *seqEntry,
1278 long offset, long l_max, bool delim_mode)
1280 int SQItemNumber = 0;
1282 long offsetStartCurrentSQItem = offset;
1286 // the first time, we read the fff0,e000 of the first SQItem
1287 DocEntry *newDocEntry = ReadNextDocEntry();
1291 gdcmWarningMacro("in ParseSQ : should never get here!");
1296 if ( newDocEntry->IsSequenceDelimitor() )
1298 seqEntry->SetDelimitationItem( newDocEntry );
1299 newDocEntry->Delete();
1303 else // ! delim_mode
1305 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1307 newDocEntry->Delete();
1311 // create the current SQItem
1312 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1313 unsigned int l = newDocEntry->GetReadLength();
1315 if ( l == 0xffffffff )
1324 // fill up the current SQItem, starting at the beginning of fff0,e000
1326 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); // Once per SQItem
1327 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1328 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1330 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1332 newDocEntry->Delete();
1334 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1335 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1343 * \brief When a private Sequence + Implicit VR is encountered
1344 * we cannot guess it's a Sequence till we find the first
1345 * Item Starter. We then backtrack to do the job.
1346 * @param docEntry Item Starter that warned us
1348 DocEntry *Document::Backtrack(DocEntry *docEntry)
1350 // delete the Item Starter, built erroneously out of any Sequence
1351 // it's not yet in the HTable/chained list
1354 // Get all info we can from PreviousDocEntry
1355 uint16_t group = PreviousDocEntry->GetGroup();
1356 uint16_t elem = PreviousDocEntry->GetElement();
1357 uint32_t lgt = PreviousDocEntry->GetLength();
1358 long offset = PreviousDocEntry->GetOffset();
1360 gdcmDebugMacro( "Backtrack :" << std::hex << group
1362 << " at offset 0x(" <<offset << ")" );
1363 RemoveEntry( PreviousDocEntry );
1365 // forge the Seq Entry
1366 DocEntry *newEntry = NewSeqEntry(group, elem);
1367 newEntry->SetLength(lgt);
1368 newEntry->SetOffset(offset);
1370 // Move back to the beginning of the Sequence
1372 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1377 * \brief Loads (or not) the element content depending if its length exceeds
1378 * or not the value specified with Document::SetMaxSizeLoadEntry()
1379 * @param entry Header Entry (Dicom Element) to be dealt with
1380 * @param forceLoad whether you want to force loading of 'long' elements
1382 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1384 uint16_t group = entry->GetGroup();
1385 uint16_t elem = entry->GetElement();
1386 const VRKey &vr = entry->GetVR();
1387 uint32_t length = entry->GetLength();
1389 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1391 // A SeQuence "contains" a set of Elements.
1392 // (fffe e000) tells us an Element is beginning
1393 // (fffe e00d) tells us an Element just ended
1394 // (fffe e0dd) tells us the current SeQuence just ended
1395 // (fffe 0000) is an 'impossible' tag value,
1396 // found in MR-PHILIPS-16-Multi-Seq.dcm
1398 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1400 // NO more value field for SQ !
1404 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1410 // When the length is zero things are easy:
1413 dataEntryPtr->SetBinArea(NULL,true);
1417 // The elements whose length is bigger than the specified upper bound
1422 if (length > MaxSizeLoadEntry)
1424 dataEntryPtr->SetBinArea(NULL,true);
1425 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1427 // to be sure we are at the end of the value ...
1428 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1429 // std::ios::beg); //JPRx
1434 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1435 /// + a ForceLoad call on the +/- 20 'usefull' fields
1436 /// Allow user to tell the fields he wants to ForceLoad
1437 /// during initial stage.
1438 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1439 /// + a method that load *everything* that's not yet loaded
1441 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1445 * \brief Find the value Length of the passed Doc Entry
1446 * @param entry Header Entry whose length of the value shall be loaded.
1448 void Document::FindDocEntryLength( DocEntry *entry )
1449 throw ( FormatError )
1451 const VRKey &vr = entry->GetVR();
1454 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1456 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1459 // The following reserved two bytes (see PS 3.5-2003, section
1460 // "7.1.2 Data element structure with explicit vr", p 27) must be
1461 // skipped before proceeding on reading the length on 4 bytes.
1463 Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1464 uint32_t length32 = ReadInt32();
1466 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1471 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1473 catch ( FormatUnexpected )
1475 // Computing the length failed (this happens with broken
1476 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1477 // chance to get the pixels by deciding the element goes
1478 // until the end of the file. Hence we artificially fix the
1479 // the length and proceed.
1480 gdcmWarningMacro( " Computing the length failed for " <<
1481 entry->GetKey() <<" in " <<GetFileName());
1483 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1484 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1486 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1487 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1489 entry->SetReadLength(lengthUntilEOF);
1490 entry->SetLength(lengthUntilEOF);
1493 entry->SetReadLength(lengthOB);
1494 entry->SetLength(lengthOB);
1497 FixDocEntryFoundLength(entry, length32);
1501 // Length is encoded on 2 bytes.
1502 length16 = ReadInt16();
1504 // 0xffff means that we deal with 'No Length' Sequence
1505 // or 'No Length' SQItem
1506 if ( length16 == 0xffff)
1510 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1515 // Either implicit VR or a non DICOM conformal (see note below) explicit
1516 // VR that ommited the VR of (at least) this element. Farts happen.
1517 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1518 // on Data elements "Implicit and Explicit VR Data Elements shall
1519 // not coexist in a Data Set and Data Sets nested within it".]
1520 // Length is on 4 bytes.
1522 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1523 // even if Transfer Syntax is 'Implicit VR ...'
1524 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1525 // where Group 0x0002 is *also* encoded in Implicit VR !
1527 FixDocEntryFoundLength( entry, ReadInt32() );
1533 * \brief Find the Length till the next sequence delimiter
1534 * \warning NOT end user intended method !
1537 uint32_t Document::FindDocEntryLengthOBOrOW()
1538 throw( FormatUnexpected )
1540 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1541 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1543 bool foundSequenceDelimiter = false;
1544 uint32_t totalLength = 0;
1546 while ( !foundSequenceDelimiter )
1552 group = ReadInt16();
1555 catch ( FormatError )
1557 throw FormatError("Unexpected end of file encountered during ",
1558 "Document::FindDocEntryLengthOBOrOW()");
1560 // We have to decount the group and element we just read
1562 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1565 "Neither an Item tag nor a Sequence delimiter tag on :"
1566 << std::hex << group << " , " << elem
1569 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1570 throw FormatUnexpected(
1571 "Neither an Item tag nor a Sequence delimiter tag.");
1573 if ( elem == 0xe0dd )
1575 foundSequenceDelimiter = true;
1577 uint32_t itemLength = ReadInt32();
1578 // We add 4 bytes since we just read the ItemLength with ReadInt32
1579 totalLength += itemLength + 4;
1580 SkipBytes(itemLength);
1582 if ( foundSequenceDelimiter )
1587 Fp->seekg( positionOnEntry, std::ios::beg); // Only for OB,OW DataElements
1592 * \brief Find the Value Representation of the current Dicom Element.
1593 * @return Value Representation of the current Entry
1595 VRKey Document::FindDocEntryVR()
1597 if ( Filetype != ExplicitVR )
1599 return GDCM_VRUNKNOWN;
1602 // Delimiters (0xfffe), are not explicit VR ...
1603 if ( CurrentGroup == 0xfffe )
1604 return GDCM_VRUNKNOWN;
1606 long positionOnEntry;
1607 if( Debug::GetWarningFlag() )
1608 positionOnEntry = Fp->tellg(); // Only in Warning Mode
1610 // Warning: we believe this is explicit VR (Value Representation) because
1611 // we used a heuristic that found "UL" in the first tag and/or
1612 // 'Transfer Syntax' told us it is.
1613 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1614 // In some cases one finds implicit VR tags mixed within an explicit VR file
1616 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1618 // Hence we make sure the present tag is in explicit VR and try to fix things
1619 // if it happens not to be the case.
1622 Fp->read(&(vr[0]),(size_t)2);
1624 if ( !CheckDocEntryVR(vr) )
1627 // std::cout << "================================================================Unknown VR"
1628 << std::hex << "0x("
1629 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1630 << ")" << "for : " << CurrentGroup
1631 << " at offset : 0x(" << positionOnEntry << ")"
1634 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1635 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1637 << " at offset : 0x(" << positionOnEntry<< ") for group " << CurrentGroup
1640 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1641 Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1642 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1643 return GDCM_VRUNKNOWN;
1649 * \brief Check the correspondance between the VR of the header entry
1650 * and the taken VR. If they are different, the header entry is
1651 * updated with the new VR.
1652 * @param vr Dicom Value Representation
1653 * @return false if the VR is incorrect or if the VR isn't referenced
1654 * otherwise, it returns true
1656 bool Document::CheckDocEntryVR(const VRKey &vr)
1658 return Global::GetVR()->IsValidVR(vr);
1662 * \brief Skip a given Header Entry
1663 * @param entry entry to skip
1665 void Document::SkipDocEntry(DocEntry *entry)
1667 SkipBytes(entry->GetLength());
1671 * \brief Skips to the beginning of the next Header Entry
1672 * @param currentDocEntry entry to skip
1674 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1676 long l = currentDocEntry->GetReadLength();
1677 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1678 // ... but PMS imagers happen !
1680 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1681 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1683 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1688 * \brief When the length of an element value is obviously wrong (because
1689 * the parser went Jabberwocky) one can hope improving things by
1690 * applying some heuristics.
1691 * @param entry entry to check
1692 * @param foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)
1694 void Document::FixDocEntryFoundLength(DocEntry *entry,
1695 uint32_t foundLength)
1697 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1699 if ( foundLength == 0xffffffff)
1702 //entry->SetLength(foundLength);
1703 entry->SetLength(0);
1704 return; // return ASAP; don't waist time on useless tests
1707 uint16_t gr = entry->GetGroup();
1708 uint16_t elem = entry->GetElement();
1710 if ( foundLength % 2)
1712 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1713 << " in x(" << std::hex << gr << "," << elem <<")");
1716 //////// Fix for some naughty General Electric images.
1717 // Allthough not recent many such GE corrupted images are still present
1718 // on Creatis hard disks. Hence this fix shall remain when such images
1719 // are no longer in use (we are talking a few years, here)...
1720 // Note: XMedCon probably uses such a trick since it is able to read
1721 // those pesky GE images ...
1722 if ( foundLength == 13)
1724 // Only happens for this length !
1725 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1728 entry->SetReadLength(10); // a bug is to be fixed !?
1732 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1733 // Occurence of such images is quite low (unless one leaves close to a
1734 // 'Leonardo' source. Hence, one might consider commenting out the
1735 // following fix on efficiency reasons.
1736 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1738 // Ideally we should check we are in Explicit and double check
1739 // that VR=UL... this is done properly in gdcm2
1740 if( foundLength == 6 )
1742 gdcmWarningMacro( "Replacing Length from 6 into 4" );
1744 entry->SetReadLength(4); // a bug is to be fixed !
1746 else if ( foundLength%4 )
1748 gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1749 "The length of this tag seems to be wrong" );
1753 else if ( entry->GetVR() == "SQ" )
1755 foundLength = 0; // ReadLength is unchanged
1758 //////// We encountered a 'delimiter' element i.e. a tag of the form
1759 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1760 // taken into account.
1761 else if ( gr == 0xfffe )
1763 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1764 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1765 // causes extra troubles...
1766 if ( elem != 0x0000 )
1772 foundLength=12; // to skip the mess that follows this bugged Tag !
1775 entry->SetLength(foundLength);
1779 * \brief Apply some heuristics to predict whether the considered
1780 * element value contains/represents an integer or not.
1781 * @param entry The element value on which to apply the predicate.
1782 * @return The result of the heuristical predicate.
1784 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1786 uint16_t elem = entry->GetElement();
1787 uint16_t group = entry->GetGroup();
1788 const VRKey &vr = entry->GetVR();
1789 uint32_t length = entry->GetLength();
1791 // When we have some semantics on the element we just read, and if we
1792 // a priori know we are dealing with an integer, then we shall be
1793 // able to swap it's element value properly.
1794 if ( elem == 0 ) // This is the group length of the group
1802 // Although this should never happen, still some images have a
1803 // corrupted group length [e.g. have a glance at offset x(8336) of
1804 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1805 // Since for dicom compliant and well behaved headers, the present
1806 // test is useless (and might even look a bit paranoid), when we
1807 // encounter such an ill-formed image, we simply display a warning
1808 // message and proceed on parsing (while crossing fingers).
1809 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1811 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1812 << std::hex << group << " , " << elem
1813 << ") -before- position x(" << filePosition << ")"
1814 << "lgt : " << length );
1818 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1826 * \brief Discover what the swap code is (among little endian, big endian,
1827 * bad little endian, bad big endian).
1829 * @return false when we are absolutely sure
1830 * it's neither ACR-NEMA nor DICOM
1831 * true when we hope ours assuptions are OK
1833 bool Document::CheckSwap()
1840 // First, compare HostByteOrder and NetworkByteOrder in order to
1841 // determine if we shall need to swap bytes (i.e. the Endian type).
1842 bool net2host = Util::IsCurrentProcessorBigEndian();
1844 // The easiest case is the one of a 'true' DICOM header, we just have
1845 // to look for the string "DICM" inside the file preamble.
1848 char *entCur = deb + 128;
1849 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1851 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1853 // Group 0002 should always be VR, and the first element 0000
1854 // Let's be carefull (so many wrong headers ...)
1855 // and determine the value representation (VR) :
1856 // Let's skip to the first element (0002,0000) and check there if we find
1857 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1858 // in which case we (almost) know it is explicit VR.
1859 // WARNING: if it happens to be implicit VR then what we will read
1860 // is the length of the group. If this ascii representation of this
1861 // length happens to be "UL" then we shall believe it is explicit VR.
1862 // We need to skip :
1863 // * the 128 bytes of File Preamble (often padded with zeroes),
1864 // * the 4 bytes of "DICM" string,
1865 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1866 // i.e. a total of 136 bytes.
1869 // group 0x0002 *is always* Explicit VR Sometimes ,
1870 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1871 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1873 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1874 memcmp(entCur, "OB", (size_t)2) == 0 ||
1875 memcmp(entCur, "UI", (size_t)2) == 0 ||
1876 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1877 // when Write DCM *adds*
1879 // Use Document::dicom_vr to test all the possibilities
1880 // instead of just checking for UL, OB and UI !? group 0000
1882 Filetype = ExplicitVR;
1883 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1887 Filetype = ImplicitVR;
1888 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1889 << "Looks like a bugged Header!");
1895 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1900 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1903 // Position the file position indicator at first tag
1904 // (i.e. after the file preamble and the "DICM" string).
1906 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1908 } // ------------------------------- End of DicomV3 ----------------
1910 // Alas, this is not a DicomV3 file and whatever happens there is no file
1911 // preamble. We can reset the file position indicator to where the data
1912 // is (i.e. the beginning of the file).
1914 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1916 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1918 // Let's check 'No Preamble Dicom File' :
1919 // Should start with group 0x0002
1920 // and be Explicit Value Representation
1922 s16 = *((uint16_t *)(deb));
1935 if ( SwapCode != 0 )
1937 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1938 memcmp(entCur, "OB", (size_t)2) == 0 ||
1939 memcmp(entCur, "UI", (size_t)2) == 0 ||
1940 memcmp(entCur, "SH", (size_t)2) == 0 ||
1941 memcmp(entCur, "AE", (size_t)2) == 0 ||
1942 memcmp(entCur, "OB", (size_t)2) == 0 )
1944 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
1945 // Wait untill reading Transfer Syntax
1946 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1950 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1952 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1953 // By clean we mean that the length of the first group is written down.
1954 // If this is the case and since the length of the first group HAS to be
1955 // four (bytes), then determining the proper swap code is straightforward.
1958 // We assume the array of char we are considering contains the binary
1959 // representation of a 32 bits integer. Hence the following dirty
1961 s32 = *((uint32_t *)(entCur));
1981 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1982 // It is time for despaired wild guesses.
1983 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1984 // i.e. the 'group length' element is not present :
1986 // check the supposed-to-be 'group number'
1987 // in ( 0x0001 .. 0x0008 )
1988 // to determine ' SwapCode' value .
1989 // Only 0 or 4321 will be possible
1990 // (no oportunity to check for the formerly well known
1991 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1992 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1993 // the file IS NOT ACR-NEMA nor DICOM V3
1994 // Find a trick to tell it the caller...
1996 s16 = *((uint16_t *)(deb));
2023 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2031 * \brief Change the Byte Swap code.
2033 void Document::SwitchByteSwapCode()
2035 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2036 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2037 if ( SwapCode == 1234 )
2041 else if ( SwapCode == 4321 )
2045 else if ( SwapCode == 3412 )
2049 else if ( SwapCode == 2143 )
2053 gdcmDebugMacro( " Into: "<< SwapCode );
2057 * \brief during parsing, Header Elements too long are not loaded in memory
2058 * @param newSize new size
2060 void Document::SetMaxSizeLoadEntry(long newSize)
2066 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2068 MaxSizeLoadEntry = 0xffffffff;
2071 MaxSizeLoadEntry = newSize;
2075 * \brief Read the next tag WITHOUT loading it's value
2076 * (read the 'Group Number', the 'Element Number',
2077 * gets the Dict Entry
2078 * gets the VR, gets the length, gets the offset value)
2079 * @return On succes : the newly created DocEntry, NULL on failure.
2081 DocEntry *Document::ReadNextDocEntry()
2085 CurrentGroup = ReadInt16();
2086 CurrentElem = ReadInt16();
2088 catch ( FormatError )
2090 // We reached the EOF (or an error occured) therefore
2091 // header parsing has to be considered as finished.
2095 // In 'true DICOM' files Group 0002 is always little endian
2096 if ( HasDCMPreamble )
2098 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2099 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2101 // Sometimes file contains groups of tags with reversed endianess.
2102 HandleBrokenEndian(CurrentGroup, CurrentElem);
2105 VRKey vr = FindDocEntryVR();
2108 if ( vr == GDCM_VRUNKNOWN )
2110 if ( CurrentElem == 0x0000 ) // Group Length
2112 realVR = "UL"; // must be UL
2114 else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2119 // Commented out in order not to generate 'Shadow Groups' where some
2120 // Data Elements are Explicit VR and some other ones Implicit VR
2121 // (Stupid MatLab DICOM Reader couldn't read gdcm-written images)
2123 else if (CurrentGroup%2 == 1 &&
2124 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2126 // DICOM PS 3-5 7.8.1 a) states that those
2127 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2133 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2136 realVR = dictEntry->GetVR();
2137 dictEntry->Unregister(); // GetDictEntry registered it
2143 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2146 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2150 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2151 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2154 if ( vr == GDCM_VRUNKNOWN )
2156 if ( Filetype == ExplicitVR )
2158 // We thought this was explicit VR, but we end up with an
2159 // implicit VR tag. Let's backtrack.
2161 //if ( newEntry->GetGroup() != 0xfffe )
2162 if (CurrentGroup != 0xfffe )
2164 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2166 gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2167 << offset << ") should be Explicit VR");
2170 newEntry->SetImplicitVR();
2175 FindDocEntryLength(newEntry);
2177 catch ( FormatError )
2184 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2190 * \brief Handle broken private tag from Philips NTSCAN
2191 * where the endianess is being switched to BigEndian
2192 * for no apparent reason
2195 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2197 // Endian reversion.
2198 // Some files contain groups of tags with reversed endianess.
2199 static int reversedEndian = 0;
2200 // try to fix endian switching in the middle of headers
2201 if ((group == 0xfeff) && (elem == 0x00e0))
2203 // start endian swap mark for group found
2204 gdcmDebugMacro( "Start endian swap mark found." );
2206 SwitchByteSwapCode();
2211 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2213 // end of reversed endian group
2214 gdcmDebugMacro( "End of reversed endian." );
2216 SwitchByteSwapCode();
2218 else if (group == 0xfeff && elem == 0xdde0)
2220 // reversed Sequence Terminator found
2221 // probabely a bug in the header !
2222 // Do what you want, it breaks !
2224 //SwitchByteSwapCode();
2225 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2230 else if (group == 0xfffe && elem == 0xe0dd)
2232 gdcmDebugMacro( "Straight Sequence Terminator." );
2237 * \brief Group 0002 is always coded Little Endian
2238 * whatever Transfer Syntax is
2241 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2243 // Endian reversion.
2244 // Some files contain groups of tags with reversed endianess.
2246 Group0002Parsed = true;
2247 // we just came out of group 0002
2248 // if Transfer Syntax is Big Endian we have to change CheckSwap
2250 std::string ts = GetTransferSyntax();
2251 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2253 // Group 0002 is always 'Explicit ...'
2254 // even when Transfer Syntax says 'Implicit ..."
2256 if ( s == TS::ImplicitVRLittleEndian
2258 s == TS::ImplicitVRBigEndianPrivateGE
2261 Filetype = ImplicitVR;
2264 // FIXME Strangely, this works with
2265 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2267 // --> Probabely normal, since we considered we never have
2268 // to trust manufacturers.
2269 // (we find very often 'Implicit VR' tag,
2270 // even when Transfer Syntax tells us it's Explicit ...
2272 if ( s == TS::ExplicitVRBigEndian )
2274 gdcmDebugMacro("Transfer Syntax Name = ["
2275 << GetTransferSyntaxName() << "]" );
2276 SwitchByteSwapCode();
2277 group = SwapShort(group);
2278 elem = SwapShort(elem);
2281 /// \todo find a trick to warn user and stop processing
2283 if ( s == TS::DeflatedExplicitVRLittleEndian)
2285 gdcmWarningMacro("Transfer Syntax ["
2286 << GetTransferSyntaxName() << "] :"
2287 << " not yet dealt with ");
2291 // The following shouldn't occur very often
2292 // Let's check at the very end.
2294 if ( ts == GDCM_UNKNOWN )
2296 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2300 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2302 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2308 //-----------------------------------------------------------------------------
2311 //-----------------------------------------------------------------------------
2312 } // end namespace gdcm