1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2007/05/23 14:18:09 $
7 Version: $Revision: 1.358 $
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
76 * \brief Canonical destructor.
78 Document::~Document ()
83 //-----------------------------------------------------------------------------
86 * \brief Loader. use SetLoadMode(), SetFileName() before !
87 * @return false if file cannot be open or no swap info was found,
88 * or no tag was found.
90 bool Document::Load( )
92 if ( GetFileName() == "" )
94 gdcmWarningMacro( "Use SetFileName, before !" );
97 return DoTheLoadingDocumentJob( );
101 //#ifndef GDCM_LEGACY_REMOVE
103 * \brief Loader. (DEPRECATED : not to break the API)
104 * @param fileName 'Document' (File or DicomDir) to be open for parsing
105 * @return false if file cannot be open or no swap info was found,
106 * or no tag was found.
109 bool Document::Load( std::string const &fileName )
112 return DoTheLoadingDocumentJob( );
118 * \brief Performs the Loading Job (internal use only)
119 * @return false if file cannot be open or no swap info was found,
120 * or no tag was found.
122 bool Document::DoTheLoadingDocumentJob( )
124 if ( ! IsDocumentModified ) // Nothing to do !
132 // warning already performed in OpenFile()
137 Group0002Parsed = false;
139 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
141 // Computes the total length of the file
142 Fp->seekg(0, std::ios::end); // Once per Document !
143 long lgt = Fp->tellg(); // Once per Document !
144 Fp->seekg(0, std::ios::beg); // Once per Document !
146 // CheckSwap returns a boolean
147 // (false if no swap info of any kind was found)
150 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
151 << Filename.c_str());
156 long beg = Fp->tellg(); // just after DICOM preamble (if any)
158 lgt -= beg; // remaining length to parse
161 // Loading is done during parsing
162 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
166 gdcmErrorMacro( "No tag in internal hash table for: "
167 << Filename.c_str());
171 IsDocumentAlreadyLoaded = true;
173 //Fp->seekg(0, std::ios::beg); // Once per Document!
175 // Load 'non string' values
177 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
178 if ( PhotometricInterpretation == "PALETTE COLOR " )
181 // Probabely this line should be outside the 'if'
182 // Try to find an image sample holding a 'gray LUT'
183 LoadEntryBinArea(0x0028,0x1200); // gray LUT
186 /// --> FIXME : The difference between BinEntry and DataEntry
187 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
188 /// --> Old comment restored on purpose.
189 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
190 /// --> had absolutely no meaning.
191 /// --> The whole comment will be removed when the stuff is cleaned !
193 /// The tags refered by the three following lines used to be CORRECTLY
194 /// defined as having an US Value Representation in the public
195 /// dictionary. BUT the semantics implied by the three following
196 /// lines state that the corresponding tag contents are in fact
197 /// the ones of a BinEntry.
198 /// In order to fix things "Quick and Dirty" the dictionary was
199 /// altered on PURPOSE but now contains a WRONG value.
200 /// In order to fix things and restore the dictionary to its
201 /// correct value, one needs to decide of the semantics by deciding
202 /// whether the following tags are either :
203 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
204 /// also used as BinEntry, which requires the proper conversion,
205 /// - OW, and hence loaded as BinEntry, but afterwards also used
206 /// as ValEntry, which requires the proper conversion.
208 // --> OB (byte aray) or OW (short int aray)
209 // The actual VR has to be deduced from other entries.
210 // Our way of loading them may fail in some cases :
211 // We must or not SwapByte depending on other field values.
213 LoadEntryBinArea(0x0028,0x1201); // R LUT
214 LoadEntryBinArea(0x0028,0x1202); // G LUT
215 LoadEntryBinArea(0x0028,0x1203); // B LUT
217 // Segmented Red Palette Color LUT Data
218 LoadEntryBinArea(0x0028,0x1221);
219 // Segmented Green Palette Color LUT Data
220 LoadEntryBinArea(0x0028,0x1222);
221 // Segmented Blue Palette Color LUT Data
222 LoadEntryBinArea(0x0028,0x1223);
225 //FIXME later : how to use it?
226 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
229 SQItem *sqi= modLutSeq->GetFirstSQItem();
232 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
233 if ( dataEntry != 0 )
235 if ( dataEntry->GetLength() != 0 )
237 // FIXME : CTX dependent means : contexted dependant.
238 // see upper comment.
239 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
245 // Force Loading some more elements if user asked to.
247 GDCM_NAME_SPACE::DocEntry *d;
248 for (ListElements::iterator it = UserForceLoadList.begin();
249 it != UserForceLoadList.end();
252 gdcmDebugMacro( "Force Load " << std::hex
253 << (*it).Group << "|" <<(*it).Elem );
255 d = GetDocEntry( (*it).Group, (*it).Elem);
259 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
260 << (*it).Group <<"|"<< (*it).Elem
261 << " that doesn't exist" );
265 LoadDocEntry(d, true);
270 // ----------------------------
271 // Specific code to allow gdcm to read ACR-LibIDO formated images
272 // Note: ACR-LibIDO is an extension of the ACR standard that was
273 // used at CREATIS. For the time being (say a couple of years)
274 // we keep this kludge to allow CREATIS users
275 // reading their old images.
277 // if recognition code tells us we deal with a LibIDO image
278 // we switch lineNumber and columnNumber
281 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
282 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
283 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
284 // with "little-endian strings"
286 Filetype = ACR_LIBIDO;
287 std::string rows = GetEntryString(0x0028, 0x0010);
288 std::string columns = GetEntryString(0x0028, 0x0011);
289 SetEntryString(columns, 0x0028, 0x0010);
290 SetEntryString(rows , 0x0028, 0x0011);
292 // --- End of ACR-LibIDO kludge ---
298 * \brief Adds a new element we want to load anyway
299 * @param group Group number of the target tag.
300 * @param elem Element number of the target tag.
302 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
307 UserForceLoadList.push_back(el);
310 * \brief Get the public dictionary used
312 Dict *Document::GetPubDict()
318 * \brief Get the shadow dictionary used
320 Dict *Document::GetShaDict()
326 * \brief Set the shadow dictionary used
327 * @param dict dictionary to use in shadow
329 bool Document::SetShaDict(Dict *dict)
336 * \brief Set the shadow dictionary used
337 * @param dictName name of the dictionary to use in shadow
339 bool Document::SetShaDict(DictKey const &dictName)
341 RefShaDict = Global::GetDicts()->GetDict(dictName);
346 * \brief This predicate tells us whether or not the current Document
347 * was properly parsed and contains at least *one* Dicom Element
348 * (and nothing more, sorry).
349 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
352 bool Document::IsParsable()
354 if ( Filetype == Unknown )
356 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
362 gdcmWarningMacro( "No tag in internal hash table.");
369 * \brief This predicate tells us whether or not the current Document
370 * was properly parsed and contains at least *one* Dicom Element
371 * (and nothing more, sorry).
372 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
375 bool Document::IsReadable()
381 * \brief Predicate for dicom version 3 file.
382 * @return True when the file is a dicom version 3.
384 bool Document::IsDicomV3()
386 // Checking if Transfer Syntax exists is enough
387 // Anyway, it's too late check if the 'Preamble' was found ...
388 // And ... would it be a rich idea to check ?
389 // (some 'no Preamble' DICOM images exist !)
390 return GetDocEntry(0x0002, 0x0010) != NULL;
394 * \brief Predicate for Papyrus file
395 * Dedicated to whomsoever it may concern
396 * @return True when the file is a Papyrus file.
398 bool Document::IsPapyrus()
400 // check for Papyrus private Sequence
401 DocEntry *e = GetDocEntry(0x0041, 0x1050);
404 // check if it's actually a Sequence
405 if ( !dynamic_cast<SeqEntry*>(e) )
411 * \brief returns the File Type
412 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
413 * @return the FileType code
415 FileType Document::GetFileType()
421 * \brief Accessor to the Transfer Syntax (when present) of the
422 * current document (it internally handles reading the
423 * value from disk when only parsing occured).
424 * @return The encountered Transfer Syntax of the current document, if DICOM.
425 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
427 std::string Document::GetTransferSyntax()
429 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
435 // The entry might be present but not loaded (parsing and loading
436 // happen at different stages): try loading and proceed with check...
439 // (parsing and loading happen at the very same stage!)
440 //LoadDocEntrySafe(entry); //JPRx
441 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
443 std::string transfer = dataEntry->GetString();
444 // The actual transfer (as read from disk) might be padded. We
445 // first need to remove the potential padding. We can make the
446 // weak assumption that padding was not executed with digits...
447 if ( transfer.length() == 0 )
449 // for brain damaged headers
450 gdcmWarningMacro( "Transfer Syntax has length = 0.");
453 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
455 transfer.erase(transfer.length()-1, 1);
456 if ( transfer.length() == 0 )
458 // for brain damaged headers
459 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
469 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
470 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
472 std::string Document::GetTransferSyntaxName()
474 // use the TS (TS : Transfer Syntax)
475 std::string transferSyntax = GetEntryString(0x0002,0x0010);
477 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
479 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
480 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
481 return "Uncompressed ACR-NEMA";
483 if ( transferSyntax == GDCM_UNFOUND )
485 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
486 return "Uncompressed ACR-NEMA";
489 // we do it only when we need it
490 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
492 // Global::GetTS() is a global static you shall never try to delete it!
496 // --------------- Swap Code ------------------
498 * \brief Swaps the bytes so they agree with the processor order
499 * @return The properly swaped 16 bits integer.
501 uint16_t Document::SwapShort(uint16_t a)
503 if ( SwapCode == 4321 || SwapCode == 2143 )
505 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
507 a = ( a << 8 ) | ( a >> 8 );
513 * \brief Swaps back the bytes of 4-byte long integer accordingly to
515 * @return The properly swaped 32 bits integer.
517 uint32_t Document::SwapLong(uint32_t a)
524 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
525 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
527 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
528 ((a>>8) & 0x0000ff00) | (a>>24) );
531 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
532 a=( (a<<16) | (a>>16) );
535 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
538 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
545 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
547 * @return The properly swaped 64 bits double.
549 double Document::SwapDouble(double a)
553 // There were no 'double' at ACR-NEMA time.
554 // We just have to deal with 'straight Little Endian' and
555 // 'straight Big Endian'
560 char *beg = (char *)&a;
563 for (unsigned int i = 0; i<7; i++)
574 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
581 // -----------------File I/O ---------------
583 * \brief Tries to open the file \ref Document::Filename and
584 * checks the preamble when existing,
585 * or if the file starts with an ACR-NEMA look-like element.
586 * @return The FILE pointer on success, 0 on failure.
588 std::ifstream *Document::OpenFile()
590 HasDCMPreamble = false;
591 if (Filename.length() == 0)
598 gdcmDebugMacro( "File already open: " << Filename.c_str());
602 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
605 // Don't user gdcmErrorMacro :
606 // a spurious message will appear when you use, for instance
607 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
608 // to create outputFileName.
610 // FIXME : if the upper comment is still usefull
611 // --> the constructor is not so good ...
613 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
617 //exit(1); // No function is allowed to leave the application instead
618 // of warning the caller
622 Fp->read((char*)&zero, (size_t)2);
630 Fp->seekg(126L, std::ios::cur); // Once per Document
631 char dicm[4]; // = {' ',' ',' ',' '};
632 Fp->read(dicm, (size_t)4);
639 if ( memcmp(dicm, "DICM", 4) == 0 )
641 HasDCMPreamble = true;
645 //-- Broken ACR or DICOM (?) with no Preamble; may start with a Shadow Group --
646 // FIXME : We cannot be sure the preable is only zeroes..
647 // (see ACUSON-24-YBR_FULL-RLE.dcm )
649 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
650 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
651 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
652 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 ||
653 zero == 0x0028 || 0x2800 // worse : some ACR-NEMA like files
654 // start 00028 group ?!?
657 std::string msg = Util::Format(
658 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
659 // FIXME : is it a Warning message, or a Debug message?
660 gdcmWarningMacro( msg.c_str() );
664 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
666 // Don't user Warning nor Error, not to pollute the output
667 // while directory recursive parsing ...
668 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
669 << Filename.c_str());
674 * \brief closes the file
675 * @return TRUE if the close was successfull
677 bool Document::CloseFile()
689 * \brief Writes in a file all the Entries (Dicom Elements)
690 * @param fp file pointer on an already open file (actually: Output File Stream)
691 * @param filetype Type of the File to be written
692 * (ACR-NEMA, ExplicitVR, ImplicitVR)
694 void Document::WriteContent(std::ofstream *fp, FileType filetype)
696 // Skip if user wants to write an ACR-NEMA file
698 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
699 filetype == JPEG || filetype == JPEG2000 )
701 // writing Dicom File Preamble
702 char filePreamble[128];
703 memset(filePreamble, 0, 128);
704 fp->write(filePreamble, 128);
705 fp->write("DICM", 4);
708 * \todo rewrite later, if really usefull
709 * - 'Group Length' element is optional in DICOM
710 * - but un-updated odd groups lengthes can causes pb
713 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
714 * UpdateGroupLength(false,filetype);
715 * if ( filetype == ACR)
716 * UpdateGroupLength(true,ACR);
718 * --> Computing group length for groups with embeded Sequences
719 * --> was too much tricky / we were [in a hurry / too lazy]
720 * --> We don't write the element 0x0000 (group length)
723 ElementSet::WriteContent(fp, filetype); // This one is recursive
726 // -----------------------------------------
729 * \brief Loads (from disk) the element content
730 * when a string is not suitable
731 * @param group group number of the Entry
732 * @param elem element number of the Entry
734 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
736 // Search the corresponding DocEntry
737 DocEntry *docEntry = GetDocEntry(group, elem);
740 gdcmDebugMacro(std::hex << group << "|" << elem
741 << " doesn't exist" );
744 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
747 gdcmWarningMacro(std::hex << group << "|" << elem
748 << " is NOT a DataEntry");
751 LoadEntryBinArea(dataEntry);
755 * \brief Loads (from disk) the element content
756 * when a string is not suitable
757 * @param entry Entry whose binArea is going to be loaded
759 void Document::LoadEntryBinArea(DataEntry *entry)
761 if( entry->GetBinArea() )
768 //size_t o =(size_t)entry->GetOffset();
769 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
771 size_t l = entry->GetLength();
772 uint8_t *data = new uint8_t[l];
775 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
776 << std::hex << entry->GetGroup()
777 << "|" << entry->GetElement() );
782 Fp->read((char*)data, l);
783 if ( Fp->fail() || Fp->eof() )
786 entry->SetState(DataEntry::STATE_UNREAD);
790 // Swap the data content if necessary
792 unsigned short vrLgth =
793 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
795 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
796 // if( entry->GetVR() == "OW" )
807 uint16_t *data16 = (uint16_t *)data;
808 for(i=0;i<l/vrLgth;i++)
809 data16[i] = SwapShort(data16[i]);
814 uint32_t *data32 = (uint32_t *)data;
815 for(i=0;i<l/vrLgth;i++)
816 data32[i] = SwapLong(data32[i]);
821 double *data64 = (double *)data;
822 for(i=0;i<l/vrLgth;i++)
823 data64[i] = SwapDouble(data64[i]);
828 entry->SetBinArea(data);
830 if ( openFile ) // The file is left in the state (open/close) it was at entrance
835 * \brief Loads the element while preserving the current
836 * underlying file position indicator as opposed to
837 * LoadDocEntry that modifies it
838 * \note seems to be unused!.
839 * @param entry DocEntry whose value will be loaded.
841 //void Document::LoadDocEntrySafe(DocEntry *entry)
845 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
846 // LoadDocEntry(entry);
847 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
852 * \brief Compares two documents, according to \ref DicomDir rules
853 * \warning Does NOT work with ACR-NEMA files
854 * \todo Find a trick to solve the pb (use RET fields ?)
855 * @param document to compare with current one
856 * @return true if 'smaller'
858 bool Document::operator<(Document &document)
861 std::string s1 = GetEntryString(0x0010,0x0010);
862 std::string s2 = document.GetEntryString(0x0010,0x0010);
874 s1 = GetEntryString(0x0010,0x0020);
875 s2 = document.GetEntryString(0x0010,0x0020);
886 // Study Instance UID
887 s1 = GetEntryString(0x0020,0x000d);
888 s2 = document.GetEntryString(0x0020,0x000d);
899 // Serie Instance UID
900 s1 = GetEntryString(0x0020,0x000e);
901 s2 = document.GetEntryString(0x0020,0x000e);
916 //-----------------------------------------------------------------------------
920 * \brief Reads a given length of bytes
921 * (in order to avoid to many CPU time consuming fread-s)
922 * @param l length to read
924 void Document::ReadBegBuffer(size_t l)
927 Fp->read (BegBuffer, (size_t)l);
930 throw FormatError( "Document::ReadBegBuffer()", " file error." );
934 throw FormatError( "Document::ReadBegBuffer()", "EOF." );
936 PtrBegBuffer = BegBuffer;
937 CurrentOffsetPosition+=l;
940 * \brief Reads a supposed to be 16 Bits integer
941 * (swaps it depending on processor endianness)
944 uint16_t Document::ReadInt16()
948 Fp->read ((char*)&g, (size_t)2);
951 throw FormatError( "Document::ReadInt16()", " file error." );
955 throw FormatError( "Document::ReadInt16()", "EOF." );
962 * \brief Gets from BegBuffer a supposed to be 16 Bits integer
963 * (swaps it depending on processor endianness)
966 uint16_t Document::GetInt16()
968 uint16_t g = *((uint16_t*)PtrBegBuffer);
974 * \brief Reads a supposed to be 32 Bits integer
975 * (swaps it depending on processor endianness)
978 uint32_t Document::ReadInt32()
982 Fp->read ((char*)&g, (size_t)4);
985 throw FormatError( "Document::ReadInt32()", " file error." );
989 throw FormatError( "Document::ReadInt32()", "EOF." );
996 * \brief Gets from BegBuffer a supposed to be 32 Bits integer
997 * (swaps it depending on processor endianness)
1000 uint32_t Document::GetInt32()
1002 uint32_t g = *((uint32_t*)PtrBegBuffer);
1009 * \brief Re-computes the length of the Dicom group 0002.
1011 int Document::ComputeGroup0002Length( )
1016 int groupLength = 0;
1017 bool found0002 = false;
1019 // for each zero-level Tag in the DCM Header
1020 DocEntry *entry = GetFirstEntry();
1023 gr = entry->GetGroup();
1029 if ( entry->GetElement() != 0x0000 )
1031 vr = entry->GetVR();
1033 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
1034 // (no SQ, OW, UT in group 0x0002;)
1037 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
1040 groupLength += 2 + 2 + 4 + entry->GetLength();
1043 else if (found0002 )
1046 entry = GetNextEntry();
1052 * \brief CallStartMethod
1054 void Document::CallStartMethod()
1058 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1062 * \brief CallProgressMethod
1064 void Document::CallProgressMethod()
1066 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1070 * \brief CallEndMethod
1072 void Document::CallEndMethod()
1075 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1078 //-----------------------------------------------------------------------------
1081 * \brief Loads all the needed Dictionaries
1082 * \warning NOT end user intended method !
1084 void Document::Initialize()
1086 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1092 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1093 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1094 * @param offset start of parsing
1095 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1096 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1098 void Document::ParseDES(DocEntrySet *set, long offset,
1099 long l_max, bool delim_mode)
1101 DocEntry *newDocEntry;
1102 DataEntry *newDataEntry;
1103 SeqEntry *newSeqEntry;
1105 bool used; // will be set to false when something wrong happens to an Entry.
1106 // (Entry will then be deleted)
1107 bool delim_mode_intern = delim_mode;
1109 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1110 << " at offset " << std::hex << "0x(" << offset << ")" );
1114 ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1115 /// Probabely a bug in gdcm code somwhere (some memory erased ?)
1117 // Uncomment to track the bug
1119 if( Debug::GetDebugFlag() )
1120 std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1121 << std::hex << " 0x(" <<(long)(Fp->tellg()) << ")" << std::endl;
1124 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1125 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1126 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1131 newDocEntry = ReadNextDocEntry( );
1138 // Uncoment this cerr line to be able to 'follow' the DocEntries
1139 // when something *very* strange happens
1140 if( Debug::GetDebugFlag() )
1141 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1143 // an Item Starter found elsewhere but in the first position
1144 // of a SeqEntry means previous entry was a Sequence
1145 // but we didn't get it (private Sequence + Implicit VR)
1146 // we have to backtrack.
1147 if ( !first && newDocEntry->IsItemStarter() )
1149 // Debug message within the method !
1150 newDocEntry = Backtrack(newDocEntry);
1154 PreviousDocEntry = newDocEntry;
1158 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1162 //////////////////////////// DataEntry
1164 //vr = newDocEntry->GetVR(); // useless ?
1166 if ( !set->AddEntry( newDataEntry ) )
1168 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1169 << newDataEntry->GetKey()
1170 << " (at offset : 0x("
1171 << newDataEntry->GetOffset() << ") )" );
1176 newDataEntry->Delete();
1177 // Load only if we can add (not a duplicate key)
1178 LoadDocEntry( newDataEntry );
1180 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1182 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1184 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1186 std::string strLgrGroup = newDataEntry->GetString();
1189 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1191 lgrGroup = atoi(strLgrGroup.c_str());
1192 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1193 RemoveEntry( newDocEntry ); // Remove and delete
1200 bool delimitor = newDataEntry->IsItemDelimitor();
1201 bool outOfBounds = false;
1203 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1206 // 'and then', 'or else' don't exist in C++ :-(
1207 // if ( (delimitor) ||
1208 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1210 if ( delimitor || outOfBounds )
1213 newDocEntry->Delete();
1217 // Just to make sure we are at the beginning of next entry.
1218 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1222 /////////////////////// SeqEntry : VR = "SQ"
1224 unsigned long l = newDocEntry->GetReadLength();
1225 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1227 if ( l == 0xffffffff )
1229 delim_mode_intern = true;
1233 delim_mode_intern = false;
1237 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1239 // User asked to skip SeQuences *only* if they belong to Shadow Group
1240 if ( newDocEntry->GetGroup()%2 != 0 )
1242 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1243 newDocEntry->Delete(); // Delete, not in the set
1247 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1249 // User asked to skip *any* SeQuence
1250 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1251 newDocEntry->Delete(); // Delete, not in the set
1254 // delay the dynamic cast as late as possible
1255 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1257 // no other way to create the Delimitor ...
1258 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1260 // At the top of the hierarchy, stands a Document. When "set"
1261 // is a Document, then we are building the first depth level.
1262 // Hence the SeqEntry we are building simply has a depth
1264 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1266 newSeqEntry->SetDepthLevel( 1 );
1268 // But when "set" is already a SQItem, we are building a nested
1269 // sequence, and hence the depth level of the new SeqEntry
1270 // we are building, is one level deeper:
1272 // time waste hunting
1273 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1275 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1279 { // Don't try to parse zero-length sequences
1281 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1282 << " at offset 0x(" << std::hex
1283 << newDocEntry->GetOffset() << ")");
1285 ParseSQ( newSeqEntry,
1286 newDocEntry->GetOffset(),
1287 l, delim_mode_intern);
1289 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1291 if ( !set->AddEntry( newSeqEntry ) )
1293 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1294 << newSeqEntry->GetKey()
1295 << " (at offset : 0x("
1296 << newSeqEntry->GetOffset() << ") )" );
1301 newDocEntry->Delete();
1304 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1306 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1307 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1311 newDocEntry->Delete();
1314 } // end SeqEntry : VR = "SQ"
1318 newDocEntry->Delete();
1322 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1326 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1327 * @return parsed length for this level
1329 void Document::ParseSQ( SeqEntry *seqEntry,
1330 long offset, long l_max, bool delim_mode)
1332 int SQItemNumber = 0;
1334 long offsetStartCurrentSQItem = offset;
1338 // the first time, we read the fff0,e000 of the first SQItem
1339 DocEntry *newDocEntry = ReadNextDocEntry();
1343 gdcmWarningMacro("in ParseSQ : should never get here!");
1348 if ( newDocEntry->IsSequenceDelimitor() )
1350 seqEntry->SetDelimitationItem( newDocEntry );
1351 newDocEntry->Delete();
1355 else // ! delim_mode
1357 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1359 newDocEntry->Delete();
1363 // create the current SQItem
1364 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1365 unsigned int l = newDocEntry->GetReadLength();
1367 if ( l == 0xffffffff )
1376 // fill up the current SQItem, starting at the beginning of fff0,e000
1378 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); // Once per SQItem
1379 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1380 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1382 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1384 newDocEntry->Delete();
1386 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1387 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1395 * \brief When a private Sequence + Implicit VR is encountered
1396 * we cannot guess it's a Sequence till we find the first
1397 * Item Starter. We then backtrack to do the job.
1398 * @param docEntry Item Starter that warned us
1400 DocEntry *Document::Backtrack(DocEntry *docEntry)
1402 // delete the Item Starter, built erroneously out of any Sequence
1403 // it's not yet in the HTable/chained list
1406 // Get all info we can from PreviousDocEntry
1407 uint16_t group = PreviousDocEntry->GetGroup();
1408 uint16_t elem = PreviousDocEntry->GetElement();
1409 uint32_t lgt = PreviousDocEntry->GetLength();
1410 long offset = PreviousDocEntry->GetOffset();
1412 gdcmDebugMacro( "Backtrack :" << std::hex << group
1414 << " at offset 0x(" <<offset << ")" );
1415 RemoveEntry( PreviousDocEntry );
1417 // forge the Seq Entry
1418 DocEntry *newEntry = NewSeqEntry(group, elem);
1419 newEntry->SetLength(lgt);
1420 newEntry->SetOffset(offset);
1422 // Move back to the beginning of the Sequence
1424 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1429 * \brief Loads (or not) the element content depending if its length exceeds
1430 * or not the value specified with Document::SetMaxSizeLoadEntry()
1431 * @param entry Header Entry (Dicom Element) to be dealt with
1432 * @param forceLoad whether you want to force loading of 'long' elements
1434 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1436 uint16_t group = entry->GetGroup();
1437 uint16_t elem = entry->GetElement();
1438 const VRKey &vr = entry->GetVR();
1439 uint32_t length = entry->GetLength();
1441 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1443 // A SeQuence "contains" a set of Elements.
1444 // (fffe e000) tells us an Element is beginning
1445 // (fffe e00d) tells us an Element just ended
1446 // (fffe e0dd) tells us the current SeQuence just ended
1447 // (fffe 0000) is an 'impossible' tag value,
1448 // found in MR-PHILIPS-16-Multi-Seq.dcm
1450 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1452 // NO more value field for SQ !
1456 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1462 // When the length is zero things are easy:
1465 dataEntryPtr->SetBinArea(NULL,true);
1469 // The elements whose length is bigger than the specified upper bound
1474 if (length > MaxSizeLoadEntry)
1476 dataEntryPtr->SetBinArea(NULL,true);
1477 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1479 // to be sure we are at the end of the value ...
1480 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1481 // std::ios::beg); //JPRx
1486 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1487 /// + a ForceLoad call on the +/- 20 'usefull' fields
1488 /// Allow user to tell the fields he wants to ForceLoad
1489 /// during initial stage.
1490 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1491 /// + a method that load *everything* that's not yet loaded
1493 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1497 * \brief Find the value Length of the passed Doc Entry
1498 * @param entry Header Entry whose length of the value shall be loaded.
1500 void Document::FindDocEntryLength( DocEntry *entry )
1501 throw ( FormatError )
1503 const VRKey &vr = entry->GetVR();
1506 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1508 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1511 // The following reserved two bytes (see PS 3.5-2003, section
1512 // "7.1.2 Data element structure with explicit vr", p 27) must be
1513 // skipped before proceeding on reading the length on 4 bytes.
1515 //Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1516 uint32_t length32 = ReadInt32(); // Once per OW,OB,SQ DocEntry
1517 CurrentOffsetPosition+=4;
1518 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1523 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1525 catch ( FormatUnexpected )
1527 // Computing the length failed (this happens with broken
1528 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1529 // chance to get the pixels by deciding the element goes
1530 // until the end of the file. Hence we artificially fix the
1531 // the length and proceed.
1532 gdcmWarningMacro( " Computing the length failed for " <<
1533 entry->GetKey() <<" in " <<GetFileName());
1535 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1536 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1538 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1539 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1541 entry->SetReadLength(lengthUntilEOF);
1542 entry->SetLength(lengthUntilEOF);
1545 entry->SetReadLength(lengthOB);
1546 entry->SetLength(lengthOB);
1549 FixDocEntryFoundLength(entry, length32);
1553 // Length is encoded on 2 bytes.
1554 //length16 = ReadInt16();
1555 length16 = GetInt16();
1557 // 0xffff means that we deal with 'No Length' Sequence
1558 // or 'No Length' SQItem
1559 if ( length16 == 0xffff)
1563 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1568 // Either implicit VR or a non DICOM conformal (see note below) explicit
1569 // VR that ommited the VR of (at least) this element. Farts happen.
1570 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1571 // on Data elements "Implicit and Explicit VR Data Elements shall
1572 // not coexist in a Data Set and Data Sets nested within it".]
1573 // Length is on 4 bytes.
1575 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1576 // even if Transfer Syntax is 'Implicit VR ...'
1577 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1578 // where Group 0x0002 is *also* encoded in Implicit VR !
1580 FixDocEntryFoundLength( entry, GetInt32() /*ReadInt32()*/ );
1586 * \brief Find the Length till the next sequence delimiter
1587 * \warning NOT end user intended method !
1590 uint32_t Document::FindDocEntryLengthOBOrOW()
1591 throw( FormatUnexpected )
1593 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1595 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1597 bool foundSequenceDelimiter = false;
1598 uint32_t totalLength = 0;
1600 while ( !foundSequenceDelimiter )
1607 //group = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1608 //elem = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1609 ReadBegBuffer(4); // Once per fragment (if any) of OB,OW DataElements
1611 catch ( FormatError )
1613 throw FormatError("Unexpected end of file encountered during ",
1614 "Document::FindDocEntryLengthOBOrOW()");
1619 // We have to decount the group and element we just read
1621 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1624 "Neither an Item tag nor a Sequence delimiter tag on :"
1625 << std::hex << group << " , " << elem
1628 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1629 throw FormatUnexpected(
1630 "Neither an Item tag nor a Sequence delimiter tag.");
1632 if ( elem == 0xe0dd )
1634 foundSequenceDelimiter = true;
1636 uint32_t itemLength = ReadInt32(); // Once per fragment (if any) of OB,OW DataElements
1637 // We add 4 bytes since we just read the ItemLength with ReadInt32
1638 totalLength += itemLength + 4;
1639 SkipBytes(itemLength);
1641 if ( foundSequenceDelimiter )
1646 Fp->seekg( positionOnEntry, std::ios::beg); // Only once for OB,OW DataElements
1651 * \brief Find the Value Representation of the current Dicom Element.
1652 * @return Value Representation of the current Entry
1654 VRKey Document::FindDocEntryVR()
1656 if ( Filetype != ExplicitVR )
1658 return GDCM_VRUNKNOWN;
1661 // Delimiters (0xfffe), are not explicit VR ...
1662 if ( CurrentGroup == 0xfffe )
1663 return GDCM_VRUNKNOWN;
1665 //long positionOnEntry;
1666 //if( Debug::GetWarningFlag() )
1667 // positionOnEntry = Fp->tellg(); // Only in Warning Mode
1669 // Warning: we believe this is explicit VR (Value Representation) because
1670 // we used a heuristic that found "UL" in the first tag and/or
1671 // 'Transfer Syntax' told us it is.
1672 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1673 // In some cases one finds implicit VR tags mixed within an explicit VR file
1675 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1677 // Hence we make sure the present tag is in explicit VR and try to fix things
1678 // if it happens not to be the case.
1681 //Fp->read(&(vr[0]),(size_t)2);
1682 vr[0] = *PtrBegBuffer++;
1683 vr[1] = *PtrBegBuffer++;
1685 //if ( !CheckDocEntryVR(vr) ) // avoid useless function call
1686 if ( !Global::GetVR()->IsValidVR(vr) )
1689 // std::cout << "================================================================Unknown VR"
1690 << std::hex << "0x("
1691 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1692 << ")" << "for : " << CurrentGroup
1693 << " at offset : 0x(" << positionOnEntry << ")"
1696 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1697 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1699 << " at offset : 0x(" << CurrentOffsetPosition-4<< ") for group " << CurrentGroup
1702 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1703 //Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1704 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1706 return GDCM_VRUNKNOWN;
1712 * \brief Check the correspondance between the VR of the header entry
1713 * and the taken VR. If they are different, the header entry is
1714 * updated with the new VR.
1715 * @param vr Dicom Value Representation
1716 * @return false if the VR is incorrect or if the VR isn't referenced
1717 * otherwise, it returns true
1719 bool Document::CheckDocEntryVR(const VRKey &vr)
1721 return Global::GetVR()->IsValidVR(vr);
1725 * \brief Skip a given Header Entry
1726 * @param entry entry to skip
1728 void Document::SkipDocEntry(DocEntry *entry)
1730 SkipBytes(entry->GetLength());
1734 * \brief Skips to the beginning of the next Header Entry
1735 * @param currentDocEntry entry to skip
1737 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1739 long l = currentDocEntry->GetReadLength();
1740 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1741 // ... but PMS imagers happen !
1743 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1744 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1746 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1751 * \brief When the length of an element value is obviously wrong (because
1752 * the parser went Jabberwocky) one can hope improving things by
1753 * applying some heuristics.
1754 * @param entry entry to check
1755 * @param foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)
1757 void Document::FixDocEntryFoundLength(DocEntry *entry,
1758 uint32_t foundLength)
1760 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1762 if ( foundLength == 0xffffffff)
1765 //entry->SetLength(foundLength);
1766 entry->SetLength(0);
1767 return; // return ASAP; don't waist time on useless tests
1770 uint16_t gr = entry->GetGroup();
1771 uint16_t elem = entry->GetElement();
1773 if ( foundLength % 2)
1775 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1776 << " in x(" << std::hex << gr << "," << elem <<")");
1779 //////// Fix for some naughty General Electric images.
1780 // Allthough not recent many such GE corrupted images are still present
1781 // on Creatis hard disks. Hence this fix shall remain when such images
1782 // are no longer in use (we are talking a few years, here)...
1783 // Note: XMedCon probably uses such a trick since it is able to read
1784 // those pesky GE images ...
1785 if ( foundLength == 13)
1787 // Only happens for this length !
1788 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1791 entry->SetReadLength(10); // a bug is to be fixed !?
1795 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1796 // Occurence of such images is quite low (unless one leaves close to a
1797 // 'Leonardo' source. Hence, one might consider commenting out the
1798 // following fix on efficiency reasons.
1799 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1801 // Ideally we should check we are in Explicit and double check
1802 // that VR=UL... this is done properly in gdcm2
1803 if( foundLength == 6 )
1805 gdcmWarningMacro( "Replacing Length from 6 into 4" );
1807 entry->SetReadLength(4); // a bug is to be fixed !
1809 else if ( foundLength%4 )
1811 gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1812 "The length of this tag seems to be wrong" );
1816 else if ( entry->GetVR() == "SQ" )
1818 foundLength = 0; // ReadLength is unchanged
1821 //////// We encountered a 'delimiter' element i.e. a tag of the form
1822 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1823 // taken into account.
1824 else if ( gr == 0xfffe )
1826 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1827 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1828 // causes extra troubles...
1829 if ( elem != 0x0000 )
1835 foundLength=12; // to skip the mess that follows this bugged Tag !
1838 entry->SetLength(foundLength);
1842 * \brief Apply some heuristics to predict whether the considered
1843 * element value contains/represents an integer or not.
1844 * @param entry The element value on which to apply the predicate.
1845 * @return The result of the heuristical predicate.
1847 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1849 uint16_t elem = entry->GetElement();
1850 uint16_t group = entry->GetGroup();
1851 const VRKey &vr = entry->GetVR();
1852 uint32_t length = entry->GetLength();
1854 // When we have some semantics on the element we just read, and if we
1855 // a priori know we are dealing with an integer, then we shall be
1856 // able to swap its element value properly.
1857 if ( elem == 0 ) // This is the group length of the group
1865 // Although this should never happen, still some images have a
1866 // corrupted group length [e.g. have a glance at offset x(8336) of
1867 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1868 // Since for dicom compliant and well behaved headers, the present
1869 // test is useless (and might even look a bit paranoid), when we
1870 // encounter such an ill-formed image, we simply display a warning
1871 // message and proceed on parsing (while crossing fingers).
1872 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1874 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1875 << std::hex << group << " , " << elem
1876 << ") -before- position x(" << filePosition << ")"
1877 << "lgt : " << length );
1881 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1889 * \brief Discover what the swap code is (among little endian, big endian,
1890 * bad little endian, bad big endian).
1892 * @return false when we are absolutely sure
1893 * it's neither ACR-NEMA nor DICOM
1894 * true when we hope ours assuptions are OK
1896 bool Document::CheckSwap()
1903 // First, compare HostByteOrder and NetworkByteOrder in order to
1904 // determine if we shall need to swap bytes (i.e. the Endian type).
1905 bool net2host = Util::IsCurrentProcessorBigEndian();
1907 // The easiest case is the one of a 'true' DICOM header, we just have
1908 // to look for the string "DICM" inside the file preamble.
1911 char *entCur = deb + 128;
1912 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1914 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1916 // Group 0002 should always be VR, and the first element 0000
1917 // Let's be carefull (so many wrong headers ...)
1918 // and determine the value representation (VR) :
1919 // Let's skip to the first element (0002,0000) and check there if we find
1920 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1921 // in which case we (almost) know it is explicit VR.
1922 // WARNING: if it happens to be implicit VR then what we will read
1923 // is the length of the group. If this ascii representation of this
1924 // length happens to be "UL" then we shall believe it is explicit VR.
1925 // We need to skip :
1926 // * the 128 bytes of File Preamble (often padded with zeroes),
1927 // * the 4 bytes of "DICM" string,
1928 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1929 // i.e. a total of 136 bytes.
1932 // group 0x0002 *is always* Explicit VR Sometimes,
1933 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1934 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1936 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1937 memcmp(entCur, "OB", (size_t)2) == 0 ||
1938 memcmp(entCur, "UI", (size_t)2) == 0 ||
1939 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1940 // when Write DCM *adds*
1942 // Use Document::dicom_vr to test all the possibilities
1943 // instead of just checking for UL, OB and UI !? group 0000
1945 Filetype = ExplicitVR;
1946 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1950 Filetype = ImplicitVR;
1951 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1952 << "Looks like a bugged Header!");
1955 // Here, we assume that the file IS kosher Dicom !
1956 // (The meta elements - group 0x0002 - ARE little endian !)
1960 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1965 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1968 // Position the file position indicator at first tag
1969 // (i.e. after the file preamble and the "DICM" string).
1971 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1972 CurrentOffsetPosition = 132;
1974 } // ------------------------------- End of DicomV3 ----------------
1976 // Alas, this is not a DicomV3 file and whatever happens there is no file
1977 // preamble. We can reset the file position indicator to where the data
1978 // is (i.e. the beginning of the file).
1980 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1982 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1983 CurrentOffsetPosition = 0;
1984 // Let's check 'No Preamble Dicom File' :
1985 // Should start with group 0x0002
1986 // and be Explicit Value Representation
1988 s16 = *((uint16_t *)(deb));
2001 if ( SwapCode != 0 )
2003 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2004 memcmp(entCur, "OB", (size_t)2) == 0 ||
2005 memcmp(entCur, "UI", (size_t)2) == 0 ||
2006 memcmp(entCur, "SH", (size_t)2) == 0 ||
2007 memcmp(entCur, "AE", (size_t)2) == 0 ||
2008 memcmp(entCur, "OB", (size_t)2) == 0 )
2010 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
2011 // Wait untill reading Transfer Syntax
2012 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
2016 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2018 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2019 // By clean we mean that the length of the first group is written down.
2020 // If this is the case and since the length of the first group HAS to be
2021 // four (bytes), then determining the proper swap code is straightforward.
2024 // We assume the array of char we are considering contains the binary
2025 // representation of a 32 bits integer. Hence the following dirty
2027 s32 = *((uint32_t *)(entCur));
2047 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2048 // It is time for despaired wild guesses.
2049 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2050 // i.e. the 'group length' element is not present :
2052 // check the supposed-to-be 'group number'
2053 // in ( 0x0001 .. 0x0008 )
2054 // to determine ' SwapCode' value .
2055 // Only 0 or 4321 will be possible
2056 // (no oportunity to check for the formerly well known
2057 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2058 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
2059 // the file IS NOT ACR-NEMA nor DICOM V3
2060 // Find a trick to tell it the caller...
2062 s16 = *((uint16_t *)(deb));
2064 gdcmDebugMacro("not a DicomV3 nor a 'clean' ACR/NEMA;"
2065 << " (->despaired wild guesses !)");
2094 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2102 * \brief Change the Byte Swap code.
2104 void Document::SwitchByteSwapCode()
2106 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2107 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2108 if ( SwapCode == 1234 )
2112 else if ( SwapCode == 4321 )
2116 else if ( SwapCode == 3412 )
2120 else if ( SwapCode == 2143 )
2124 gdcmDebugMacro( " Into: "<< SwapCode );
2128 * \brief during parsing, Header Elements too long are not loaded in memory
2129 * @param newSize new size
2131 void Document::SetMaxSizeLoadEntry(long newSize)
2137 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2139 MaxSizeLoadEntry = 0xffffffff;
2142 MaxSizeLoadEntry = newSize;
2146 * \brief Read the next tag WITHOUT loading it's value
2147 * (read the 'Group Number', the 'Element Number',
2148 * gets the Dict Entry
2149 * gets the VR, gets the length, gets the offset value)
2150 * @return On succes : the newly created DocEntry, NULL on failure.
2152 DocEntry *Document::ReadNextDocEntry()
2156 ReadBegBuffer(8); // Avoid to many time consuming freads
2157 //CurrentGroup = ReadInt16();
2158 //CurrentElem = ReadInt16();
2160 catch ( FormatError )
2162 // We reached the EOF (or an error occured) therefore
2163 // header parsing has to be considered as finished.
2167 CurrentGroup = GetInt16();
2168 CurrentElem = GetInt16();
2170 // In 'true DICOM' files Group 0002 is always little endian
2171 if ( HasDCMPreamble )
2173 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2174 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2176 // Sometimes file contains groups of tags with reversed endianess.
2177 HandleBrokenEndian(CurrentGroup, CurrentElem);
2180 VRKey vr = FindDocEntryVR();
2183 if ( vr == GDCM_VRUNKNOWN )
2185 if ( CurrentElem == 0x0000 ) // Group Length
2187 realVR = "UL"; // must be UL
2189 else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2194 // Commented out in order not to generate 'Shadow Groups' where some
2195 // Data Elements are Explicit VR and some other ones Implicit VR
2196 // (Stupid MatLab DICOM Reader couldn't read gdcm-written images)
2198 else if (CurrentGroup%2 == 1 &&
2199 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2201 // DICOM PS 3-5 7.8.1 a) states that those
2202 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2208 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2211 realVR = dictEntry->GetVR();
2212 dictEntry->Unregister(); // GetDictEntry registered it
2218 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2221 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2225 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2226 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2229 if ( vr == GDCM_VRUNKNOWN )
2231 if ( Filetype == ExplicitVR )
2233 // We thought this was explicit VR, but we end up with an
2234 // implicit VR tag. Let's backtrack.
2236 //if ( newEntry->GetGroup() != 0xfffe )
2237 if (CurrentGroup != 0xfffe)
2239 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2241 gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2242 << offset << ") should be Explicit VR");
2245 newEntry->SetImplicitVR();
2250 FindDocEntryLength(newEntry);
2252 catch ( FormatError )
2259 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2264 * \brief Handle broken private tag from Philips NTSCAN
2265 * where the endianess is being switched to BigEndian
2266 * for no apparent reason
2269 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2271 // for strange PMS Gyroscan Intera images
2272 // Item 'starter' has a tag : 0x3f3f,0x3f00, for no apparent reason
2274 // --- Feel free to remove this test *on your own coy of gdcm*
2275 // if you are sure you'll never face this problem.
2277 if ((group == 0x3f3f) && (elem == 0x3f00))
2279 // start endian swap mark for group found
2280 gdcmDebugMacro( " delimiter 0x3f3f found." );
2286 // --- End of removable code
2288 // Endian reversion.
2289 // Some files contain groups of tags with reversed endianess.
2290 static int reversedEndian = 0;
2291 // try to fix endian switching in the middle of headers
2292 if ((group == 0xfeff) && (elem == 0x00e0))
2294 // start endian swap mark for group found
2295 gdcmDebugMacro( "Start endian swap mark found." );
2297 SwitchByteSwapCode();
2302 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2304 // end of reversed endian group
2305 gdcmDebugMacro( "End of reversed endian." );
2307 SwitchByteSwapCode();
2309 else if (group == 0xfeff && elem == 0xdde0)
2311 // reversed Sequence Terminator found
2312 // probabely a bug in the header !
2313 // Do what you want, it breaks !
2315 //SwitchByteSwapCode();
2316 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2321 else if (group == 0xfffe && elem == 0xe0dd)
2323 gdcmDebugMacro( "Straight Sequence Terminator." );
2328 * \brief Group 0002 is always coded Little Endian
2329 * whatever Transfer Syntax is
2332 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2334 // Endian reversion.
2335 // Some files contain groups of tags with reversed endianess.
2337 Group0002Parsed = true;
2338 // we just came out of group 0002
2339 // if Transfer Syntax is Big Endian we have to change CheckSwap
2341 std::string ts = GetTransferSyntax();
2342 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2344 // Group 0002 is always 'Explicit ...'
2345 // even when Transfer Syntax says 'Implicit ..."
2347 if ( s == TS::ImplicitVRLittleEndian
2349 s == TS::ImplicitVRBigEndianPrivateGE
2352 Filetype = ImplicitVR;
2355 // FIXME Strangely, this works with
2356 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2358 // --> Probabely normal, since we considered we never have
2359 // to trust manufacturers.
2360 // (we often find 'Implicit VR' tag,
2361 // even when Transfer Syntax tells us it's Explicit ...
2363 // NEVER trust the meta elements!
2364 // (see what ezDICOM does ...)
2367 if ( s == TS::ExplicitVRBigEndian )
2369 gdcmDebugMacro("Transfer Syntax Name = ["
2370 << GetTransferSyntaxName() << "]" );
2371 SwitchByteSwapCode();
2372 group = SwapShort(group);
2373 elem = SwapShort(elem);
2376 //-- Broken ACR may start with a Shadow Group --
2377 // worse : some ACR-NEMA like files start 00028 group ?!?
2378 if ( !( (group >= 0x0001 && group <= 0x0008) || group == 0x0028 ) )
2380 // We trust what we see.
2381 SwitchByteSwapCode();
2382 group = SwapShort(group);
2383 elem = SwapShort(elem);
2384 // not what we where told (by meta elements) !
2385 gdcmDebugMacro("Transfer Syntax Name = ["
2386 << GetTransferSyntaxName() << "]" );
2389 /// \todo find a trick to warn user and stop processing
2391 if ( s == TS::DeflatedExplicitVRLittleEndian)
2393 gdcmWarningMacro("Transfer Syntax ["
2394 << GetTransferSyntaxName() << "] :"
2395 << " not yet dealt with ");
2399 // The following shouldn't occur very often
2400 // Let's check at the very end.
2402 if ( ts == GDCM_UNKNOWN )
2404 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2408 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2410 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2416 //-----------------------------------------------------------------------------
2419 //-----------------------------------------------------------------------------
2420 } // end namespace gdcm