1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2006/02/09 10:48:04 $
7 Version: $Revision: 1.341 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmSeqEntry.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmDebug.h"
25 #include "gdcmDictSet.h"
26 #include "gdcmDocEntrySet.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
33 #include <ctype.h> // for isdigit
34 #include <stdlib.h> // for atoi
36 #if defined(__BORLANDC__)
37 #include <mem.h> // for memset
42 //-----------------------------------------------------------------------------
44 // Refer to Document::SetMaxSizeLoadEntry()
45 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
49 // Constructors and destructors are protected to avoid user to invoke directly
52 * \brief This default constructor neither loads nor parses the file.
53 * You should then invoke \ref Document::Load.
61 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
64 Filetype = ExplicitVR;
65 // Load will set it to true if sucessfull
66 Group0002Parsed = false;
67 IsDocumentAlreadyLoaded = false;
68 IsDocumentModified = true;
69 LoadMode = LD_ALL; // default : load everything, later
74 * \brief Canonical destructor.
76 Document::~Document ()
81 //-----------------------------------------------------------------------------
84 * \brief Loader. use SetLoadMode(), SetFileName() before !
85 * @return false if file cannot be open or no swap info was found,
86 * or no tag was found.
88 bool Document::Load( )
90 if ( GetFileName() == "" )
92 gdcmWarningMacro( "Use SetFileName, before !" );
95 return DoTheLoadingDocumentJob( );
99 * \brief Performs the Loading Job (internal use only)
100 * @return false if file cannot be open or no swap info was found,
101 * or no tag was found.
103 bool Document::DoTheLoadingDocumentJob( )
105 if ( ! IsDocumentModified ) // Nothing to do !
113 // warning already performed in OpenFile()
118 Group0002Parsed = false;
120 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
122 // Computes the total length of the file
123 Fp->seekg(0, std::ios::end); // Once per Document !
124 long lgt = Fp->tellg(); // Once per Document !
125 Fp->seekg(0, std::ios::beg); // Once per Document !
127 // CheckSwap returns a boolean
128 // (false if no swap info of any kind was found)
131 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
132 << Filename.c_str());
137 long beg = Fp->tellg(); // just after DICOM preamble (if any)
139 lgt -= beg; // remaining length to parse
142 // Loading is done during parsing
143 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
147 gdcmErrorMacro( "No tag in internal hash table for: "
148 << Filename.c_str());
152 IsDocumentAlreadyLoaded = true;
154 //Fp->seekg(0, std::ios::beg); // Once per Document!
156 // Load 'non string' values
158 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
159 if ( PhotometricInterpretation == "PALETTE COLOR " )
162 // Probabely this line should be outside the 'if'
163 // Try to find an image sample holding a 'gray LUT'
164 LoadEntryBinArea(0x0028,0x1200); // gray LUT
167 /// --> FIXME : The difference between BinEntry and DataEntry
168 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
169 /// --> Old comment restored on purpose.
170 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
171 /// --> had absolutely no meaning.
172 /// --> The whole comment will be removed when the stuff is cleaned !
174 /// The tags refered by the three following lines used to be CORRECTLY
175 /// defined as having an US Value Representation in the public
176 /// dictionary. BUT the semantics implied by the three following
177 /// lines state that the corresponding tag contents are in fact
178 /// the ones of a BinEntry.
179 /// In order to fix things "Quick and Dirty" the dictionary was
180 /// altered on PURPOSE but now contains a WRONG value.
181 /// In order to fix things and restore the dictionary to its
182 /// correct value, one needs to decide of the semantics by deciding
183 /// whether the following tags are either :
184 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
185 /// also used as BinEntry, which requires the proper conversion,
186 /// - OW, and hence loaded as BinEntry, but afterwards also used
187 /// as ValEntry, which requires the proper conversion.
189 // --> OB (byte aray) or OW (short int aray)
190 // The actual VR has to be deduced from other entries.
191 // Our way of loading them may fail in some cases :
192 // We must or not SwapByte depending on other field values.
194 LoadEntryBinArea(0x0028,0x1201); // R LUT
195 LoadEntryBinArea(0x0028,0x1202); // G LUT
196 LoadEntryBinArea(0x0028,0x1203); // B LUT
198 // Segmented Red Palette Color LUT Data
199 LoadEntryBinArea(0x0028,0x1221);
200 // Segmented Green Palette Color LUT Data
201 LoadEntryBinArea(0x0028,0x1222);
202 // Segmented Blue Palette Color LUT Data
203 LoadEntryBinArea(0x0028,0x1223);
206 //FIXME later : how to use it?
207 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
210 SQItem *sqi= modLutSeq->GetFirstSQItem();
213 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
214 if ( dataEntry != 0 )
216 if ( dataEntry->GetLength() != 0 )
218 // FIXME : CTX dependent means : contexted dependant.
219 // see upper comment.
220 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
226 // Force Loading some more elements if user asked to.
229 for (ListElements::iterator it = UserForceLoadList.begin();
230 it != UserForceLoadList.end();
233 gdcmDebugMacro( "Force Load " << std::hex
234 << (*it).Group << "|" <<(*it).Elem );
236 d = GetDocEntry( (*it).Group, (*it).Elem);
240 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
241 << (*it).Group <<"|"<< (*it).Elem
242 << " that doesn't exist" );
246 LoadDocEntry(d, true);
251 // ----------------------------
252 // Specific code to allow gdcm to read ACR-LibIDO formated images
253 // Note: ACR-LibIDO is an extension of the ACR standard that was
254 // used at CREATIS. For the time being (say a couple of years)
255 // we keep this kludge to allow CREATIS users
256 // reading their old images.
258 // if recognition code tells us we deal with a LibIDO image
259 // we switch lineNumber and columnNumber
262 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
263 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
264 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
265 // with "little-endian strings"
267 Filetype = ACR_LIBIDO;
268 std::string rows = GetEntryString(0x0028, 0x0010);
269 std::string columns = GetEntryString(0x0028, 0x0011);
270 SetEntryString(columns, 0x0028, 0x0010);
271 SetEntryString(rows , 0x0028, 0x0011);
273 // --- End of ACR-LibIDO kludge ---
279 * \brief Adds a new element we want to load anyway
280 * @param group Group number of the target tag.
281 * @param elem Element number of the target tag.
283 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
288 UserForceLoadList.push_back(el);
291 * \brief Get the public dictionary used
293 Dict *Document::GetPubDict()
299 * \brief Get the shadow dictionary used
301 Dict *Document::GetShaDict()
307 * \brief Set the shadow dictionary used
308 * @param dict dictionary to use in shadow
310 bool Document::SetShaDict(Dict *dict)
317 * \brief Set the shadow dictionary used
318 * @param dictName name of the dictionary to use in shadow
320 bool Document::SetShaDict(DictKey const &dictName)
322 RefShaDict = Global::GetDicts()->GetDict(dictName);
327 * \brief This predicate tells us whether or not the current Document
328 * was properly parsed and contains at least *one* Dicom Element
329 * (and nothing more, sorry).
330 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
333 bool Document::IsParsable()
335 if ( Filetype == Unknown )
337 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
343 gdcmWarningMacro( "No tag in internal hash table.");
350 * \brief This predicate tells us whether or not the current Document
351 * was properly parsed and contains at least *one* Dicom Element
352 * (and nothing more, sorry).
353 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
356 bool Document::IsReadable()
362 * \brief Predicate for dicom version 3 file.
363 * @return True when the file is a dicom version 3.
365 bool Document::IsDicomV3()
367 // Checking if Transfer Syntax exists is enough
368 // Anyway, it's too late check if the 'Preamble' was found ...
369 // And ... would it be a rich idea to check ?
370 // (some 'no Preamble' DICOM images exist !)
371 return GetDocEntry(0x0002, 0x0010) != NULL;
375 * \brief Predicate for Papyrus file
376 * Dedicated to whomsoever it may concern
377 * @return True when the file is a Papyrus file.
379 bool Document::IsPapyrus()
381 // check for Papyrus private Sequence
382 DocEntry *e = GetDocEntry(0x0041, 0x1050);
385 // check if it's actually a Sequence
386 if ( !dynamic_cast<SeqEntry*>(e) )
392 * \brief returns the File Type
393 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
394 * @return the FileType code
396 FileType Document::GetFileType()
402 * \brief Accessor to the Transfer Syntax (when present) of the
403 * current document (it internally handles reading the
404 * value from disk when only parsing occured).
405 * @return The encountered Transfer Syntax of the current document, if DICOM.
406 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
408 std::string Document::GetTransferSyntax()
410 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
416 // The entry might be present but not loaded (parsing and loading
417 // happen at different stages): try loading and proceed with check...
420 // (parsing and loading happen at the very same stage!)
421 //LoadDocEntrySafe(entry); //JPRx
422 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
424 std::string transfer = dataEntry->GetString();
425 // The actual transfer (as read from disk) might be padded. We
426 // first need to remove the potential padding. We can make the
427 // weak assumption that padding was not executed with digits...
428 if ( transfer.length() == 0 )
430 // for brain damaged headers
431 gdcmWarningMacro( "Transfer Syntax has length = 0.");
434 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
436 transfer.erase(transfer.length()-1, 1);
437 if ( transfer.length() == 0 )
439 // for brain damaged headers
440 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
450 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
451 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
453 std::string Document::GetTransferSyntaxName()
455 // use the TS (TS : Transfer Syntax)
456 std::string transferSyntax = GetEntryString(0x0002,0x0010);
458 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
460 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
461 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
462 return "Uncompressed ACR-NEMA";
464 if ( transferSyntax == GDCM_UNFOUND )
466 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
467 return "Uncompressed ACR-NEMA";
470 // we do it only when we need it
471 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
473 // Global::GetTS() is a global static you shall never try to delete it!
477 // --------------- Swap Code ------------------
479 * \brief Swaps the bytes so they agree with the processor order
480 * @return The properly swaped 16 bits integer.
482 uint16_t Document::SwapShort(uint16_t a)
484 if ( SwapCode == 4321 || SwapCode == 2143 )
486 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
488 a = ( a << 8 ) | ( a >> 8 );
494 * \brief Swaps back the bytes of 4-byte long integer accordingly to
496 * @return The properly swaped 32 bits integer.
498 uint32_t Document::SwapLong(uint32_t a)
505 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
506 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
508 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
509 ((a>>8) & 0x0000ff00) | (a>>24) );
512 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
513 a=( (a<<16) | (a>>16) );
516 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
519 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
526 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
528 * @return The properly swaped 64 bits double.
530 double Document::SwapDouble(double a)
534 // There were no 'double' at ACR-NEMA time.
535 // We just have to deal with 'straight Little Endian' and
536 // 'straight Big Endian'
541 char *beg = (char *)&a;
544 for (unsigned int i = 0; i<7; i++)
555 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
562 // -----------------File I/O ---------------
564 * \brief Tries to open the file \ref Document::Filename and
565 * checks the preamble when existing.
566 * @return The FILE pointer on success.
568 std::ifstream *Document::OpenFile()
570 HasDCMPreamble = false;
571 if (Filename.length() == 0)
578 gdcmDebugMacro( "File already open: " << Filename.c_str());
582 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
585 // Don't user gdcmErrorMacro :
586 // a spurious message will appear when you use, for instance
587 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
588 // to create outputFileName.
590 // FIXME : if the upper comment is still usefull
591 // --> the constructor is not so good ...
593 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
597 //exit(1); // No function is allowed to leave the application instead
598 // of warning the caller
602 Fp->read((char*)&zero, (size_t)2);
609 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
611 // FIXME : We cannot be sure the preable is only zeroes..
612 // (see ACUSON-24-YBR_FULL-RLE.dcm )
614 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
615 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
616 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
617 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
619 std::string msg = Util::Format(
620 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
621 // FIXME : is it a Warning message, or a Debug message?
622 gdcmWarningMacro( msg.c_str() );
627 Fp->seekg(126L, std::ios::cur); // Once per Document
628 char dicm[4]; // = {' ',' ',' ',' '};
629 Fp->read(dicm, (size_t)4);
635 if ( memcmp(dicm, "DICM", 4) == 0 )
637 HasDCMPreamble = true;
641 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
643 // Don't user Warning nor Error, not to polute the output
644 // while directory recursive parsing ...
645 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
646 << Filename.c_str());
651 * \brief closes the file
652 * @return TRUE if the close was successfull
654 bool Document::CloseFile()
666 * \brief Writes in a file all the Entries (Dicom Elements)
667 * @param fp file pointer on an already open file (actually: Output File Stream)
668 * @param filetype Type of the File to be written
669 * (ACR-NEMA, ExplicitVR, ImplicitVR)
671 void Document::WriteContent(std::ofstream *fp, FileType filetype)
673 // Skip if user wants to write an ACR-NEMA file
675 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
678 // writing Dicom File Preamble
679 char filePreamble[128];
680 memset(filePreamble, 0, 128);
681 fp->write(filePreamble, 128);
682 fp->write("DICM", 4);
686 * \todo rewrite later, if really usefull
687 * - 'Group Length' element is optional in DICOM
688 * - but un-updated odd groups lengthes can causes pb
691 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
692 * UpdateGroupLength(false,filetype);
693 * if ( filetype == ACR)
694 * UpdateGroupLength(true,ACR);
696 * --> Computing group length for groups with embeded Sequences
697 * --> was too much tricky / we were [in a hurry / too lazy]
698 * --> We don't write the element 0x0000 (group length)
701 ElementSet::WriteContent(fp, filetype); // This one is recursive
704 // -----------------------------------------
707 * \brief Loads (from disk) the element content
708 * when a string is not suitable
709 * @param group group number of the Entry
710 * @param elem element number of the Entry
712 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
714 // Search the corresponding DocEntry
715 DocEntry *docEntry = GetDocEntry(group, elem);
718 gdcmDebugMacro(std::hex << group << "|" << elem
719 << " doesn't exist" );
722 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
725 gdcmWarningMacro(std::hex << group << "|" << elem
726 << " is NOT a DataEntry");
729 LoadEntryBinArea(dataEntry);
733 * \brief Loads (from disk) the element content
734 * when a string is not suitable
735 * @param entry Entry whose binArea is going to be loaded
737 void Document::LoadEntryBinArea(DataEntry *entry)
739 if( entry->GetBinArea() )
746 //size_t o =(size_t)entry->GetOffset();
747 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
749 size_t l = entry->GetLength();
750 uint8_t *data = new uint8_t[l];
753 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
754 << std::hex << entry->GetGroup()
755 << "|" << entry->GetElement() );
760 Fp->read((char*)data, l);
761 if ( Fp->fail() || Fp->eof() )
764 entry->SetState(DataEntry::STATE_UNREAD);
768 // Swap the data content if necessary
770 unsigned short vrLgth =
771 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
773 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
774 // if( entry->GetVR() == "OW" )
785 uint16_t *data16 = (uint16_t *)data;
786 for(i=0;i<l/vrLgth;i++)
787 data16[i] = SwapShort(data16[i]);
792 uint32_t *data32 = (uint32_t *)data;
793 for(i=0;i<l/vrLgth;i++)
794 data32[i] = SwapLong(data32[i]);
799 double *data64 = (double *)data;
800 for(i=0;i<l/vrLgth;i++)
801 data64[i] = SwapDouble(data64[i]);
806 entry->SetBinArea(data);
808 if ( openFile ) // The file is left in the state (open/close) it was at entrance
813 * \brief Loads the element while preserving the current
814 * underlying file position indicator as opposed to
815 * LoadDocEntry that modifies it
816 * \note seems to be unused!.
817 * @param entry DocEntry whose value will be loaded.
819 //void Document::LoadDocEntrySafe(DocEntry *entry)
823 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
824 // LoadDocEntry(entry);
825 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
830 * \brief Compares two documents, according to \ref DicomDir rules
831 * \warning Does NOT work with ACR-NEMA files
832 * \todo Find a trick to solve the pb (use RET fields ?)
833 * @param document to compare with current one
834 * @return true if 'smaller'
836 bool Document::operator<(Document &document)
839 std::string s1 = GetEntryString(0x0010,0x0010);
840 std::string s2 = document.GetEntryString(0x0010,0x0010);
852 s1 = GetEntryString(0x0010,0x0020);
853 s2 = document.GetEntryString(0x0010,0x0020);
864 // Study Instance UID
865 s1 = GetEntryString(0x0020,0x000d);
866 s2 = document.GetEntryString(0x0020,0x000d);
877 // Serie Instance UID
878 s1 = GetEntryString(0x0020,0x000e);
879 s2 = document.GetEntryString(0x0020,0x000e);
894 //-----------------------------------------------------------------------------
897 * \brief Reads a supposed to be 16 Bits integer
898 * (swaps it depending on processor endianness)
901 uint16_t Document::ReadInt16()
905 Fp->read ((char*)&g, (size_t)2);
908 throw FormatError( "Document::ReadInt16()", " file error." );
912 throw FormatError( "Document::ReadInt16()", "EOF." );
919 * \brief Reads a supposed to be 32 Bits integer
920 * (swaps it depending on processor endianness)
923 uint32_t Document::ReadInt32()
927 Fp->read ((char*)&g, (size_t)4);
930 throw FormatError( "Document::ReadInt32()", " file error." );
934 throw FormatError( "Document::ReadInt32()", "EOF." );
941 * \brief Re-computes the length of the Dicom group 0002.
943 int Document::ComputeGroup0002Length( )
949 bool found0002 = false;
951 // for each zero-level Tag in the DCM Header
952 DocEntry *entry = GetFirstEntry();
955 gr = entry->GetGroup();
961 if ( entry->GetElement() != 0x0000 )
965 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
966 // (no SQ, OW, UT in group 0x0002;)
969 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
973 groupLength += 2 + 2 + 4 + entry->GetLength();
979 entry = GetNextEntry();
985 * \brief CallStartMethod
987 void Document::CallStartMethod()
991 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
995 * \brief CallProgressMethod
997 void Document::CallProgressMethod()
999 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1003 * \brief CallEndMethod
1005 void Document::CallEndMethod()
1008 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1011 //-----------------------------------------------------------------------------
1014 * \brief Loads all the needed Dictionaries
1016 void Document::Initialize()
1018 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1024 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1025 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1026 * @param offset start of parsing
1027 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1028 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1030 void Document::ParseDES(DocEntrySet *set, long offset,
1031 long l_max, bool delim_mode)
1033 DocEntry *newDocEntry;
1034 DataEntry *newDataEntry;
1035 SeqEntry *newSeqEntry;
1037 bool used; // will be set to false when something wrong happens to an Entry.
1038 // (Entry will then be deleted)
1039 bool delim_mode_intern = delim_mode;
1041 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1042 << " at offset " << std::hex << "0x(" << offset << ")" );
1045 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1047 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1048 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1052 newDocEntry = ReadNextDocEntry( );
1054 // Uncoment this cerr line to be able to 'follow' the DocEntries
1055 // when something *very* strange happens
1056 if( Debug::GetDebugFlag() )
1057 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1064 // an Item Starter found elsewhere but the first position
1065 // of a SeqEntry means previous entry was a Sequence
1066 // but we didn't get it (private Sequence + Implicit VR)
1067 // we have to backtrack.
1068 if ( !first && newDocEntry->IsItemStarter() )
1070 // Debug message within the method !
1071 newDocEntry = Backtrack(newDocEntry);
1075 PreviousDocEntry = newDocEntry;
1079 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1083 //////////////////////////// DataEntry
1085 vr = newDocEntry->GetVR();
1087 if ( !set->AddEntry( newDataEntry ) )
1089 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1090 << newDataEntry->GetKey()
1091 << " (at offset : 0x("
1092 << newDataEntry->GetOffset() << ") )" );
1097 newDataEntry->Delete();
1098 // Load only if we can add (not a duplicate key)
1099 LoadDocEntry( newDataEntry );
1101 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1103 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1105 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1107 std::string strLgrGroup = newDataEntry->GetString();
1110 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1112 lgrGroup = atoi(strLgrGroup.c_str());
1113 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1114 RemoveEntry( newDocEntry ); // Remove and delete
1121 bool delimitor = newDataEntry->IsItemDelimitor();
1122 bool outOfBounds = false;
1124 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1127 // 'and then', 'or else' don't exist in C++ :-(
1128 // if ( (delimitor) ||
1129 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1131 if ( delimitor || outOfBounds )
1134 newDocEntry->Delete();
1138 // Just to make sure we are at the beginning of next entry.
1139 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1143 /////////////////////// SeqEntry : VR = "SQ"
1145 unsigned long l = newDocEntry->GetReadLength();
1146 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1148 if ( l == 0xffffffff )
1150 delim_mode_intern = true;
1154 delim_mode_intern = false;
1158 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1160 // User asked to skip SeQuences *only* if they belong to Shadow Group
1161 if ( newDocEntry->GetGroup()%2 != 0 )
1163 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1164 newDocEntry->Delete(); // Delete, not in the set
1168 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1170 // User asked to skip *any* SeQuence
1171 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1172 newDocEntry->Delete(); // Delete, not in the set
1175 // delay the dynamic cast as late as possible
1176 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1178 // no other way to create the Delimitor ...
1179 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1181 // At the top of the hierarchy, stands a Document. When "set"
1182 // is a Document, then we are building the first depth level.
1183 // Hence the SeqEntry we are building simply has a depth
1185 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1187 newSeqEntry->SetDepthLevel( 1 );
1189 // But when "set" is already a SQItem, we are building a nested
1190 // sequence, and hence the depth level of the new SeqEntry
1191 // we are building, is one level deeper:
1193 // time waste hunting
1194 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1196 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1200 { // Don't try to parse zero-length sequences
1202 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1203 << " at offset 0x(" << std::hex
1204 << newDocEntry->GetOffset() << ")");
1206 ParseSQ( newSeqEntry,
1207 newDocEntry->GetOffset(),
1208 l, delim_mode_intern);
1210 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1213 if ( !set->AddEntry( newSeqEntry ) )
1215 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1216 << newSeqEntry->GetKey()
1217 << " (at offset : 0x("
1218 << newSeqEntry->GetOffset() << ") )" );
1223 newDocEntry->Delete();
1226 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1228 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1229 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1233 newDocEntry->Delete();
1236 } // end SeqEntry : VR = "SQ"
1240 newDocEntry->Delete();
1244 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1248 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1249 * @return parsed length for this level
1251 void Document::ParseSQ( SeqEntry *seqEntry,
1252 long offset, long l_max, bool delim_mode)
1254 int SQItemNumber = 0;
1256 long offsetStartCurrentSQItem = offset;
1260 // the first time, we read the fff0,e000 of the first SQItem
1261 DocEntry *newDocEntry = ReadNextDocEntry();
1265 gdcmWarningMacro("in ParseSQ : should never get here!");
1270 if ( newDocEntry->IsSequenceDelimitor() )
1272 seqEntry->SetDelimitationItem( newDocEntry );
1273 newDocEntry->Delete();
1277 if ( !delim_mode ) // andthen doesn't exist in C++ :-(
1278 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1280 newDocEntry->Delete();
1283 // create the current SQItem
1284 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1285 unsigned int l = newDocEntry->GetReadLength();
1287 if ( l == 0xffffffff )
1296 // remove fff0,e000, created out of the SQItem
1298 //Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); //JPRx
1300 // fill up the current SQItem, starting at the beginning of fff0,e000
1302 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1304 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1306 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1308 newDocEntry->Delete();
1310 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1311 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1319 * \brief When a private Sequence + Implicit VR is encountered
1320 * we cannot guess it's a Sequence till we find the first
1321 * Item Starter. We then backtrack to do the job.
1322 * @param docEntry Item Starter that warned us
1324 DocEntry *Document::Backtrack(DocEntry *docEntry)
1326 // delete the Item Starter, built erroneously out of any Sequence
1327 // it's not yet in the HTable/chained list
1330 // Get all info we can from PreviousDocEntry
1331 uint16_t group = PreviousDocEntry->GetGroup();
1332 uint16_t elem = PreviousDocEntry->GetElement();
1333 uint32_t lgt = PreviousDocEntry->GetLength();
1334 long offset = PreviousDocEntry->GetOffset();
1336 gdcmDebugMacro( "Backtrack :" << std::hex << group
1338 << " at offset 0x(" <<offset << ")" );
1339 RemoveEntry( PreviousDocEntry );
1341 // forge the Seq Entry
1342 DocEntry *newEntry = NewSeqEntry(group, elem);
1343 newEntry->SetLength(lgt);
1344 newEntry->SetOffset(offset);
1346 // Move back to the beginning of the Sequence
1347 // Fp->seekg( 0, std::ios::beg); // JPRx
1348 // Fp->seekg(offset, std::ios::cur); // JPRx
1349 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1354 * \brief Loads (or not) the element content depending if its length exceeds
1355 * or not the value specified with Document::SetMaxSizeLoadEntry()
1356 * @param entry Header Entry (Dicom Element) to be dealt with
1357 * @param forceLoad whether you want to force loading of 'long' elements
1359 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1361 uint16_t group = entry->GetGroup();
1362 uint16_t elem = entry->GetElement();
1363 const VRKey &vr = entry->GetVR();
1364 uint32_t length = entry->GetLength();
1366 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1368 // A SeQuence "contains" a set of Elements.
1369 // (fffe e000) tells us an Element is beginning
1370 // (fffe e00d) tells us an Element just ended
1371 // (fffe e0dd) tells us the current SeQuence just ended
1373 // (fffe 0000) is an 'impossible' tag value,
1374 // found in MR-PHILIPS-16-Multi-Seq.dcm
1376 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1378 // NO more value field for SQ !
1382 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1388 // When the length is zero things are easy:
1391 dataEntryPtr->SetBinArea(NULL,true);
1395 // The elements whose length is bigger than the specified upper bound
1400 if (length > MaxSizeLoadEntry)
1402 dataEntryPtr->SetBinArea(NULL,true);
1403 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1405 // to be sure we are at the end of the value ...
1406 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1407 // std::ios::beg); //JPRx
1412 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1413 /// + a ForceLoad call on the +/- 20 'usefull' fields
1414 /// Allow user to tell the fields he wants to ForceLoad
1415 /// during initial stage.
1416 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1417 /// + a method that load *everything* that's not yet loaded
1419 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1423 * \brief Find the value Length of the passed Doc Entry
1424 * @param entry Header Entry whose length of the value shall be loaded.
1426 void Document::FindDocEntryLength( DocEntry *entry )
1427 throw ( FormatError )
1429 const VRKey &vr = entry->GetVR();
1432 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1434 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1437 // The following reserved two bytes (see PS 3.5-2003, section
1438 // "7.1.2 Data element structure with explicit vr", p 27) must be
1439 // skipped before proceeding on reading the length on 4 bytes.
1441 Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1442 uint32_t length32 = ReadInt32();
1444 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1449 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1451 catch ( FormatUnexpected )
1453 // Computing the length failed (this happens with broken
1454 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1455 // chance to get the pixels by deciding the element goes
1456 // until the end of the file. Hence we artificially fix the
1457 // the length and proceed.
1458 gdcmWarningMacro( " Computing the length failed for " <<
1459 entry->GetKey() <<" in " <<GetFileName());
1461 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1462 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1464 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1465 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1467 entry->SetReadLength(lengthUntilEOF);
1468 entry->SetLength(lengthUntilEOF);
1471 entry->SetReadLength(lengthOB);
1472 entry->SetLength(lengthOB);
1475 FixDocEntryFoundLength(entry, length32);
1479 // Length is encoded on 2 bytes.
1480 length16 = ReadInt16();
1482 // 0xffff means that we deal with 'No Length' Sequence
1483 // or 'No Length' SQItem
1484 if ( length16 == 0xffff)
1488 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1493 // Either implicit VR or a non DICOM conformal (see note below) explicit
1494 // VR that ommited the VR of (at least) this element. Farts happen.
1495 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1496 // on Data elements "Implicit and Explicit VR Data Elements shall
1497 // not coexist in a Data Set and Data Sets nested within it".]
1498 // Length is on 4 bytes.
1500 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1501 // even if Transfer Syntax is 'Implicit VR ...'
1502 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1504 FixDocEntryFoundLength( entry, ReadInt32() );
1510 * \brief Find the Length till the next sequence delimiter
1513 uint32_t Document::FindDocEntryLengthOBOrOW()
1514 throw( FormatUnexpected )
1516 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1517 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1519 bool foundSequenceDelimiter = false;
1520 uint32_t totalLength = 0;
1522 while ( !foundSequenceDelimiter )
1528 group = ReadInt16();
1531 catch ( FormatError )
1533 throw FormatError("Unexpected end of file encountered during ",
1534 "Document::FindDocEntryLengthOBOrOW()");
1536 // We have to decount the group and element we just read
1538 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1540 // long filePosition = Fp->tellg(); JPRx
1542 "Neither an Item tag nor a Sequence delimiter tag on :"
1543 << std::hex << group << " , " << elem
1544 //<< ") -before- position x(" << filePosition // JPRx
1547 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1548 throw FormatUnexpected(
1549 "Neither an Item tag nor a Sequence delimiter tag.");
1551 if ( elem == 0xe0dd )
1553 foundSequenceDelimiter = true;
1555 uint32_t itemLength = ReadInt32();
1556 // We add 4 bytes since we just read the ItemLength with ReadInt32
1557 totalLength += itemLength + 4;
1558 SkipBytes(itemLength);
1560 if ( foundSequenceDelimiter )
1565 Fp->seekg( positionOnEntry, std::ios::beg); // Only for OB,OW DataElements
1570 * \brief Find the Value Representation of the current Dicom Element.
1571 * @return Value Representation of the current Entry
1573 VRKey Document::FindDocEntryVR()
1575 if ( Filetype != ExplicitVR )
1576 return GDCM_VRUNKNOWN;
1578 // Delimiters (0xfffe), are not explicit VR ...
1579 if ( CurrentGroup == 0xfffe )
1580 return GDCM_VRUNKNOWN;
1582 long positionOnEntry;
1583 if( Debug::GetWarningFlag() )
1584 positionOnEntry = Fp->tellg(); // Only in Warning Mode
1586 // Warning: we believe this is explicit VR (Value Representation) because
1587 // we used a heuristic that found "UL" in the first tag and/or
1588 // 'Transfer Syntax' told us it is.
1589 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1590 // In some cases one finds implicit VR tags mixed within an explicit VR file
1592 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1594 // Hence we make sure the present tag is in explicit VR and try to fix things
1595 // if it happens not to be the case.
1598 Fp->read(&(vr[0]),(size_t)2);
1600 if ( !CheckDocEntryVR(vr) )
1603 std::cout << "================================================================Unknown VR"
1604 << std::hex << "0x("
1605 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1606 << ")" << "for : " << CurrentGroup
1607 << " at offset : 0x(" << positionOnEntry << ")"
1610 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1611 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1613 << " at offset : 0x(" << positionOnEntry<< ") for group " << CurrentGroup
1616 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1617 Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1618 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1619 return GDCM_VRUNKNOWN;
1625 * \brief Check the correspondance between the VR of the header entry
1626 * and the taken VR. If they are different, the header entry is
1627 * updated with the new VR.
1628 * @param vr Dicom Value Representation
1629 * @return false if the VR is incorrect or if the VR isn't referenced
1630 * otherwise, it returns true
1632 bool Document::CheckDocEntryVR(const VRKey &vr)
1634 return Global::GetVR()->IsValidVR(vr);
1638 * \brief Skip a given Header Entry
1639 * @param entry entry to skip
1641 void Document::SkipDocEntry(DocEntry *entry)
1643 SkipBytes(entry->GetLength());
1647 * \brief Skips to the beginning of the next Header Entry
1648 * @param currentDocEntry entry to skip
1650 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1652 long l = currentDocEntry->GetReadLength();
1653 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1654 // ... but PMS imagers happen !
1656 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1657 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1659 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1664 * \brief When the length of an element value is obviously wrong (because
1665 * the parser went Jabberwocky) one can hope improving things by
1666 * applying some heuristics.
1667 * @param entry entry to check
1668 * @param foundLength first assumption about length
1670 void Document::FixDocEntryFoundLength(DocEntry *entry,
1671 uint32_t foundLength)
1673 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1674 if ( foundLength == 0xffffffff)
1679 uint16_t gr = entry->GetGroup();
1680 uint16_t elem = entry->GetElement();
1682 if ( foundLength % 2)
1684 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1685 << " in x(" << std::hex << gr << "," << elem <<")");
1688 //////// Fix for some naughty General Electric images.
1689 // Allthough not recent many such GE corrupted images are still present
1690 // on Creatis hard disks. Hence this fix shall remain when such images
1691 // are no longer in use (we are talking a few years, here)...
1692 // Note: XMedCon probably uses such a trick since it is able to read
1693 // those pesky GE images ...
1694 if ( foundLength == 13)
1696 // Only happens for this length !
1697 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1700 entry->SetReadLength(10); // a bug is to be fixed !?
1704 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1705 // Occurence of such images is quite low (unless one leaves close to a
1706 // 'Leonardo' source. Hence, one might consider commenting out the
1707 // following fix on efficiency reasons.
1708 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1711 entry->SetReadLength(4); // a bug is to be fixed !
1714 else if ( entry->GetVR() == "SQ" )
1716 foundLength = 0; // ReadLength is unchanged
1719 //////// We encountered a 'delimiter' element i.e. a tag of the form
1720 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1721 // taken into account.
1722 else if ( gr == 0xfffe )
1724 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1725 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1726 // causes extra troubles...
1727 if ( entry->GetElement() != 0x0000 )
1733 foundLength=12; // to skip the mess that follows this bugged Tag !
1736 entry->SetLength(foundLength);
1740 * \brief Apply some heuristics to predict whether the considered
1741 * element value contains/represents an integer or not.
1742 * @param entry The element value on which to apply the predicate.
1743 * @return The result of the heuristical predicate.
1745 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1747 uint16_t elem = entry->GetElement();
1748 uint16_t group = entry->GetGroup();
1749 const VRKey &vr = entry->GetVR();
1750 uint32_t length = entry->GetLength();
1752 // When we have some semantics on the element we just read, and if we
1753 // a priori know we are dealing with an integer, then we shall be
1754 // able to swap it's element value properly.
1755 if ( elem == 0 ) // This is the group length of the group
1763 // Although this should never happen, still some images have a
1764 // corrupted group length [e.g. have a glance at offset x(8336) of
1765 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1766 // Since for dicom compliant and well behaved headers, the present
1767 // test is useless (and might even look a bit paranoid), when we
1768 // encounter such an ill-formed image, we simply display a warning
1769 // message and proceed on parsing (while crossing fingers).
1770 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1771 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1772 << std::hex << group << " , " << elem
1773 << ") -before- position x(" << filePosition << ")"
1774 << "lgt : " << length );
1778 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1786 * \brief Discover what the swap code is (among little endian, big endian,
1787 * bad little endian, bad big endian).
1789 * @return false when we are absolutely sure
1790 * it's neither ACR-NEMA nor DICOM
1791 * true when we hope ours assuptions are OK
1793 bool Document::CheckSwap()
1800 // First, compare HostByteOrder and NetworkByteOrder in order to
1801 // determine if we shall need to swap bytes (i.e. the Endian type).
1802 bool net2host = Util::IsCurrentProcessorBigEndian();
1804 // The easiest case is the one of a 'true' DICOM header, we just have
1805 // to look for the string "DICM" inside the file preamble.
1808 char *entCur = deb + 128;
1809 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1811 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1813 // Group 0002 should always be VR, and the first element 0000
1814 // Let's be carefull (so many wrong headers ...)
1815 // and determine the value representation (VR) :
1816 // Let's skip to the first element (0002,0000) and check there if we find
1817 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1818 // in which case we (almost) know it is explicit VR.
1819 // WARNING: if it happens to be implicit VR then what we will read
1820 // is the length of the group. If this ascii representation of this
1821 // length happens to be "UL" then we shall believe it is explicit VR.
1822 // We need to skip :
1823 // * the 128 bytes of File Preamble (often padded with zeroes),
1824 // * the 4 bytes of "DICM" string,
1825 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1826 // i.e. a total of 136 bytes.
1829 // group 0x0002 *is always* Explicit VR Sometimes ,
1830 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1831 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1833 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1834 memcmp(entCur, "OB", (size_t)2) == 0 ||
1835 memcmp(entCur, "UI", (size_t)2) == 0 ||
1836 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1837 // when Write DCM *adds*
1839 // Use Document::dicom_vr to test all the possibilities
1840 // instead of just checking for UL, OB and UI !? group 0000
1842 Filetype = ExplicitVR;
1843 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1847 Filetype = ImplicitVR;
1848 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1849 << "Looks like a bugged Header!");
1855 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1860 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1863 // Position the file position indicator at first tag
1864 // (i.e. after the file preamble and the "DICM" string).
1866 //Fp->seekg(0, std::ios::beg); // JPRx
1868 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1870 } // ------------------------------- End of DicomV3 ----------------
1872 // Alas, this is not a DicomV3 file and whatever happens there is no file
1873 // preamble. We can reset the file position indicator to where the data
1874 // is (i.e. the beginning of the file).
1876 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1878 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1880 // Let's check 'No Preamble Dicom File' :
1881 // Should start with group 0x0002
1882 // and be Explicit Value Representation
1884 s16 = *((uint16_t *)(deb));
1897 if ( SwapCode != 0 )
1899 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1900 memcmp(entCur, "OB", (size_t)2) == 0 ||
1901 memcmp(entCur, "UI", (size_t)2) == 0 ||
1902 memcmp(entCur, "SH", (size_t)2) == 0 ||
1903 memcmp(entCur, "AE", (size_t)2) == 0 ||
1904 memcmp(entCur, "OB", (size_t)2) == 0 )
1906 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
1907 // Wait untill reading Transfer Syntax
1908 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1912 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1914 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1915 // By clean we mean that the length of the first group is written down.
1916 // If this is the case and since the length of the first group HAS to be
1917 // four (bytes), then determining the proper swap code is straightforward.
1920 // We assume the array of char we are considering contains the binary
1921 // representation of a 32 bits integer. Hence the following dirty
1923 s32 = *((uint32_t *)(entCur));
1943 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1944 // It is time for despaired wild guesses.
1945 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1946 // i.e. the 'group length' element is not present :
1948 // check the supposed-to-be 'group number'
1949 // in ( 0x0001 .. 0x0008 )
1950 // to determine ' SwapCode' value .
1951 // Only 0 or 4321 will be possible
1952 // (no oportunity to check for the formerly well known
1953 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1954 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1955 // the file IS NOT ACR-NEMA nor DICOM V3
1956 // Find a trick to tell it the caller...
1958 s16 = *((uint16_t *)(deb));
1985 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1993 * \brief Change the Byte Swap code.
1995 void Document::SwitchByteSwapCode()
1997 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1998 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
1999 if ( SwapCode == 1234 )
2003 else if ( SwapCode == 4321 )
2007 else if ( SwapCode == 3412 )
2011 else if ( SwapCode == 2143 )
2015 gdcmDebugMacro( " Into: "<< SwapCode );
2019 * \brief during parsing, Header Elements too long are not loaded in memory
2020 * @param newSize new size
2022 void Document::SetMaxSizeLoadEntry(long newSize)
2028 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2030 MaxSizeLoadEntry = 0xffffffff;
2033 MaxSizeLoadEntry = newSize;
2037 * \brief Read the next tag WITHOUT loading it's value
2038 * (read the 'Group Number', the 'Element Number',
2039 * gets the Dict Entry
2040 * gets the VR, gets the length, gets the offset value)
2041 * @return On succes : the newly created DocEntry, NULL on failure.
2043 DocEntry *Document::ReadNextDocEntry()
2047 CurrentGroup = ReadInt16();
2048 CurrentElem = ReadInt16();
2050 catch ( FormatError )
2052 // We reached the EOF (or an error occured) therefore
2053 // header parsing has to be considered as finished.
2057 // In 'true DICOM' files Group 0002 is always little endian
2058 if ( HasDCMPreamble )
2060 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2061 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2063 // Sometimes file contains groups of tags with reversed endianess.
2064 HandleBrokenEndian(CurrentGroup, CurrentElem);
2067 VRKey vr = FindDocEntryVR();
2071 if ( vr == GDCM_VRUNKNOWN )
2073 if ( CurrentElem == 0x0000 ) // Group Length
2075 realVR = "UL"; // must be UL
2077 // Commented out in order not to generate 'Shadow Groups' where some
2078 // Data Elements are Explicit VR and some other ones Implicit VR
2079 // (Stupid MatLab DICOM Reader couln't read gdcm-written images)
2081 else if (CurrentGroup%2 == 1 &&
2082 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2084 // DICOM PS 3-5 7.8.1 a) states that those
2085 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2091 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2094 realVR = dictEntry->GetVR();
2095 dictEntry->Unregister();
2101 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2103 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2106 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2107 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2110 if ( vr == GDCM_VRUNKNOWN )
2112 if ( Filetype == ExplicitVR )
2114 // We thought this was explicit VR, but we end up with an
2115 // implicit VR tag. Let's backtrack.
2116 if ( newEntry->GetGroup() != 0xfffe )
2119 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2121 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2122 newEntry->GetGroup(), newEntry->GetElement(), offset );
2123 gdcmWarningMacro( msg.c_str() );
2126 newEntry->SetImplicitVR();
2131 FindDocEntryLength(newEntry);
2133 catch ( FormatError )
2140 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2146 * \brief Handle broken private tag from Philips NTSCAN
2147 * where the endianess is being switched to BigEndian
2148 * for no apparent reason
2151 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2153 // Endian reversion.
2154 // Some files contain groups of tags with reversed endianess.
2155 static int reversedEndian = 0;
2156 // try to fix endian switching in the middle of headers
2157 if ((group == 0xfeff) && (elem == 0x00e0))
2159 // start endian swap mark for group found
2160 gdcmDebugMacro( "Start endian swap mark found." );
2162 SwitchByteSwapCode();
2167 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2169 // end of reversed endian group
2170 gdcmDebugMacro( "End of reversed endian." );
2172 SwitchByteSwapCode();
2174 else if (group == 0xfeff && elem == 0xdde0)
2176 // reversed Sequence Terminator found
2177 // probabely a bug in the header !
2178 // Do what you want, it breaks !
2180 //SwitchByteSwapCode();
2181 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2186 else if (group == 0xfffe && elem == 0xe0dd)
2188 gdcmDebugMacro( "Straight Sequence Terminator." );
2193 * \brief Group 0002 is always coded Little Endian
2194 * whatever Transfer Syntax is
2197 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2199 // Endian reversion.
2200 // Some files contain groups of tags with reversed endianess.
2202 Group0002Parsed = true;
2203 // we just came out of group 0002
2204 // if Transfer Syntax is Big Endian we have to change CheckSwap
2206 std::string ts = GetTransferSyntax();
2207 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2209 // Group 0002 is always 'Explicit ...'
2210 // even when Transfer Syntax says 'Implicit ..."
2212 if ( s == TS::ImplicitVRLittleEndian
2214 s == TS::ImplicitVRBigEndianPrivateGE
2217 Filetype = ImplicitVR;
2220 // FIXME Strangely, this works with
2221 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2223 // --> Probabely normal, since we considered we never have
2224 // to trust manufacturers.
2225 // (we find very often 'Implicit VR' tag,
2226 // even when Transfer Syntax tells us it's Explicit ...
2228 if ( s == TS::ExplicitVRBigEndian )
2230 gdcmDebugMacro("Transfer Syntax Name = ["
2231 << GetTransferSyntaxName() << "]" );
2232 SwitchByteSwapCode();
2233 group = SwapShort(group);
2234 elem = SwapShort(elem);
2237 /// \todo find a trick to warn user and stop processing
2239 if ( s == TS::DeflatedExplicitVRLittleEndian)
2241 gdcmWarningMacro("Transfer Syntax ["
2242 << GetTransferSyntaxName() << "] :"
2243 << " not yet dealt with ");
2247 // The following shouldn't occur very often
2248 // Let's check at the very end.
2250 if ( ts == GDCM_UNKNOWN )
2252 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2256 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2258 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2264 //-----------------------------------------------------------------------------
2267 //-----------------------------------------------------------------------------
2268 } // end namespace gdcm