1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/11/21 16:28:06 $
7 Version: $Revision: 1.331 $
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
38 //-----------------------------------------------------------------------------
40 // Refer to Document::SetMaxSizeLoadEntry()
41 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
43 //-----------------------------------------------------------------------------
44 // Constructor / Destructor
45 // Constructors and destructors are protected to avoid user to invoke directly
48 * \brief This default constructor neither loads nor parses the file.
49 * You should then invoke \ref Document::Load.
57 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
60 Filetype = ExplicitVR;
61 // Load will set it to true if sucessfull
62 Group0002Parsed = false;
63 IsDocumentAlreadyLoaded = false;
64 IsDocumentModified = true;
65 LoadMode = LD_ALL; // default : load everything, later
70 * \brief Canonical destructor.
72 Document::~Document ()
77 //-----------------------------------------------------------------------------
80 * \brief Loader. use SetLoadMode(), SetFileName() before !
81 * @return false if file cannot be open or no swap info was found,
82 * or no tag was found.
84 bool Document::Load( )
86 if ( GetFileName() == "" )
88 gdcmWarningMacro( "Use SetFileName, before !" );
91 return DoTheLoadingDocumentJob( );
95 //#ifndef GDCM_LEGACY_REMOVE
96 bool Document::Load( std::string const &fileName )
99 return DoTheLoadingDocumentJob( );
105 * \brief Performs the Loading Job (internal use only)
106 * @return false if file cannot be open or no swap info was found,
107 * or no tag was found.
109 bool Document::DoTheLoadingDocumentJob( )
111 if ( ! IsDocumentModified ) // Nothing to do !
119 // warning already performed in OpenFile()
124 Group0002Parsed = false;
126 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
128 Fp->seekg(0, std::ios::end);
129 long lgt = Fp->tellg(); // total length of the file
131 Fp->seekg(0, std::ios::beg);
133 // CheckSwap returns a boolean
134 // (false if no swap info of any kind was found)
137 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
138 << Filename.c_str());
143 long beg = Fp->tellg(); // just after DICOM preamble (if any)
145 lgt -= beg; // remaining length to parse
148 // Loading is done during parsing
149 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
153 gdcmErrorMacro( "No tag in internal hash table for: "
154 << Filename.c_str());
158 IsDocumentAlreadyLoaded = true;
160 Fp->seekg( 0, std::ios::beg);
162 // Load 'non string' values
164 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
165 if ( PhotometricInterpretation == "PALETTE COLOR " )
168 // Probabely this line should be outside the 'if'
169 // Try to find an image sample holding a 'gray LUT'
170 LoadEntryBinArea(0x0028,0x1200); // gray LUT
173 /// --> FIXME : The difference between BinEntry and DataEntry
174 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
175 /// --> Old comment restored on purpose.
176 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
177 /// --> had absolutely no meaning.
178 /// --> The whole comment will be removed when the stuff is cleaned !
180 /// The tags refered by the three following lines used to be CORRECTLY
181 /// defined as having an US Value Representation in the public
182 /// dictionary. BUT the semantics implied by the three following
183 /// lines state that the corresponding tag contents are in fact
184 /// the ones of a BinEntry.
185 /// In order to fix things "Quick and Dirty" the dictionary was
186 /// altered on PURPOSE but now contains a WRONG value.
187 /// In order to fix things and restore the dictionary to its
188 /// correct value, one needs to decide of the semantics by deciding
189 /// whether the following tags are either :
190 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
191 /// also used as BinEntry, which requires the proper conversion,
192 /// - OW, and hence loaded as BinEntry, but afterwards also used
193 /// as ValEntry, which requires the proper conversion.
195 // --> OB (byte aray) or OW (short int aray)
196 // The actual VR has to be deduced from other entries.
197 // Our way of loading them may fail in some cases :
198 // We must or not SwapByte depending on other field values.
200 LoadEntryBinArea(0x0028,0x1201); // R LUT
201 LoadEntryBinArea(0x0028,0x1202); // G LUT
202 LoadEntryBinArea(0x0028,0x1203); // B LUT
204 // Segmented Red Palette Color LUT Data
205 LoadEntryBinArea(0x0028,0x1221);
206 // Segmented Green Palette Color LUT Data
207 LoadEntryBinArea(0x0028,0x1222);
208 // Segmented Blue Palette Color LUT Data
209 LoadEntryBinArea(0x0028,0x1223);
212 //FIXME later : how to use it?
213 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
216 SQItem *sqi= modLutSeq->GetFirstSQItem();
219 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
220 if ( dataEntry != 0 )
222 if ( dataEntry->GetLength() != 0 )
224 // FIXME : CTX dependent means : contexted dependant.
225 // see upper comment.
226 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
232 // Force Loading some more elements if user asked to.
235 for (ListElements::iterator it = UserForceLoadList.begin();
236 it != UserForceLoadList.end();
239 gdcmDebugMacro( "Force Load " << std::hex
240 << (*it).Group << "|" <<(*it).Elem );
242 d = GetDocEntry( (*it).Group, (*it).Elem);
246 gdcmWarningMacro( "You asked toForce Load " << std::hex
247 << (*it).Group <<"|"<< (*it).Elem
248 << " that doesn't exist" );
252 LoadDocEntry(d, true);
257 // ----------------------------
258 // Specific code to allow gdcm to read ACR-LibIDO formated images
259 // Note: ACR-LibIDO is an extension of the ACR standard that was
260 // used at CREATIS. For the time being (say a couple of years)
261 // we keep this kludge to allow CREATIS users
262 // reading their old images.
264 // if recognition code tells us we deal with a LibIDO image
265 // we switch lineNumber and columnNumber
268 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
269 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
270 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
271 // with "little-endian strings"
273 Filetype = ACR_LIBIDO;
274 std::string rows = GetEntryString(0x0028, 0x0010);
275 std::string columns = GetEntryString(0x0028, 0x0011);
276 SetEntryString(columns, 0x0028, 0x0010);
277 SetEntryString(rows , 0x0028, 0x0011);
279 // --- End of ACR-LibIDO kludge ---
285 * \brief Adds a new element we want to load anyway
286 * @param group Group number of the target tag.
287 * @param elem Element number of the target tag.
289 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
294 UserForceLoadList.push_back(el);
297 * \brief Get the public dictionary used
299 Dict *Document::GetPubDict()
305 * \brief Get the shadow dictionary used
307 Dict *Document::GetShaDict()
313 * \brief Set the shadow dictionary used
314 * @param dict dictionary to use in shadow
316 bool Document::SetShaDict(Dict *dict)
323 * \brief Set the shadow dictionary used
324 * @param dictName name of the dictionary to use in shadow
326 bool Document::SetShaDict(DictKey const &dictName)
328 RefShaDict = Global::GetDicts()->GetDict(dictName);
333 * \brief This predicate tells us whether or not the current Document
334 * was properly parsed and contains at least *one* Dicom Element
335 * (and nothing more, sorry).
336 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
339 bool Document::IsParsable()
341 if ( Filetype == Unknown )
343 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
349 gdcmWarningMacro( "No tag in internal hash table.");
356 * \brief This predicate tells us whether or not the current Document
357 * was properly parsed and contains at least *one* Dicom Element
358 * (and nothing more, sorry).
359 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
362 bool Document::IsReadable()
368 * \brief Predicate for dicom version 3 file.
369 * @return True when the file is a dicom version 3.
371 bool Document::IsDicomV3()
373 // Checking if Transfer Syntax exists is enough
374 // Anyway, it's too late check if the 'Preamble' was found ...
375 // And ... would it be a rich idea to check ?
376 // (some 'no Preamble' DICOM images exist !)
377 return GetDocEntry(0x0002, 0x0010) != NULL;
381 * \brief Predicate for Papyrus file
382 * Dedicated to whomsoever it may concern
383 * @return True when the file is a Papyrus file.
385 bool Document::IsPapyrus()
387 // check for Papyrus private Sequence
388 DocEntry *e = GetDocEntry(0x0041, 0x1050);
391 // check if it's actually a Sequence
392 if ( !dynamic_cast<SeqEntry*>(e) )
398 * \brief returns the File Type
399 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
400 * @return the FileType code
402 FileType Document::GetFileType()
408 * \brief Accessor to the Transfer Syntax (when present) of the
409 * current document (it internally handles reading the
410 * value from disk when only parsing occured).
411 * @return The encountered Transfer Syntax of the current document, if DICOM.
412 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
414 std::string Document::GetTransferSyntax()
416 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
422 // The entry might be present but not loaded (parsing and loading
423 // happen at different stages): try loading and proceed with check...
424 LoadDocEntrySafe(entry);
425 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
427 std::string transfer = dataEntry->GetString();
428 // The actual transfer (as read from disk) might be padded. We
429 // first need to remove the potential padding. We can make the
430 // weak assumption that padding was not executed with digits...
431 if ( transfer.length() == 0 )
433 // for brain damaged headers
434 gdcmWarningMacro( "Transfer Syntax has length = 0.");
437 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
439 transfer.erase(transfer.length()-1, 1);
440 if ( transfer.length() == 0 )
442 // for brain damaged headers
443 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
453 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
454 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
456 std::string Document::GetTransferSyntaxName()
458 // use the TS (TS : Transfer Syntax)
459 std::string transferSyntax = GetEntryString(0x0002,0x0010);
461 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
463 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
464 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
465 return "Uncompressed ACR-NEMA";
467 if ( transferSyntax == GDCM_UNFOUND )
469 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
470 return "Uncompressed ACR-NEMA";
473 // we do it only when we need it
474 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
476 // Global::GetTS() is a global static you shall never try to delete it!
480 // --------------- Swap Code ------------------
482 * \brief Swaps the bytes so they agree with the processor order
483 * @return The properly swaped 16 bits integer.
485 uint16_t Document::SwapShort(uint16_t a)
487 if ( SwapCode == 4321 || SwapCode == 2143 )
489 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
491 a = ( a << 8 ) | ( a >> 8 );
497 * \brief Swaps back the bytes of 4-byte long integer accordingly to
499 * @return The properly swaped 32 bits integer.
501 uint32_t Document::SwapLong(uint32_t a)
508 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
509 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
511 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
512 ((a>>8) & 0x0000ff00) | (a>>24) );
515 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
516 a=( (a<<16) | (a>>16) );
519 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
522 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
529 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
531 * @return The properly swaped 64 bits double.
533 double Document::SwapDouble(double a)
537 // There were no 'double' at ACR-NEMA time.
538 // We just have to deal with 'straight Little Endian' and
539 // 'straight Big Endian'
544 char *beg = (char *)&a;
547 for (unsigned int i = 0; i<7; i++)
558 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
565 // -----------------File I/O ---------------
567 * \brief Tries to open the file \ref Document::Filename and
568 * checks the preamble when existing.
569 * @return The FILE pointer on success.
571 std::ifstream *Document::OpenFile()
573 HasDCMPreamble = false;
574 if (Filename.length() == 0)
581 gdcmDebugMacro( "File already open: " << Filename.c_str());
585 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
588 // Don't user gdcmErrorMacro :
589 // a spurious message will appear when you use, for instance
590 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
591 // to create outputFileName.
593 // FIXME : if the upper comment is still usefull
594 // --> the constructor is not so good ...
596 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
600 //exit(1); // No function is allowed to leave the application instead
601 // of warning the caller
605 Fp->read((char*)&zero, (size_t)2);
612 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
614 // FIXME : We cannot be sure the preable is only zeroes..
615 // (see ACUSON-24-YBR_FULL-RLE.dcm )
617 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
618 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
619 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
620 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
622 std::string msg = Util::Format(
623 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
624 // FIXME : is it a Warning message, or a Debug message?
625 gdcmWarningMacro( msg.c_str() );
630 Fp->seekg(126L, std::ios::cur);
631 char dicm[4]; // = {' ',' ',' ',' '};
632 Fp->read(dicm, (size_t)4);
638 if ( memcmp(dicm, "DICM", 4) == 0 )
640 HasDCMPreamble = true;
644 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
646 // Don't user Warning nor Error, not to polute the output
647 // while directory recursive parsing ...
648 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
649 << Filename.c_str());
654 * \brief closes the file
655 * @return TRUE if the close was successfull
657 bool Document::CloseFile()
669 * \brief Writes in a file all the Entries (Dicom Elements)
670 * @param fp file pointer on an already open file (actually: Output File Stream)
671 * @param filetype Type of the File to be written
672 * (ACR-NEMA, ExplicitVR, ImplicitVR)
674 void Document::WriteContent(std::ofstream *fp, FileType filetype)
676 // Skip if user wants to write an ACR-NEMA file
678 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
681 // writing Dicom File Preamble
682 char filePreamble[128];
683 memset(filePreamble, 0, 128);
684 fp->write(filePreamble, 128);
685 fp->write("DICM", 4);
689 * \todo rewrite later, if really usefull
690 * - 'Group Length' element is optional in DICOM
691 * - but un-updated odd groups lengthes can causes pb
694 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
695 * UpdateGroupLength(false,filetype);
696 * if ( filetype == ACR)
697 * UpdateGroupLength(true,ACR);
699 * --> Computing group length for groups with embeded Sequences
700 * --> was too much tricky / we were [in a hurry / too lazy]
701 * --> We don't write the element 0x0000 (group length)
704 ElementSet::WriteContent(fp, filetype); // This one is recursive
707 // -----------------------------------------
710 * \brief Loads (from disk) the element content
711 * when a string is not suitable
712 * @param group group number of the Entry
713 * @param elem element number of the Entry
715 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
717 // Search the corresponding DocEntry
718 DocEntry *docEntry = GetDocEntry(group, elem);
721 gdcmDebugMacro(std::hex << group << "|" << elem
722 << " doesn't exist" );
725 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
728 gdcmWarningMacro(std::hex << group << "|" << elem
729 << " is NOT a DataEntry");
732 LoadEntryBinArea(dataEntry);
736 * \brief Loads (from disk) the element content
737 * when a string is not suitable
738 * @param entry Entry whose binArea is going to be loaded
740 void Document::LoadEntryBinArea(DataEntry *entry)
742 if( entry->GetBinArea() )
749 size_t o =(size_t)entry->GetOffset();
750 Fp->seekg(o, std::ios::beg);
752 size_t l = entry->GetLength();
753 uint8_t *data = new uint8_t[l];
756 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
757 << std::hex << entry->GetGroup()
758 << "|" << entry->GetElement() );
763 Fp->read((char*)data, l);
764 if ( Fp->fail() || Fp->eof() )
767 entry->SetState(DataEntry::STATE_UNREAD);
771 // Swap the data content if necessary
773 unsigned short vrLgth =
774 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
776 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
777 // if( entry->GetVR() == "OW" )
788 uint16_t *data16 = (uint16_t *)data;
789 for(i=0;i<l/vrLgth;i++)
790 data16[i] = SwapShort(data16[i]);
795 uint32_t *data32 = (uint32_t *)data;
796 for(i=0;i<l/vrLgth;i++)
797 data32[i] = SwapLong(data32[i]);
802 double *data64 = (double *)data;
803 for(i=0;i<l/vrLgth;i++)
804 data64[i] = SwapDouble(data64[i]);
809 entry->SetBinArea(data);
816 * \brief Loads the element while preserving the current
817 * underlying file position indicator as opposed to
818 * LoadDocEntry that modifies it.
819 * @param entry DocEntry whose value will be loaded.
821 void Document::LoadDocEntrySafe(DocEntry *entry)
825 long PositionOnEntry = Fp->tellg();
827 Fp->seekg(PositionOnEntry, std::ios::beg);
832 * \brief Compares two documents, according to \ref DicomDir rules
833 * \warning Does NOT work with ACR-NEMA files
834 * \todo Find a trick to solve the pb (use RET fields ?)
835 * @param document to compare with current one
836 * @return true if 'smaller'
838 bool Document::operator<(Document &document)
841 std::string s1 = GetEntryString(0x0010,0x0010);
842 std::string s2 = document.GetEntryString(0x0010,0x0010);
854 s1 = GetEntryString(0x0010,0x0020);
855 s2 = document.GetEntryString(0x0010,0x0020);
866 // Study Instance UID
867 s1 = GetEntryString(0x0020,0x000d);
868 s2 = document.GetEntryString(0x0020,0x000d);
879 // Serie Instance UID
880 s1 = GetEntryString(0x0020,0x000e);
881 s2 = document.GetEntryString(0x0020,0x000e);
896 //-----------------------------------------------------------------------------
899 * \brief Reads a supposed to be 16 Bits integer
900 * (swaps it depending on processor endianness)
903 uint16_t Document::ReadInt16()
907 Fp->read ((char*)&g, (size_t)2);
910 throw FormatError( "Document::ReadInt16()", " file error." );
914 throw FormatError( "Document::ReadInt16()", "EOF." );
921 * \brief Reads a supposed to be 32 Bits integer
922 * (swaps it depending on processor endianness)
925 uint32_t Document::ReadInt32()
929 Fp->read ((char*)&g, (size_t)4);
932 throw FormatError( "Document::ReadInt32()", " file error." );
936 throw FormatError( "Document::ReadInt32()", "EOF." );
943 * \brief skips bytes inside the source file
946 void Document::SkipBytes(uint32_t nBytes)
948 //FIXME don't dump the returned value
949 Fp->seekg((long)nBytes, std::ios::cur);
953 * \brief Re-computes the length of the Dicom group 0002.
955 int Document::ComputeGroup0002Length( )
961 bool found0002 = false;
963 // for each zero-level Tag in the DCM Header
964 DocEntry *entry = GetFirstEntry();
967 gr = entry->GetGroup();
973 if ( entry->GetElement() != 0x0000 )
977 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
978 // (no SQ, OW, UT in group 0x0002;)
981 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
985 groupLength += 2 + 2 + 4 + entry->GetLength();
991 entry = GetNextEntry();
996 //-----------------------------------------------------------------------------
999 * \brief Loads all the needed Dictionaries
1001 void Document::Initialize()
1003 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1009 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1010 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1011 * @param offset start of parsing
1012 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1013 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1015 void Document::ParseDES(DocEntrySet *set, long offset,
1016 long l_max, bool delim_mode)
1018 DocEntry *newDocEntry;
1019 DataEntry *newDataEntry;
1020 SeqEntry *newSeqEntry;
1022 bool used; // will be set to false when something wrong happens to an Entry.
1023 // (Entry will then be deleted)
1024 bool delim_mode_intern = delim_mode;
1026 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1027 << " at offset " << std::hex << offset );
1030 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1035 newDocEntry = ReadNextDocEntry( );
1037 // Uncoment this cerr line to be able to 'follow' the DocEntries
1038 // when something *very* strange happens
1039 if( Debug::GetDebugFlag() )
1040 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1047 // an Item Starter found elsewhere but the first position
1048 // of a SeqEntry means previous entry was a Sequence
1049 // but we didn't get it (private Sequence + Implicit VR)
1050 // we have to backtrack.
1051 if ( !first && newDocEntry->IsItemStarter() )
1053 // Debug message within the method !
1054 newDocEntry = Backtrack(newDocEntry);
1058 PreviousDocEntry = newDocEntry;
1062 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1066 //////////////////////////// DataEntry
1068 vr = newDocEntry->GetVR();
1070 if ( !set->AddEntry( newDataEntry ) )
1072 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1073 << newDataEntry->GetKey()
1075 << newDataEntry->GetOffset() << " )" );
1080 newDataEntry->Delete();
1081 // Load only if we can add (not a duplicate key)
1082 LoadDocEntry( newDataEntry );
1085 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1087 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1089 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1091 std::string strLgrGroup = newDataEntry->GetString();
1093 if ( newDataEntry->IsUnfound() )
1095 lgrGroup = atoi(strLgrGroup.c_str());
1096 Fp->seekg(lgrGroup, std::ios::cur);
1097 //used = false; // never used
1098 RemoveEntry( newDocEntry ); // Remove and delete
1099 // bcc 5.5 is right "assigned a value that's never used"
1107 bool delimitor = newDataEntry->IsItemDelimitor();
1110 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1113 newDocEntry->Delete();
1117 // Just to make sure we are at the beginning of next entry.
1118 SkipToNextDocEntry(newDocEntry);
1122 /////////////////////// SeqEntry : VR = "SQ"
1124 unsigned long l = newDocEntry->GetReadLength();
1125 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1127 if ( l == 0xffffffff )
1129 delim_mode_intern = true;
1133 delim_mode_intern = false;
1137 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1139 // User asked to skip SeQuences *only* if they belong to Shadow Group
1140 if ( newDocEntry->GetGroup()%2 != 0 )
1142 Fp->seekg( l, std::ios::cur);
1143 newDocEntry->Delete(); // Delete, not in the set
1147 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1149 // User asked to skip *any* SeQuence
1150 Fp->seekg( l, std::ios::cur);
1151 newDocEntry->Delete(); // Delete, not in the set
1154 // delay the dynamic cast as late as possible
1155 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1157 // no other way to create the Delimitor ...
1158 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1160 // At the top of the hierarchy, stands a Document. When "set"
1161 // is a Document, then we are building the first depth level.
1162 // Hence the SeqEntry we are building simply has a depth
1164 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1166 newSeqEntry->SetDepthLevel( 1 );
1168 // But when "set" is already a SQItem, we are building a nested
1169 // sequence, and hence the depth level of the new SeqEntry
1170 // we are building, is one level deeper:
1172 // time waste hunting
1173 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1175 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1179 { // Don't try to parse zero-length sequences
1181 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1182 << " at offset " << std::hex
1183 << newDocEntry->GetOffset() );
1185 ParseSQ( newSeqEntry,
1186 newDocEntry->GetOffset(),
1187 l, delim_mode_intern);
1189 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1192 if ( !set->AddEntry( newSeqEntry ) )
1194 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1195 << newSeqEntry->GetKey()
1197 << newSeqEntry->GetOffset() << " )" );
1202 newDocEntry->Delete();
1205 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1208 newDocEntry->Delete();
1211 } // end SeqEntry : VR = "SQ"
1215 newDocEntry->Delete();
1219 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1223 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1224 * @return parsed length for this level
1226 void Document::ParseSQ( SeqEntry *seqEntry,
1227 long offset, long l_max, bool delim_mode)
1229 int SQItemNumber = 0;
1231 long offsetStartCurrentSQItem = offset;
1235 // the first time, we read the fff0,e000 of the first SQItem
1236 DocEntry *newDocEntry = ReadNextDocEntry();
1240 gdcmWarningMacro("in ParseSQ : should never get here!");
1245 if ( newDocEntry->IsSequenceDelimitor() )
1247 seqEntry->SetDelimitationItem( newDocEntry );
1248 newDocEntry->Delete();
1252 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1254 newDocEntry->Delete();
1257 // create the current SQItem
1258 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1259 unsigned int l = newDocEntry->GetReadLength();
1261 if ( l == 0xffffffff )
1270 // remove fff0,e000, created out of the SQItem
1271 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1272 // fill up the current SQItem, starting at the beginning of fff0,e000
1274 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1276 offsetStartCurrentSQItem = Fp->tellg();
1278 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1280 newDocEntry->Delete();
1282 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1290 * \brief When a private Sequence + Implicit VR is encountered
1291 * we cannot guess it's a Sequence till we find the first
1292 * Item Starter. We then backtrack to do the job.
1293 * @param docEntry Item Starter that warned us
1295 DocEntry *Document::Backtrack(DocEntry *docEntry)
1297 // delete the Item Starter, built erroneously out of any Sequence
1298 // it's not yet in the HTable/chained list
1301 // Get all info we can from PreviousDocEntry
1302 uint16_t group = PreviousDocEntry->GetGroup();
1303 uint16_t elem = PreviousDocEntry->GetElement();
1304 uint32_t lgt = PreviousDocEntry->GetLength();
1305 long offset = PreviousDocEntry->GetOffset();
1307 gdcmDebugMacro( "Backtrack :" << std::hex << group
1309 << " at offset " << offset );
1310 RemoveEntry( PreviousDocEntry );
1312 // forge the Seq Entry
1313 DocEntry *newEntry = NewSeqEntry(group, elem);
1314 newEntry->SetLength(lgt);
1315 newEntry->SetOffset(offset);
1317 // Move back to the beginning of the Sequence
1318 Fp->seekg( 0, std::ios::beg);
1319 Fp->seekg(offset, std::ios::cur);
1325 * \brief Loads (or not) the element content depending if its length exceeds
1326 * or not the value specified with Document::SetMaxSizeLoadEntry()
1327 * @param entry Header Entry (Dicom Element) to be dealt with
1328 * @param forceLoad whether you want to force loading of 'long' elements
1330 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1332 uint16_t group = entry->GetGroup();
1333 uint16_t elem = entry->GetElement();
1334 const VRKey &vr = entry->GetVR();
1335 uint32_t length = entry->GetLength();
1337 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1339 // A SeQuence "contains" a set of Elements.
1340 // (fffe e000) tells us an Element is beginning
1341 // (fffe e00d) tells us an Element just ended
1342 // (fffe e0dd) tells us the current SeQuence just ended
1344 // (fffe 0000) is an 'impossible' tag value,
1345 // found in MR-PHILIPS-16-Multi-Seq.dcm
1347 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1349 // NO more value field for SQ !
1353 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1359 // When the length is zero things are easy:
1362 dataEntryPtr->SetBinArea(NULL,true);
1366 // The elements whose length is bigger than the specified upper bound
1369 std::ostringstream s;
1373 if (length > MaxSizeLoadEntry)
1375 dataEntryPtr->SetBinArea(NULL,true);
1376 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1378 // to be sure we are at the end of the value ...
1379 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1385 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1389 * \brief Find the value Length of the passed Doc Entry
1390 * @param entry Header Entry whose length of the value shall be loaded.
1392 void Document::FindDocEntryLength( DocEntry *entry )
1393 throw ( FormatError )
1395 const VRKey &vr = entry->GetVR();
1398 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1400 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1403 // The following reserved two bytes (see PS 3.5-2003, section
1404 // "7.1.2 Data element structure with explicit vr", p 27) must be
1405 // skipped before proceeding on reading the length on 4 bytes.
1406 Fp->seekg( 2L, std::ios::cur);
1407 uint32_t length32 = ReadInt32();
1409 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1414 lengthOB = FindDocEntryLengthOBOrOW();
1416 catch ( FormatUnexpected )
1418 // Computing the length failed (this happens with broken
1419 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1420 // chance to get the pixels by deciding the element goes
1421 // until the end of the file. Hence we artificially fix the
1422 // the length and proceed.
1423 gdcmWarningMacro( " Computing the length failed for " <<
1424 entry->GetKey() <<" in " <<GetFileName());
1426 long currentPosition = Fp->tellg();
1427 Fp->seekg(0L,std::ios::end);
1429 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1430 Fp->seekg(currentPosition, std::ios::beg);
1432 entry->SetReadLength(lengthUntilEOF);
1433 entry->SetLength(lengthUntilEOF);
1436 entry->SetReadLength(lengthOB);
1437 entry->SetLength(lengthOB);
1440 FixDocEntryFoundLength(entry, length32);
1444 // Length is encoded on 2 bytes.
1445 length16 = ReadInt16();
1447 // 0xffff means that we deal with 'No Length' Sequence
1448 // or 'No Length' SQItem
1449 if ( length16 == 0xffff)
1453 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1458 // Either implicit VR or a non DICOM conformal (see note below) explicit
1459 // VR that ommited the VR of (at least) this element. Farts happen.
1460 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1461 // on Data elements "Implicit and Explicit VR Data Elements shall
1462 // not coexist in a Data Set and Data Sets nested within it".]
1463 // Length is on 4 bytes.
1465 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1466 // even if Transfer Syntax is 'Implicit VR ...'
1467 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1469 FixDocEntryFoundLength( entry, ReadInt32() );
1475 * \brief Find the Length till the next sequence delimiter
1478 uint32_t Document::FindDocEntryLengthOBOrOW()
1479 throw( FormatUnexpected )
1481 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1482 long positionOnEntry = Fp->tellg();
1483 bool foundSequenceDelimiter = false;
1484 uint32_t totalLength = 0;
1486 while ( !foundSequenceDelimiter )
1492 group = ReadInt16();
1495 catch ( FormatError )
1497 throw FormatError("Unexpected end of file encountered during ",
1498 "Document::FindDocEntryLengthOBOrOW()");
1500 // We have to decount the group and element we just read
1502 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1504 long filePosition = Fp->tellg();
1506 "Neither an Item tag nor a Sequence delimiter tag on :"
1507 << std::hex << group << " , " << elem
1508 << ") -before- position x(" << filePosition << ")" );
1510 Fp->seekg(positionOnEntry, std::ios::beg);
1511 throw FormatUnexpected(
1512 "Neither an Item tag nor a Sequence delimiter tag.");
1514 if ( elem == 0xe0dd )
1516 foundSequenceDelimiter = true;
1518 uint32_t itemLength = ReadInt32();
1519 // We add 4 bytes since we just read the ItemLength with ReadInt32
1520 totalLength += itemLength + 4;
1521 SkipBytes(itemLength);
1523 if ( foundSequenceDelimiter )
1528 Fp->seekg( positionOnEntry, std::ios::beg);
1533 * \brief Find the Value Representation of the current Dicom Element.
1534 * @return Value Representation of the current Entry
1536 VRKey Document::FindDocEntryVR()
1538 if ( Filetype != ExplicitVR )
1539 return GDCM_VRUNKNOWN;
1541 long positionOnEntry = Fp->tellg();
1542 // Warning: we believe this is explicit VR (Value Representation) because
1543 // we used a heuristic that found "UL" in the first tag and/or
1544 // 'Transfer Syntax' told us it is.
1545 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1546 // In some cases one finds implicit VR tags mixed within an explicit VR file.
1547 // Hence we make sure the present tag is in explicit VR and try to fix things
1548 // if it happens not to be the case.
1551 Fp->read(&(vr[0]),(size_t)2);
1553 if ( !CheckDocEntryVR(vr) )
1555 // Don't warn user with useless messages
1556 // Often, delimiters (0xfffe), are not explicit VR ...
1557 if ( CurrentGroup != 0xfffe )
1558 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1559 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1560 << ") at offset :" << positionOnEntry );
1561 Fp->seekg(positionOnEntry, std::ios::beg);
1562 return GDCM_VRUNKNOWN;
1568 * \brief Check the correspondance between the VR of the header entry
1569 * and the taken VR. If they are different, the header entry is
1570 * updated with the new VR.
1571 * @param vr Dicom Value Representation
1572 * @return false if the VR is incorrect or if the VR isn't referenced
1573 * otherwise, it returns true
1575 bool Document::CheckDocEntryVR(const VRKey &vr)
1577 return Global::GetVR()->IsValidVR(vr);
1581 * \brief Skip a given Header Entry
1582 * @param entry entry to skip
1584 void Document::SkipDocEntry(DocEntry *entry)
1586 SkipBytes(entry->GetLength());
1590 * \brief Skips to the beginning of the next Header Entry
1591 * @param currentDocEntry entry to skip
1593 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1595 int l = currentDocEntry->GetReadLength();
1596 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1597 // ... but PMS imagers happen !
1599 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1600 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1602 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1607 * \brief When the length of an element value is obviously wrong (because
1608 * the parser went Jabberwocky) one can hope improving things by
1609 * applying some heuristics.
1610 * @param entry entry to check
1611 * @param foundLength first assumption about length
1613 void Document::FixDocEntryFoundLength(DocEntry *entry,
1614 uint32_t foundLength)
1616 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1617 if ( foundLength == 0xffffffff)
1622 uint16_t gr = entry->GetGroup();
1623 uint16_t elem = entry->GetElement();
1625 if ( foundLength % 2)
1627 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1628 << " in x(" << std::hex << gr << "," << elem <<")");
1631 //////// Fix for some naughty General Electric images.
1632 // Allthough not recent many such GE corrupted images are still present
1633 // on Creatis hard disks. Hence this fix shall remain when such images
1634 // are no longer in use (we are talking a few years, here)...
1635 // Note: XMedCon probably uses such a trick since it is able to read
1636 // those pesky GE images ...
1637 if ( foundLength == 13)
1639 // Only happens for this length !
1640 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1643 entry->SetReadLength(10); // a bug is to be fixed !?
1647 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1648 // Occurence of such images is quite low (unless one leaves close to a
1649 // 'Leonardo' source. Hence, one might consider commenting out the
1650 // following fix on efficiency reasons.
1651 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1654 entry->SetReadLength(4); // a bug is to be fixed !
1657 else if ( entry->GetVR() == "SQ" )
1659 foundLength = 0; // ReadLength is unchanged
1662 //////// We encountered a 'delimiter' element i.e. a tag of the form
1663 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1664 // taken into account.
1665 else if ( gr == 0xfffe )
1667 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1668 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1669 // causes extra troubles...
1670 if ( entry->GetElement() != 0x0000 )
1676 foundLength=12; // to skip the mess that follows this bugged Tag !
1679 entry->SetLength(foundLength);
1683 * \brief Apply some heuristics to predict whether the considered
1684 * element value contains/represents an integer or not.
1685 * @param entry The element value on which to apply the predicate.
1686 * @return The result of the heuristical predicate.
1688 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1690 uint16_t elem = entry->GetElement();
1691 uint16_t group = entry->GetGroup();
1692 const VRKey &vr = entry->GetVR();
1693 uint32_t length = entry->GetLength();
1695 // When we have some semantics on the element we just read, and if we
1696 // a priori know we are dealing with an integer, then we shall be
1697 // able to swap it's element value properly.
1698 if ( elem == 0 ) // This is the group length of the group
1706 // Although this should never happen, still some images have a
1707 // corrupted group length [e.g. have a glance at offset x(8336) of
1708 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1709 // Since for dicom compliant and well behaved headers, the present
1710 // test is useless (and might even look a bit paranoid), when we
1711 // encounter such an ill-formed image, we simply display a warning
1712 // message and proceed on parsing (while crossing fingers).
1713 long filePosition = Fp->tellg();
1714 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1715 << std::hex << group << " , " << elem
1716 << ") -before- position x(" << filePosition << ")"
1717 << "lgt : " << length );
1721 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1729 * \brief Discover what the swap code is (among little endian, big endian,
1730 * bad little endian, bad big endian).
1732 * @return false when we are absolutely sure
1733 * it's neither ACR-NEMA nor DICOM
1734 * true when we hope ours assuptions are OK
1736 bool Document::CheckSwap()
1743 // First, compare HostByteOrder and NetworkByteOrder in order to
1744 // determine if we shall need to swap bytes (i.e. the Endian type).
1745 bool net2host = Util::IsCurrentProcessorBigEndian();
1747 // The easiest case is the one of a 'true' DICOM header, we just have
1748 // to look for the string "DICM" inside the file preamble.
1751 char *entCur = deb + 128;
1752 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1754 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1756 // Group 0002 should always be VR, and the first element 0000
1757 // Let's be carefull (so many wrong headers ...)
1758 // and determine the value representation (VR) :
1759 // Let's skip to the first element (0002,0000) and check there if we find
1760 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1761 // in which case we (almost) know it is explicit VR.
1762 // WARNING: if it happens to be implicit VR then what we will read
1763 // is the length of the group. If this ascii representation of this
1764 // length happens to be "UL" then we shall believe it is explicit VR.
1765 // We need to skip :
1766 // * the 128 bytes of File Preamble (often padded with zeroes),
1767 // * the 4 bytes of "DICM" string,
1768 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1769 // i.e. a total of 136 bytes.
1772 // group 0x0002 *is always* Explicit VR Sometimes ,
1773 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1774 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1776 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1777 memcmp(entCur, "OB", (size_t)2) == 0 ||
1778 memcmp(entCur, "UI", (size_t)2) == 0 ||
1779 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1780 // when Write DCM *adds*
1782 // Use Document::dicom_vr to test all the possibilities
1783 // instead of just checking for UL, OB and UI !? group 0000
1785 Filetype = ExplicitVR;
1786 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1790 Filetype = ImplicitVR;
1791 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1792 << "Looks like a bugged Header!");
1798 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1803 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1806 // Position the file position indicator at first tag
1807 // (i.e. after the file preamble and the "DICM" string).
1809 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1811 Fp->seekg ( 132L, std::ios::beg);
1813 } // ------------------------------- End of DicomV3 ----------------
1815 // Alas, this is not a DicomV3 file and whatever happens there is no file
1816 // preamble. We can reset the file position indicator to where the data
1817 // is (i.e. the beginning of the file).
1819 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1821 Fp->seekg(0, std::ios::beg);
1823 // Let's check 'No Preamble Dicom File' :
1824 // Should start with group 0x0002
1825 // and be Explicit Value Representation
1827 s16 = *((uint16_t *)(deb));
1840 if ( SwapCode != 0 )
1842 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1843 memcmp(entCur, "OB", (size_t)2) == 0 ||
1844 memcmp(entCur, "UI", (size_t)2) == 0 ||
1845 memcmp(entCur, "SH", (size_t)2) == 0 ||
1846 memcmp(entCur, "AE", (size_t)2) == 0 ||
1847 memcmp(entCur, "OB", (size_t)2) == 0 )
1849 Filetype = ExplicitVR;
1850 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1854 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1856 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1857 // By clean we mean that the length of the first group is written down.
1858 // If this is the case and since the length of the first group HAS to be
1859 // four (bytes), then determining the proper swap code is straightforward.
1862 // We assume the array of char we are considering contains the binary
1863 // representation of a 32 bits integer. Hence the following dirty
1865 s32 = *((uint32_t *)(entCur));
1885 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1886 // It is time for despaired wild guesses.
1887 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1888 // i.e. the 'group length' element is not present :
1890 // check the supposed-to-be 'group number'
1891 // in ( 0x0001 .. 0x0008 )
1892 // to determine ' SwapCode' value .
1893 // Only 0 or 4321 will be possible
1894 // (no oportunity to check for the formerly well known
1895 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1896 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1897 // the file IS NOT ACR-NEMA nor DICOM V3
1898 // Find a trick to tell it the caller...
1900 s16 = *((uint16_t *)(deb));
1927 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1935 * \brief Change the Byte Swap code.
1937 void Document::SwitchByteSwapCode()
1939 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1940 << " at: 0x" << std::hex << Fp->tellg() );
1941 if ( SwapCode == 1234 )
1945 else if ( SwapCode == 4321 )
1949 else if ( SwapCode == 3412 )
1953 else if ( SwapCode == 2143 )
1957 gdcmDebugMacro( " Into: "<< SwapCode );
1961 * \brief during parsing, Header Elements too long are not loaded in memory
1962 * @param newSize new size
1964 void Document::SetMaxSizeLoadEntry(long newSize)
1970 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1972 MaxSizeLoadEntry = 0xffffffff;
1975 MaxSizeLoadEntry = newSize;
1979 * \brief Read the next tag WITHOUT loading it's value
1980 * (read the 'Group Number', the 'Element Number',
1981 * gets the Dict Entry
1982 * gets the VR, gets the length, gets the offset value)
1983 * @return On succes : the newly created DocEntry, NULL on failure.
1985 DocEntry *Document::ReadNextDocEntry()
1989 CurrentGroup = ReadInt16();
1990 CurrentElem = ReadInt16();
1992 catch ( FormatError )
1994 // We reached the EOF (or an error occured) therefore
1995 // header parsing has to be considered as finished.
1999 // Sometimes file contains groups of tags with reversed endianess.
2000 HandleBrokenEndian(CurrentGroup, CurrentElem);
2002 // In 'true DICOM' files Group 0002 is always little endian
2003 if ( HasDCMPreamble )
2004 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2006 VRKey vr = FindDocEntryVR();
2010 if ( vr == GDCM_VRUNKNOWN )
2012 if ( CurrentElem == 0x0000 ) // Group Length
2014 realVR = "UL"; // must be UL
2016 else if (CurrentGroup%2 == 1 &&
2017 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2019 // DICOM PS 3-5 7.8.1 a) states that those
2020 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2025 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2028 realVR = dictEntry->GetVR();
2029 dictEntry->Unregister();
2033 // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2036 if ( Global::GetVR()->IsVROfSequence(realVR) )
2037 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2040 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2041 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2044 if ( vr == GDCM_VRUNKNOWN )
2046 if ( Filetype == ExplicitVR )
2048 // We thought this was explicit VR, but we end up with an
2049 // implicit VR tag. Let's backtrack.
2050 if ( newEntry->GetGroup() != 0xfffe )
2053 int offset = Fp->tellg();
2055 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2056 newEntry->GetGroup(), newEntry->GetElement(), offset );
2057 gdcmWarningMacro( msg.c_str() );
2060 newEntry->SetImplicitVR();
2065 FindDocEntryLength(newEntry);
2067 catch ( FormatError )
2074 newEntry->SetOffset(Fp->tellg());
2080 * \brief Handle broken private tag from Philips NTSCAN
2081 * where the endianess is being switched to BigEndian
2082 * for no apparent reason
2085 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2087 // Endian reversion.
2088 // Some files contain groups of tags with reversed endianess.
2089 static int reversedEndian = 0;
2090 // try to fix endian switching in the middle of headers
2091 if ((group == 0xfeff) && (elem == 0x00e0))
2093 // start endian swap mark for group found
2094 gdcmDebugMacro( "Start endian swap mark found." );
2096 SwitchByteSwapCode();
2101 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2103 // end of reversed endian group
2104 gdcmDebugMacro( "End of reversed endian." );
2106 SwitchByteSwapCode();
2108 else if (group == 0xfeff && elem == 0xdde0)
2110 // reversed Sequence Terminator found
2111 // probabely a bug in the header !
2112 // Do what you want, it breaks !
2114 //SwitchByteSwapCode();
2115 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2120 else if (group == 0xfffe && elem == 0xe0dd)
2122 gdcmDebugMacro( "Straight Sequence Terminator." );
2127 * \brief Group 0002 is always coded Little Endian
2128 * whatever Transfer Syntax is
2131 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2133 // Endian reversion.
2134 // Some files contain groups of tags with reversed endianess.
2135 if ( !Group0002Parsed && group != 0x0002)
2137 Group0002Parsed = true;
2138 // we just came out of group 0002
2139 // if Transfer Syntax is Big Endian we have to change CheckSwap
2141 std::string ts = GetTransferSyntax();
2142 if ( ts == GDCM_UNKNOWN )
2144 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2147 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2149 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2154 // Group 0002 is always 'Explicit ...'
2155 // even when Transfer Syntax says 'Implicit ..."
2157 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2158 TS::ImplicitVRLittleEndian )
2160 Filetype = ImplicitVR;
2163 // FIXME Strangely, this works with
2164 //'Implicit VR BigEndian Transfer Syntax (GE Private)
2166 // --> Probabely normal, since we considered we never have
2167 // to trust manufacturers.
2168 // (we find very often 'Implicit VR' tag,
2169 // even when Transfer Syntax tells us it's Explicit ...
2170 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2171 TS::ExplicitVRBigEndian )
2173 gdcmDebugMacro("Transfer Syntax Name = ["
2174 << GetTransferSyntaxName() << "]" );
2175 SwitchByteSwapCode();
2176 group = SwapShort(group);
2177 elem = SwapShort(elem);
2182 //-----------------------------------------------------------------------------
2185 //-----------------------------------------------------------------------------
2186 } // end namespace gdcm