1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2006/07/10 09:41:46 $
7 Version: $Revision: 1.353 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmSeqEntry.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmDebug.h"
25 #include "gdcmDictSet.h"
26 #include "gdcmDocEntrySet.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
33 #include <ctype.h> // for isdigit
34 #include <stdlib.h> // for atoi
36 #if defined(__BORLANDC__)
37 #include <mem.h> // for memset
42 //-----------------------------------------------------------------------------
44 // Refer to Document::SetMaxSizeLoadEntry()
45 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
49 // Constructors and destructors are protected to avoid user to invoke directly
52 * \brief This default constructor neither loads nor parses the file.
53 * You should then invoke \ref Document::Load.
61 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
64 Filetype = ExplicitVR;
65 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.
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 * @return The FILE pointer on success.
587 std::ifstream *Document::OpenFile()
589 HasDCMPreamble = false;
590 if (Filename.length() == 0)
597 gdcmDebugMacro( "File already open: " << Filename.c_str());
601 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
604 // Don't user gdcmErrorMacro :
605 // a spurious message will appear when you use, for instance
606 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
607 // to create outputFileName.
609 // FIXME : if the upper comment is still usefull
610 // --> the constructor is not so good ...
612 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
616 //exit(1); // No function is allowed to leave the application instead
617 // of warning the caller
621 Fp->read((char*)&zero, (size_t)2);
628 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
629 // FIXME : We cannot be sure the preable is only zeroes..
630 // (see ACUSON-24-YBR_FULL-RLE.dcm )
632 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
633 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
634 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
635 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
637 std::string msg = Util::Format(
638 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
639 // FIXME : is it a Warning message, or a Debug message?
640 gdcmWarningMacro( msg.c_str() );
645 Fp->seekg(126L, std::ios::cur); // Once per Document
646 char dicm[4]; // = {' ',' ',' ',' '};
647 Fp->read(dicm, (size_t)4);
653 if ( memcmp(dicm, "DICM", 4) == 0 )
655 HasDCMPreamble = true;
659 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
661 // Don't user Warning nor Error, not to pollute the output
662 // while directory recursive parsing ...
663 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
664 << Filename.c_str());
669 * \brief closes the file
670 * @return TRUE if the close was successfull
672 bool Document::CloseFile()
684 * \brief Writes in a file all the Entries (Dicom Elements)
685 * @param fp file pointer on an already open file (actually: Output File Stream)
686 * @param filetype Type of the File to be written
687 * (ACR-NEMA, ExplicitVR, ImplicitVR)
689 void Document::WriteContent(std::ofstream *fp, FileType filetype)
691 // Skip if user wants to write an ACR-NEMA file
693 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
694 filetype == JPEG || filetype == JPEG2000 )
696 // writing Dicom File Preamble
697 char filePreamble[128];
698 memset(filePreamble, 0, 128);
699 fp->write(filePreamble, 128);
700 fp->write("DICM", 4);
703 * \todo rewrite later, if really usefull
704 * - 'Group Length' element is optional in DICOM
705 * - but un-updated odd groups lengthes can causes pb
708 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
709 * UpdateGroupLength(false,filetype);
710 * if ( filetype == ACR)
711 * UpdateGroupLength(true,ACR);
713 * --> Computing group length for groups with embeded Sequences
714 * --> was too much tricky / we were [in a hurry / too lazy]
715 * --> We don't write the element 0x0000 (group length)
718 ElementSet::WriteContent(fp, filetype); // This one is recursive
721 // -----------------------------------------
724 * \brief Loads (from disk) the element content
725 * when a string is not suitable
726 * @param group group number of the Entry
727 * @param elem element number of the Entry
729 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
731 // Search the corresponding DocEntry
732 DocEntry *docEntry = GetDocEntry(group, elem);
735 gdcmDebugMacro(std::hex << group << "|" << elem
736 << " doesn't exist" );
739 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
742 gdcmWarningMacro(std::hex << group << "|" << elem
743 << " is NOT a DataEntry");
746 LoadEntryBinArea(dataEntry);
750 * \brief Loads (from disk) the element content
751 * when a string is not suitable
752 * @param entry Entry whose binArea is going to be loaded
754 void Document::LoadEntryBinArea(DataEntry *entry)
756 if( entry->GetBinArea() )
763 //size_t o =(size_t)entry->GetOffset();
764 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
766 size_t l = entry->GetLength();
767 uint8_t *data = new uint8_t[l];
770 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
771 << std::hex << entry->GetGroup()
772 << "|" << entry->GetElement() );
777 Fp->read((char*)data, l);
778 if ( Fp->fail() || Fp->eof() )
781 entry->SetState(DataEntry::STATE_UNREAD);
785 // Swap the data content if necessary
787 unsigned short vrLgth =
788 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
790 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
791 // if( entry->GetVR() == "OW" )
802 uint16_t *data16 = (uint16_t *)data;
803 for(i=0;i<l/vrLgth;i++)
804 data16[i] = SwapShort(data16[i]);
809 uint32_t *data32 = (uint32_t *)data;
810 for(i=0;i<l/vrLgth;i++)
811 data32[i] = SwapLong(data32[i]);
816 double *data64 = (double *)data;
817 for(i=0;i<l/vrLgth;i++)
818 data64[i] = SwapDouble(data64[i]);
823 entry->SetBinArea(data);
825 if ( openFile ) // The file is left in the state (open/close) it was at entrance
830 * \brief Loads the element while preserving the current
831 * underlying file position indicator as opposed to
832 * LoadDocEntry that modifies it
833 * \note seems to be unused!.
834 * @param entry DocEntry whose value will be loaded.
836 //void Document::LoadDocEntrySafe(DocEntry *entry)
840 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
841 // LoadDocEntry(entry);
842 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
847 * \brief Compares two documents, according to \ref DicomDir rules
848 * \warning Does NOT work with ACR-NEMA files
849 * \todo Find a trick to solve the pb (use RET fields ?)
850 * @param document to compare with current one
851 * @return true if 'smaller'
853 bool Document::operator<(Document &document)
856 std::string s1 = GetEntryString(0x0010,0x0010);
857 std::string s2 = document.GetEntryString(0x0010,0x0010);
869 s1 = GetEntryString(0x0010,0x0020);
870 s2 = document.GetEntryString(0x0010,0x0020);
881 // Study Instance UID
882 s1 = GetEntryString(0x0020,0x000d);
883 s2 = document.GetEntryString(0x0020,0x000d);
894 // Serie Instance UID
895 s1 = GetEntryString(0x0020,0x000e);
896 s2 = document.GetEntryString(0x0020,0x000e);
911 //-----------------------------------------------------------------------------
915 * \brief Reads a given length of bytes
916 * (in order to avoid to many CPU time consuming fread-s)
917 * @param l length to read
919 void Document::ReadBegBuffer(size_t l)
922 Fp->read (BegBuffer, (size_t)l);
925 throw FormatError( "Document::ReadBegBuffer()", " file error." );
929 throw FormatError( "Document::ReadBegBuffer()", "EOF." );
931 PtrBegBuffer = BegBuffer;
932 CurrentOffsetPosition+=l;
935 * \brief Reads a supposed to be 16 Bits integer
936 * (swaps it depending on processor endianness)
939 uint16_t Document::ReadInt16()
943 Fp->read ((char*)&g, (size_t)2);
946 throw FormatError( "Document::ReadInt16()", " file error." );
950 throw FormatError( "Document::ReadInt16()", "EOF." );
957 * \brief Gets from BegBuffer a supposed to be 16 Bits integer
958 * (swaps it depending on processor endianness)
961 uint16_t Document::GetInt16()
963 uint16_t g = *((uint16_t*)PtrBegBuffer);
969 * \brief Reads a supposed to be 32 Bits integer
970 * (swaps it depending on processor endianness)
973 uint32_t Document::ReadInt32()
977 Fp->read ((char*)&g, (size_t)4);
980 throw FormatError( "Document::ReadInt32()", " file error." );
984 throw FormatError( "Document::ReadInt32()", "EOF." );
991 * \brief Gets from BegBuffer a supposed to be 32 Bits integer
992 * (swaps it depending on processor endianness)
995 uint32_t Document::GetInt32()
997 uint32_t g = *((uint32_t*)PtrBegBuffer);
1004 * \brief Re-computes the length of the Dicom group 0002.
1006 int Document::ComputeGroup0002Length( )
1011 int groupLength = 0;
1012 bool found0002 = false;
1014 // for each zero-level Tag in the DCM Header
1015 DocEntry *entry = GetFirstEntry();
1018 gr = entry->GetGroup();
1024 if ( entry->GetElement() != 0x0000 )
1026 vr = entry->GetVR();
1028 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
1029 // (no SQ, OW, UT in group 0x0002;)
1032 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
1035 groupLength += 2 + 2 + 4 + entry->GetLength();
1038 else if (found0002 )
1041 entry = GetNextEntry();
1047 * \brief CallStartMethod
1049 void Document::CallStartMethod()
1053 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1057 * \brief CallProgressMethod
1059 void Document::CallProgressMethod()
1061 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1065 * \brief CallEndMethod
1067 void Document::CallEndMethod()
1070 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1073 //-----------------------------------------------------------------------------
1076 * \brief Loads all the needed Dictionaries
1077 * \warning NOT end user intended method !
1079 void Document::Initialize()
1081 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1087 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1088 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1089 * @param offset start of parsing
1090 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1091 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1093 void Document::ParseDES(DocEntrySet *set, long offset,
1094 long l_max, bool delim_mode)
1096 DocEntry *newDocEntry;
1097 DataEntry *newDataEntry;
1098 SeqEntry *newSeqEntry;
1100 bool used; // will be set to false when something wrong happens to an Entry.
1101 // (Entry will then be deleted)
1102 bool delim_mode_intern = delim_mode;
1104 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1105 << " at offset " << std::hex << "0x(" << offset << ")" );
1109 ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1110 /// Probabely a bug in gdcm code somwhere (some memory erased ?)
1112 // Uncomment to track the bug
1114 if( Debug::GetDebugFlag() )
1115 std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1116 << std::hex << " 0x(" <<(long)(Fp->tellg()) << ")" << std::endl;
1119 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1120 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1121 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1126 newDocEntry = ReadNextDocEntry( );
1133 // Uncoment this cerr line to be able to 'follow' the DocEntries
1134 // when something *very* strange happens
1135 if( Debug::GetDebugFlag() )
1136 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1138 // an Item Starter found elsewhere but in the first position
1139 // of a SeqEntry means previous entry was a Sequence
1140 // but we didn't get it (private Sequence + Implicit VR)
1141 // we have to backtrack.
1142 if ( !first && newDocEntry->IsItemStarter() )
1144 // Debug message within the method !
1145 newDocEntry = Backtrack(newDocEntry);
1149 PreviousDocEntry = newDocEntry;
1153 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1157 //////////////////////////// DataEntry
1159 //vr = newDocEntry->GetVR(); // useless ?
1161 if ( !set->AddEntry( newDataEntry ) )
1163 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1164 << newDataEntry->GetKey()
1165 << " (at offset : 0x("
1166 << newDataEntry->GetOffset() << ") )" );
1171 newDataEntry->Delete();
1172 // Load only if we can add (not a duplicate key)
1173 LoadDocEntry( newDataEntry );
1175 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1177 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1179 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1181 std::string strLgrGroup = newDataEntry->GetString();
1184 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1186 lgrGroup = atoi(strLgrGroup.c_str());
1187 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1188 RemoveEntry( newDocEntry ); // Remove and delete
1195 bool delimitor = newDataEntry->IsItemDelimitor();
1196 bool outOfBounds = false;
1198 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1201 // 'and then', 'or else' don't exist in C++ :-(
1202 // if ( (delimitor) ||
1203 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1205 if ( delimitor || outOfBounds )
1208 newDocEntry->Delete();
1212 // Just to make sure we are at the beginning of next entry.
1213 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1217 /////////////////////// SeqEntry : VR = "SQ"
1219 unsigned long l = newDocEntry->GetReadLength();
1220 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1222 if ( l == 0xffffffff )
1224 delim_mode_intern = true;
1228 delim_mode_intern = false;
1232 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1234 // User asked to skip SeQuences *only* if they belong to Shadow Group
1235 if ( newDocEntry->GetGroup()%2 != 0 )
1237 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1238 newDocEntry->Delete(); // Delete, not in the set
1242 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1244 // User asked to skip *any* SeQuence
1245 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1246 newDocEntry->Delete(); // Delete, not in the set
1249 // delay the dynamic cast as late as possible
1250 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1252 // no other way to create the Delimitor ...
1253 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1255 // At the top of the hierarchy, stands a Document. When "set"
1256 // is a Document, then we are building the first depth level.
1257 // Hence the SeqEntry we are building simply has a depth
1259 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1261 newSeqEntry->SetDepthLevel( 1 );
1263 // But when "set" is already a SQItem, we are building a nested
1264 // sequence, and hence the depth level of the new SeqEntry
1265 // we are building, is one level deeper:
1267 // time waste hunting
1268 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1270 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1274 { // Don't try to parse zero-length sequences
1276 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1277 << " at offset 0x(" << std::hex
1278 << newDocEntry->GetOffset() << ")");
1280 ParseSQ( newSeqEntry,
1281 newDocEntry->GetOffset(),
1282 l, delim_mode_intern);
1284 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1286 if ( !set->AddEntry( newSeqEntry ) )
1288 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1289 << newSeqEntry->GetKey()
1290 << " (at offset : 0x("
1291 << newSeqEntry->GetOffset() << ") )" );
1296 newDocEntry->Delete();
1299 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1301 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1302 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1306 newDocEntry->Delete();
1309 } // end SeqEntry : VR = "SQ"
1313 newDocEntry->Delete();
1317 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1321 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1322 * @return parsed length for this level
1324 void Document::ParseSQ( SeqEntry *seqEntry,
1325 long offset, long l_max, bool delim_mode)
1327 int SQItemNumber = 0;
1329 long offsetStartCurrentSQItem = offset;
1333 // the first time, we read the fff0,e000 of the first SQItem
1334 DocEntry *newDocEntry = ReadNextDocEntry();
1338 gdcmWarningMacro("in ParseSQ : should never get here!");
1343 if ( newDocEntry->IsSequenceDelimitor() )
1345 seqEntry->SetDelimitationItem( newDocEntry );
1346 newDocEntry->Delete();
1350 else // ! delim_mode
1352 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1354 newDocEntry->Delete();
1358 // create the current SQItem
1359 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1360 unsigned int l = newDocEntry->GetReadLength();
1362 if ( l == 0xffffffff )
1371 // fill up the current SQItem, starting at the beginning of fff0,e000
1373 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); // Once per SQItem
1374 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1375 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1377 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1379 newDocEntry->Delete();
1381 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1382 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1390 * \brief When a private Sequence + Implicit VR is encountered
1391 * we cannot guess it's a Sequence till we find the first
1392 * Item Starter. We then backtrack to do the job.
1393 * @param docEntry Item Starter that warned us
1395 DocEntry *Document::Backtrack(DocEntry *docEntry)
1397 // delete the Item Starter, built erroneously out of any Sequence
1398 // it's not yet in the HTable/chained list
1401 // Get all info we can from PreviousDocEntry
1402 uint16_t group = PreviousDocEntry->GetGroup();
1403 uint16_t elem = PreviousDocEntry->GetElement();
1404 uint32_t lgt = PreviousDocEntry->GetLength();
1405 long offset = PreviousDocEntry->GetOffset();
1407 gdcmDebugMacro( "Backtrack :" << std::hex << group
1409 << " at offset 0x(" <<offset << ")" );
1410 RemoveEntry( PreviousDocEntry );
1412 // forge the Seq Entry
1413 DocEntry *newEntry = NewSeqEntry(group, elem);
1414 newEntry->SetLength(lgt);
1415 newEntry->SetOffset(offset);
1417 // Move back to the beginning of the Sequence
1419 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1424 * \brief Loads (or not) the element content depending if its length exceeds
1425 * or not the value specified with Document::SetMaxSizeLoadEntry()
1426 * @param entry Header Entry (Dicom Element) to be dealt with
1427 * @param forceLoad whether you want to force loading of 'long' elements
1429 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1431 uint16_t group = entry->GetGroup();
1432 uint16_t elem = entry->GetElement();
1433 const VRKey &vr = entry->GetVR();
1434 uint32_t length = entry->GetLength();
1436 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1438 // A SeQuence "contains" a set of Elements.
1439 // (fffe e000) tells us an Element is beginning
1440 // (fffe e00d) tells us an Element just ended
1441 // (fffe e0dd) tells us the current SeQuence just ended
1442 // (fffe 0000) is an 'impossible' tag value,
1443 // found in MR-PHILIPS-16-Multi-Seq.dcm
1445 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1447 // NO more value field for SQ !
1451 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1457 // When the length is zero things are easy:
1460 dataEntryPtr->SetBinArea(NULL,true);
1464 // The elements whose length is bigger than the specified upper bound
1469 if (length > MaxSizeLoadEntry)
1471 dataEntryPtr->SetBinArea(NULL,true);
1472 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1474 // to be sure we are at the end of the value ...
1475 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1476 // std::ios::beg); //JPRx
1481 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1482 /// + a ForceLoad call on the +/- 20 'usefull' fields
1483 /// Allow user to tell the fields he wants to ForceLoad
1484 /// during initial stage.
1485 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1486 /// + a method that load *everything* that's not yet loaded
1488 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1492 * \brief Find the value Length of the passed Doc Entry
1493 * @param entry Header Entry whose length of the value shall be loaded.
1495 void Document::FindDocEntryLength( DocEntry *entry )
1496 throw ( FormatError )
1498 const VRKey &vr = entry->GetVR();
1501 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1503 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1506 // The following reserved two bytes (see PS 3.5-2003, section
1507 // "7.1.2 Data element structure with explicit vr", p 27) must be
1508 // skipped before proceeding on reading the length on 4 bytes.
1510 //Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1511 uint32_t length32 = ReadInt32(); // Once per OW,OB,SQ DocEntry
1512 CurrentOffsetPosition+=4;
1513 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1518 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1520 catch ( FormatUnexpected )
1522 // Computing the length failed (this happens with broken
1523 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1524 // chance to get the pixels by deciding the element goes
1525 // until the end of the file. Hence we artificially fix the
1526 // the length and proceed.
1527 gdcmWarningMacro( " Computing the length failed for " <<
1528 entry->GetKey() <<" in " <<GetFileName());
1530 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1531 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1533 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1534 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1536 entry->SetReadLength(lengthUntilEOF);
1537 entry->SetLength(lengthUntilEOF);
1540 entry->SetReadLength(lengthOB);
1541 entry->SetLength(lengthOB);
1544 FixDocEntryFoundLength(entry, length32);
1548 // Length is encoded on 2 bytes.
1549 //length16 = ReadInt16();
1550 length16 = GetInt16();
1552 // 0xffff means that we deal with 'No Length' Sequence
1553 // or 'No Length' SQItem
1554 if ( length16 == 0xffff)
1558 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1563 // Either implicit VR or a non DICOM conformal (see note below) explicit
1564 // VR that ommited the VR of (at least) this element. Farts happen.
1565 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1566 // on Data elements "Implicit and Explicit VR Data Elements shall
1567 // not coexist in a Data Set and Data Sets nested within it".]
1568 // Length is on 4 bytes.
1570 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1571 // even if Transfer Syntax is 'Implicit VR ...'
1572 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1573 // where Group 0x0002 is *also* encoded in Implicit VR !
1575 FixDocEntryFoundLength( entry, GetInt32() /*ReadInt32()*/ );
1581 * \brief Find the Length till the next sequence delimiter
1582 * \warning NOT end user intended method !
1585 uint32_t Document::FindDocEntryLengthOBOrOW()
1586 throw( FormatUnexpected )
1588 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1590 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1592 bool foundSequenceDelimiter = false;
1593 uint32_t totalLength = 0;
1595 while ( !foundSequenceDelimiter )
1602 //group = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1603 //elem = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1604 ReadBegBuffer(4); // Once per fragment (if any) of OB,OW DataElements
1606 catch ( FormatError )
1608 throw FormatError("Unexpected end of file encountered during ",
1609 "Document::FindDocEntryLengthOBOrOW()");
1614 // We have to decount the group and element we just read
1616 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1619 "Neither an Item tag nor a Sequence delimiter tag on :"
1620 << std::hex << group << " , " << elem
1623 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1624 throw FormatUnexpected(
1625 "Neither an Item tag nor a Sequence delimiter tag.");
1627 if ( elem == 0xe0dd )
1629 foundSequenceDelimiter = true;
1631 uint32_t itemLength = ReadInt32(); // Once per fragment (if any) of OB,OW DataElements
1632 // We add 4 bytes since we just read the ItemLength with ReadInt32
1633 totalLength += itemLength + 4;
1634 SkipBytes(itemLength);
1636 if ( foundSequenceDelimiter )
1641 Fp->seekg( positionOnEntry, std::ios::beg); // Only once for OB,OW DataElements
1646 * \brief Find the Value Representation of the current Dicom Element.
1647 * @return Value Representation of the current Entry
1649 VRKey Document::FindDocEntryVR()
1651 if ( Filetype != ExplicitVR )
1653 return GDCM_VRUNKNOWN;
1656 // Delimiters (0xfffe), are not explicit VR ...
1657 if ( CurrentGroup == 0xfffe )
1658 return GDCM_VRUNKNOWN;
1660 //long positionOnEntry;
1661 //if( Debug::GetWarningFlag() )
1662 // positionOnEntry = Fp->tellg(); // Only in Warning Mode
1664 // Warning: we believe this is explicit VR (Value Representation) because
1665 // we used a heuristic that found "UL" in the first tag and/or
1666 // 'Transfer Syntax' told us it is.
1667 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1668 // In some cases one finds implicit VR tags mixed within an explicit VR file
1670 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1672 // Hence we make sure the present tag is in explicit VR and try to fix things
1673 // if it happens not to be the case.
1676 //Fp->read(&(vr[0]),(size_t)2);
1677 vr[0] = *PtrBegBuffer++;
1678 vr[1] = *PtrBegBuffer++;
1680 //if ( !CheckDocEntryVR(vr) ) // avoid useless function call
1681 if ( !Global::GetVR()->IsValidVR(vr) )
1684 // std::cout << "================================================================Unknown VR"
1685 << std::hex << "0x("
1686 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1687 << ")" << "for : " << CurrentGroup
1688 << " at offset : 0x(" << positionOnEntry << ")"
1691 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1692 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1694 << " at offset : 0x(" << CurrentOffsetPosition-4<< ") for group " << CurrentGroup
1697 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1698 //Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1699 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1701 return GDCM_VRUNKNOWN;
1707 * \brief Check the correspondance between the VR of the header entry
1708 * and the taken VR. If they are different, the header entry is
1709 * updated with the new VR.
1710 * @param vr Dicom Value Representation
1711 * @return false if the VR is incorrect or if the VR isn't referenced
1712 * otherwise, it returns true
1714 bool Document::CheckDocEntryVR(const VRKey &vr)
1716 return Global::GetVR()->IsValidVR(vr);
1720 * \brief Skip a given Header Entry
1721 * @param entry entry to skip
1723 void Document::SkipDocEntry(DocEntry *entry)
1725 SkipBytes(entry->GetLength());
1729 * \brief Skips to the beginning of the next Header Entry
1730 * @param currentDocEntry entry to skip
1732 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1734 long l = currentDocEntry->GetReadLength();
1735 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1736 // ... but PMS imagers happen !
1738 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1739 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1741 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1746 * \brief When the length of an element value is obviously wrong (because
1747 * the parser went Jabberwocky) one can hope improving things by
1748 * applying some heuristics.
1749 * @param entry entry to check
1750 * @param foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)
1752 void Document::FixDocEntryFoundLength(DocEntry *entry,
1753 uint32_t foundLength)
1755 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1757 if ( foundLength == 0xffffffff)
1760 //entry->SetLength(foundLength);
1761 entry->SetLength(0);
1762 return; // return ASAP; don't waist time on useless tests
1765 uint16_t gr = entry->GetGroup();
1766 uint16_t elem = entry->GetElement();
1768 if ( foundLength % 2)
1770 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1771 << " in x(" << std::hex << gr << "," << elem <<")");
1774 //////// Fix for some naughty General Electric images.
1775 // Allthough not recent many such GE corrupted images are still present
1776 // on Creatis hard disks. Hence this fix shall remain when such images
1777 // are no longer in use (we are talking a few years, here)...
1778 // Note: XMedCon probably uses such a trick since it is able to read
1779 // those pesky GE images ...
1780 if ( foundLength == 13)
1782 // Only happens for this length !
1783 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1786 entry->SetReadLength(10); // a bug is to be fixed !?
1790 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1791 // Occurence of such images is quite low (unless one leaves close to a
1792 // 'Leonardo' source. Hence, one might consider commenting out the
1793 // following fix on efficiency reasons.
1794 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1796 // Ideally we should check we are in Explicit and double check
1797 // that VR=UL... this is done properly in gdcm2
1798 if( foundLength == 6 )
1800 gdcmWarningMacro( "Replacing Length from 6 into 4" );
1802 entry->SetReadLength(4); // a bug is to be fixed !
1804 else if ( foundLength%4 )
1806 gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1807 "The length of this tag seems to be wrong" );
1811 else if ( entry->GetVR() == "SQ" )
1813 foundLength = 0; // ReadLength is unchanged
1816 //////// We encountered a 'delimiter' element i.e. a tag of the form
1817 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1818 // taken into account.
1819 else if ( gr == 0xfffe )
1821 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1822 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1823 // causes extra troubles...
1824 if ( elem != 0x0000 )
1830 foundLength=12; // to skip the mess that follows this bugged Tag !
1833 entry->SetLength(foundLength);
1837 * \brief Apply some heuristics to predict whether the considered
1838 * element value contains/represents an integer or not.
1839 * @param entry The element value on which to apply the predicate.
1840 * @return The result of the heuristical predicate.
1842 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1844 uint16_t elem = entry->GetElement();
1845 uint16_t group = entry->GetGroup();
1846 const VRKey &vr = entry->GetVR();
1847 uint32_t length = entry->GetLength();
1849 // When we have some semantics on the element we just read, and if we
1850 // a priori know we are dealing with an integer, then we shall be
1851 // able to swap it's element value properly.
1852 if ( elem == 0 ) // This is the group length of the group
1860 // Although this should never happen, still some images have a
1861 // corrupted group length [e.g. have a glance at offset x(8336) of
1862 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1863 // Since for dicom compliant and well behaved headers, the present
1864 // test is useless (and might even look a bit paranoid), when we
1865 // encounter such an ill-formed image, we simply display a warning
1866 // message and proceed on parsing (while crossing fingers).
1867 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1869 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1870 << std::hex << group << " , " << elem
1871 << ") -before- position x(" << filePosition << ")"
1872 << "lgt : " << length );
1876 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1884 * \brief Discover what the swap code is (among little endian, big endian,
1885 * bad little endian, bad big endian).
1887 * @return false when we are absolutely sure
1888 * it's neither ACR-NEMA nor DICOM
1889 * true when we hope ours assuptions are OK
1891 bool Document::CheckSwap()
1898 // First, compare HostByteOrder and NetworkByteOrder in order to
1899 // determine if we shall need to swap bytes (i.e. the Endian type).
1900 bool net2host = Util::IsCurrentProcessorBigEndian();
1902 // The easiest case is the one of a 'true' DICOM header, we just have
1903 // to look for the string "DICM" inside the file preamble.
1906 char *entCur = deb + 128;
1907 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1909 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1911 // Group 0002 should always be VR, and the first element 0000
1912 // Let's be carefull (so many wrong headers ...)
1913 // and determine the value representation (VR) :
1914 // Let's skip to the first element (0002,0000) and check there if we find
1915 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1916 // in which case we (almost) know it is explicit VR.
1917 // WARNING: if it happens to be implicit VR then what we will read
1918 // is the length of the group. If this ascii representation of this
1919 // length happens to be "UL" then we shall believe it is explicit VR.
1920 // We need to skip :
1921 // * the 128 bytes of File Preamble (often padded with zeroes),
1922 // * the 4 bytes of "DICM" string,
1923 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1924 // i.e. a total of 136 bytes.
1927 // group 0x0002 *is always* Explicit VR Sometimes ,
1928 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1929 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1931 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1932 memcmp(entCur, "OB", (size_t)2) == 0 ||
1933 memcmp(entCur, "UI", (size_t)2) == 0 ||
1934 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1935 // when Write DCM *adds*
1937 // Use Document::dicom_vr to test all the possibilities
1938 // instead of just checking for UL, OB and UI !? group 0000
1940 Filetype = ExplicitVR;
1941 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1945 Filetype = ImplicitVR;
1946 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1947 << "Looks like a bugged Header!");
1953 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1958 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1961 // Position the file position indicator at first tag
1962 // (i.e. after the file preamble and the "DICM" string).
1964 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1965 CurrentOffsetPosition = 132;
1967 } // ------------------------------- End of DicomV3 ----------------
1969 // Alas, this is not a DicomV3 file and whatever happens there is no file
1970 // preamble. We can reset the file position indicator to where the data
1971 // is (i.e. the beginning of the file).
1973 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1975 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1976 CurrentOffsetPosition = 0;
1977 // Let's check 'No Preamble Dicom File' :
1978 // Should start with group 0x0002
1979 // and be Explicit Value Representation
1981 s16 = *((uint16_t *)(deb));
1994 if ( SwapCode != 0 )
1996 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1997 memcmp(entCur, "OB", (size_t)2) == 0 ||
1998 memcmp(entCur, "UI", (size_t)2) == 0 ||
1999 memcmp(entCur, "SH", (size_t)2) == 0 ||
2000 memcmp(entCur, "AE", (size_t)2) == 0 ||
2001 memcmp(entCur, "OB", (size_t)2) == 0 )
2003 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
2004 // Wait untill reading Transfer Syntax
2005 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
2009 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2011 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2012 // By clean we mean that the length of the first group is written down.
2013 // If this is the case and since the length of the first group HAS to be
2014 // four (bytes), then determining the proper swap code is straightforward.
2017 // We assume the array of char we are considering contains the binary
2018 // representation of a 32 bits integer. Hence the following dirty
2020 s32 = *((uint32_t *)(entCur));
2040 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2041 // It is time for despaired wild guesses.
2042 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2043 // i.e. the 'group length' element is not present :
2045 // check the supposed-to-be 'group number'
2046 // in ( 0x0001 .. 0x0008 )
2047 // to determine ' SwapCode' value .
2048 // Only 0 or 4321 will be possible
2049 // (no oportunity to check for the formerly well known
2050 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2051 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
2052 // the file IS NOT ACR-NEMA nor DICOM V3
2053 // Find a trick to tell it the caller...
2055 s16 = *((uint16_t *)(deb));
2057 gdcmDebugMacro("not a DicomV3 nor a 'clean' ACR/NEMA;"
2058 << " (->despaired wild guesses !)");
2085 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2093 * \brief Change the Byte Swap code.
2095 void Document::SwitchByteSwapCode()
2097 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2098 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2099 if ( SwapCode == 1234 )
2103 else if ( SwapCode == 4321 )
2107 else if ( SwapCode == 3412 )
2111 else if ( SwapCode == 2143 )
2115 gdcmDebugMacro( " Into: "<< SwapCode );
2119 * \brief during parsing, Header Elements too long are not loaded in memory
2120 * @param newSize new size
2122 void Document::SetMaxSizeLoadEntry(long newSize)
2128 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2130 MaxSizeLoadEntry = 0xffffffff;
2133 MaxSizeLoadEntry = newSize;
2137 * \brief Read the next tag WITHOUT loading it's value
2138 * (read the 'Group Number', the 'Element Number',
2139 * gets the Dict Entry
2140 * gets the VR, gets the length, gets the offset value)
2141 * @return On succes : the newly created DocEntry, NULL on failure.
2143 DocEntry *Document::ReadNextDocEntry()
2147 ReadBegBuffer(8); // Avoid to many time consuming freads
2148 //CurrentGroup = ReadInt16();
2149 //CurrentElem = ReadInt16();
2151 catch ( FormatError )
2153 // We reached the EOF (or an error occured) therefore
2154 // header parsing has to be considered as finished.
2158 CurrentGroup = GetInt16();
2159 CurrentElem = GetInt16();
2161 // In 'true DICOM' files Group 0002 is always little endian
2162 if ( HasDCMPreamble )
2164 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2165 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2167 // Sometimes file contains groups of tags with reversed endianess.
2168 HandleBrokenEndian(CurrentGroup, CurrentElem);
2171 VRKey vr = FindDocEntryVR();
2174 if ( vr == GDCM_VRUNKNOWN )
2176 if ( CurrentElem == 0x0000 ) // Group Length
2178 realVR = "UL"; // must be UL
2180 else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2185 // Commented out in order not to generate 'Shadow Groups' where some
2186 // Data Elements are Explicit VR and some other ones Implicit VR
2187 // (Stupid MatLab DICOM Reader couldn't read gdcm-written images)
2189 else if (CurrentGroup%2 == 1 &&
2190 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2192 // DICOM PS 3-5 7.8.1 a) states that those
2193 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2199 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2202 realVR = dictEntry->GetVR();
2203 dictEntry->Unregister(); // GetDictEntry registered it
2209 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2212 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2216 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2217 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2220 if ( vr == GDCM_VRUNKNOWN )
2222 if ( Filetype == ExplicitVR )
2224 // We thought this was explicit VR, but we end up with an
2225 // implicit VR tag. Let's backtrack.
2227 //if ( newEntry->GetGroup() != 0xfffe )
2228 if (CurrentGroup != 0xfffe)
2230 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2232 gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2233 << offset << ") should be Explicit VR");
2236 newEntry->SetImplicitVR();
2241 FindDocEntryLength(newEntry);
2243 catch ( FormatError )
2250 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2255 * \brief Handle broken private tag from Philips NTSCAN
2256 * where the endianess is being switched to BigEndian
2257 * for no apparent reason
2260 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2262 // for strange PMS Gyroscan Intera images
2263 // Item 'starter' has a tag : 0x3f3f,0x3f00, for no apparent reason
2265 // --- Feel free to remove this test *on your own coy of gdcm*
2266 // if you are sure you'll never face this problem.
2268 if ((group == 0x3f3f) && (elem == 0x3f00))
2270 // start endian swap mark for group found
2271 gdcmDebugMacro( " delimiter 0x3f3f found." );
2277 // --- End of removable code
2279 // Endian reversion.
2280 // Some files contain groups of tags with reversed endianess.
2281 static int reversedEndian = 0;
2282 // try to fix endian switching in the middle of headers
2283 if ((group == 0xfeff) && (elem == 0x00e0))
2285 // start endian swap mark for group found
2286 gdcmDebugMacro( "Start endian swap mark found." );
2288 SwitchByteSwapCode();
2293 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2295 // end of reversed endian group
2296 gdcmDebugMacro( "End of reversed endian." );
2298 SwitchByteSwapCode();
2300 else if (group == 0xfeff && elem == 0xdde0)
2302 // reversed Sequence Terminator found
2303 // probabely a bug in the header !
2304 // Do what you want, it breaks !
2306 //SwitchByteSwapCode();
2307 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2312 else if (group == 0xfffe && elem == 0xe0dd)
2314 gdcmDebugMacro( "Straight Sequence Terminator." );
2319 * \brief Group 0002 is always coded Little Endian
2320 * whatever Transfer Syntax is
2323 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2325 // Endian reversion.
2326 // Some files contain groups of tags with reversed endianess.
2328 Group0002Parsed = true;
2329 // we just came out of group 0002
2330 // if Transfer Syntax is Big Endian we have to change CheckSwap
2332 std::string ts = GetTransferSyntax();
2333 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2335 // Group 0002 is always 'Explicit ...'
2336 // even when Transfer Syntax says 'Implicit ..."
2338 if ( s == TS::ImplicitVRLittleEndian
2340 s == TS::ImplicitVRBigEndianPrivateGE
2343 Filetype = ImplicitVR;
2346 // FIXME Strangely, this works with
2347 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2349 // --> Probabely normal, since we considered we never have
2350 // to trust manufacturers.
2351 // (we find very often 'Implicit VR' tag,
2352 // even when Transfer Syntax tells us it's Explicit ...
2354 if ( s == TS::ExplicitVRBigEndian )
2356 gdcmDebugMacro("Transfer Syntax Name = ["
2357 << GetTransferSyntaxName() << "]" );
2358 SwitchByteSwapCode();
2359 group = SwapShort(group);
2360 elem = SwapShort(elem);
2363 /// \todo find a trick to warn user and stop processing
2365 if ( s == TS::DeflatedExplicitVRLittleEndian)
2367 gdcmWarningMacro("Transfer Syntax ["
2368 << GetTransferSyntaxName() << "] :"
2369 << " not yet dealt with ");
2373 // The following shouldn't occur very often
2374 // Let's check at the very end.
2376 if ( ts == GDCM_UNKNOWN )
2378 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2382 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2384 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2390 //-----------------------------------------------------------------------------
2393 //-----------------------------------------------------------------------------
2394 } // end namespace gdcm