1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2006/02/16 20:06:14 $
7 Version: $Revision: 1.342 $
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( );
98 #ifndef GDCM_LEGACY_REMOVE
100 * \brief Loader. (DEPRECATED : not to break the API)
101 * @param fileName 'Document' (File or DicomDir) to be open for parsing
102 * @return false if file cannot be open or no swap info was found,
103 * or no tag was found.
105 bool Document::Load( std::string const &fileName )
108 return DoTheLoadingDocumentJob( );
113 * \brief Performs the Loading Job (internal use only)
114 * @return false if file cannot be open or no swap info was found,
115 * or no tag was found.
117 bool Document::DoTheLoadingDocumentJob( )
119 if ( ! IsDocumentModified ) // Nothing to do !
127 // warning already performed in OpenFile()
132 Group0002Parsed = false;
134 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
136 // Computes the total length of the file
137 Fp->seekg(0, std::ios::end); // Once per Document !
138 long lgt = Fp->tellg(); // Once per Document !
139 Fp->seekg(0, std::ios::beg); // Once per Document !
141 // CheckSwap returns a boolean
142 // (false if no swap info of any kind was found)
145 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
146 << Filename.c_str());
151 long beg = Fp->tellg(); // just after DICOM preamble (if any)
153 lgt -= beg; // remaining length to parse
156 // Loading is done during parsing
157 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
161 gdcmErrorMacro( "No tag in internal hash table for: "
162 << Filename.c_str());
166 IsDocumentAlreadyLoaded = true;
168 //Fp->seekg(0, std::ios::beg); // Once per Document!
170 // Load 'non string' values
172 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
173 if ( PhotometricInterpretation == "PALETTE COLOR " )
176 // Probabely this line should be outside the 'if'
177 // Try to find an image sample holding a 'gray LUT'
178 LoadEntryBinArea(0x0028,0x1200); // gray LUT
181 /// --> FIXME : The difference between BinEntry and DataEntry
182 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
183 /// --> Old comment restored on purpose.
184 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
185 /// --> had absolutely no meaning.
186 /// --> The whole comment will be removed when the stuff is cleaned !
188 /// The tags refered by the three following lines used to be CORRECTLY
189 /// defined as having an US Value Representation in the public
190 /// dictionary. BUT the semantics implied by the three following
191 /// lines state that the corresponding tag contents are in fact
192 /// the ones of a BinEntry.
193 /// In order to fix things "Quick and Dirty" the dictionary was
194 /// altered on PURPOSE but now contains a WRONG value.
195 /// In order to fix things and restore the dictionary to its
196 /// correct value, one needs to decide of the semantics by deciding
197 /// whether the following tags are either :
198 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
199 /// also used as BinEntry, which requires the proper conversion,
200 /// - OW, and hence loaded as BinEntry, but afterwards also used
201 /// as ValEntry, which requires the proper conversion.
203 // --> OB (byte aray) or OW (short int aray)
204 // The actual VR has to be deduced from other entries.
205 // Our way of loading them may fail in some cases :
206 // We must or not SwapByte depending on other field values.
208 LoadEntryBinArea(0x0028,0x1201); // R LUT
209 LoadEntryBinArea(0x0028,0x1202); // G LUT
210 LoadEntryBinArea(0x0028,0x1203); // B LUT
212 // Segmented Red Palette Color LUT Data
213 LoadEntryBinArea(0x0028,0x1221);
214 // Segmented Green Palette Color LUT Data
215 LoadEntryBinArea(0x0028,0x1222);
216 // Segmented Blue Palette Color LUT Data
217 LoadEntryBinArea(0x0028,0x1223);
220 //FIXME later : how to use it?
221 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
224 SQItem *sqi= modLutSeq->GetFirstSQItem();
227 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
228 if ( dataEntry != 0 )
230 if ( dataEntry->GetLength() != 0 )
232 // FIXME : CTX dependent means : contexted dependant.
233 // see upper comment.
234 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
240 // Force Loading some more elements if user asked to.
243 for (ListElements::iterator it = UserForceLoadList.begin();
244 it != UserForceLoadList.end();
247 gdcmDebugMacro( "Force Load " << std::hex
248 << (*it).Group << "|" <<(*it).Elem );
250 d = GetDocEntry( (*it).Group, (*it).Elem);
254 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
255 << (*it).Group <<"|"<< (*it).Elem
256 << " that doesn't exist" );
260 LoadDocEntry(d, true);
265 // ----------------------------
266 // Specific code to allow gdcm to read ACR-LibIDO formated images
267 // Note: ACR-LibIDO is an extension of the ACR standard that was
268 // used at CREATIS. For the time being (say a couple of years)
269 // we keep this kludge to allow CREATIS users
270 // reading their old images.
272 // if recognition code tells us we deal with a LibIDO image
273 // we switch lineNumber and columnNumber
276 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
277 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
278 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
279 // with "little-endian strings"
281 Filetype = ACR_LIBIDO;
282 std::string rows = GetEntryString(0x0028, 0x0010);
283 std::string columns = GetEntryString(0x0028, 0x0011);
284 SetEntryString(columns, 0x0028, 0x0010);
285 SetEntryString(rows , 0x0028, 0x0011);
287 // --- End of ACR-LibIDO kludge ---
293 * \brief Adds a new element we want to load anyway
294 * @param group Group number of the target tag.
295 * @param elem Element number of the target tag.
297 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
302 UserForceLoadList.push_back(el);
305 * \brief Get the public dictionary used
307 Dict *Document::GetPubDict()
313 * \brief Get the shadow dictionary used
315 Dict *Document::GetShaDict()
321 * \brief Set the shadow dictionary used
322 * @param dict dictionary to use in shadow
324 bool Document::SetShaDict(Dict *dict)
331 * \brief Set the shadow dictionary used
332 * @param dictName name of the dictionary to use in shadow
334 bool Document::SetShaDict(DictKey const &dictName)
336 RefShaDict = Global::GetDicts()->GetDict(dictName);
341 * \brief This predicate tells us whether or not the current Document
342 * was properly parsed and contains at least *one* Dicom Element
343 * (and nothing more, sorry).
344 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
347 bool Document::IsParsable()
349 if ( Filetype == Unknown )
351 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
357 gdcmWarningMacro( "No tag in internal hash table.");
364 * \brief This predicate tells us whether or not the current Document
365 * was properly parsed and contains at least *one* Dicom Element
366 * (and nothing more, sorry).
367 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
370 bool Document::IsReadable()
376 * \brief Predicate for dicom version 3 file.
377 * @return True when the file is a dicom version 3.
379 bool Document::IsDicomV3()
381 // Checking if Transfer Syntax exists is enough
382 // Anyway, it's too late check if the 'Preamble' was found ...
383 // And ... would it be a rich idea to check ?
384 // (some 'no Preamble' DICOM images exist !)
385 return GetDocEntry(0x0002, 0x0010) != NULL;
389 * \brief Predicate for Papyrus file
390 * Dedicated to whomsoever it may concern
391 * @return True when the file is a Papyrus file.
393 bool Document::IsPapyrus()
395 // check for Papyrus private Sequence
396 DocEntry *e = GetDocEntry(0x0041, 0x1050);
399 // check if it's actually a Sequence
400 if ( !dynamic_cast<SeqEntry*>(e) )
406 * \brief returns the File Type
407 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
408 * @return the FileType code
410 FileType Document::GetFileType()
416 * \brief Accessor to the Transfer Syntax (when present) of the
417 * current document (it internally handles reading the
418 * value from disk when only parsing occured).
419 * @return The encountered Transfer Syntax of the current document, if DICOM.
420 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
422 std::string Document::GetTransferSyntax()
424 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
430 // The entry might be present but not loaded (parsing and loading
431 // happen at different stages): try loading and proceed with check...
434 // (parsing and loading happen at the very same stage!)
435 //LoadDocEntrySafe(entry); //JPRx
436 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
438 std::string transfer = dataEntry->GetString();
439 // The actual transfer (as read from disk) might be padded. We
440 // first need to remove the potential padding. We can make the
441 // weak assumption that padding was not executed with digits...
442 if ( transfer.length() == 0 )
444 // for brain damaged headers
445 gdcmWarningMacro( "Transfer Syntax has length = 0.");
448 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
450 transfer.erase(transfer.length()-1, 1);
451 if ( transfer.length() == 0 )
453 // for brain damaged headers
454 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
464 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
465 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
467 std::string Document::GetTransferSyntaxName()
469 // use the TS (TS : Transfer Syntax)
470 std::string transferSyntax = GetEntryString(0x0002,0x0010);
472 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
474 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
475 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
476 return "Uncompressed ACR-NEMA";
478 if ( transferSyntax == GDCM_UNFOUND )
480 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
481 return "Uncompressed ACR-NEMA";
484 // we do it only when we need it
485 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
487 // Global::GetTS() is a global static you shall never try to delete it!
491 // --------------- Swap Code ------------------
493 * \brief Swaps the bytes so they agree with the processor order
494 * @return The properly swaped 16 bits integer.
496 uint16_t Document::SwapShort(uint16_t a)
498 if ( SwapCode == 4321 || SwapCode == 2143 )
500 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
502 a = ( a << 8 ) | ( a >> 8 );
508 * \brief Swaps back the bytes of 4-byte long integer accordingly to
510 * @return The properly swaped 32 bits integer.
512 uint32_t Document::SwapLong(uint32_t a)
519 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
520 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
522 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
523 ((a>>8) & 0x0000ff00) | (a>>24) );
526 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
527 a=( (a<<16) | (a>>16) );
530 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
533 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
540 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
542 * @return The properly swaped 64 bits double.
544 double Document::SwapDouble(double a)
548 // There were no 'double' at ACR-NEMA time.
549 // We just have to deal with 'straight Little Endian' and
550 // 'straight Big Endian'
555 char *beg = (char *)&a;
558 for (unsigned int i = 0; i<7; i++)
569 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
576 // -----------------File I/O ---------------
578 * \brief Tries to open the file \ref Document::Filename and
579 * checks the preamble when existing.
580 * @return The FILE pointer on success.
582 std::ifstream *Document::OpenFile()
584 HasDCMPreamble = false;
585 if (Filename.length() == 0)
592 gdcmDebugMacro( "File already open: " << Filename.c_str());
596 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
599 // Don't user gdcmErrorMacro :
600 // a spurious message will appear when you use, for instance
601 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
602 // to create outputFileName.
604 // FIXME : if the upper comment is still usefull
605 // --> the constructor is not so good ...
607 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
611 //exit(1); // No function is allowed to leave the application instead
612 // of warning the caller
616 Fp->read((char*)&zero, (size_t)2);
623 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
625 // FIXME : We cannot be sure the preable is only zeroes..
626 // (see ACUSON-24-YBR_FULL-RLE.dcm )
628 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
629 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
630 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
631 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
633 std::string msg = Util::Format(
634 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
635 // FIXME : is it a Warning message, or a Debug message?
636 gdcmWarningMacro( msg.c_str() );
641 Fp->seekg(126L, std::ios::cur); // Once per Document
642 char dicm[4]; // = {' ',' ',' ',' '};
643 Fp->read(dicm, (size_t)4);
649 if ( memcmp(dicm, "DICM", 4) == 0 )
651 HasDCMPreamble = true;
655 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
657 // Don't user Warning nor Error, not to pollute the output
658 // while directory recursive parsing ...
659 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
660 << Filename.c_str());
665 * \brief closes the file
666 * @return TRUE if the close was successfull
668 bool Document::CloseFile()
680 * \brief Writes in a file all the Entries (Dicom Elements)
681 * @param fp file pointer on an already open file (actually: Output File Stream)
682 * @param filetype Type of the File to be written
683 * (ACR-NEMA, ExplicitVR, ImplicitVR)
685 void Document::WriteContent(std::ofstream *fp, FileType filetype)
687 // Skip if user wants to write an ACR-NEMA file
689 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
692 // writing Dicom File Preamble
693 char filePreamble[128];
694 memset(filePreamble, 0, 128);
695 fp->write(filePreamble, 128);
696 fp->write("DICM", 4);
700 * \todo rewrite later, if really usefull
701 * - 'Group Length' element is optional in DICOM
702 * - but un-updated odd groups lengthes can causes pb
705 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
706 * UpdateGroupLength(false,filetype);
707 * if ( filetype == ACR)
708 * UpdateGroupLength(true,ACR);
710 * --> Computing group length for groups with embeded Sequences
711 * --> was too much tricky / we were [in a hurry / too lazy]
712 * --> We don't write the element 0x0000 (group length)
715 ElementSet::WriteContent(fp, filetype); // This one is recursive
718 // -----------------------------------------
721 * \brief Loads (from disk) the element content
722 * when a string is not suitable
723 * @param group group number of the Entry
724 * @param elem element number of the Entry
726 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
728 // Search the corresponding DocEntry
729 DocEntry *docEntry = GetDocEntry(group, elem);
732 gdcmDebugMacro(std::hex << group << "|" << elem
733 << " doesn't exist" );
736 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
739 gdcmWarningMacro(std::hex << group << "|" << elem
740 << " is NOT a DataEntry");
743 LoadEntryBinArea(dataEntry);
747 * \brief Loads (from disk) the element content
748 * when a string is not suitable
749 * @param entry Entry whose binArea is going to be loaded
751 void Document::LoadEntryBinArea(DataEntry *entry)
753 if( entry->GetBinArea() )
760 //size_t o =(size_t)entry->GetOffset();
761 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
763 size_t l = entry->GetLength();
764 uint8_t *data = new uint8_t[l];
767 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
768 << std::hex << entry->GetGroup()
769 << "|" << entry->GetElement() );
774 Fp->read((char*)data, l);
775 if ( Fp->fail() || Fp->eof() )
778 entry->SetState(DataEntry::STATE_UNREAD);
782 // Swap the data content if necessary
784 unsigned short vrLgth =
785 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
787 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
788 // if( entry->GetVR() == "OW" )
799 uint16_t *data16 = (uint16_t *)data;
800 for(i=0;i<l/vrLgth;i++)
801 data16[i] = SwapShort(data16[i]);
806 uint32_t *data32 = (uint32_t *)data;
807 for(i=0;i<l/vrLgth;i++)
808 data32[i] = SwapLong(data32[i]);
813 double *data64 = (double *)data;
814 for(i=0;i<l/vrLgth;i++)
815 data64[i] = SwapDouble(data64[i]);
820 entry->SetBinArea(data);
822 if ( openFile ) // The file is left in the state (open/close) it was at entrance
827 * \brief Loads the element while preserving the current
828 * underlying file position indicator as opposed to
829 * LoadDocEntry that modifies it
830 * \note seems to be unused!.
831 * @param entry DocEntry whose value will be loaded.
833 //void Document::LoadDocEntrySafe(DocEntry *entry)
837 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
838 // LoadDocEntry(entry);
839 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
844 * \brief Compares two documents, according to \ref DicomDir rules
845 * \warning Does NOT work with ACR-NEMA files
846 * \todo Find a trick to solve the pb (use RET fields ?)
847 * @param document to compare with current one
848 * @return true if 'smaller'
850 bool Document::operator<(Document &document)
853 std::string s1 = GetEntryString(0x0010,0x0010);
854 std::string s2 = document.GetEntryString(0x0010,0x0010);
866 s1 = GetEntryString(0x0010,0x0020);
867 s2 = document.GetEntryString(0x0010,0x0020);
878 // Study Instance UID
879 s1 = GetEntryString(0x0020,0x000d);
880 s2 = document.GetEntryString(0x0020,0x000d);
891 // Serie Instance UID
892 s1 = GetEntryString(0x0020,0x000e);
893 s2 = document.GetEntryString(0x0020,0x000e);
908 //-----------------------------------------------------------------------------
911 * \brief Reads a supposed to be 16 Bits integer
912 * (swaps it depending on processor endianness)
915 uint16_t Document::ReadInt16()
919 Fp->read ((char*)&g, (size_t)2);
922 throw FormatError( "Document::ReadInt16()", " file error." );
926 throw FormatError( "Document::ReadInt16()", "EOF." );
933 * \brief Reads a supposed to be 32 Bits integer
934 * (swaps it depending on processor endianness)
937 uint32_t Document::ReadInt32()
941 Fp->read ((char*)&g, (size_t)4);
944 throw FormatError( "Document::ReadInt32()", " file error." );
948 throw FormatError( "Document::ReadInt32()", "EOF." );
955 * \brief Re-computes the length of the Dicom group 0002.
957 int Document::ComputeGroup0002Length( )
963 bool found0002 = false;
965 // for each zero-level Tag in the DCM Header
966 DocEntry *entry = GetFirstEntry();
969 gr = entry->GetGroup();
975 if ( entry->GetElement() != 0x0000 )
979 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
980 // (no SQ, OW, UT in group 0x0002;)
983 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
986 groupLength += 2 + 2 + 4 + entry->GetLength();
992 entry = GetNextEntry();
998 * \brief CallStartMethod
1000 void Document::CallStartMethod()
1004 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1008 * \brief CallProgressMethod
1010 void Document::CallProgressMethod()
1012 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1016 * \brief CallEndMethod
1018 void Document::CallEndMethod()
1021 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1024 //-----------------------------------------------------------------------------
1027 * \brief Loads all the needed Dictionaries
1028 * \warning NOT end user intended method !
1030 void Document::Initialize()
1032 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1038 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1039 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1040 * @param offset start of parsing
1041 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1042 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1044 void Document::ParseDES(DocEntrySet *set, long offset,
1045 long l_max, bool delim_mode)
1047 DocEntry *newDocEntry;
1048 DataEntry *newDataEntry;
1049 SeqEntry *newSeqEntry;
1051 bool used; // will be set to false when something wrong happens to an Entry.
1052 // (Entry will then be deleted)
1053 bool delim_mode_intern = delim_mode;
1055 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1056 << " at offset " << std::hex << "0x(" << offset << ")" );
1059 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1061 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1062 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1066 newDocEntry = ReadNextDocEntry( );
1068 // Uncoment this cerr line to be able to 'follow' the DocEntries
1069 // when something *very* strange happens
1070 if( Debug::GetDebugFlag() )
1071 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1078 // an Item Starter found elsewhere but the first position
1079 // of a SeqEntry means previous entry was a Sequence
1080 // but we didn't get it (private Sequence + Implicit VR)
1081 // we have to backtrack.
1082 if ( !first && newDocEntry->IsItemStarter() )
1084 // Debug message within the method !
1085 newDocEntry = Backtrack(newDocEntry);
1089 PreviousDocEntry = newDocEntry;
1093 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1097 //////////////////////////// DataEntry
1099 vr = newDocEntry->GetVR();
1101 if ( !set->AddEntry( newDataEntry ) )
1103 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1104 << newDataEntry->GetKey()
1105 << " (at offset : 0x("
1106 << newDataEntry->GetOffset() << ") )" );
1111 newDataEntry->Delete();
1112 // Load only if we can add (not a duplicate key)
1113 LoadDocEntry( newDataEntry );
1115 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1117 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1119 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1121 std::string strLgrGroup = newDataEntry->GetString();
1124 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1126 lgrGroup = atoi(strLgrGroup.c_str());
1127 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1128 RemoveEntry( newDocEntry ); // Remove and delete
1135 bool delimitor = newDataEntry->IsItemDelimitor();
1136 bool outOfBounds = false;
1138 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1141 // 'and then', 'or else' don't exist in C++ :-(
1142 // if ( (delimitor) ||
1143 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1145 if ( delimitor || outOfBounds )
1148 newDocEntry->Delete();
1152 // Just to make sure we are at the beginning of next entry.
1153 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1157 /////////////////////// SeqEntry : VR = "SQ"
1159 unsigned long l = newDocEntry->GetReadLength();
1160 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1162 if ( l == 0xffffffff )
1164 delim_mode_intern = true;
1168 delim_mode_intern = false;
1172 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1174 // User asked to skip SeQuences *only* if they belong to Shadow Group
1175 if ( newDocEntry->GetGroup()%2 != 0 )
1177 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1178 newDocEntry->Delete(); // Delete, not in the set
1182 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1184 // User asked to skip *any* SeQuence
1185 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1186 newDocEntry->Delete(); // Delete, not in the set
1189 // delay the dynamic cast as late as possible
1190 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1192 // no other way to create the Delimitor ...
1193 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1195 // At the top of the hierarchy, stands a Document. When "set"
1196 // is a Document, then we are building the first depth level.
1197 // Hence the SeqEntry we are building simply has a depth
1199 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1201 newSeqEntry->SetDepthLevel( 1 );
1203 // But when "set" is already a SQItem, we are building a nested
1204 // sequence, and hence the depth level of the new SeqEntry
1205 // we are building, is one level deeper:
1207 // time waste hunting
1208 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1210 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1214 { // Don't try to parse zero-length sequences
1216 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1217 << " at offset 0x(" << std::hex
1218 << newDocEntry->GetOffset() << ")");
1220 ParseSQ( newSeqEntry,
1221 newDocEntry->GetOffset(),
1222 l, delim_mode_intern);
1224 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1227 if ( !set->AddEntry( newSeqEntry ) )
1229 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1230 << newSeqEntry->GetKey()
1231 << " (at offset : 0x("
1232 << newSeqEntry->GetOffset() << ") )" );
1237 newDocEntry->Delete();
1240 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1242 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1243 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1247 newDocEntry->Delete();
1250 } // end SeqEntry : VR = "SQ"
1254 newDocEntry->Delete();
1258 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1262 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1263 * @return parsed length for this level
1265 void Document::ParseSQ( SeqEntry *seqEntry,
1266 long offset, long l_max, bool delim_mode)
1268 int SQItemNumber = 0;
1270 long offsetStartCurrentSQItem = offset;
1274 // the first time, we read the fff0,e000 of the first SQItem
1275 DocEntry *newDocEntry = ReadNextDocEntry();
1279 gdcmWarningMacro("in ParseSQ : should never get here!");
1284 if ( newDocEntry->IsSequenceDelimitor() )
1286 seqEntry->SetDelimitationItem( newDocEntry );
1287 newDocEntry->Delete();
1291 if ( !delim_mode ) // andthen doesn't exist in C++ :-(
1292 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1294 newDocEntry->Delete();
1297 // create the current SQItem
1298 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1299 unsigned int l = newDocEntry->GetReadLength();
1301 if ( l == 0xffffffff )
1310 // remove fff0,e000, created out of the SQItem
1312 //Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); //JPRx
1314 // fill up the current SQItem, starting at the beginning of fff0,e000
1316 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1318 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1320 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1322 newDocEntry->Delete();
1324 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1325 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1333 * \brief When a private Sequence + Implicit VR is encountered
1334 * we cannot guess it's a Sequence till we find the first
1335 * Item Starter. We then backtrack to do the job.
1336 * @param docEntry Item Starter that warned us
1338 DocEntry *Document::Backtrack(DocEntry *docEntry)
1340 // delete the Item Starter, built erroneously out of any Sequence
1341 // it's not yet in the HTable/chained list
1344 // Get all info we can from PreviousDocEntry
1345 uint16_t group = PreviousDocEntry->GetGroup();
1346 uint16_t elem = PreviousDocEntry->GetElement();
1347 uint32_t lgt = PreviousDocEntry->GetLength();
1348 long offset = PreviousDocEntry->GetOffset();
1350 gdcmDebugMacro( "Backtrack :" << std::hex << group
1352 << " at offset 0x(" <<offset << ")" );
1353 RemoveEntry( PreviousDocEntry );
1355 // forge the Seq Entry
1356 DocEntry *newEntry = NewSeqEntry(group, elem);
1357 newEntry->SetLength(lgt);
1358 newEntry->SetOffset(offset);
1360 // Move back to the beginning of the Sequence
1362 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1367 * \brief Loads (or not) the element content depending if its length exceeds
1368 * or not the value specified with Document::SetMaxSizeLoadEntry()
1369 * @param entry Header Entry (Dicom Element) to be dealt with
1370 * @param forceLoad whether you want to force loading of 'long' elements
1372 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1374 uint16_t group = entry->GetGroup();
1375 uint16_t elem = entry->GetElement();
1376 const VRKey &vr = entry->GetVR();
1377 uint32_t length = entry->GetLength();
1379 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1381 // A SeQuence "contains" a set of Elements.
1382 // (fffe e000) tells us an Element is beginning
1383 // (fffe e00d) tells us an Element just ended
1384 // (fffe e0dd) tells us the current SeQuence just ended
1385 // (fffe 0000) is an 'impossible' tag value,
1386 // found in MR-PHILIPS-16-Multi-Seq.dcm
1388 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1390 // NO more value field for SQ !
1394 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1400 // When the length is zero things are easy:
1403 dataEntryPtr->SetBinArea(NULL,true);
1407 // The elements whose length is bigger than the specified upper bound
1412 if (length > MaxSizeLoadEntry)
1414 dataEntryPtr->SetBinArea(NULL,true);
1415 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1417 // to be sure we are at the end of the value ...
1418 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1419 // std::ios::beg); //JPRx
1424 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1425 /// + a ForceLoad call on the +/- 20 'usefull' fields
1426 /// Allow user to tell the fields he wants to ForceLoad
1427 /// during initial stage.
1428 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1429 /// + a method that load *everything* that's not yet loaded
1431 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1435 * \brief Find the value Length of the passed Doc Entry
1436 * @param entry Header Entry whose length of the value shall be loaded.
1438 void Document::FindDocEntryLength( DocEntry *entry )
1439 throw ( FormatError )
1441 const VRKey &vr = entry->GetVR();
1444 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1446 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1449 // The following reserved two bytes (see PS 3.5-2003, section
1450 // "7.1.2 Data element structure with explicit vr", p 27) must be
1451 // skipped before proceeding on reading the length on 4 bytes.
1453 Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1454 uint32_t length32 = ReadInt32();
1456 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1461 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1463 catch ( FormatUnexpected )
1465 // Computing the length failed (this happens with broken
1466 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1467 // chance to get the pixels by deciding the element goes
1468 // until the end of the file. Hence we artificially fix the
1469 // the length and proceed.
1470 gdcmWarningMacro( " Computing the length failed for " <<
1471 entry->GetKey() <<" in " <<GetFileName());
1473 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1474 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1476 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1477 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1479 entry->SetReadLength(lengthUntilEOF);
1480 entry->SetLength(lengthUntilEOF);
1483 entry->SetReadLength(lengthOB);
1484 entry->SetLength(lengthOB);
1487 FixDocEntryFoundLength(entry, length32);
1491 // Length is encoded on 2 bytes.
1492 length16 = ReadInt16();
1494 // 0xffff means that we deal with 'No Length' Sequence
1495 // or 'No Length' SQItem
1496 if ( length16 == 0xffff)
1500 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1505 // Either implicit VR or a non DICOM conformal (see note below) explicit
1506 // VR that ommited the VR of (at least) this element. Farts happen.
1507 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1508 // on Data elements "Implicit and Explicit VR Data Elements shall
1509 // not coexist in a Data Set and Data Sets nested within it".]
1510 // Length is on 4 bytes.
1512 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1513 // even if Transfer Syntax is 'Implicit VR ...'
1514 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1516 FixDocEntryFoundLength( entry, ReadInt32() );
1522 * \brief Find the Length till the next sequence delimiter
1523 * \warning NOT end user intended method !
1526 uint32_t Document::FindDocEntryLengthOBOrOW()
1527 throw( FormatUnexpected )
1529 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1530 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1532 bool foundSequenceDelimiter = false;
1533 uint32_t totalLength = 0;
1535 while ( !foundSequenceDelimiter )
1541 group = ReadInt16();
1544 catch ( FormatError )
1546 throw FormatError("Unexpected end of file encountered during ",
1547 "Document::FindDocEntryLengthOBOrOW()");
1549 // We have to decount the group and element we just read
1551 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1554 "Neither an Item tag nor a Sequence delimiter tag on :"
1555 << std::hex << group << " , " << elem
1558 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1559 throw FormatUnexpected(
1560 "Neither an Item tag nor a Sequence delimiter tag.");
1562 if ( elem == 0xe0dd )
1564 foundSequenceDelimiter = true;
1566 uint32_t itemLength = ReadInt32();
1567 // We add 4 bytes since we just read the ItemLength with ReadInt32
1568 totalLength += itemLength + 4;
1569 SkipBytes(itemLength);
1571 if ( foundSequenceDelimiter )
1576 Fp->seekg( positionOnEntry, std::ios::beg); // Only for OB,OW DataElements
1581 * \brief Find the Value Representation of the current Dicom Element.
1582 * @return Value Representation of the current Entry
1584 VRKey Document::FindDocEntryVR()
1586 if ( Filetype != ExplicitVR )
1587 return GDCM_VRUNKNOWN;
1589 // Delimiters (0xfffe), are not explicit VR ...
1590 if ( CurrentGroup == 0xfffe )
1591 return GDCM_VRUNKNOWN;
1593 long positionOnEntry;
1594 if( Debug::GetWarningFlag() )
1595 positionOnEntry = Fp->tellg(); // Only in Warning Mode
1597 // Warning: we believe this is explicit VR (Value Representation) because
1598 // we used a heuristic that found "UL" in the first tag and/or
1599 // 'Transfer Syntax' told us it is.
1600 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1601 // In some cases one finds implicit VR tags mixed within an explicit VR file
1603 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1605 // Hence we make sure the present tag is in explicit VR and try to fix things
1606 // if it happens not to be the case.
1609 Fp->read(&(vr[0]),(size_t)2);
1611 if ( !CheckDocEntryVR(vr) )
1614 std::cout << "================================================================Unknown VR"
1615 << std::hex << "0x("
1616 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1617 << ")" << "for : " << CurrentGroup
1618 << " at offset : 0x(" << positionOnEntry << ")"
1621 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1622 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1624 << " at offset : 0x(" << positionOnEntry<< ") for group " << CurrentGroup
1627 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1628 Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1629 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1630 return GDCM_VRUNKNOWN;
1636 * \brief Check the correspondance between the VR of the header entry
1637 * and the taken VR. If they are different, the header entry is
1638 * updated with the new VR.
1639 * @param vr Dicom Value Representation
1640 * @return false if the VR is incorrect or if the VR isn't referenced
1641 * otherwise, it returns true
1643 bool Document::CheckDocEntryVR(const VRKey &vr)
1645 return Global::GetVR()->IsValidVR(vr);
1649 * \brief Skip a given Header Entry
1650 * @param entry entry to skip
1652 void Document::SkipDocEntry(DocEntry *entry)
1654 SkipBytes(entry->GetLength());
1658 * \brief Skips to the beginning of the next Header Entry
1659 * @param currentDocEntry entry to skip
1661 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1663 long l = currentDocEntry->GetReadLength();
1664 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1665 // ... but PMS imagers happen !
1667 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1668 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1670 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1675 * \brief When the length of an element value is obviously wrong (because
1676 * the parser went Jabberwocky) one can hope improving things by
1677 * applying some heuristics.
1678 * @param entry entry to check
1679 * @param foundLength first assumption about length
1681 void Document::FixDocEntryFoundLength(DocEntry *entry,
1682 uint32_t foundLength)
1684 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1685 if ( foundLength == 0xffffffff)
1690 uint16_t gr = entry->GetGroup();
1691 uint16_t elem = entry->GetElement();
1693 if ( foundLength % 2)
1695 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1696 << " in x(" << std::hex << gr << "," << elem <<")");
1699 //////// Fix for some naughty General Electric images.
1700 // Allthough not recent many such GE corrupted images are still present
1701 // on Creatis hard disks. Hence this fix shall remain when such images
1702 // are no longer in use (we are talking a few years, here)...
1703 // Note: XMedCon probably uses such a trick since it is able to read
1704 // those pesky GE images ...
1705 if ( foundLength == 13)
1707 // Only happens for this length !
1708 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1711 entry->SetReadLength(10); // a bug is to be fixed !?
1715 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1716 // Occurence of such images is quite low (unless one leaves close to a
1717 // 'Leonardo' source. Hence, one might consider commenting out the
1718 // following fix on efficiency reasons.
1719 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1722 entry->SetReadLength(4); // a bug is to be fixed !
1725 else if ( entry->GetVR() == "SQ" )
1727 foundLength = 0; // ReadLength is unchanged
1730 //////// We encountered a 'delimiter' element i.e. a tag of the form
1731 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1732 // taken into account.
1733 else if ( gr == 0xfffe )
1735 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1736 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1737 // causes extra troubles...
1738 if ( entry->GetElement() != 0x0000 )
1744 foundLength=12; // to skip the mess that follows this bugged Tag !
1747 entry->SetLength(foundLength);
1751 * \brief Apply some heuristics to predict whether the considered
1752 * element value contains/represents an integer or not.
1753 * @param entry The element value on which to apply the predicate.
1754 * @return The result of the heuristical predicate.
1756 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1758 uint16_t elem = entry->GetElement();
1759 uint16_t group = entry->GetGroup();
1760 const VRKey &vr = entry->GetVR();
1761 uint32_t length = entry->GetLength();
1763 // When we have some semantics on the element we just read, and if we
1764 // a priori know we are dealing with an integer, then we shall be
1765 // able to swap it's element value properly.
1766 if ( elem == 0 ) // This is the group length of the group
1774 // Although this should never happen, still some images have a
1775 // corrupted group length [e.g. have a glance at offset x(8336) of
1776 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1777 // Since for dicom compliant and well behaved headers, the present
1778 // test is useless (and might even look a bit paranoid), when we
1779 // encounter such an ill-formed image, we simply display a warning
1780 // message and proceed on parsing (while crossing fingers).
1781 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1782 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1783 << std::hex << group << " , " << elem
1784 << ") -before- position x(" << filePosition << ")"
1785 << "lgt : " << length );
1789 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1797 * \brief Discover what the swap code is (among little endian, big endian,
1798 * bad little endian, bad big endian).
1800 * @return false when we are absolutely sure
1801 * it's neither ACR-NEMA nor DICOM
1802 * true when we hope ours assuptions are OK
1804 bool Document::CheckSwap()
1811 // First, compare HostByteOrder and NetworkByteOrder in order to
1812 // determine if we shall need to swap bytes (i.e. the Endian type).
1813 bool net2host = Util::IsCurrentProcessorBigEndian();
1815 // The easiest case is the one of a 'true' DICOM header, we just have
1816 // to look for the string "DICM" inside the file preamble.
1819 char *entCur = deb + 128;
1820 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1822 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1824 // Group 0002 should always be VR, and the first element 0000
1825 // Let's be carefull (so many wrong headers ...)
1826 // and determine the value representation (VR) :
1827 // Let's skip to the first element (0002,0000) and check there if we find
1828 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1829 // in which case we (almost) know it is explicit VR.
1830 // WARNING: if it happens to be implicit VR then what we will read
1831 // is the length of the group. If this ascii representation of this
1832 // length happens to be "UL" then we shall believe it is explicit VR.
1833 // We need to skip :
1834 // * the 128 bytes of File Preamble (often padded with zeroes),
1835 // * the 4 bytes of "DICM" string,
1836 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1837 // i.e. a total of 136 bytes.
1840 // group 0x0002 *is always* Explicit VR Sometimes ,
1841 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1842 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1844 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1845 memcmp(entCur, "OB", (size_t)2) == 0 ||
1846 memcmp(entCur, "UI", (size_t)2) == 0 ||
1847 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1848 // when Write DCM *adds*
1850 // Use Document::dicom_vr to test all the possibilities
1851 // instead of just checking for UL, OB and UI !? group 0000
1853 Filetype = ExplicitVR;
1854 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1858 Filetype = ImplicitVR;
1859 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1860 << "Looks like a bugged Header!");
1866 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1871 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1874 // Position the file position indicator at first tag
1875 // (i.e. after the file preamble and the "DICM" string).
1877 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1879 } // ------------------------------- End of DicomV3 ----------------
1881 // Alas, this is not a DicomV3 file and whatever happens there is no file
1882 // preamble. We can reset the file position indicator to where the data
1883 // is (i.e. the beginning of the file).
1885 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1887 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1889 // Let's check 'No Preamble Dicom File' :
1890 // Should start with group 0x0002
1891 // and be Explicit Value Representation
1893 s16 = *((uint16_t *)(deb));
1906 if ( SwapCode != 0 )
1908 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1909 memcmp(entCur, "OB", (size_t)2) == 0 ||
1910 memcmp(entCur, "UI", (size_t)2) == 0 ||
1911 memcmp(entCur, "SH", (size_t)2) == 0 ||
1912 memcmp(entCur, "AE", (size_t)2) == 0 ||
1913 memcmp(entCur, "OB", (size_t)2) == 0 )
1915 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
1916 // Wait untill reading Transfer Syntax
1917 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1921 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1923 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1924 // By clean we mean that the length of the first group is written down.
1925 // If this is the case and since the length of the first group HAS to be
1926 // four (bytes), then determining the proper swap code is straightforward.
1929 // We assume the array of char we are considering contains the binary
1930 // representation of a 32 bits integer. Hence the following dirty
1932 s32 = *((uint32_t *)(entCur));
1952 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1953 // It is time for despaired wild guesses.
1954 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1955 // i.e. the 'group length' element is not present :
1957 // check the supposed-to-be 'group number'
1958 // in ( 0x0001 .. 0x0008 )
1959 // to determine ' SwapCode' value .
1960 // Only 0 or 4321 will be possible
1961 // (no oportunity to check for the formerly well known
1962 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1963 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1964 // the file IS NOT ACR-NEMA nor DICOM V3
1965 // Find a trick to tell it the caller...
1967 s16 = *((uint16_t *)(deb));
1994 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2002 * \brief Change the Byte Swap code.
2004 void Document::SwitchByteSwapCode()
2006 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2007 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2008 if ( SwapCode == 1234 )
2012 else if ( SwapCode == 4321 )
2016 else if ( SwapCode == 3412 )
2020 else if ( SwapCode == 2143 )
2024 gdcmDebugMacro( " Into: "<< SwapCode );
2028 * \brief during parsing, Header Elements too long are not loaded in memory
2029 * @param newSize new size
2031 void Document::SetMaxSizeLoadEntry(long newSize)
2037 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2039 MaxSizeLoadEntry = 0xffffffff;
2042 MaxSizeLoadEntry = newSize;
2046 * \brief Read the next tag WITHOUT loading it's value
2047 * (read the 'Group Number', the 'Element Number',
2048 * gets the Dict Entry
2049 * gets the VR, gets the length, gets the offset value)
2050 * @return On succes : the newly created DocEntry, NULL on failure.
2052 DocEntry *Document::ReadNextDocEntry()
2056 CurrentGroup = ReadInt16();
2057 CurrentElem = ReadInt16();
2059 catch ( FormatError )
2061 // We reached the EOF (or an error occured) therefore
2062 // header parsing has to be considered as finished.
2066 // In 'true DICOM' files Group 0002 is always little endian
2067 if ( HasDCMPreamble )
2069 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2070 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2072 // Sometimes file contains groups of tags with reversed endianess.
2073 HandleBrokenEndian(CurrentGroup, CurrentElem);
2076 VRKey vr = FindDocEntryVR();
2080 if ( vr == GDCM_VRUNKNOWN )
2082 if ( CurrentElem == 0x0000 ) // Group Length
2084 realVR = "UL"; // must be UL
2086 // Commented out in order not to generate 'Shadow Groups' where some
2087 // Data Elements are Explicit VR and some other ones Implicit VR
2088 // (Stupid MatLab DICOM Reader couln't read gdcm-written images)
2090 else if (CurrentGroup%2 == 1 &&
2091 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2093 // DICOM PS 3-5 7.8.1 a) states that those
2094 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2100 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2103 realVR = dictEntry->GetVR();
2104 dictEntry->Unregister();
2110 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2112 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2115 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2116 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2119 if ( vr == GDCM_VRUNKNOWN )
2121 if ( Filetype == ExplicitVR )
2123 // We thought this was explicit VR, but we end up with an
2124 // implicit VR tag. Let's backtrack.
2125 if ( newEntry->GetGroup() != 0xfffe )
2128 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2130 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2131 newEntry->GetGroup(), newEntry->GetElement(), offset );
2132 gdcmWarningMacro( msg.c_str() );
2135 newEntry->SetImplicitVR();
2140 FindDocEntryLength(newEntry);
2142 catch ( FormatError )
2149 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2155 * \brief Handle broken private tag from Philips NTSCAN
2156 * where the endianess is being switched to BigEndian
2157 * for no apparent reason
2160 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2162 // Endian reversion.
2163 // Some files contain groups of tags with reversed endianess.
2164 static int reversedEndian = 0;
2165 // try to fix endian switching in the middle of headers
2166 if ((group == 0xfeff) && (elem == 0x00e0))
2168 // start endian swap mark for group found
2169 gdcmDebugMacro( "Start endian swap mark found." );
2171 SwitchByteSwapCode();
2176 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2178 // end of reversed endian group
2179 gdcmDebugMacro( "End of reversed endian." );
2181 SwitchByteSwapCode();
2183 else if (group == 0xfeff && elem == 0xdde0)
2185 // reversed Sequence Terminator found
2186 // probabely a bug in the header !
2187 // Do what you want, it breaks !
2189 //SwitchByteSwapCode();
2190 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2195 else if (group == 0xfffe && elem == 0xe0dd)
2197 gdcmDebugMacro( "Straight Sequence Terminator." );
2202 * \brief Group 0002 is always coded Little Endian
2203 * whatever Transfer Syntax is
2206 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2208 // Endian reversion.
2209 // Some files contain groups of tags with reversed endianess.
2211 Group0002Parsed = true;
2212 // we just came out of group 0002
2213 // if Transfer Syntax is Big Endian we have to change CheckSwap
2215 std::string ts = GetTransferSyntax();
2216 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2218 // Group 0002 is always 'Explicit ...'
2219 // even when Transfer Syntax says 'Implicit ..."
2221 if ( s == TS::ImplicitVRLittleEndian
2223 s == TS::ImplicitVRBigEndianPrivateGE
2226 Filetype = ImplicitVR;
2229 // FIXME Strangely, this works with
2230 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2232 // --> Probabely normal, since we considered we never have
2233 // to trust manufacturers.
2234 // (we find very often 'Implicit VR' tag,
2235 // even when Transfer Syntax tells us it's Explicit ...
2237 if ( s == TS::ExplicitVRBigEndian )
2239 gdcmDebugMacro("Transfer Syntax Name = ["
2240 << GetTransferSyntaxName() << "]" );
2241 SwitchByteSwapCode();
2242 group = SwapShort(group);
2243 elem = SwapShort(elem);
2246 /// \todo find a trick to warn user and stop processing
2248 if ( s == TS::DeflatedExplicitVRLittleEndian)
2250 gdcmWarningMacro("Transfer Syntax ["
2251 << GetTransferSyntaxName() << "] :"
2252 << " not yet dealt with ");
2256 // The following shouldn't occur very often
2257 // Let's check at the very end.
2259 if ( ts == GDCM_UNKNOWN )
2261 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2265 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2267 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2273 //-----------------------------------------------------------------------------
2276 //-----------------------------------------------------------------------------
2277 } // end namespace gdcm