1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2011/03/29 07:36:00 $
7 Version: $Revision: 1.386 $
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 Document::Load.
61 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
64 Filetype = ExplicitVR;
65 CurrentOffsetPosition = 0;
66 OffsetOfPreviousParseDES =0;
67 // Load will set it to true if sucessfull
68 Group0002Parsed = false;
69 IsDocumentAlreadyLoaded = false;
70 IsDocumentModified = true;
71 LoadMode = LD_ALL; // default : load everything, later
79 * \brief Canonical destructor.
81 Document::~Document ()
86 //-----------------------------------------------------------------------------
89 * \brief Loader. use SetLoadMode(), SetFileName() before !
90 * @return false if file cannot be open or no swap info was found,
91 * or no tag was found.
93 bool Document::Load( )
95 if ( GetFileName() == "" )
97 gdcmWarningMacro( "Use SetFileName, before !" );
100 return DoTheLoadingDocumentJob( );
104 //#ifndef GDCM_LEGACY_REMOVE
106 * \brief Loader. (DEPRECATED : not to break the API)
107 * @param fileName 'Document' (File or DicomDir) to be open for parsing
108 * @return false if file cannot be open or no swap info was found,
109 * or no tag was found.
112 bool Document::Load( std::string const &fileName )
115 return DoTheLoadingDocumentJob( );
121 * \brief Performs the Loading Job (internal use only)
122 * @return false if file cannot be open or no swap info was found,
123 * or no tag was found.
125 bool Document::DoTheLoadingDocumentJob( )
127 if ( ! IsDocumentModified ) // Nothing to do !
135 // warning already performed in OpenFile()
140 Group0002Parsed = false;
142 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
144 // Computes the total length of the file
145 Fp->seekg(0, std::ios::end); // Once per Document !
146 long lgt = Fp->tellg(); // Once per Document !
147 Fp->seekg(0, std::ios::beg); // Once per Document !
149 // CheckSwap returns a boolean
150 // (false if no swap info of any kind was found)
153 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
154 << Filename.c_str());
159 long beg = Fp->tellg(); // just after DICOM preamble (if any)
161 lgt -= beg; // remaining length to parse
164 // Loading is done during parsing
165 OffsetOfPreviousParseDES = beg;
166 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
170 gdcmErrorMacro( "No tag in internal hash table for: "
171 << Filename.c_str());
175 IsDocumentAlreadyLoaded = true;
177 //Fp->seekg(0, std::ios::beg); // Once per Document!
179 // Load 'non string' values
181 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
182 if ( PhotometricInterpretation == "PALETTE COLOR " )
185 // Probabely this line should be outside the 'if'
186 // Try to find an image sample holding a 'gray LUT'
187 LoadEntryBinArea(0x0028,0x1200); // gray LUT
190 /// --> FIXME : The difference between BinEntry and DataEntry
191 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
192 /// --> Old comment restored on purpose.
193 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
194 /// --> had absolutely no meaning.
195 /// --> The whole comment will be removed when the stuff is cleaned !
197 /// The tags refered by the three following lines used to be CORRECTLY
198 /// defined as having an US Value Representation in the public
199 /// dictionary. BUT the semantics implied by the three following
200 /// lines state that the corresponding tag contents are in fact
201 /// the ones of a BinEntry.
202 /// In order to fix things "Quick and Dirty" the dictionary was
203 /// altered on PURPOSE but now contains a WRONG value.
204 /// In order to fix things and restore the dictionary to its
205 /// correct value, one needs to decide of the semantics by deciding
206 /// whether the following tags are either :
207 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
208 /// also used as BinEntry, which requires the proper conversion,
209 /// - OW, and hence loaded as BinEntry, but afterwards also used
210 /// as ValEntry, which requires the proper conversion.
212 // --> OB (byte aray) or OW (short int aray)
213 // The actual VR has to be deduced from other entries.
214 // Our way of loading them may fail in some cases :
215 // We must or not SwapByte depending on other field values.
217 LoadEntryBinArea(0x0028,0x1201); // R LUT
218 LoadEntryBinArea(0x0028,0x1202); // G LUT
219 LoadEntryBinArea(0x0028,0x1203); // B LUT
221 // Segmented Red Palette Color LUT Data
222 LoadEntryBinArea(0x0028,0x1221);
223 // Segmented Green Palette Color LUT Data
224 LoadEntryBinArea(0x0028,0x1222);
225 // Segmented Blue Palette Color LUT Data
226 LoadEntryBinArea(0x0028,0x1223);
229 //FIXME later : how to use it?
230 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
233 SQItem *sqi= modLutSeq->GetFirstSQItem();
236 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
237 if ( dataEntry != 0 )
239 if ( dataEntry->GetLength() != 0 )
241 // FIXME : CTX dependent means : contexted dependant.
242 // see upper comment.
243 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
249 // Force Loading some more elements if user asked to.
251 GDCM_NAME_SPACE::DocEntry *d;
252 for (ListElements::iterator it = UserForceLoadList.begin();
253 it != UserForceLoadList.end();
256 gdcmDebugMacro( "Force Load " << std::hex
257 << (*it).Group << "|" <<(*it).Elem );
259 d = GetDocEntry( (*it).Group, (*it).Elem);
263 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
264 << (*it).Group <<"|"<< (*it).Elem
265 << " that doesn't exist" );
269 LoadDocEntry(d, true);
274 // ----------------------------
275 // Specific code to allow gdcm to read ACR-LibIDO formated images
276 // Note: ACR-LibIDO is an extension of the ACR standard that was
277 // used at CREATIS. For the time being (say a couple of years)
278 // we keep this kludge to allow CREATIS users
279 // reading their old images.
281 // if recognition code tells us we deal with a LibIDO image
282 // we switch lineNumber and columnNumber
285 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
288 if(RecCode.find("ACRNEMA_LIBIDO") == 0 || // any version
289 RecCode.find("CANRME_AILIBOD") == 0) // for brain-damaged softwares
290 // with "little-endian strings"
293 Filetype = ACR_LIBIDO;
294 std::string rows = GetEntryString(0x0028, 0x0010);
295 std::string columns = GetEntryString(0x0028, 0x0011);
296 SetEntryString(columns, 0x0028, 0x0010);
297 SetEntryString(rows , 0x0028, 0x0011);
299 // --- End of ACR-LibIDO kludge ---
305 * \brief Adds a new element we want to load anyway
306 * @param group Group number of the target tag.
307 * @param elem Element number of the target tag.
309 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
314 UserForceLoadList.push_back(el);
317 * \brief Get the public dictionary used
319 Dict *Document::GetPubDict()
325 * \brief Get the shadow dictionary used
327 Dict *Document::GetShaDict()
333 * \brief Set the shadow dictionary used
334 * @param dict dictionary to use in shadow
336 bool Document::SetShaDict(Dict *dict)
343 * \brief Set the shadow dictionary used
344 * @param dictName name of the dictionary to use in shadow
346 bool Document::SetShaDict(DictKey const &dictName)
348 RefShaDict = Global::GetDicts()->GetDict(dictName);
353 * \brief This predicate tells us whether or not the current Document
354 * was properly parsed and contains at least *one* Dicom Element
355 * (and nothing more, sorry).
356 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
359 bool Document::IsParsable()
361 if ( Filetype == Unknown )
363 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
369 gdcmWarningMacro( "No tag in internal hash table.");
376 * \brief This predicate tells us whether or not the current Document
377 * was properly parsed and contains at least *one* Dicom Element
378 * (and nothing more, sorry).
379 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
382 bool Document::IsReadable()
388 * \brief Predicate for dicom version 3 file.
389 * @return True when the file is a dicom version 3.
391 bool Document::IsDicomV3()
393 // Checking if Transfer Syntax exists is enough
394 // Anyway, it's too late check if the 'Preamble' was found ...
395 // And ... would it be a rich idea to check ?
396 // (some 'no Preamble' DICOM images exist !)
397 return GetDocEntry(0x0002, 0x0010) != NULL;
401 * \brief Predicate for Papyrus file
402 * Dedicated to whomsoever it may concern
403 * @return True when the file is a Papyrus file.
405 bool Document::IsPapyrus()
407 // check for Papyrus private Sequence
408 DocEntry *e = GetDocEntry(0x0041, 0x1050);
411 // check if it's actually a Sequence
412 if ( !dynamic_cast<SeqEntry*>(e) )
418 * \brief returns the File Type
419 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
420 * @return the FileType code
422 FileType Document::GetFileType()
428 * \brief Accessor to the Transfer Syntax (when present) of the
429 * current document (it internally handles reading the
430 * value from disk when only parsing occured).
431 * @return The encountered Transfer Syntax of the current document, if DICOM.
432 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
434 std::string Document::GetTransferSyntax()
436 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
442 // The entry might be present but not loaded (parsing and loading
443 // happen at different stages): try loading and proceed with check...
446 // (parsing and loading happen at the very same stage!)
447 //LoadDocEntrySafe(entry); //JPRx
448 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
450 std::string transfer = dataEntry->GetString();
451 // The actual transfer (as read from disk) might be padded. We
452 // first need to remove the potential padding. We can make the
453 // weak assumption that padding was not executed with digits...
454 if ( transfer.length() == 0 )
456 // for brain damaged headers
457 gdcmWarningMacro( "Transfer Syntax has length = 0.");
460 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
462 transfer.erase(transfer.length()-1, 1);
463 if ( transfer.length() == 0 )
465 // for brain damaged headers
466 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
476 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
477 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
479 std::string Document::GetTransferSyntaxName()
481 // use the TS (TS : Transfer Syntax)
482 std::string transferSyntax = GetEntryString(0x0002,0x0010);
484 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
486 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
487 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
488 return "Uncompressed ACR-NEMA";
490 if ( transferSyntax == GDCM_UNFOUND )
492 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
493 return "Uncompressed ACR-NEMA";
496 // we do it only when we need it
497 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
499 // Global::GetTS() is a global static you shall never try to delete it!
503 // --------------- Swap Code ------------------
505 * \brief Swaps the bytes so they agree with the processor order
506 * @return The properly swaped 16 bits integer.
508 uint16_t Document::SwapShort(uint16_t a)
510 if ( SwapCode == 4321 || SwapCode == 2143 )
512 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
514 a = ( a << 8 ) | ( a >> 8 );
520 * \brief Swaps back the bytes of 4-byte long integer accordingly to
522 * @return The properly swaped 32 bits integer.
524 uint32_t Document::SwapLong(uint32_t a)
531 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
532 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
534 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
535 ((a>>8) & 0x0000ff00) | (a>>24) );
538 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
539 a=( (a<<16) | (a>>16) );
542 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
545 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
552 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
554 * @return The properly swaped 64 bits double.
556 double Document::SwapDouble(double a)
560 // There were no 'double' at ACR-NEMA time.
561 // We just have to deal with 'straight Little Endian' and
562 // 'straight Big Endian'
567 char *beg = (char *)&a;
570 for (unsigned int i = 0; i<7; i++)
581 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
588 // -----------------File I/O ---------------
590 * \brief Tries to open the file Document::Filename and
591 * checks the preamble when existing,
592 * or if the file starts with an ACR-NEMA look-like element.
593 * @return The FILE pointer on success, 0 on failure.
595 std::ifstream *Document::OpenFile()
597 HasDCMPreamble = false;
598 if (Filename.length() == 0)
605 gdcmDebugMacro( "File already open: " << Filename.c_str());
609 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
612 // Don't user gdcmErrorMacro :
613 // a spurious message will appear when you use, for instance
614 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
615 // to create outputFileName.
617 // FIXME : if the upper comment is still usefull
618 // --> the constructor is not so good ...
620 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
624 //exit(1); // No function is allowed to leave the application instead
625 // of warning the caller
629 Fp->read((char*)&zero, (size_t)2);
637 Fp->seekg(126L, std::ios::cur); // Once per Document
638 char dicm[4]; // = {' ',' ',' ',' '};
639 Fp->read(dicm, (size_t)4);
646 if ( memcmp(dicm, "DICM", 4) == 0 )
648 HasDCMPreamble = true;
652 //-- Broken ACR or DICOM (?) with no Preamble; may start with a Shadow Group --
653 // FIXME : We cannot be sure the preable is only zeroes..
654 // (see ACUSON-24-YBR_FULL-RLE.dcm )
656 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
657 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
658 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
659 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 ||
660 zero == 0x0028 || 0x2800 // worse : some ACR-NEMA like files
661 // start 00028 group ?!?
664 std::string msg = Util::Format(
665 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
666 // FIXME : is it a Warning message, or a Debug message?
667 gdcmWarningMacro( msg.c_str() );
671 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
673 // Don't user Warning nor Error, not to pollute the output
674 // while directory recursive parsing ...
675 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
676 << Filename.c_str());
681 * \brief closes the file
682 * @return TRUE if the close was successfull
684 bool Document::CloseFile()
696 * \brief Writes in a file all the Entries (Dicom Elements)
697 * @param fp file pointer on an already open file (actually: Output File Stream)
698 * @param filetype Type of the File to be written
699 * (ACR-NEMA, ExplicitVR, ImplicitVR)
701 void Document::WriteContent(std::ofstream *fp, FileType filetype, bool, bool)
703 // Skip if user wants to write an ACR-NEMA file
705 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
706 filetype == JPEG || filetype == JPEG2000 )
708 // writing Dicom File Preamble
709 char filePreamble[128];
710 memset(filePreamble, 0, 128);
711 fp->write(filePreamble, 128);
712 fp->write("DICM", 4);
715 * \todo rewrite later, if really usefull
716 * - 'Group Length' element is optional in DICOM
717 * - but un-updated odd groups lengthes can causes pb
720 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
721 * UpdateGroupLength(false,filetype);
722 * if ( filetype == ACR)
723 * UpdateGroupLength(true,ACR);
725 * --> Computing group length for groups with embeded Sequences
726 * --> was too much tricky / we were [in a hurry / too lazy]
727 * --> We don't write the element 0x0000 (group length)
729 // This one is recursive
730 // false : outside MetaElements
731 // false : outside Sequence
732 ElementSet::WriteContent(fp, filetype, false, false);
735 // -----------------------------------------
738 * \brief Loads (from disk) the element content
739 * when a string is not suitable
740 * @param group group number of the Entry
741 * @param elem element number of the Entry
743 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
745 // Search the corresponding DocEntry
746 DocEntry *docEntry = GetDocEntry(group, elem);
749 gdcmDebugMacro(std::hex << group << "|" << elem
750 << " doesn't exist" );
753 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
756 gdcmWarningMacro(std::hex << group << "|" << elem
757 << " is NOT a DataEntry");
760 LoadEntryBinArea(dataEntry);
764 * \brief Loads (from disk) the element content
765 * when a string is not suitable
766 * @param entry Entry whose binArea is going to be loaded
768 void Document::LoadEntryBinArea(DataEntry *entry)
770 if( entry->GetBinArea() )
777 //size_t o =(size_t)entry->GetOffset();
778 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
780 size_t l = entry->GetLength();
781 uint8_t *data = new uint8_t[l];
784 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
785 << std::hex << entry->GetGroup()
786 << "|" << entry->GetElement() );
791 Fp->read((char*)data, l);
792 if ( Fp->fail() || Fp->eof() )
795 entry->SetState(DataEntry::STATE_UNREAD);
799 // Swap the data content if necessary
801 unsigned short vrLgth =
802 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
804 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
805 // if( entry->GetVR() == "OW" )
816 uint16_t *data16 = (uint16_t *)data;
817 for(i=0;i<l/vrLgth;i++)
818 data16[i] = SwapShort(data16[i]);
823 uint32_t *data32 = (uint32_t *)data;
824 for(i=0;i<l/vrLgth;i++)
825 data32[i] = SwapLong(data32[i]);
830 double *data64 = (double *)data;
831 for(i=0;i<l/vrLgth;i++)
832 data64[i] = SwapDouble(data64[i]);
837 entry->SetBinArea(data);
839 if ( openFile ) // The file is left in the state (open/close) it was at entrance
844 * \brief Loads the element while preserving the current
845 * underlying file position indicator as opposed to
846 * LoadDocEntry that modifies it
847 * \note seems to be unused!.
848 * @param entry DocEntry whose value will be loaded.
850 //void Document::LoadDocEntrySafe(DocEntry *entry)
854 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
855 // LoadDocEntry(entry);
856 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
861 * \brief Compares two documents, according to DicomDir rules
862 * \warning Does NOT work with ACR-NEMA files
863 * \todo Find a trick to solve the pb (use RET fields ?)
864 * @param document to compare with current one
865 * @return true if 'smaller'
867 bool Document::operator<(Document &document)
870 std::string s1 = GetEntryString(0x0010,0x0010);
871 std::string s2 = document.GetEntryString(0x0010,0x0010);
883 s1 = GetEntryString(0x0010,0x0020);
884 s2 = document.GetEntryString(0x0010,0x0020);
895 // Study Instance UID
896 s1 = GetEntryString(0x0020,0x000d);
897 s2 = document.GetEntryString(0x0020,0x000d);
908 // Serie Instance UID
909 s1 = GetEntryString(0x0020,0x000e);
910 s2 = document.GetEntryString(0x0020,0x000e);
925 //-----------------------------------------------------------------------------
929 * \brief Reads a given length of bytes
930 * (in order to avoid to many CPU time-consuming fread-s)
931 * @param l length to read
933 void Document::ReadBegBuffer(size_t l)
936 Fp->read (BegBuffer, (size_t)l);
939 throw FormatError( "Document::ReadBegBuffer()", " file error." );
943 throw FormatError( "Document::ReadBegBuffer()", "EOF." );
945 PtrBegBuffer = BegBuffer;
946 CurrentOffsetPosition+=l;
949 * \brief Reads a supposed to be 16 Bits integer
950 * (swaps it depending on processor endianness)
953 uint16_t Document::ReadInt16()
957 Fp->read ((char*)&g, (size_t)2);
960 throw FormatError( "Document::ReadInt16()", " file error." );
964 throw FormatError( "Document::ReadInt16()", "EOF." );
971 * \brief Gets from BegBuffer a supposed to be 16 Bits integer
972 * (swaps it depending on processor endianness)
975 uint16_t Document::GetInt16()
977 uint16_t g = *((uint16_t*)PtrBegBuffer);
983 * \brief Reads a supposed to be 32 Bits integer
984 * (swaps it depending on processor endianness)
987 uint32_t Document::ReadInt32()
991 Fp->read ((char*)&g, (size_t)4);
994 throw FormatError( "Document::ReadInt32()", " file error." );
998 throw FormatError( "Document::ReadInt32()", "EOF." );
1005 * \brief Gets from BegBuffer a supposed to be 32 Bits integer
1006 * (swaps it depending on processor endianness)
1007 * @return read value
1009 uint32_t Document::GetInt32()
1011 uint32_t g = *((uint32_t*)PtrBegBuffer);
1018 * \brief Re-computes the length of the Dicom group 0002.
1020 int Document::ComputeGroup0002Length( )
1025 int groupLength = 0;
1026 bool found0002 = false;
1028 // for each zero-level Tag in the DCM Header
1029 DocEntry *entry = GetFirstEntry();
1032 gr = entry->GetGroup();
1038 if ( entry->GetElement() != 0x0000 )
1040 vr = entry->GetVR();
1042 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
1043 // (no SQ, OW, OL, UT in group 0x0002;)
1046 // explicit VR AND (OB, OW, OL, SQ, UT, UN) : 4 more bytes
1049 groupLength += 2 + 2 + 4 + entry->GetLength();
1052 else if (found0002 )
1055 entry = GetNextEntry();
1061 * \brief CallStartMethod
1063 void Document::CallStartMethod()
1067 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1071 * \brief CallProgressMethod
1073 void Document::CallProgressMethod()
1075 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1079 * \brief CallEndMethod
1081 void Document::CallEndMethod()
1084 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1087 //-----------------------------------------------------------------------------
1090 * \brief Loads all the needed Dictionaries
1091 * \warning NOT end user intended method !
1093 void Document::Initialize()
1095 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1101 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1102 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1103 * @param offset start of parsing
1104 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1105 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1107 void Document::ParseDES(DocEntrySet *set, long offset,
1108 long l_max, bool delim_mode)
1110 DocEntry *newDocEntry;
1111 DataEntry *newDataEntry;
1112 SeqEntry *newSeqEntry;
1114 bool used; // will be set to false when something wrong happens to an Entry.
1115 // (Entry will then be deleted)
1116 bool delim_mode_intern = delim_mode;
1118 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1119 << " at offset " << std::hex << "0x(" << offset << ")" );
1123 ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1124 /// Probabely a bug in gdcm code somewhere (some memory erased ?)
1126 // Uncomment to track the bug
1128 if( Debug::GetDebugFlag() )
1129 std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1130 << std::hex << " 0x(" <<(long)(Fp->tellg()) << ")" << std::endl;
1132 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1133 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1134 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1139 newDocEntry = ReadNextDocEntry( );
1146 // Uncoment this cerr line to be able to 'follow' the DocEntries
1147 // when something *very* strange happens
1148 if( Debug::GetDebugFlag() )
1149 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1151 // an Item Starter found elsewhere but in the first position
1152 // of a SeqEntry means previous entry was a Sequence
1153 // but we didn't get it (private Sequence + Implicit VR)
1154 // we have to backtrack.
1155 if ( !first && newDocEntry->IsItemStarter() )
1157 // Debug message within the method !
1158 newDocEntry = Backtrack(newDocEntry, set);
1162 PreviousDocEntry = newDocEntry;
1166 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1170 //////////////////////////// DataEntry
1172 //vr = newDocEntry->GetVR(); // useless ?
1174 if ( !set->AddEntry( newDataEntry ) )
1176 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1177 << newDataEntry->GetKey()
1178 << " (at offset : 0x("
1179 << newDataEntry->GetOffset() << ") )" );
1184 newDataEntry->Delete();
1185 // Load only if we can add (not a duplicate key)
1186 LoadDocEntry( newDataEntry );
1188 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1190 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1192 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1194 std::string strLgrGroup = newDataEntry->GetString();
1197 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1199 lgrGroup = atoi(strLgrGroup.c_str());
1200 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1201 RemoveEntry( newDocEntry ); // Remove and delete
1208 bool delimitor = newDataEntry->IsItemDelimitor();
1209 bool outOfBounds = false;
1211 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1214 // 'and then', 'or else' don't exist in C++ :-(
1215 // if ( (delimitor) ||
1216 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1218 if ( delimitor || outOfBounds )
1221 newDocEntry->Delete();
1225 // Just to make sure we are at the beginning of next entry.
1226 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1230 /////////////////////// SeqEntry : VR = "SQ"
1232 unsigned long l = newDocEntry->GetReadLength();
1233 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1235 if ( l == 0xffffffff )
1237 delim_mode_intern = true;
1241 delim_mode_intern = false;
1245 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1247 // User asked to skip SeQuences *only* if they belong to Shadow Group
1248 if ( newDocEntry->GetGroup()%2 != 0 )
1250 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1251 newDocEntry->Delete(); // Delete, not in the set
1255 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1257 // User asked to skip *any* SeQuence
1258 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1259 newDocEntry->Delete(); // Delete, not in the set
1262 // delay the dynamic cast as late as possible
1263 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1265 // no other way to create the Delimitor ...
1266 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1268 // At the top of the hierarchy, stands a Document. When "set"
1269 // is a Document, then we are building the first depth level.
1270 // Hence the SeqEntry we are building simply has a depth
1272 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1274 newSeqEntry->SetDepthLevel( 1 );
1276 // But when "set" is already a SQItem, we are building a nested
1277 // sequence, and hence the depth level of the new SeqEntry
1278 // we are building, is one level deeper:
1280 // time waste hunting
1281 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1283 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1287 { // Don't try to parse zero-length sequences
1289 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1290 << " at offset 0x(" << std::hex
1291 << newDocEntry->GetOffset() << ")");
1293 bool res = ParseSQ( newSeqEntry,
1294 newDocEntry->GetOffset(),
1295 l, delim_mode_intern);
1297 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern << " -->return : " << res);
1299 if ( !set->AddEntry( newSeqEntry ) )
1301 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1302 << newSeqEntry->GetKey()
1303 << " (at offset : 0x("
1304 << newSeqEntry->GetOffset() << ") )" );
1309 newDocEntry->Delete();
1312 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1314 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1315 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1319 newDocEntry->Delete();
1322 } // end SeqEntry : VR = "SQ"
1326 newDocEntry->Delete();
1330 if (UnexpectedEOF) // some terminator was missing
1335 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1339 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1340 * @return false if expected fff0,e000 not found
1342 bool Document::ParseSQ( SeqEntry *seqEntry,
1343 long offset, long l_max, bool delim_mode)
1345 int SQItemNumber = 0;
1347 long offsetStartCurrentSQItem = offset;
1351 // the first time, we read the fff0,e000 of the first SQItem
1352 DocEntry *newDocEntry = ReadNextDocEntry();
1356 // The most frequent is when a SQ terminator is missing (?!?)
1357 gdcmWarningMacro("in ParseSQ : should never get here!");
1358 UnexpectedEOF = true;
1363 if ( newDocEntry->IsSequenceDelimitor() )
1365 seqEntry->SetDelimitationItem( newDocEntry );
1366 newDocEntry->Delete();
1370 else // ! delim_mode
1372 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1374 newDocEntry->Delete();
1378 // create the current SQItem
1379 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1380 unsigned int l = newDocEntry->GetReadLength();
1382 if ( l == 0xffffffff )
1391 // avoid infinite loop when Bad assumption was made on illegal 'unknown length' UN //JPRx
1393 if (offsetStartCurrentSQItem <= OffsetOfPreviousParseDES)
1395 gdcmWarningMacro("Bad assumption was made on illegal 'unknown length' UN!" << std::endl <<
1396 "OffsetOfPreviousParseDES " << std::hex << OffsetOfPreviousParseDES
1397 << " offsetStartCurrentSQItem " << offsetStartCurrentSQItem);
1398 /// \todo when "Bad assumption (SQ) on illegal 'unknown length' UN", Backtrack again + try OB
1403 OffsetOfPreviousParseDES = offsetStartCurrentSQItem;
1406 // fill up the current SQItem, starting at the beginning of fff0,e000
1407 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); // Once per SQItem
1408 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1409 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1411 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1413 newDocEntry->Delete();
1415 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1416 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1425 * \brief When a private Sequence + Implicit VR is encountered
1426 * we cannot guess it's a Sequence till we find the first
1427 * Item Starter. We then backtrack to do the job.
1428 * @param docEntry Item Starter that warned us
1429 * @param set DocEntrySet (ElementSet/SQItem) the DocEntry will belong
1431 DocEntry *Document::Backtrack(DocEntry *docEntry, DocEntrySet *set)
1433 // delete the Item Starter, built erroneously out of any Sequence
1434 // it's not yet in the HTable/chained list
1437 // Get all info we can from PreviousDocEntry
1438 uint16_t group = PreviousDocEntry->GetGroup();
1439 uint16_t elem = PreviousDocEntry->GetElement();
1440 uint32_t lgt = PreviousDocEntry->GetLength();
1441 long offset = PreviousDocEntry->GetOffset();
1443 gdcmDebugMacro( "Backtrack :" << std::hex << group
1445 << " at offset 0x(" <<offset << ")" );
1447 set->RemoveEntry( PreviousDocEntry );
1449 // forge the Seq Entry
1450 DocEntry *newEntry = NewSeqEntry(group, elem);
1451 newEntry->SetLength(lgt);
1452 newEntry->SetOffset(offset);
1454 // Move back to the beginning of the Sequence
1456 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1457 return newEntry; // It will added where it has to be!
1461 * \brief Loads (or not) the element content depending if its length exceeds
1462 * or not the value specified with Document::SetMaxSizeLoadEntry()
1463 * @param entry Header Entry (Dicom Element) to be dealt with
1464 * @param forceLoad whether you want to force loading of 'long' elements
1466 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1468 uint16_t group = entry->GetGroup();
1469 uint16_t elem = entry->GetElement();
1470 const VRKey &vr = entry->GetVR();
1471 uint32_t length = entry->GetLength();
1473 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1475 // A SeQuence "contains" a set of Elements.
1476 // (fffe e000) tells us an Element is beginning
1477 // (fffe e00d) tells us an Element just ended
1478 // (fffe e0dd) tells us the current SeQuence just ended
1479 // (fffe 0000) is an 'impossible' tag value,
1480 // found in MR-PHILIPS-16-Multi-Seq.dcm
1482 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1484 // NO more value field for SQ !
1488 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1494 // When the length is zero things are easy:
1497 dataEntryPtr->SetBinArea(NULL,true);
1501 // The elements whose length is bigger than the specified upper bound
1506 if (length > MaxSizeLoadEntry)
1508 dataEntryPtr->SetBinArea(NULL,true);
1509 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1511 // to be sure we are at the end of the value ...
1512 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1513 // std::ios::beg); //JPRx
1518 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1519 /// + a ForceLoad call on the +/- 20 'usefull' fields
1520 /// Allow user to tell the fields he wants to ForceLoad
1521 /// during initial stage.
1522 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1523 /// + a method that load *everything* that's not yet loaded
1525 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1529 * \brief Find the value Length of the passed Doc Entry
1530 * @param entry Header Entry whose length of the value shall be loaded.
1532 void Document::FindDocEntryLength( DocEntry *entry )
1533 throw ( FormatError )
1535 const VRKey &vr = entry->GetVR();
1537 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1542 // For some images, length of UN elements is coded on 2 bytes (instead of 4)
1543 // There are *not* readable !
1544 // You can make a quick and dirty patch, commenting out
1546 // in the following line.
1547 // (the 'straight' images will no longer be readable ...)
1549 if ( vr == "OB" || vr == "OW" || vr == "OL" || vr == "SQ" || vr == "UT"
1550 || vr == "UN" || changeFromUN == true)
1552 changeFromUN = false;
1553 // The following reserved two bytes (see PS 3.5-2003, section
1554 // "7.1.2 Data element structure with explicit vr", p 27) must be
1555 // skipped before proceeding on reading the length on 4 bytes.
1557 //Fp->seekg( 2L, std::ios::cur); // Once per OB,OW,OL,UT,UN,SQ DocEntry
1558 uint32_t length32 = ReadInt32(); // Once per OB,OW,OL,UT,UN,SQ DocEntry
1559 CurrentOffsetPosition+=4;
1560 if ( (vr == "OB" || vr == "OW" || vr == "OL") && length32 == 0xffffffff )
1565 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1567 catch ( FormatUnexpected )
1569 // Computing the length failed (this happens with broken
1570 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1571 // chance to get the pixels by deciding the element goes
1572 // until the end of the file. Hence we artificially fix the
1573 // the length and proceed.
1574 gdcmWarningMacro( " Computing the length failed for " <<
1575 entry->GetKey() <<" in " <<GetFileName());
1577 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1578 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1580 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1581 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1583 entry->SetReadLength(lengthUntilEOF);
1584 entry->SetLength(lengthUntilEOF);
1587 entry->SetReadLength(lengthOB);
1588 entry->SetLength(lengthOB);
1591 FixDocEntryFoundLength(entry, length32);
1594 // Length is encoded on 2 bytes.
1595 //length16 = ReadInt16();
1596 length16 = GetInt16();
1597 // 0xffff means that we deal with 'No Length' Sequence
1598 // or 'No Length' SQItem
1599 if ( length16 == 0xffff)
1603 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1608 // Either implicit VR or a non DICOM conformal (see note below) explicit
1609 // VR that ommited the VR of (at least) this element. Farts happen.
1610 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1611 // on Data elements "Implicit and Explicit VR Data Elements shall
1612 // not coexist in a Data Set and Data Sets nested within it".]
1613 // Length is on 4 bytes.
1615 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1616 // even if Transfer Syntax is 'Implicit VR ...'
1617 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1618 // where Group 0x0002 is *also* encoded in Implicit VR !
1620 FixDocEntryFoundLength( entry, GetInt32() /*ReadInt32()*/ );
1626 * \brief Find the Length till the next sequence delimiter
1627 * \warning NOT end user intended method !
1630 uint32_t Document::FindDocEntryLengthOBOrOW()
1631 throw( FormatUnexpected )
1633 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1635 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1637 bool foundSequenceDelimiter = false;
1638 uint32_t totalLength = 0;
1640 while ( !foundSequenceDelimiter )
1646 { ///\todo make sure there is never OL encoded pixel data!
1648 //group = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1649 //elem = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1650 ReadBegBuffer(4); // Once per fragment (if any) of OB,OW DataElements
1652 catch ( FormatError )
1654 throw FormatError("Unexpected end of file encountered during ",
1655 "Document::FindDocEntryLengthOBOrOW()");
1660 // We have to decount the group and element we just read
1662 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1665 "Neither an Item tag nor a Sequence delimiter tag on :"
1666 << std::hex << group << "|" << elem << ") Pos. on entry was 0x(" <<positionOnEntry<< ") "
1669 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1670 throw FormatUnexpected(
1671 "Neither an Item tag nor a Sequence delimiter tag.");
1673 if ( elem == 0xe0dd )
1675 foundSequenceDelimiter = true;
1677 uint32_t itemLength = ReadInt32(); // Once per fragment (if any) of OB,OW DataElements
1678 // We add 4 bytes since we just read the ItemLength with ReadInt32
1679 totalLength += itemLength + 4;
1680 SkipBytes(itemLength);
1682 if ( foundSequenceDelimiter )
1687 Fp->seekg( positionOnEntry, std::ios::beg); // Only once for OB,OW DataElements
1692 * \brief Find the Value Representation of the current Dicom Element.
1693 * @return Value Representation of the current Entry
1695 VRKey Document::FindDocEntryVR()
1697 if ( Filetype != ExplicitVR )
1699 return GDCM_VRUNKNOWN;
1702 // Delimiters (0xfffe), are not explicit VR ...
1703 if ( CurrentGroup == 0xfffe )
1704 return GDCM_VRUNKNOWN;
1706 //long positionOnEntry;
1707 //if( Debug::GetWarningFlag() )
1708 // positionOnEntry = Fp->tellg(); // Only in Warning Mode
1710 // Warning: we believe this is explicit VR (Value Representation) because
1711 // we used a heuristic that found "UL" in the first tag and/or
1712 // 'Transfer Syntax' told us it is.
1713 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1714 // In some cases one finds implicit VR tags mixed within an explicit VR file
1716 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1718 // Hence we make sure the present tag is in explicit VR and try to fix things
1719 // if it happens not to be the case.
1722 //Fp->read(&(vr[0]),(size_t)2);
1723 vr[0] = *PtrBegBuffer++;
1724 vr[1] = *PtrBegBuffer++;
1726 //if ( !CheckDocEntryVR(vr) ) // avoid useless function call
1727 if ( !Global::GetVR()->IsValidVR(vr) )
1730 gdcmWarningMacro( "Unknown VR " << vr.GetHexaRepresentation() << std::hex
1731 << " at offset : 0x(" << CurrentOffsetPosition-4
1732 << ") for group " << std::hex << CurrentGroup );
1734 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1735 //Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1736 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1738 return GDCM_VRUNKNOWN;
1744 * \brief Check the correspondance between the VR of the header entry
1745 * and the taken VR. If they are different, the header entry is
1746 * updated with the new VR.
1747 * @param vr Dicom Value Representation
1748 * @return false if the VR is incorrect or if the VR isn't referenced
1749 * otherwise, it returns true
1751 bool Document::CheckDocEntryVR(const VRKey &vr)
1753 return Global::GetVR()->IsValidVR(vr);
1757 * \brief Skip a given Header Entry
1758 * @param entry entry to skip
1760 void Document::SkipDocEntry(DocEntry *entry)
1762 SkipBytes(entry->GetLength());
1766 * \brief Skips to the beginning of the next Header Entry
1767 * @param currentDocEntry entry to skip
1769 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1771 long l = currentDocEntry->GetReadLength();
1772 if ( (uint32_t) l == (uint32_t)-1 ) // length = 0xffff shouldn't appear here ...
1773 // ... but PMS imagers happen !
1775 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1776 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1778 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1783 * \brief When the length of an element value is obviously wrong (because
1784 * the parser went Jabberwocky) one can hope improving things by
1785 * applying some heuristics.
1786 * @param entry entry to check
1787 * @param foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)
1789 void Document::FixDocEntryFoundLength(DocEntry *entry,
1790 uint32_t foundLength)
1792 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1794 if ( foundLength == 0xffffffff)
1797 //entry->SetLength(foundLength);
1798 entry->SetLength(0);
1799 return; // return ASAP; don't waist time on useless tests
1802 uint16_t gr = entry->GetGroup();
1803 uint16_t elem = entry->GetElement();
1805 if ( foundLength % 2)
1807 gdcmWarningMacro( "Warning : Tag (" << std::hex << gr << "|" << elem << ") with uneven length "
1808 << std::dec << foundLength << " 0x(" << std::hex << foundLength << ") "
1809 //<< " at offset x(" << offset << ")"
1813 //////// Fix for some naughty General Electric images.
1814 // Allthough not recent many such GE corrupted images are still present
1815 // on Creatis hard disks. Hence this fix shall remain when such images
1816 // are no longer in use (we are talking a few years, here)...
1817 // Note: XMedCon probably uses such a trick since it is able to read
1818 // those pesky GE images ...
1819 if ( foundLength == 13)
1821 // Only happens for this length !
1822 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1825 entry->SetReadLength(10); // a bug is to be fixed !?
1829 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1830 // Occurence of such images is quite low (unless one leaves close to a
1831 // 'Leonardo' source. Hence, one might consider commenting out the
1832 // following fix on efficiency reasons.
1833 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1835 // Ideally we should check we are in Explicit and double check
1836 // that VR=UL... this is done properly in gdcm2
1837 if( foundLength == 6 )
1839 gdcmWarningMacro( "Replacing Length from 6 into 4" );
1841 entry->SetReadLength(4); // a bug is to be fixed !
1843 else if ( foundLength%4 )
1845 gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1846 "The length of this tag seems to be wrong" );
1850 else if ( entry->GetVR() == "SQ" )
1852 foundLength = 0; // ReadLength is unchanged
1855 //////// We encountered a 'delimiter' element i.e. a tag of the form
1856 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1857 // taken into account.
1858 else if ( gr == 0xfffe )
1860 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1861 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1862 // causes extra troubles...
1863 if ( elem != 0x0000 )
1869 foundLength=12; // to skip the mess that follows this bugged Tag !
1872 entry->SetLength(foundLength);
1876 * \brief Apply some heuristics to predict whether the considered
1877 * element value contains/represents an integer or not.
1878 * @param entry The element value on which to apply the predicate.
1879 * @return The result of the heuristical predicate.
1881 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1883 uint16_t elem = entry->GetElement();
1884 uint16_t group = entry->GetGroup();
1885 const VRKey &vr = entry->GetVR();
1886 uint32_t length = entry->GetLength();
1888 // When we have some semantics on the element we just read, and if we
1889 // a priori know we are dealing with an integer, then we shall be
1890 // able to swap its element value properly.
1891 if ( elem == 0 ) // This is the group length of the group
1899 // Although this should never happen, still some images have a
1900 // corrupted group length [e.g. have a glance at offset x(8336) of
1901 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1902 // Since for dicom compliant and well behaved headers, the present
1903 // test is useless (and might even look a bit paranoid), when we
1904 // encounter such an ill-formed image, we simply display a warning
1905 // message and proceed on parsing (while crossing fingers).
1906 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1908 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1909 << std::hex << group << " , " << elem
1910 << ") -before- position x(" << filePosition << ")"
1911 << "lgt : " << length );
1915 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1923 * \brief Discover what the swap code is (among little endian, big endian,
1924 * bad little endian, bad big endian).
1926 * @return false when we are absolutely sure
1927 * it's neither ACR-NEMA nor DICOM
1928 * true when we hope ours assuptions are OK
1930 bool Document::CheckSwap()
1937 // First, compare HostByteOrder and NetworkByteOrder in order to
1938 // determine if we shall need to swap bytes (i.e. the Endian type).
1939 bool net2host = Util::IsCurrentProcessorBigEndian();
1941 // The easiest case is the one of a 'true' DICOM header, we just have
1942 // to look for the string "DICM" inside the file preamble.
1945 char *entCur = deb + 128;
1946 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1948 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1950 // Group 0002 should always be VR, and the first element 0000
1951 // Let's be carefull (so many wrong headers ...)
1952 // and determine the value representation (VR) :
1953 // Let's skip to the first element (0002,0000) and check there if we find
1954 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1955 // in which case we (almost) know it is explicit VR.
1956 // WARNING: if it happens to be implicit VR then what we will read
1957 // is the length of the group. If this ascii representation of this
1958 // length happens to be "UL" then we shall believe it is explicit VR.
1959 // We need to skip :
1960 // * the 128 bytes of File Preamble (often padded with zeroes),
1961 // * the 4 bytes of "DICM" string,
1962 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1963 // i.e. a total of 136 bytes.
1966 // group 0x0002 *is always* Explicit VR Sometimes,
1967 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1968 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1970 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1971 memcmp(entCur, "OB", (size_t)2) == 0 ||
1972 memcmp(entCur, "UI", (size_t)2) == 0 ||
1973 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1974 // when Write DCM *adds*
1976 // Use Document::dicom_vr to test all the possibilities
1977 // instead of just checking for UL, OB and UI !? group 0000
1979 Filetype = ExplicitVR;
1980 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1984 Filetype = ImplicitVR;
1985 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1986 << "Looks like a bugged Header!");
1989 // Here, we assume that the file IS kosher Dicom !
1990 // (The meta elements - group 0x0002 - ARE little endian !)
1994 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1999 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
2002 // Position the file position indicator at first tag
2003 // (i.e. after the file preamble and the "DICM" string).
2005 Fp->seekg ( 132L, std::ios::beg); // Once per Document
2006 CurrentOffsetPosition = 132;
2008 } // ------------------------------- End of DicomV3 ----------------
2010 // Alas, this is not a DicomV3 file and whatever happens there is no file
2011 // preamble. We can reset the file position indicator to where the data
2012 // is (i.e. the beginning of the file).
2014 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2016 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
2017 CurrentOffsetPosition = 0;
2018 // Let's check 'No Preamble Dicom File' :
2019 // Should start with group 0x0002
2020 // and be Explicit Value Representation
2022 s16 = *((uint16_t *)(deb));
2035 if ( SwapCode != 0 )
2037 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2038 memcmp(entCur, "OB", (size_t)2) == 0 ||
2039 memcmp(entCur, "UI", (size_t)2) == 0 ||
2040 memcmp(entCur, "SH", (size_t)2) == 0 ||
2041 memcmp(entCur, "AE", (size_t)2) == 0 ||
2042 memcmp(entCur, "OB", (size_t)2) == 0 )
2044 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
2045 // Wait untill reading Transfer Syntax
2046 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
2050 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2052 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2053 // By clean we mean that the length of the first group is written down.
2054 // If this is the case and since the length of the first group HAS to be
2055 // four (bytes), then determining the proper swap code is straightforward.
2058 // We assume the array of char we are considering contains the binary
2059 // representation of a 32 bits integer. Hence the following dirty
2061 s32 = *((uint32_t *)(entCur));
2081 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2082 // It is time for despaired wild guesses.
2083 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2084 // i.e. the 'group length' element is not present :
2086 // check the supposed-to-be 'group number'
2087 // in ( 0x0001 .. 0x0008 )
2088 // to determine ' SwapCode' value .
2089 // Only 0 or 4321 will be possible
2090 // (no oportunity to check for the formerly well known
2091 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2092 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
2093 // the file IS NOT ACR-NEMA nor DICOM V3
2094 // Find a trick to tell it the caller...
2096 s16 = *((uint16_t *)(deb));
2098 gdcmDebugMacro("not a DicomV3 nor a 'clean' ACR/NEMA;"
2099 << " (->despaired wild guesses !)");
2112 // Brute hack to allow reading DICOM RT files
2113 //Filetype = ACR; // DICOM RT are *not* ACR-Nema files!
2114 Filetype = ExplicitVR;
2130 s16 = *((uint16_t *)(deb));
2133 s16 = *((uint16_t *)(deb+2));
2135 Fp->seekg ( 0L, std::ios::beg); // Once per Document
2136 CurrentOffsetPosition = 0;
2137 switch(s16) // try an other trick!
2138 // -> to be able to decode 0029|1010 DataElement
2139 // -> and be not less cleaver than dcmdump ;-)
2148 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2152 // Check if next 2 bytes are a VR
2153 // Probabely something more time-consuming exists with std::string
2154 const char VRvalues[] = "AEASATCSDADTFLFDISLOLTPNSHSLSSSTTMUIULUSUTOBOWOLOFATUNSQRT";
2156 const char *pt = VRvalues;
2157 for (int i=0;i<nbVal;i++)
2159 if(*(deb+4) == *pt++) {
2160 if(*(deb+5) == *pt++) {
2161 Filetype = ExplicitVR;
2169 Filetype = ImplicitVR;
2176 * \brief Change the Byte Swap code.
2178 void Document::SwitchByteSwapCode()
2180 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2181 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2182 if ( SwapCode == 1234 )
2186 else if ( SwapCode == 4321 )
2190 else if ( SwapCode == 3412 )
2194 else if ( SwapCode == 2143 )
2198 gdcmDebugMacro( " Into: "<< SwapCode );
2202 * \brief during parsing, Header Elements too long are not loaded in memory
2203 * @param newSize new size
2205 void Document::SetMaxSizeLoadEntry(long newSize)
2211 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2213 MaxSizeLoadEntry = 0xffffffff;
2216 MaxSizeLoadEntry = newSize;
2220 * \brief Read the next tag WITHOUT loading it's value
2221 * (read the 'Group Number', the 'Element Number',
2222 * gets the Dict Entry
2223 * gets the VR, gets the length, gets the offset value)
2224 * @return On succes : the newly created DocEntry, NULL on failure.
2226 DocEntry *Document::ReadNextDocEntry()
2230 ReadBegBuffer(8); // Avoid to many time consuming freads
2231 //CurrentGroup = ReadInt16();
2232 //CurrentElem = ReadInt16();
2234 catch ( FormatError )
2236 // We reached the EOF (or an error occured) therefore
2237 // header parsing has to be considered as finished.
2241 changeFromUN = false;
2242 CurrentGroup = GetInt16();
2243 CurrentElem = GetInt16();
2245 // In 'true DICOM' files Group 0002 is always little endian
2246 if ( HasDCMPreamble )
2248 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2249 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2251 // Sometimes file contains groups of tags with reversed endianess.
2252 HandleBrokenEndian(CurrentGroup, CurrentElem);
2255 VRKey vr = FindDocEntryVR();
2258 if ( vr == GDCM_VRUNKNOWN )
2260 if ( CurrentElem == 0x0000 ) // Group Length
2262 realVR = "UL"; // must be UL
2264 else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2269 // Was commented out in order not to generate 'Shadow Groups' where some
2270 // Data Elements are Explicit VR and some other ones Implicit VR
2271 // -> Better we fix the problem at Write time
2273 else if (CurrentGroup%2 == 1 )
2275 if (CurrentElem >= 0x0010 && CurrentElem <=0x00ff )
2277 // DICOM PS 3-5 7.8.1 a) states that :
2278 // Private Creator Data Elements numbered (gggg,0010-00FF) (gggg is odd)
2279 // attributes have to be LO (Long String) and the VM shall be equal to 1
2282 // Seems not to be true
2283 // Still in gdcmtk, David Clunnie disagrees, Marco Eichelberg says it's OK ...
2284 // We let it for a while?
2285 //(We should check length==4, for more security, but we don't have it yet !)
2287 else if ( CurrentElem == 0x0001)
2289 realVR = "UL"; // Private Group Length To End
2291 else // check the private dictionary for shadow elements when Implicit VR!
2293 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2296 realVR = dictEntry->GetVR();
2297 dictEntry->Unregister(); // GetDictEntry registered it
2304 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2307 realVR = dictEntry->GetVR();
2308 dictEntry->Unregister(); // GetDictEntry registered it
2313 // if UN found, let's check the dictionary, and trust it!
2314 // (maybe a private dictionary exists?)
2315 else if (vr == "UN")
2317 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2320 realVR = dictEntry->GetVR();
2321 dictEntry->Unregister(); // GetDictEntry registered it
2323 // for VR = "UN", length is always stored on 4 bytes.
2324 // remember this info, in order not to crash later
2326 /// \todo : fixme If inside a vr = "UN" DataElement (but SQ according to a private dictionnary)
2327 /// there is some more vr = "UN" DataElements, it will probabely fail.
2328 /// --> find a -non time consuming- trick to store changeFromUN info at DataElement level,
2329 /// not at the Document level.
2336 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2339 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2343 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2344 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2347 if ( vr == GDCM_VRUNKNOWN )
2349 if ( Filetype == ExplicitVR )
2351 // We thought this was explicit VR, but we end up with an
2352 // implicit VR tag. Let's backtrack.
2354 //if ( newEntry->GetGroup() != 0xfffe )
2355 if (CurrentGroup != 0xfffe)
2357 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2359 gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2360 << std::hex << offset << ") should be Explicit VR");
2363 newEntry->SetImplicitVR();
2368 FindDocEntryLength(newEntry);
2370 catch ( FormatError )
2377 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2382 * \brief Handle broken private tag from Philips NTSCAN
2383 * where the endianess is being switched to BigEndian
2384 * for no apparent reason
2387 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2389 // for strange PMS Gyroscan Intera images
2390 // Item 'starter' has a tag : 0x3f3f,0x3f00, for no apparent reason
2392 // --- Feel free to remove this test *on your own coy of gdcm*
2393 // if you are sure you'll never face this problem.
2395 if ((group == 0x3f3f) && (elem == 0x3f00))
2397 // start endian swap mark for group found
2398 gdcmDebugMacro( " delimiter 0x3f3f found." );
2404 // --- End of removable code
2406 // Endian reversion.
2407 // Some files contain groups of tags with reversed endianess.
2408 static int reversedEndian = 0;
2409 // try to fix endian switching in the middle of headers
2410 if ((group == 0xfeff) && (elem == 0x00e0))
2412 // start endian swap mark for group found
2413 gdcmDebugMacro( "Start endian swap mark found." );
2415 SwitchByteSwapCode();
2420 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2422 // end of reversed endian group
2423 gdcmDebugMacro( "End of reversed endian." );
2425 SwitchByteSwapCode();
2427 else if (group == 0xfeff && elem == 0xdde0)
2429 // reversed Sequence Terminator found
2430 // probabely a bug in the header !
2431 // Do what you want, it breaks !
2433 //SwitchByteSwapCode();
2434 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2439 else if (group == 0xfffe && elem == 0xe0dd)
2441 gdcmDebugMacro( "Straight Sequence Terminator." );
2446 * \brief Group 0002 is always coded Little Endian
2447 * whatever Transfer Syntax is
2450 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2452 // Endian reversion.
2453 // Some files contain groups of tags with reversed endianess.
2455 Group0002Parsed = true;
2456 // we just came out of group 0002
2457 // if Transfer Syntax is Big Endian we have to change CheckSwap
2459 std::string ts = GetTransferSyntax();
2460 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2462 // Group 0002 is always 'Explicit ...'
2463 // even when Transfer Syntax says 'Implicit ..."
2465 if ( s == TS::ImplicitVRLittleEndian
2467 s == TS::ImplicitVRBigEndianPrivateGE
2470 Filetype = ImplicitVR;
2473 // FIXME Strangely, this works with
2474 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2476 // --> Probabely normal, since we considered we never have
2477 // to trust manufacturers.
2478 // (we often find 'Implicit VR' tag,
2479 // even when Transfer Syntax tells us it's Explicit ...
2481 // NEVER trust the meta elements!
2482 // (see what ezDICOM does ...)
2485 if ( s == TS::ExplicitVRBigEndian )
2487 gdcmDebugMacro("Transfer Syntax Name = ["
2488 << GetTransferSyntaxName() << "]" );
2489 SwitchByteSwapCode();
2490 group = SwapShort(group);
2491 elem = SwapShort(elem);
2494 //-- Broken ACR may start with a Shadow Group --
2495 // worse : some ACR-NEMA like files start 00028 group ?!?
2496 if ( !( (group >= 0x0001 && group <= 0x0008) || group == 0x0028 ) )
2498 // We trust what we see.
2499 SwitchByteSwapCode();
2500 group = SwapShort(group);
2501 elem = SwapShort(elem);
2502 // not what we where told (by meta elements) !
2503 gdcmDebugMacro("Transfer Syntax Name = ["
2504 << GetTransferSyntaxName() << "]" );
2507 /// \todo find a trick to warn user and stop processing
2509 if ( s == TS::DeflatedExplicitVRLittleEndian)
2511 gdcmWarningMacro("Transfer Syntax ["
2512 << GetTransferSyntaxName() << "] :"
2513 << " not yet dealt with ");
2517 // The following shouldn't occur very often
2518 // Let's check at the very end.
2520 if ( ts == GDCM_UNKNOWN )
2522 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2526 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2528 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2534 //-----------------------------------------------------------------------------
2537 //-----------------------------------------------------------------------------
2538 } // end namespace gdcm