1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2007/06/15 13:16:55 $
7 Version: $Revision: 1.360 $
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
40 namespace GDCM_NAME_SPACE
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 CurrentOffsetPosition = 0;
66 // Load will set it to true if sucessfull
67 Group0002Parsed = false;
68 IsDocumentAlreadyLoaded = false;
69 IsDocumentModified = true;
70 LoadMode = LD_ALL; // default : load everything, later
77 * \brief Canonical destructor.
79 Document::~Document ()
84 //-----------------------------------------------------------------------------
87 * \brief Loader. use SetLoadMode(), SetFileName() before !
88 * @return false if file cannot be open or no swap info was found,
89 * or no tag was found.
91 bool Document::Load( )
93 if ( GetFileName() == "" )
95 gdcmWarningMacro( "Use SetFileName, before !" );
98 return DoTheLoadingDocumentJob( );
102 //#ifndef GDCM_LEGACY_REMOVE
104 * \brief Loader. (DEPRECATED : not to break the API)
105 * @param fileName 'Document' (File or DicomDir) to be open for parsing
106 * @return false if file cannot be open or no swap info was found,
107 * or no tag was found.
110 bool Document::Load( std::string const &fileName )
113 return DoTheLoadingDocumentJob( );
119 * \brief Performs the Loading Job (internal use only)
120 * @return false if file cannot be open or no swap info was found,
121 * or no tag was found.
123 bool Document::DoTheLoadingDocumentJob( )
125 if ( ! IsDocumentModified ) // Nothing to do !
133 // warning already performed in OpenFile()
138 Group0002Parsed = false;
140 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
142 // Computes the total length of the file
143 Fp->seekg(0, std::ios::end); // Once per Document !
144 long lgt = Fp->tellg(); // Once per Document !
145 Fp->seekg(0, std::ios::beg); // Once per Document !
147 // CheckSwap returns a boolean
148 // (false if no swap info of any kind was found)
151 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
152 << Filename.c_str());
157 long beg = Fp->tellg(); // just after DICOM preamble (if any)
159 lgt -= beg; // remaining length to parse
162 // Loading is done during parsing
163 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
167 gdcmErrorMacro( "No tag in internal hash table for: "
168 << Filename.c_str());
172 IsDocumentAlreadyLoaded = true;
174 //Fp->seekg(0, std::ios::beg); // Once per Document!
176 // Load 'non string' values
178 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
179 if ( PhotometricInterpretation == "PALETTE COLOR " )
182 // Probabely this line should be outside the 'if'
183 // Try to find an image sample holding a 'gray LUT'
184 LoadEntryBinArea(0x0028,0x1200); // gray LUT
187 /// --> FIXME : The difference between BinEntry and DataEntry
188 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
189 /// --> Old comment restored on purpose.
190 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
191 /// --> had absolutely no meaning.
192 /// --> The whole comment will be removed when the stuff is cleaned !
194 /// The tags refered by the three following lines used to be CORRECTLY
195 /// defined as having an US Value Representation in the public
196 /// dictionary. BUT the semantics implied by the three following
197 /// lines state that the corresponding tag contents are in fact
198 /// the ones of a BinEntry.
199 /// In order to fix things "Quick and Dirty" the dictionary was
200 /// altered on PURPOSE but now contains a WRONG value.
201 /// In order to fix things and restore the dictionary to its
202 /// correct value, one needs to decide of the semantics by deciding
203 /// whether the following tags are either :
204 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
205 /// also used as BinEntry, which requires the proper conversion,
206 /// - OW, and hence loaded as BinEntry, but afterwards also used
207 /// as ValEntry, which requires the proper conversion.
209 // --> OB (byte aray) or OW (short int aray)
210 // The actual VR has to be deduced from other entries.
211 // Our way of loading them may fail in some cases :
212 // We must or not SwapByte depending on other field values.
214 LoadEntryBinArea(0x0028,0x1201); // R LUT
215 LoadEntryBinArea(0x0028,0x1202); // G LUT
216 LoadEntryBinArea(0x0028,0x1203); // B LUT
218 // Segmented Red Palette Color LUT Data
219 LoadEntryBinArea(0x0028,0x1221);
220 // Segmented Green Palette Color LUT Data
221 LoadEntryBinArea(0x0028,0x1222);
222 // Segmented Blue Palette Color LUT Data
223 LoadEntryBinArea(0x0028,0x1223);
226 //FIXME later : how to use it?
227 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
230 SQItem *sqi= modLutSeq->GetFirstSQItem();
233 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
234 if ( dataEntry != 0 )
236 if ( dataEntry->GetLength() != 0 )
238 // FIXME : CTX dependent means : contexted dependant.
239 // see upper comment.
240 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
246 // Force Loading some more elements if user asked to.
248 GDCM_NAME_SPACE::DocEntry *d;
249 for (ListElements::iterator it = UserForceLoadList.begin();
250 it != UserForceLoadList.end();
253 gdcmDebugMacro( "Force Load " << std::hex
254 << (*it).Group << "|" <<(*it).Elem );
256 d = GetDocEntry( (*it).Group, (*it).Elem);
260 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
261 << (*it).Group <<"|"<< (*it).Elem
262 << " that doesn't exist" );
266 LoadDocEntry(d, true);
271 // ----------------------------
272 // Specific code to allow gdcm to read ACR-LibIDO formated images
273 // Note: ACR-LibIDO is an extension of the ACR standard that was
274 // used at CREATIS. For the time being (say a couple of years)
275 // we keep this kludge to allow CREATIS users
276 // reading their old images.
278 // if recognition code tells us we deal with a LibIDO image
279 // we switch lineNumber and columnNumber
282 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
283 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
284 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
285 // with "little-endian strings"
287 Filetype = ACR_LIBIDO;
288 std::string rows = GetEntryString(0x0028, 0x0010);
289 std::string columns = GetEntryString(0x0028, 0x0011);
290 SetEntryString(columns, 0x0028, 0x0010);
291 SetEntryString(rows , 0x0028, 0x0011);
293 // --- End of ACR-LibIDO kludge ---
299 * \brief Adds a new element we want to load anyway
300 * @param group Group number of the target tag.
301 * @param elem Element number of the target tag.
303 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
308 UserForceLoadList.push_back(el);
311 * \brief Get the public dictionary used
313 Dict *Document::GetPubDict()
319 * \brief Get the shadow dictionary used
321 Dict *Document::GetShaDict()
327 * \brief Set the shadow dictionary used
328 * @param dict dictionary to use in shadow
330 bool Document::SetShaDict(Dict *dict)
337 * \brief Set the shadow dictionary used
338 * @param dictName name of the dictionary to use in shadow
340 bool Document::SetShaDict(DictKey const &dictName)
342 RefShaDict = Global::GetDicts()->GetDict(dictName);
347 * \brief This predicate tells us whether or not the current Document
348 * was properly parsed and contains at least *one* Dicom Element
349 * (and nothing more, sorry).
350 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
353 bool Document::IsParsable()
355 if ( Filetype == Unknown )
357 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
363 gdcmWarningMacro( "No tag in internal hash table.");
370 * \brief This predicate tells us whether or not the current Document
371 * was properly parsed and contains at least *one* Dicom Element
372 * (and nothing more, sorry).
373 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
376 bool Document::IsReadable()
382 * \brief Predicate for dicom version 3 file.
383 * @return True when the file is a dicom version 3.
385 bool Document::IsDicomV3()
387 // Checking if Transfer Syntax exists is enough
388 // Anyway, it's too late check if the 'Preamble' was found ...
389 // And ... would it be a rich idea to check ?
390 // (some 'no Preamble' DICOM images exist !)
391 return GetDocEntry(0x0002, 0x0010) != NULL;
395 * \brief Predicate for Papyrus file
396 * Dedicated to whomsoever it may concern
397 * @return True when the file is a Papyrus file.
399 bool Document::IsPapyrus()
401 // check for Papyrus private Sequence
402 DocEntry *e = GetDocEntry(0x0041, 0x1050);
405 // check if it's actually a Sequence
406 if ( !dynamic_cast<SeqEntry*>(e) )
412 * \brief returns the File Type
413 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
414 * @return the FileType code
416 FileType Document::GetFileType()
422 * \brief Accessor to the Transfer Syntax (when present) of the
423 * current document (it internally handles reading the
424 * value from disk when only parsing occured).
425 * @return The encountered Transfer Syntax of the current document, if DICOM.
426 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
428 std::string Document::GetTransferSyntax()
430 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
436 // The entry might be present but not loaded (parsing and loading
437 // happen at different stages): try loading and proceed with check...
440 // (parsing and loading happen at the very same stage!)
441 //LoadDocEntrySafe(entry); //JPRx
442 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
444 std::string transfer = dataEntry->GetString();
445 // The actual transfer (as read from disk) might be padded. We
446 // first need to remove the potential padding. We can make the
447 // weak assumption that padding was not executed with digits...
448 if ( transfer.length() == 0 )
450 // for brain damaged headers
451 gdcmWarningMacro( "Transfer Syntax has length = 0.");
454 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
456 transfer.erase(transfer.length()-1, 1);
457 if ( transfer.length() == 0 )
459 // for brain damaged headers
460 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
470 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
471 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
473 std::string Document::GetTransferSyntaxName()
475 // use the TS (TS : Transfer Syntax)
476 std::string transferSyntax = GetEntryString(0x0002,0x0010);
478 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
480 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
481 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
482 return "Uncompressed ACR-NEMA";
484 if ( transferSyntax == GDCM_UNFOUND )
486 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
487 return "Uncompressed ACR-NEMA";
490 // we do it only when we need it
491 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
493 // Global::GetTS() is a global static you shall never try to delete it!
497 // --------------- Swap Code ------------------
499 * \brief Swaps the bytes so they agree with the processor order
500 * @return The properly swaped 16 bits integer.
502 uint16_t Document::SwapShort(uint16_t a)
504 if ( SwapCode == 4321 || SwapCode == 2143 )
506 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
508 a = ( a << 8 ) | ( a >> 8 );
514 * \brief Swaps back the bytes of 4-byte long integer accordingly to
516 * @return The properly swaped 32 bits integer.
518 uint32_t Document::SwapLong(uint32_t a)
525 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
526 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
528 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
529 ((a>>8) & 0x0000ff00) | (a>>24) );
532 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
533 a=( (a<<16) | (a>>16) );
536 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
539 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
546 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
548 * @return The properly swaped 64 bits double.
550 double Document::SwapDouble(double a)
554 // There were no 'double' at ACR-NEMA time.
555 // We just have to deal with 'straight Little Endian' and
556 // 'straight Big Endian'
561 char *beg = (char *)&a;
564 for (unsigned int i = 0; i<7; i++)
575 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
582 // -----------------File I/O ---------------
584 * \brief Tries to open the file \ref Document::Filename and
585 * checks the preamble when existing,
586 * or if the file starts with an ACR-NEMA look-like element.
587 * @return The FILE pointer on success, 0 on failure.
589 std::ifstream *Document::OpenFile()
591 HasDCMPreamble = false;
592 if (Filename.length() == 0)
599 gdcmDebugMacro( "File already open: " << Filename.c_str());
603 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
606 // Don't user gdcmErrorMacro :
607 // a spurious message will appear when you use, for instance
608 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
609 // to create outputFileName.
611 // FIXME : if the upper comment is still usefull
612 // --> the constructor is not so good ...
614 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
618 //exit(1); // No function is allowed to leave the application instead
619 // of warning the caller
623 Fp->read((char*)&zero, (size_t)2);
631 Fp->seekg(126L, std::ios::cur); // Once per Document
632 char dicm[4]; // = {' ',' ',' ',' '};
633 Fp->read(dicm, (size_t)4);
640 if ( memcmp(dicm, "DICM", 4) == 0 )
642 HasDCMPreamble = true;
646 //-- Broken ACR or DICOM (?) with no Preamble; may start with a Shadow Group --
647 // FIXME : We cannot be sure the preable is only zeroes..
648 // (see ACUSON-24-YBR_FULL-RLE.dcm )
650 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
651 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
652 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
653 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 ||
654 zero == 0x0028 || 0x2800 // worse : some ACR-NEMA like files
655 // start 00028 group ?!?
658 std::string msg = Util::Format(
659 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
660 // FIXME : is it a Warning message, or a Debug message?
661 gdcmWarningMacro( msg.c_str() );
665 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
667 // Don't user Warning nor Error, not to pollute the output
668 // while directory recursive parsing ...
669 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
670 << Filename.c_str());
675 * \brief closes the file
676 * @return TRUE if the close was successfull
678 bool Document::CloseFile()
690 * \brief Writes in a file all the Entries (Dicom Elements)
691 * @param fp file pointer on an already open file (actually: Output File Stream)
692 * @param filetype Type of the File to be written
693 * (ACR-NEMA, ExplicitVR, ImplicitVR)
695 void Document::WriteContent(std::ofstream *fp, FileType filetype)
697 // Skip if user wants to write an ACR-NEMA file
699 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
700 filetype == JPEG || filetype == JPEG2000 )
702 // writing Dicom File Preamble
703 char filePreamble[128];
704 memset(filePreamble, 0, 128);
705 fp->write(filePreamble, 128);
706 fp->write("DICM", 4);
709 * \todo rewrite later, if really usefull
710 * - 'Group Length' element is optional in DICOM
711 * - but un-updated odd groups lengthes can causes pb
714 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
715 * UpdateGroupLength(false,filetype);
716 * if ( filetype == ACR)
717 * UpdateGroupLength(true,ACR);
719 * --> Computing group length for groups with embeded Sequences
720 * --> was too much tricky / we were [in a hurry / too lazy]
721 * --> We don't write the element 0x0000 (group length)
724 ElementSet::WriteContent(fp, filetype); // This one is recursive
727 // -----------------------------------------
730 * \brief Loads (from disk) the element content
731 * when a string is not suitable
732 * @param group group number of the Entry
733 * @param elem element number of the Entry
735 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
737 // Search the corresponding DocEntry
738 DocEntry *docEntry = GetDocEntry(group, elem);
741 gdcmDebugMacro(std::hex << group << "|" << elem
742 << " doesn't exist" );
745 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
748 gdcmWarningMacro(std::hex << group << "|" << elem
749 << " is NOT a DataEntry");
752 LoadEntryBinArea(dataEntry);
756 * \brief Loads (from disk) the element content
757 * when a string is not suitable
758 * @param entry Entry whose binArea is going to be loaded
760 void Document::LoadEntryBinArea(DataEntry *entry)
762 if( entry->GetBinArea() )
769 //size_t o =(size_t)entry->GetOffset();
770 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
772 size_t l = entry->GetLength();
773 uint8_t *data = new uint8_t[l];
776 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
777 << std::hex << entry->GetGroup()
778 << "|" << entry->GetElement() );
783 Fp->read((char*)data, l);
784 if ( Fp->fail() || Fp->eof() )
787 entry->SetState(DataEntry::STATE_UNREAD);
791 // Swap the data content if necessary
793 unsigned short vrLgth =
794 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
796 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
797 // if( entry->GetVR() == "OW" )
808 uint16_t *data16 = (uint16_t *)data;
809 for(i=0;i<l/vrLgth;i++)
810 data16[i] = SwapShort(data16[i]);
815 uint32_t *data32 = (uint32_t *)data;
816 for(i=0;i<l/vrLgth;i++)
817 data32[i] = SwapLong(data32[i]);
822 double *data64 = (double *)data;
823 for(i=0;i<l/vrLgth;i++)
824 data64[i] = SwapDouble(data64[i]);
829 entry->SetBinArea(data);
831 if ( openFile ) // The file is left in the state (open/close) it was at entrance
836 * \brief Loads the element while preserving the current
837 * underlying file position indicator as opposed to
838 * LoadDocEntry that modifies it
839 * \note seems to be unused!.
840 * @param entry DocEntry whose value will be loaded.
842 //void Document::LoadDocEntrySafe(DocEntry *entry)
846 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
847 // LoadDocEntry(entry);
848 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
853 * \brief Compares two documents, according to \ref DicomDir rules
854 * \warning Does NOT work with ACR-NEMA files
855 * \todo Find a trick to solve the pb (use RET fields ?)
856 * @param document to compare with current one
857 * @return true if 'smaller'
859 bool Document::operator<(Document &document)
862 std::string s1 = GetEntryString(0x0010,0x0010);
863 std::string s2 = document.GetEntryString(0x0010,0x0010);
875 s1 = GetEntryString(0x0010,0x0020);
876 s2 = document.GetEntryString(0x0010,0x0020);
887 // Study Instance UID
888 s1 = GetEntryString(0x0020,0x000d);
889 s2 = document.GetEntryString(0x0020,0x000d);
900 // Serie Instance UID
901 s1 = GetEntryString(0x0020,0x000e);
902 s2 = document.GetEntryString(0x0020,0x000e);
917 //-----------------------------------------------------------------------------
921 * \brief Reads a given length of bytes
922 * (in order to avoid to many CPU time consuming fread-s)
923 * @param l length to read
925 void Document::ReadBegBuffer(size_t l)
928 Fp->read (BegBuffer, (size_t)l);
931 throw FormatError( "Document::ReadBegBuffer()", " file error." );
935 throw FormatError( "Document::ReadBegBuffer()", "EOF." );
937 PtrBegBuffer = BegBuffer;
938 CurrentOffsetPosition+=l;
941 * \brief Reads a supposed to be 16 Bits integer
942 * (swaps it depending on processor endianness)
945 uint16_t Document::ReadInt16()
949 Fp->read ((char*)&g, (size_t)2);
952 throw FormatError( "Document::ReadInt16()", " file error." );
956 throw FormatError( "Document::ReadInt16()", "EOF." );
963 * \brief Gets from BegBuffer a supposed to be 16 Bits integer
964 * (swaps it depending on processor endianness)
967 uint16_t Document::GetInt16()
969 uint16_t g = *((uint16_t*)PtrBegBuffer);
975 * \brief Reads a supposed to be 32 Bits integer
976 * (swaps it depending on processor endianness)
979 uint32_t Document::ReadInt32()
983 Fp->read ((char*)&g, (size_t)4);
986 throw FormatError( "Document::ReadInt32()", " file error." );
990 throw FormatError( "Document::ReadInt32()", "EOF." );
997 * \brief Gets from BegBuffer a supposed to be 32 Bits integer
998 * (swaps it depending on processor endianness)
1001 uint32_t Document::GetInt32()
1003 uint32_t g = *((uint32_t*)PtrBegBuffer);
1010 * \brief Re-computes the length of the Dicom group 0002.
1012 int Document::ComputeGroup0002Length( )
1017 int groupLength = 0;
1018 bool found0002 = false;
1020 // for each zero-level Tag in the DCM Header
1021 DocEntry *entry = GetFirstEntry();
1024 gr = entry->GetGroup();
1030 if ( entry->GetElement() != 0x0000 )
1032 vr = entry->GetVR();
1034 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
1035 // (no SQ, OW, UT in group 0x0002;)
1038 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
1041 groupLength += 2 + 2 + 4 + entry->GetLength();
1044 else if (found0002 )
1047 entry = GetNextEntry();
1053 * \brief CallStartMethod
1055 void Document::CallStartMethod()
1059 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1063 * \brief CallProgressMethod
1065 void Document::CallProgressMethod()
1067 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1071 * \brief CallEndMethod
1073 void Document::CallEndMethod()
1076 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1079 //-----------------------------------------------------------------------------
1082 * \brief Loads all the needed Dictionaries
1083 * \warning NOT end user intended method !
1085 void Document::Initialize()
1087 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1093 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1094 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1095 * @param offset start of parsing
1096 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1097 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1099 void Document::ParseDES(DocEntrySet *set, long offset,
1100 long l_max, bool delim_mode)
1102 DocEntry *newDocEntry;
1103 DataEntry *newDataEntry;
1104 SeqEntry *newSeqEntry;
1106 bool used; // will be set to false when something wrong happens to an Entry.
1107 // (Entry will then be deleted)
1108 bool delim_mode_intern = delim_mode;
1110 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1111 << " at offset " << std::hex << "0x(" << offset << ")" );
1115 ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1116 /// Probabely a bug in gdcm code somwhere (some memory erased ?)
1118 // Uncomment to track the bug
1120 if( Debug::GetDebugFlag() )
1121 std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1122 << std::hex << " 0x(" <<(long)(Fp->tellg()) << ")" << std::endl;
1125 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1126 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1127 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1132 newDocEntry = ReadNextDocEntry( );
1139 // Uncoment this cerr line to be able to 'follow' the DocEntries
1140 // when something *very* strange happens
1141 if( Debug::GetDebugFlag() )
1142 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1144 // an Item Starter found elsewhere but in the first position
1145 // of a SeqEntry means previous entry was a Sequence
1146 // but we didn't get it (private Sequence + Implicit VR)
1147 // we have to backtrack.
1148 if ( !first && newDocEntry->IsItemStarter() )
1150 // Debug message within the method !
1151 newDocEntry = Backtrack(newDocEntry);
1155 PreviousDocEntry = newDocEntry;
1159 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1163 //////////////////////////// DataEntry
1165 //vr = newDocEntry->GetVR(); // useless ?
1167 if ( !set->AddEntry( newDataEntry ) )
1169 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1170 << newDataEntry->GetKey()
1171 << " (at offset : 0x("
1172 << newDataEntry->GetOffset() << ") )" );
1177 newDataEntry->Delete();
1178 // Load only if we can add (not a duplicate key)
1179 LoadDocEntry( newDataEntry );
1181 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1183 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1185 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1187 std::string strLgrGroup = newDataEntry->GetString();
1190 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1192 lgrGroup = atoi(strLgrGroup.c_str());
1193 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1194 RemoveEntry( newDocEntry ); // Remove and delete
1201 bool delimitor = newDataEntry->IsItemDelimitor();
1202 bool outOfBounds = false;
1204 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1207 // 'and then', 'or else' don't exist in C++ :-(
1208 // if ( (delimitor) ||
1209 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1211 if ( delimitor || outOfBounds )
1214 newDocEntry->Delete();
1218 // Just to make sure we are at the beginning of next entry.
1219 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1223 /////////////////////// SeqEntry : VR = "SQ"
1225 unsigned long l = newDocEntry->GetReadLength();
1226 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1228 if ( l == 0xffffffff )
1230 delim_mode_intern = true;
1234 delim_mode_intern = false;
1238 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1240 // User asked to skip SeQuences *only* if they belong to Shadow Group
1241 if ( newDocEntry->GetGroup()%2 != 0 )
1243 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1244 newDocEntry->Delete(); // Delete, not in the set
1248 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1250 // User asked to skip *any* SeQuence
1251 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1252 newDocEntry->Delete(); // Delete, not in the set
1255 // delay the dynamic cast as late as possible
1256 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1258 // no other way to create the Delimitor ...
1259 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1261 // At the top of the hierarchy, stands a Document. When "set"
1262 // is a Document, then we are building the first depth level.
1263 // Hence the SeqEntry we are building simply has a depth
1265 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1267 newSeqEntry->SetDepthLevel( 1 );
1269 // But when "set" is already a SQItem, we are building a nested
1270 // sequence, and hence the depth level of the new SeqEntry
1271 // we are building, is one level deeper:
1273 // time waste hunting
1274 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1276 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1280 { // Don't try to parse zero-length sequences
1282 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1283 << " at offset 0x(" << std::hex
1284 << newDocEntry->GetOffset() << ")");
1286 ParseSQ( newSeqEntry,
1287 newDocEntry->GetOffset(),
1288 l, delim_mode_intern);
1290 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1292 if ( !set->AddEntry( newSeqEntry ) )
1294 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1295 << newSeqEntry->GetKey()
1296 << " (at offset : 0x("
1297 << newSeqEntry->GetOffset() << ") )" );
1302 newDocEntry->Delete();
1305 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1307 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1308 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1312 newDocEntry->Delete();
1315 } // end SeqEntry : VR = "SQ"
1319 newDocEntry->Delete();
1323 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1327 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1328 * @return parsed length for this level
1330 void Document::ParseSQ( SeqEntry *seqEntry,
1331 long offset, long l_max, bool delim_mode)
1333 int SQItemNumber = 0;
1335 long offsetStartCurrentSQItem = offset;
1339 // the first time, we read the fff0,e000 of the first SQItem
1340 DocEntry *newDocEntry = ReadNextDocEntry();
1344 gdcmWarningMacro("in ParseSQ : should never get here!");
1349 if ( newDocEntry->IsSequenceDelimitor() )
1351 seqEntry->SetDelimitationItem( newDocEntry );
1352 newDocEntry->Delete();
1356 else // ! delim_mode
1358 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1360 newDocEntry->Delete();
1364 // create the current SQItem
1365 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1366 unsigned int l = newDocEntry->GetReadLength();
1368 if ( l == 0xffffffff )
1377 // fill up the current SQItem, starting at the beginning of fff0,e000
1379 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); // Once per SQItem
1380 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1381 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1383 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1385 newDocEntry->Delete();
1387 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1388 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1396 * \brief When a private Sequence + Implicit VR is encountered
1397 * we cannot guess it's a Sequence till we find the first
1398 * Item Starter. We then backtrack to do the job.
1399 * @param docEntry Item Starter that warned us
1401 DocEntry *Document::Backtrack(DocEntry *docEntry)
1403 // delete the Item Starter, built erroneously out of any Sequence
1404 // it's not yet in the HTable/chained list
1407 // Get all info we can from PreviousDocEntry
1408 uint16_t group = PreviousDocEntry->GetGroup();
1409 uint16_t elem = PreviousDocEntry->GetElement();
1410 uint32_t lgt = PreviousDocEntry->GetLength();
1411 long offset = PreviousDocEntry->GetOffset();
1413 gdcmDebugMacro( "Backtrack :" << std::hex << group
1415 << " at offset 0x(" <<offset << ")" );
1416 RemoveEntry( PreviousDocEntry );
1418 // forge the Seq Entry
1419 DocEntry *newEntry = NewSeqEntry(group, elem);
1420 newEntry->SetLength(lgt);
1421 newEntry->SetOffset(offset);
1423 // Move back to the beginning of the Sequence
1425 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1430 * \brief Loads (or not) the element content depending if its length exceeds
1431 * or not the value specified with Document::SetMaxSizeLoadEntry()
1432 * @param entry Header Entry (Dicom Element) to be dealt with
1433 * @param forceLoad whether you want to force loading of 'long' elements
1435 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1437 uint16_t group = entry->GetGroup();
1438 uint16_t elem = entry->GetElement();
1439 const VRKey &vr = entry->GetVR();
1440 uint32_t length = entry->GetLength();
1442 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1444 // A SeQuence "contains" a set of Elements.
1445 // (fffe e000) tells us an Element is beginning
1446 // (fffe e00d) tells us an Element just ended
1447 // (fffe e0dd) tells us the current SeQuence just ended
1448 // (fffe 0000) is an 'impossible' tag value,
1449 // found in MR-PHILIPS-16-Multi-Seq.dcm
1451 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1453 // NO more value field for SQ !
1457 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1463 // When the length is zero things are easy:
1466 dataEntryPtr->SetBinArea(NULL,true);
1470 // The elements whose length is bigger than the specified upper bound
1475 if (length > MaxSizeLoadEntry)
1477 dataEntryPtr->SetBinArea(NULL,true);
1478 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1480 // to be sure we are at the end of the value ...
1481 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1482 // std::ios::beg); //JPRx
1487 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1488 /// + a ForceLoad call on the +/- 20 'usefull' fields
1489 /// Allow user to tell the fields he wants to ForceLoad
1490 /// during initial stage.
1491 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1492 /// + a method that load *everything* that's not yet loaded
1494 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1498 * \brief Find the value Length of the passed Doc Entry
1499 * @param entry Header Entry whose length of the value shall be loaded.
1501 void Document::FindDocEntryLength( DocEntry *entry )
1502 throw ( FormatError )
1504 const VRKey &vr = entry->GetVR();
1506 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1508 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1509 || vr == "UN" || changeFromUN == true)
1511 changeFromUN = false;
1512 // The following reserved two bytes (see PS 3.5-2003, section
1513 // "7.1.2 Data element structure with explicit vr", p 27) must be
1514 // skipped before proceeding on reading the length on 4 bytes.
1516 //Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1517 uint32_t length32 = ReadInt32(); // Once per OW,OB,SQ DocEntry
1518 CurrentOffsetPosition+=4;
1519 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1524 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1526 catch ( FormatUnexpected )
1528 // Computing the length failed (this happens with broken
1529 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1530 // chance to get the pixels by deciding the element goes
1531 // until the end of the file. Hence we artificially fix the
1532 // the length and proceed.
1533 gdcmWarningMacro( " Computing the length failed for " <<
1534 entry->GetKey() <<" in " <<GetFileName());
1536 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1537 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1539 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1540 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1542 entry->SetReadLength(lengthUntilEOF);
1543 entry->SetLength(lengthUntilEOF);
1546 entry->SetReadLength(lengthOB);
1547 entry->SetLength(lengthOB);
1550 FixDocEntryFoundLength(entry, length32);
1553 // Length is encoded on 2 bytes.
1554 //length16 = ReadInt16();
1555 length16 = GetInt16();
1556 // 0xffff means that we deal with 'No Length' Sequence
1557 // or 'No Length' SQItem
1558 if ( length16 == 0xffff)
1562 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1567 // Either implicit VR or a non DICOM conformal (see note below) explicit
1568 // VR that ommited the VR of (at least) this element. Farts happen.
1569 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1570 // on Data elements "Implicit and Explicit VR Data Elements shall
1571 // not coexist in a Data Set and Data Sets nested within it".]
1572 // Length is on 4 bytes.
1574 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1575 // even if Transfer Syntax is 'Implicit VR ...'
1576 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1577 // where Group 0x0002 is *also* encoded in Implicit VR !
1579 FixDocEntryFoundLength( entry, GetInt32() /*ReadInt32()*/ );
1585 * \brief Find the Length till the next sequence delimiter
1586 * \warning NOT end user intended method !
1589 uint32_t Document::FindDocEntryLengthOBOrOW()
1590 throw( FormatUnexpected )
1592 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1594 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1596 bool foundSequenceDelimiter = false;
1597 uint32_t totalLength = 0;
1599 while ( !foundSequenceDelimiter )
1606 //group = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1607 //elem = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1608 ReadBegBuffer(4); // Once per fragment (if any) of OB,OW DataElements
1610 catch ( FormatError )
1612 throw FormatError("Unexpected end of file encountered during ",
1613 "Document::FindDocEntryLengthOBOrOW()");
1618 // We have to decount the group and element we just read
1620 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1623 "Neither an Item tag nor a Sequence delimiter tag on :"
1624 << std::hex << group << " , " << elem
1627 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1628 throw FormatUnexpected(
1629 "Neither an Item tag nor a Sequence delimiter tag.");
1631 if ( elem == 0xe0dd )
1633 foundSequenceDelimiter = true;
1635 uint32_t itemLength = ReadInt32(); // Once per fragment (if any) of OB,OW DataElements
1636 // We add 4 bytes since we just read the ItemLength with ReadInt32
1637 totalLength += itemLength + 4;
1638 SkipBytes(itemLength);
1640 if ( foundSequenceDelimiter )
1645 Fp->seekg( positionOnEntry, std::ios::beg); // Only once for OB,OW DataElements
1650 * \brief Find the Value Representation of the current Dicom Element.
1651 * @return Value Representation of the current Entry
1653 VRKey Document::FindDocEntryVR()
1655 if ( Filetype != ExplicitVR )
1657 return GDCM_VRUNKNOWN;
1660 // Delimiters (0xfffe), are not explicit VR ...
1661 if ( CurrentGroup == 0xfffe )
1662 return GDCM_VRUNKNOWN;
1664 //long positionOnEntry;
1665 //if( Debug::GetWarningFlag() )
1666 // positionOnEntry = Fp->tellg(); // Only in Warning Mode
1668 // Warning: we believe this is explicit VR (Value Representation) because
1669 // we used a heuristic that found "UL" in the first tag and/or
1670 // 'Transfer Syntax' told us it is.
1671 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1672 // In some cases one finds implicit VR tags mixed within an explicit VR file
1674 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1676 // Hence we make sure the present tag is in explicit VR and try to fix things
1677 // if it happens not to be the case.
1680 //Fp->read(&(vr[0]),(size_t)2);
1681 vr[0] = *PtrBegBuffer++;
1682 vr[1] = *PtrBegBuffer++;
1684 //if ( !CheckDocEntryVR(vr) ) // avoid useless function call
1685 if ( !Global::GetVR()->IsValidVR(vr) )
1688 // std::cout << "================================================================Unknown VR"
1689 << std::hex << "0x("
1690 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1691 << ")" << "for : " << CurrentGroup
1692 << " at offset : 0x(" << positionOnEntry << ")"
1695 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1696 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1698 << " at offset : 0x(" << CurrentOffsetPosition-4<< ") for group " << CurrentGroup
1701 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1702 //Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1703 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1705 return GDCM_VRUNKNOWN;
1711 * \brief Check the correspondance between the VR of the header entry
1712 * and the taken VR. If they are different, the header entry is
1713 * updated with the new VR.
1714 * @param vr Dicom Value Representation
1715 * @return false if the VR is incorrect or if the VR isn't referenced
1716 * otherwise, it returns true
1718 bool Document::CheckDocEntryVR(const VRKey &vr)
1720 return Global::GetVR()->IsValidVR(vr);
1724 * \brief Skip a given Header Entry
1725 * @param entry entry to skip
1727 void Document::SkipDocEntry(DocEntry *entry)
1729 SkipBytes(entry->GetLength());
1733 * \brief Skips to the beginning of the next Header Entry
1734 * @param currentDocEntry entry to skip
1736 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1738 long l = currentDocEntry->GetReadLength();
1739 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1740 // ... but PMS imagers happen !
1742 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1743 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1745 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1750 * \brief When the length of an element value is obviously wrong (because
1751 * the parser went Jabberwocky) one can hope improving things by
1752 * applying some heuristics.
1753 * @param entry entry to check
1754 * @param foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)
1756 void Document::FixDocEntryFoundLength(DocEntry *entry,
1757 uint32_t foundLength)
1759 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1761 if ( foundLength == 0xffffffff)
1764 //entry->SetLength(foundLength);
1765 entry->SetLength(0);
1766 return; // return ASAP; don't waist time on useless tests
1769 uint16_t gr = entry->GetGroup();
1770 uint16_t elem = entry->GetElement();
1772 if ( foundLength % 2)
1774 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1775 << " in x(" << std::hex << gr << "," << elem <<")");
1778 //////// Fix for some naughty General Electric images.
1779 // Allthough not recent many such GE corrupted images are still present
1780 // on Creatis hard disks. Hence this fix shall remain when such images
1781 // are no longer in use (we are talking a few years, here)...
1782 // Note: XMedCon probably uses such a trick since it is able to read
1783 // those pesky GE images ...
1784 if ( foundLength == 13)
1786 // Only happens for this length !
1787 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1790 entry->SetReadLength(10); // a bug is to be fixed !?
1794 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1795 // Occurence of such images is quite low (unless one leaves close to a
1796 // 'Leonardo' source. Hence, one might consider commenting out the
1797 // following fix on efficiency reasons.
1798 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1800 // Ideally we should check we are in Explicit and double check
1801 // that VR=UL... this is done properly in gdcm2
1802 if( foundLength == 6 )
1804 gdcmWarningMacro( "Replacing Length from 6 into 4" );
1806 entry->SetReadLength(4); // a bug is to be fixed !
1808 else if ( foundLength%4 )
1810 gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1811 "The length of this tag seems to be wrong" );
1815 else if ( entry->GetVR() == "SQ" )
1817 foundLength = 0; // ReadLength is unchanged
1820 //////// We encountered a 'delimiter' element i.e. a tag of the form
1821 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1822 // taken into account.
1823 else if ( gr == 0xfffe )
1825 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1826 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1827 // causes extra troubles...
1828 if ( elem != 0x0000 )
1834 foundLength=12; // to skip the mess that follows this bugged Tag !
1837 entry->SetLength(foundLength);
1841 * \brief Apply some heuristics to predict whether the considered
1842 * element value contains/represents an integer or not.
1843 * @param entry The element value on which to apply the predicate.
1844 * @return The result of the heuristical predicate.
1846 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1848 uint16_t elem = entry->GetElement();
1849 uint16_t group = entry->GetGroup();
1850 const VRKey &vr = entry->GetVR();
1851 uint32_t length = entry->GetLength();
1853 // When we have some semantics on the element we just read, and if we
1854 // a priori know we are dealing with an integer, then we shall be
1855 // able to swap its element value properly.
1856 if ( elem == 0 ) // This is the group length of the group
1864 // Although this should never happen, still some images have a
1865 // corrupted group length [e.g. have a glance at offset x(8336) of
1866 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1867 // Since for dicom compliant and well behaved headers, the present
1868 // test is useless (and might even look a bit paranoid), when we
1869 // encounter such an ill-formed image, we simply display a warning
1870 // message and proceed on parsing (while crossing fingers).
1871 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1873 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1874 << std::hex << group << " , " << elem
1875 << ") -before- position x(" << filePosition << ")"
1876 << "lgt : " << length );
1880 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1888 * \brief Discover what the swap code is (among little endian, big endian,
1889 * bad little endian, bad big endian).
1891 * @return false when we are absolutely sure
1892 * it's neither ACR-NEMA nor DICOM
1893 * true when we hope ours assuptions are OK
1895 bool Document::CheckSwap()
1902 // First, compare HostByteOrder and NetworkByteOrder in order to
1903 // determine if we shall need to swap bytes (i.e. the Endian type).
1904 bool net2host = Util::IsCurrentProcessorBigEndian();
1906 // The easiest case is the one of a 'true' DICOM header, we just have
1907 // to look for the string "DICM" inside the file preamble.
1910 char *entCur = deb + 128;
1911 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1913 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1915 // Group 0002 should always be VR, and the first element 0000
1916 // Let's be carefull (so many wrong headers ...)
1917 // and determine the value representation (VR) :
1918 // Let's skip to the first element (0002,0000) and check there if we find
1919 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1920 // in which case we (almost) know it is explicit VR.
1921 // WARNING: if it happens to be implicit VR then what we will read
1922 // is the length of the group. If this ascii representation of this
1923 // length happens to be "UL" then we shall believe it is explicit VR.
1924 // We need to skip :
1925 // * the 128 bytes of File Preamble (often padded with zeroes),
1926 // * the 4 bytes of "DICM" string,
1927 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1928 // i.e. a total of 136 bytes.
1931 // group 0x0002 *is always* Explicit VR Sometimes,
1932 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1933 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1935 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1936 memcmp(entCur, "OB", (size_t)2) == 0 ||
1937 memcmp(entCur, "UI", (size_t)2) == 0 ||
1938 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1939 // when Write DCM *adds*
1941 // Use Document::dicom_vr to test all the possibilities
1942 // instead of just checking for UL, OB and UI !? group 0000
1944 Filetype = ExplicitVR;
1945 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1949 Filetype = ImplicitVR;
1950 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1951 << "Looks like a bugged Header!");
1954 // Here, we assume that the file IS kosher Dicom !
1955 // (The meta elements - group 0x0002 - ARE little endian !)
1959 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1964 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1967 // Position the file position indicator at first tag
1968 // (i.e. after the file preamble and the "DICM" string).
1970 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1971 CurrentOffsetPosition = 132;
1973 } // ------------------------------- End of DicomV3 ----------------
1975 // Alas, this is not a DicomV3 file and whatever happens there is no file
1976 // preamble. We can reset the file position indicator to where the data
1977 // is (i.e. the beginning of the file).
1979 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1981 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1982 CurrentOffsetPosition = 0;
1983 // Let's check 'No Preamble Dicom File' :
1984 // Should start with group 0x0002
1985 // and be Explicit Value Representation
1987 s16 = *((uint16_t *)(deb));
2000 if ( SwapCode != 0 )
2002 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2003 memcmp(entCur, "OB", (size_t)2) == 0 ||
2004 memcmp(entCur, "UI", (size_t)2) == 0 ||
2005 memcmp(entCur, "SH", (size_t)2) == 0 ||
2006 memcmp(entCur, "AE", (size_t)2) == 0 ||
2007 memcmp(entCur, "OB", (size_t)2) == 0 )
2009 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
2010 // Wait untill reading Transfer Syntax
2011 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
2015 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2017 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2018 // By clean we mean that the length of the first group is written down.
2019 // If this is the case and since the length of the first group HAS to be
2020 // four (bytes), then determining the proper swap code is straightforward.
2023 // We assume the array of char we are considering contains the binary
2024 // representation of a 32 bits integer. Hence the following dirty
2026 s32 = *((uint32_t *)(entCur));
2046 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2047 // It is time for despaired wild guesses.
2048 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2049 // i.e. the 'group length' element is not present :
2051 // check the supposed-to-be 'group number'
2052 // in ( 0x0001 .. 0x0008 )
2053 // to determine ' SwapCode' value .
2054 // Only 0 or 4321 will be possible
2055 // (no oportunity to check for the formerly well known
2056 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2057 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
2058 // the file IS NOT ACR-NEMA nor DICOM V3
2059 // Find a trick to tell it the caller...
2061 s16 = *((uint16_t *)(deb));
2063 gdcmDebugMacro("not a DicomV3 nor a 'clean' ACR/NEMA;"
2064 << " (->despaired wild guesses !)");
2093 s16 = *((uint16_t *)(deb));
2096 s16 = *((uint16_t *)(deb+2));
2098 //s32 = *((uint32_t *)(deb));
2099 Fp->seekg ( 0L, std::ios::beg); // Once per Document
2100 CurrentOffsetPosition = 0;
2101 switch(s16) // try an other trick!
2102 // -> to be able to decode 0029|1010 DataElement
2103 // -> and be not less cleaver than dcmdump ;-)
2119 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2123 // Check if next 2 bytes are a VR
2124 // Probabely something more time-consuming exists with std::string
2125 const char VRvalues[] = "AEASCSDADSFLFDISLOLTPNSHSLSSSTTMUIULUSUTOBOWOFATUNSQ";
2127 const char *pt = VRvalues;
2128 for (int i=0;i<nbVal;i++)
2130 if(*(deb+4) == *pt++)
2131 if(*(deb+5) == *pt++) {
2132 Filetype = ExplicitVR;
2137 Filetype = ImplicitVR;
2144 * \brief Change the Byte Swap code.
2146 void Document::SwitchByteSwapCode()
2148 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2149 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2150 if ( SwapCode == 1234 )
2154 else if ( SwapCode == 4321 )
2158 else if ( SwapCode == 3412 )
2162 else if ( SwapCode == 2143 )
2166 gdcmDebugMacro( " Into: "<< SwapCode );
2170 * \brief during parsing, Header Elements too long are not loaded in memory
2171 * @param newSize new size
2173 void Document::SetMaxSizeLoadEntry(long newSize)
2179 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2181 MaxSizeLoadEntry = 0xffffffff;
2184 MaxSizeLoadEntry = newSize;
2188 * \brief Read the next tag WITHOUT loading it's value
2189 * (read the 'Group Number', the 'Element Number',
2190 * gets the Dict Entry
2191 * gets the VR, gets the length, gets the offset value)
2192 * @return On succes : the newly created DocEntry, NULL on failure.
2194 DocEntry *Document::ReadNextDocEntry()
2198 ReadBegBuffer(8); // Avoid to many time consuming freads
2199 //CurrentGroup = ReadInt16();
2200 //CurrentElem = ReadInt16();
2202 catch ( FormatError )
2204 // We reached the EOF (or an error occured) therefore
2205 // header parsing has to be considered as finished.
2209 changeFromUN = false;
2210 CurrentGroup = GetInt16();
2211 CurrentElem = GetInt16();
2213 // In 'true DICOM' files Group 0002 is always little endian
2214 if ( HasDCMPreamble )
2216 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2217 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2219 // Sometimes file contains groups of tags with reversed endianess.
2220 HandleBrokenEndian(CurrentGroup, CurrentElem);
2223 VRKey vr = FindDocEntryVR();
2226 if ( vr == GDCM_VRUNKNOWN )
2228 if ( CurrentElem == 0x0000 ) // Group Length
2230 realVR = "UL"; // must be UL
2232 else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2237 // Commented out in order not to generate 'Shadow Groups' where some
2238 // Data Elements are Explicit VR and some other ones Implicit VR
2239 // (Stupid MatLab DICOM Reader couldn't read gdcm-written images)
2241 else if (CurrentGroup%2 == 1 &&
2242 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2244 // DICOM PS 3-5 7.8.1 a) states that those
2245 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2251 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2254 realVR = dictEntry->GetVR();
2255 dictEntry->Unregister(); // GetDictEntry registered it
2260 // if UN found, let's check the dictionary, and trust it!
2261 // (maybe a private dictionary exists?)
2262 else if (vr == "UN")
2264 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2267 realVR = dictEntry->GetVR();
2268 dictEntry->Unregister(); // GetDictEntry registered it
2270 // for VR = "UN", length is always stored on 4 bytes.
2272 /// \todo : fixme If inside a supposed to be UN DataElement (but SQ according to a private dictionnary)
2273 /// there is some more supposed to UN DataElements, it will probabely fail.
2274 /// --> find a -non time consuming- trick to store changeFromUN info at DataElement level,
2275 /// not at the Document level.
2280 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2283 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2287 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2288 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2291 if ( vr == GDCM_VRUNKNOWN )
2293 if ( Filetype == ExplicitVR )
2295 // We thought this was explicit VR, but we end up with an
2296 // implicit VR tag. Let's backtrack.
2298 //if ( newEntry->GetGroup() != 0xfffe )
2299 if (CurrentGroup != 0xfffe)
2301 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2303 gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2304 << offset << ") should be Explicit VR");
2307 newEntry->SetImplicitVR();
2312 FindDocEntryLength(newEntry);
2314 catch ( FormatError )
2321 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2326 * \brief Handle broken private tag from Philips NTSCAN
2327 * where the endianess is being switched to BigEndian
2328 * for no apparent reason
2331 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2333 // for strange PMS Gyroscan Intera images
2334 // Item 'starter' has a tag : 0x3f3f,0x3f00, for no apparent reason
2336 // --- Feel free to remove this test *on your own coy of gdcm*
2337 // if you are sure you'll never face this problem.
2339 if ((group == 0x3f3f) && (elem == 0x3f00))
2341 // start endian swap mark for group found
2342 gdcmDebugMacro( " delimiter 0x3f3f found." );
2348 // --- End of removable code
2350 // Endian reversion.
2351 // Some files contain groups of tags with reversed endianess.
2352 static int reversedEndian = 0;
2353 // try to fix endian switching in the middle of headers
2354 if ((group == 0xfeff) && (elem == 0x00e0))
2356 // start endian swap mark for group found
2357 gdcmDebugMacro( "Start endian swap mark found." );
2359 SwitchByteSwapCode();
2364 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2366 // end of reversed endian group
2367 gdcmDebugMacro( "End of reversed endian." );
2369 SwitchByteSwapCode();
2371 else if (group == 0xfeff && elem == 0xdde0)
2373 // reversed Sequence Terminator found
2374 // probabely a bug in the header !
2375 // Do what you want, it breaks !
2377 //SwitchByteSwapCode();
2378 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2383 else if (group == 0xfffe && elem == 0xe0dd)
2385 gdcmDebugMacro( "Straight Sequence Terminator." );
2390 * \brief Group 0002 is always coded Little Endian
2391 * whatever Transfer Syntax is
2394 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2396 // Endian reversion.
2397 // Some files contain groups of tags with reversed endianess.
2399 Group0002Parsed = true;
2400 // we just came out of group 0002
2401 // if Transfer Syntax is Big Endian we have to change CheckSwap
2403 std::string ts = GetTransferSyntax();
2404 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2406 // Group 0002 is always 'Explicit ...'
2407 // even when Transfer Syntax says 'Implicit ..."
2409 if ( s == TS::ImplicitVRLittleEndian
2411 s == TS::ImplicitVRBigEndianPrivateGE
2414 Filetype = ImplicitVR;
2417 // FIXME Strangely, this works with
2418 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2420 // --> Probabely normal, since we considered we never have
2421 // to trust manufacturers.
2422 // (we often find 'Implicit VR' tag,
2423 // even when Transfer Syntax tells us it's Explicit ...
2425 // NEVER trust the meta elements!
2426 // (see what ezDICOM does ...)
2429 if ( s == TS::ExplicitVRBigEndian )
2431 gdcmDebugMacro("Transfer Syntax Name = ["
2432 << GetTransferSyntaxName() << "]" );
2433 SwitchByteSwapCode();
2434 group = SwapShort(group);
2435 elem = SwapShort(elem);
2438 //-- Broken ACR may start with a Shadow Group --
2439 // worse : some ACR-NEMA like files start 00028 group ?!?
2440 if ( !( (group >= 0x0001 && group <= 0x0008) || group == 0x0028 ) )
2442 // We trust what we see.
2443 SwitchByteSwapCode();
2444 group = SwapShort(group);
2445 elem = SwapShort(elem);
2446 // not what we where told (by meta elements) !
2447 gdcmDebugMacro("Transfer Syntax Name = ["
2448 << GetTransferSyntaxName() << "]" );
2451 /// \todo find a trick to warn user and stop processing
2453 if ( s == TS::DeflatedExplicitVRLittleEndian)
2455 gdcmWarningMacro("Transfer Syntax ["
2456 << GetTransferSyntaxName() << "] :"
2457 << " not yet dealt with ");
2461 // The following shouldn't occur very often
2462 // Let's check at the very end.
2464 if ( ts == GDCM_UNKNOWN )
2466 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2470 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2472 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2478 //-----------------------------------------------------------------------------
2481 //-----------------------------------------------------------------------------
2482 } // end namespace gdcm