1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/11/14 14:23:44 $
7 Version: $Revision: 1.327 $
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( );
94 * \brief Loader. (DEPRECATED : not to break the API)
95 * @param fileName 'Document' (File or DicomDir) to be open for parsing
96 * @return false if file cannot be open or no swap info was found,
97 * or no tag was found.
99 bool Document::Load( std::string const &fileName )
102 return DoTheLoadingDocumentJob( );
106 * \brief Performs the Loading Job (internal use only)
107 * @return false if file cannot be open or no swap info was found,
108 * or no tag was found.
110 bool Document::DoTheLoadingDocumentJob( )
112 if ( ! IsDocumentModified ) // Nothing to do !
120 // warning already performed in OpenFile()
125 Group0002Parsed = false;
127 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
129 Fp->seekg(0, std::ios::end);
130 long lgt = Fp->tellg(); // total length of the file
132 Fp->seekg(0, std::ios::beg);
134 // CheckSwap returns a boolean
135 // (false if no swap info of any kind was found)
138 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
139 << Filename.c_str());
144 long beg = Fp->tellg(); // just after DICOM preamble (if any)
146 lgt -= beg; // remaining length to parse
149 // Loading is done during parsing
150 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
154 gdcmErrorMacro( "No tag in internal hash table for: "
155 << Filename.c_str());
159 IsDocumentAlreadyLoaded = true;
161 Fp->seekg( 0, std::ios::beg);
163 // Load 'non string' values
165 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
166 if ( PhotometricInterpretation == "PALETTE COLOR " )
169 // Probabely this line should be outside the 'if'
170 // Try to find an image sample holding a 'gray LUT'
171 LoadEntryBinArea(0x0028,0x1200); // gray LUT
174 /// --> FIXME : The difference between BinEntry and DataEntry
175 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
176 /// --> Old comment restored on purpose.
177 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
178 /// --> had absolutely no meaning.
179 /// --> The whole comment will be removed when the stuff is cleaned !
181 /// The tags refered by the three following lines used to be CORRECTLY
182 /// defined as having an US Value Representation in the public
183 /// dictionary. BUT the semantics implied by the three following
184 /// lines state that the corresponding tag contents are in fact
185 /// the ones of a BinEntry.
186 /// In order to fix things "Quick and Dirty" the dictionary was
187 /// altered on PURPOSE but now contains a WRONG value.
188 /// In order to fix things and restore the dictionary to its
189 /// correct value, one needs to decide of the semantics by deciding
190 /// whether the following tags are either :
191 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
192 /// also used as BinEntry, which requires the proper conversion,
193 /// - OW, and hence loaded as BinEntry, but afterwards also used
194 /// as ValEntry, which requires the proper conversion.
196 // --> OB (byte aray) or OW (short int aray)
197 // The actual VR has to be deduced from other entries.
198 // Our way of loading them may fail in some cases :
199 // We must or not SwapByte depending on other field values.
201 LoadEntryBinArea(0x0028,0x1201); // R LUT
202 LoadEntryBinArea(0x0028,0x1202); // G LUT
203 LoadEntryBinArea(0x0028,0x1203); // B LUT
205 // Segmented Red Palette Color LUT Data
206 LoadEntryBinArea(0x0028,0x1221);
207 // Segmented Green Palette Color LUT Data
208 LoadEntryBinArea(0x0028,0x1222);
209 // Segmented Blue Palette Color LUT Data
210 LoadEntryBinArea(0x0028,0x1223);
213 //FIXME later : how to use it?
214 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
217 SQItem *sqi= modLutSeq->GetFirstSQItem();
220 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
221 if ( dataEntry != 0 )
223 if ( dataEntry->GetLength() != 0 )
225 // FIXME : CTX dependent means : contexted dependant.
226 // see upper comment.
227 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
233 // Force Loading some more elements if user asked to.
236 for (ListElements::iterator it = UserForceLoadList.begin();
237 it != UserForceLoadList.end();
240 gdcmDebugMacro( "Force Load " << std::hex
241 << (*it).Group << "|" <<(*it).Elem );
243 d = GetDocEntry( (*it).Group, (*it).Elem);
247 gdcmWarningMacro( "You asked toForce Load " << std::hex
248 << (*it).Group <<"|"<< (*it).Elem
249 << " that doesn't exist" );
253 LoadDocEntry(d, true);
258 // ----------------------------
259 // Specific code to allow gdcm to read ACR-LibIDO formated images
260 // Note: ACR-LibIDO is an extension of the ACR standard that was
261 // used at CREATIS. For the time being (say a couple of years)
262 // we keep this kludge to allow CREATIS users
263 // reading their old images.
265 // if recognition code tells us we deal with a LibIDO image
266 // we switch lineNumber and columnNumber
269 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
270 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
271 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
272 // with "little-endian strings"
274 Filetype = ACR_LIBIDO;
275 std::string rows = GetEntryString(0x0028, 0x0010);
276 std::string columns = GetEntryString(0x0028, 0x0011);
277 SetEntryString(columns, 0x0028, 0x0010);
278 SetEntryString(rows , 0x0028, 0x0011);
280 // --- End of ACR-LibIDO kludge ---
286 * \brief Adds a new element we want to load anyway
287 * @param group Group number of the target tag.
288 * @param elem Element number of the target tag.
290 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
295 UserForceLoadList.push_back(el);
298 * \brief Get the public dictionary used
300 Dict *Document::GetPubDict()
306 * \brief Get the shadow dictionary used
308 Dict *Document::GetShaDict()
314 * \brief Set the shadow dictionary used
315 * @param dict dictionary to use in shadow
317 bool Document::SetShaDict(Dict *dict)
324 * \brief Set the shadow dictionary used
325 * @param dictName name of the dictionary to use in shadow
327 bool Document::SetShaDict(DictKey const &dictName)
329 RefShaDict = Global::GetDicts()->GetDict(dictName);
334 * \brief This predicate tells us whether or not the current Document
335 * was properly parsed and contains at least *one* Dicom Element
336 * (and nothing more, sorry).
337 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
340 bool Document::IsReadable()
342 if ( Filetype == Unknown )
344 gdcmErrorMacro( "Wrong filetype for " << GetFileName());
350 gdcmErrorMacro( "No tag in internal hash table.");
358 * \brief Predicate for dicom version 3 file.
359 * @return True when the file is a dicom version 3.
361 bool Document::IsDicomV3()
363 // Checking if Transfer Syntax exists is enough
364 // Anyway, it's too late check if the 'Preamble' was found ...
365 // And ... would it be a rich idea to check ?
366 // (some 'no Preamble' DICOM images exist !)
367 return GetDocEntry(0x0002, 0x0010) != NULL;
371 * \brief Predicate for Papyrus file
372 * Dedicated to whomsoever it may concern
373 * @return True when the file is a Papyrus file.
375 bool Document::IsPapyrus()
377 // check for Papyrus private Sequence
378 DocEntry *e = GetDocEntry(0x0041, 0x1050);
381 // check if it's actually a Sequence
382 if ( !dynamic_cast<SeqEntry*>(e) )
388 * \brief returns the File Type
389 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
390 * @return the FileType code
392 FileType Document::GetFileType()
398 * \brief Accessor to the Transfer Syntax (when present) of the
399 * current document (it internally handles reading the
400 * value from disk when only parsing occured).
401 * @return The encountered Transfer Syntax of the current document, if DICOM.
402 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
404 std::string Document::GetTransferSyntax()
406 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
412 // The entry might be present but not loaded (parsing and loading
413 // happen at different stages): try loading and proceed with check...
414 LoadDocEntrySafe(entry);
415 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
417 std::string transfer = dataEntry->GetString();
418 // The actual transfer (as read from disk) might be padded. We
419 // first need to remove the potential padding. We can make the
420 // weak assumption that padding was not executed with digits...
421 if ( transfer.length() == 0 )
423 // for brain damaged headers
424 gdcmWarningMacro( "Transfer Syntax has length = 0.");
427 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
429 transfer.erase(transfer.length()-1, 1);
430 if ( transfer.length() == 0 )
432 // for brain damaged headers
433 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
443 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
444 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
446 std::string Document::GetTransferSyntaxName()
448 // use the TS (TS : Transfer Syntax)
449 std::string transferSyntax = GetEntryString(0x0002,0x0010);
451 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
453 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
454 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
455 return "Uncompressed ACR-NEMA";
457 if ( transferSyntax == GDCM_UNFOUND )
459 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
460 return "Uncompressed ACR-NEMA";
463 // we do it only when we need it
464 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
466 // Global::GetTS() is a global static you shall never try to delete it!
470 // --------------- Swap Code ------------------
472 * \brief Swaps the bytes so they agree with the processor order
473 * @return The properly swaped 16 bits integer.
475 uint16_t Document::SwapShort(uint16_t a)
477 if ( SwapCode == 4321 || SwapCode == 2143 )
479 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
481 a = ( a << 8 ) | ( a >> 8 );
487 * \brief Swaps back the bytes of 4-byte long integer accordingly to
489 * @return The properly swaped 32 bits integer.
491 uint32_t Document::SwapLong(uint32_t a)
498 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
499 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
501 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
502 ((a>>8) & 0x0000ff00) | (a>>24) );
505 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
506 a=( (a<<16) | (a>>16) );
509 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
512 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
519 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
521 * @return The properly swaped 64 bits double.
523 double Document::SwapDouble(double a)
527 // There were no 'double' at ACR-NEMA time.
528 // We just have to deal with 'straight Little Endian' and
529 // 'straight Big Endian'
534 char *beg = (char *)&a;
537 for (unsigned int i = 0; i<7; i++)
548 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
555 // -----------------File I/O ---------------
557 * \brief Tries to open the file \ref Document::Filename and
558 * checks the preamble when existing.
559 * @return The FILE pointer on success.
561 std::ifstream *Document::OpenFile()
563 HasDCMPreamble = false;
564 if (Filename.length() == 0)
571 gdcmDebugMacro( "File already open: " << Filename.c_str());
575 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
578 // Don't user gdcmErrorMacro :
579 // a spurious message will appear when you use, for instance
580 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
581 // to create outputFileName.
583 // FIXME : if the upper comment is still usefull
584 // --> the constructor is not so good ...
586 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
590 //exit(1); // No function is allowed to leave the application instead
591 // of warning the caller
595 Fp->read((char*)&zero, (size_t)2);
602 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
604 // FIXME : We cannot be sure the preable is only zeroes..
605 // (see ACUSON-24-YBR_FULL-RLE.dcm )
607 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
608 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
609 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
610 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
612 std::string msg = Util::Format(
613 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
614 // FIXME : is it a Warning message, or a Debug message?
615 gdcmWarningMacro( msg.c_str() );
620 Fp->seekg(126L, std::ios::cur);
621 char dicm[4]; // = {' ',' ',' ',' '};
622 Fp->read(dicm, (size_t)4);
628 if ( memcmp(dicm, "DICM", 4) == 0 )
630 HasDCMPreamble = true;
634 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
636 // Don't user Warning nor Error, not to polute the output
637 // while directory recursive parsing ...
638 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
639 << Filename.c_str());
644 * \brief closes the file
645 * @return TRUE if the close was successfull
647 bool Document::CloseFile()
659 * \brief Writes in a file all the Entries (Dicom Elements)
660 * @param fp file pointer on an already open file (actually: Output File Stream)
661 * @param filetype Type of the File to be written
662 * (ACR-NEMA, ExplicitVR, ImplicitVR)
664 void Document::WriteContent(std::ofstream *fp, FileType filetype)
666 // Skip if user wants to write an ACR-NEMA file
668 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
671 // writing Dicom File Preamble
672 char filePreamble[128];
673 memset(filePreamble, 0, 128);
674 fp->write(filePreamble, 128);
675 fp->write("DICM", 4);
679 * \todo rewrite later, if really usefull
680 * - 'Group Length' element is optional in DICOM
681 * - but un-updated odd groups lengthes can causes pb
684 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
685 * UpdateGroupLength(false,filetype);
686 * if ( filetype == ACR)
687 * UpdateGroupLength(true,ACR);
689 * --> Computing group length for groups with embeded Sequences
690 * --> was too much tricky / we were [in a hurry / too lazy]
691 * --> We don't write the element 0x0000 (group length)
694 ElementSet::WriteContent(fp, filetype); // This one is recursive
697 // -----------------------------------------
700 * \brief Loads (from disk) the element content
701 * when a string is not suitable
702 * @param group group number of the Entry
703 * @param elem element number of the Entry
705 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
707 // Search the corresponding DocEntry
708 DocEntry *docEntry = GetDocEntry(group, elem);
711 gdcmDebugMacro(std::hex << group << "|" << elem
712 << " doesn't exist" );
715 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
718 gdcmWarningMacro(std::hex << group << "|" << elem
719 << " is NOT a DataEntry");
722 LoadEntryBinArea(dataEntry);
726 * \brief Loads (from disk) the element content
727 * when a string is not suitable
728 * @param entry Entry whose binArea is going to be loaded
730 void Document::LoadEntryBinArea(DataEntry *entry)
732 if( entry->GetBinArea() )
739 size_t o =(size_t)entry->GetOffset();
740 Fp->seekg(o, std::ios::beg);
742 size_t l = entry->GetLength();
743 uint8_t *data = new uint8_t[l];
746 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
747 << std::hex << entry->GetGroup()
748 << "|" << entry->GetElement() );
753 Fp->read((char*)data, l);
754 if ( Fp->fail() || Fp->eof() )
757 entry->SetState(DataEntry::STATE_UNREAD);
761 // Swap the data content if necessary
763 unsigned short vrLgth =
764 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
766 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
767 // if( entry->GetVR() == "OW" )
778 uint16_t *data16 = (uint16_t *)data;
779 for(i=0;i<l/vrLgth;i++)
780 data16[i] = SwapShort(data16[i]);
785 uint32_t *data32 = (uint32_t *)data;
786 for(i=0;i<l/vrLgth;i++)
787 data32[i] = SwapLong(data32[i]);
792 double *data64 = (double *)data;
793 for(i=0;i<l/vrLgth;i++)
794 data64[i] = SwapDouble(data64[i]);
799 entry->SetBinArea(data);
806 * \brief Loads the element while preserving the current
807 * underlying file position indicator as opposed to
808 * LoadDocEntry that modifies it.
809 * @param entry DocEntry whose value will be loaded.
811 void Document::LoadDocEntrySafe(DocEntry *entry)
815 long PositionOnEntry = Fp->tellg();
817 Fp->seekg(PositionOnEntry, std::ios::beg);
822 * \brief Compares two documents, according to \ref DicomDir rules
823 * \warning Does NOT work with ACR-NEMA files
824 * \todo Find a trick to solve the pb (use RET fields ?)
825 * @param document to compare with current one
826 * @return true if 'smaller'
828 bool Document::operator<(Document &document)
831 std::string s1 = GetEntryString(0x0010,0x0010);
832 std::string s2 = document.GetEntryString(0x0010,0x0010);
844 s1 = GetEntryString(0x0010,0x0020);
845 s2 = document.GetEntryString(0x0010,0x0020);
856 // Study Instance UID
857 s1 = GetEntryString(0x0020,0x000d);
858 s2 = document.GetEntryString(0x0020,0x000d);
869 // Serie Instance UID
870 s1 = GetEntryString(0x0020,0x000e);
871 s2 = document.GetEntryString(0x0020,0x000e);
886 //-----------------------------------------------------------------------------
889 * \brief Reads a supposed to be 16 Bits integer
890 * (swaps it depending on processor endianness)
893 uint16_t Document::ReadInt16()
897 Fp->read ((char*)&g, (size_t)2);
900 throw FormatError( "Document::ReadInt16()", " file error." );
904 throw FormatError( "Document::ReadInt16()", "EOF." );
911 * \brief Reads a supposed to be 32 Bits integer
912 * (swaps it depending on processor endianness)
915 uint32_t Document::ReadInt32()
919 Fp->read ((char*)&g, (size_t)4);
922 throw FormatError( "Document::ReadInt32()", " file error." );
926 throw FormatError( "Document::ReadInt32()", "EOF." );
933 * \brief skips bytes inside the source file
936 void Document::SkipBytes(uint32_t nBytes)
938 //FIXME don't dump the returned value
939 Fp->seekg((long)nBytes, std::ios::cur);
943 * \brief Re-computes the length of the Dicom group 0002.
945 int Document::ComputeGroup0002Length( )
951 bool found0002 = false;
953 // for each zero-level Tag in the DCM Header
954 DocEntry *entry = GetFirstEntry();
957 gr = entry->GetGroup();
963 if ( entry->GetElement() != 0x0000 )
967 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
968 // (no SQ, OW, UT in group 0x0002;)
971 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
975 groupLength += 2 + 2 + 4 + entry->GetLength();
981 entry = GetNextEntry();
986 //-----------------------------------------------------------------------------
989 * \brief Loads all the needed Dictionaries
991 void Document::Initialize()
993 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
999 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1000 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1001 * @param offset start of parsing
1002 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1003 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1005 void Document::ParseDES(DocEntrySet *set, long offset,
1006 long l_max, bool delim_mode)
1008 DocEntry *newDocEntry;
1009 DataEntry *newDataEntry;
1010 SeqEntry *newSeqEntry;
1012 bool used; // will be set to false when something wrong happens to an Entry.
1013 // (Entry will then be deleted)
1014 bool delim_mode_intern = delim_mode;
1016 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1017 << " at offset " << std::hex << offset );
1020 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1025 newDocEntry = ReadNextDocEntry( );
1027 // Uncoment this cerr line to be able to 'follow' the DocEntries
1028 // when something *very* strange happens
1029 if( Debug::GetDebugFlag() )
1030 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1037 // an Item Starter found elsewhere but the first position
1038 // of a SeqEntry means previous entry was a Sequence
1039 // but we didn't get it (private Sequence + Implicit VR)
1040 // we have to backtrack.
1041 if ( !first && newDocEntry->IsItemStarter() )
1043 // Debug message within the method !
1044 newDocEntry = Backtrack(newDocEntry);
1048 PreviousDocEntry = newDocEntry;
1052 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1056 //////////////////////////// DataEntry
1058 vr = newDocEntry->GetVR();
1060 if ( !set->AddEntry( newDataEntry ) )
1062 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1063 << newDataEntry->GetKey()
1065 << newDataEntry->GetOffset() << " )" );
1070 newDataEntry->Delete();
1071 // Load only if we can add (not a duplicate key)
1072 LoadDocEntry( newDataEntry );
1075 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1077 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1079 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1081 std::string strLgrGroup = newDataEntry->GetString();
1083 if ( newDataEntry->IsUnfound() )
1085 lgrGroup = atoi(strLgrGroup.c_str());
1086 Fp->seekg(lgrGroup, std::ios::cur);
1087 //used = false; // never used
1088 RemoveEntry( newDocEntry ); // Remove and delete
1089 // bcc 5.5 is right "assigned a value that's never used"
1097 bool delimitor = newDataEntry->IsItemDelimitor();
1100 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1103 newDocEntry->Delete();
1107 // Just to make sure we are at the beginning of next entry.
1108 SkipToNextDocEntry(newDocEntry);
1112 /////////////////////// SeqEntry : VR = "SQ"
1114 unsigned long l = newDocEntry->GetReadLength();
1115 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1117 if ( l == 0xffffffff )
1119 delim_mode_intern = true;
1123 delim_mode_intern = false;
1127 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1129 // User asked to skip SeQuences *only* if they belong to Shadow Group
1130 if ( newDocEntry->GetGroup()%2 != 0 )
1132 Fp->seekg( l, std::ios::cur);
1133 newDocEntry->Delete(); // Delete, not in the set
1137 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1139 // User asked to skip *any* SeQuence
1140 Fp->seekg( l, std::ios::cur);
1141 newDocEntry->Delete(); // Delete, not in the set
1144 // delay the dynamic cast as late as possible
1145 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1147 // no other way to create the Delimitor ...
1148 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1150 // At the top of the hierarchy, stands a Document. When "set"
1151 // is a Document, then we are building the first depth level.
1152 // Hence the SeqEntry we are building simply has a depth
1154 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1156 newSeqEntry->SetDepthLevel( 1 );
1158 // But when "set" is already a SQItem, we are building a nested
1159 // sequence, and hence the depth level of the new SeqEntry
1160 // we are building, is one level deeper:
1162 // time waste hunting
1163 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1165 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1169 { // Don't try to parse zero-length sequences
1171 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1172 << " at offset " << std::hex
1173 << newDocEntry->GetOffset() );
1175 ParseSQ( newSeqEntry,
1176 newDocEntry->GetOffset(),
1177 l, delim_mode_intern);
1179 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1182 if ( !set->AddEntry( newSeqEntry ) )
1184 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1185 << newSeqEntry->GetKey()
1187 << newSeqEntry->GetOffset() << " )" );
1192 newDocEntry->Delete();
1195 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1198 newDocEntry->Delete();
1201 } // end SeqEntry : VR = "SQ"
1205 newDocEntry->Delete();
1209 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1213 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1214 * @return parsed length for this level
1216 void Document::ParseSQ( SeqEntry *seqEntry,
1217 long offset, long l_max, bool delim_mode)
1219 int SQItemNumber = 0;
1221 long offsetStartCurrentSQItem = offset;
1225 // the first time, we read the fff0,e000 of the first SQItem
1226 DocEntry *newDocEntry = ReadNextDocEntry();
1230 gdcmWarningMacro("in ParseSQ : should never get here!");
1235 if ( newDocEntry->IsSequenceDelimitor() )
1237 seqEntry->SetDelimitationItem( newDocEntry );
1238 newDocEntry->Delete();
1242 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1244 newDocEntry->Delete();
1247 // create the current SQItem
1248 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1249 unsigned int l = newDocEntry->GetReadLength();
1251 if ( l == 0xffffffff )
1260 // remove fff0,e000, created out of the SQItem
1261 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1262 // fill up the current SQItem, starting at the beginning of fff0,e000
1264 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1266 offsetStartCurrentSQItem = Fp->tellg();
1268 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1270 newDocEntry->Delete();
1272 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1280 * \brief When a private Sequence + Implicit VR is encountered
1281 * we cannot guess it's a Sequence till we find the first
1282 * Item Starter. We then backtrack to do the job.
1283 * @param docEntry Item Starter that warned us
1285 DocEntry *Document::Backtrack(DocEntry *docEntry)
1287 // delete the Item Starter, built erroneously out of any Sequence
1288 // it's not yet in the HTable/chained list
1291 // Get all info we can from PreviousDocEntry
1292 uint16_t group = PreviousDocEntry->GetGroup();
1293 uint16_t elem = PreviousDocEntry->GetElement();
1294 uint32_t lgt = PreviousDocEntry->GetLength();
1295 long offset = PreviousDocEntry->GetOffset();
1297 gdcmDebugMacro( "Backtrack :" << std::hex << group
1299 << " at offset " << offset );
1300 RemoveEntry( PreviousDocEntry );
1302 // forge the Seq Entry
1303 DocEntry *newEntry = NewSeqEntry(group, elem);
1304 newEntry->SetLength(lgt);
1305 newEntry->SetOffset(offset);
1307 // Move back to the beginning of the Sequence
1308 Fp->seekg( 0, std::ios::beg);
1309 Fp->seekg(offset, std::ios::cur);
1315 * \brief Loads (or not) the element content depending if its length exceeds
1316 * or not the value specified with Document::SetMaxSizeLoadEntry()
1317 * @param entry Header Entry (Dicom Element) to be dealt with
1318 * @param forceLoad whether you want to force loading of 'long' elements
1320 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1322 uint16_t group = entry->GetGroup();
1323 uint16_t elem = entry->GetElement();
1324 const VRKey &vr = entry->GetVR();
1325 uint32_t length = entry->GetLength();
1327 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1329 // A SeQuence "contains" a set of Elements.
1330 // (fffe e000) tells us an Element is beginning
1331 // (fffe e00d) tells us an Element just ended
1332 // (fffe e0dd) tells us the current SeQuence just ended
1334 // (fffe 0000) is an 'impossible' tag value,
1335 // found in MR-PHILIPS-16-Multi-Seq.dcm
1337 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1339 // NO more value field for SQ !
1343 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1349 // When the length is zero things are easy:
1352 dataEntryPtr->SetBinArea(NULL,true);
1356 // The elements whose length is bigger than the specified upper bound
1359 std::ostringstream s;
1363 if (length > MaxSizeLoadEntry)
1365 dataEntryPtr->SetBinArea(NULL,true);
1366 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1368 // to be sure we are at the end of the value ...
1369 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1375 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1379 * \brief Find the value Length of the passed Doc Entry
1380 * @param entry Header Entry whose length of the value shall be loaded.
1382 void Document::FindDocEntryLength( DocEntry *entry )
1383 throw ( FormatError )
1385 const VRKey &vr = entry->GetVR();
1388 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1390 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1393 // The following reserved two bytes (see PS 3.5-2003, section
1394 // "7.1.2 Data element structure with explicit vr", p 27) must be
1395 // skipped before proceeding on reading the length on 4 bytes.
1396 Fp->seekg( 2L, std::ios::cur);
1397 uint32_t length32 = ReadInt32();
1399 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1404 lengthOB = FindDocEntryLengthOBOrOW();
1406 catch ( FormatUnexpected )
1408 // Computing the length failed (this happens with broken
1409 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1410 // chance to get the pixels by deciding the element goes
1411 // until the end of the file. Hence we artificially fix the
1412 // the length and proceed.
1413 gdcmWarningMacro( " Computing the length failed for " <<
1414 entry->GetKey() <<" in " <<GetFileName());
1416 long currentPosition = Fp->tellg();
1417 Fp->seekg(0L,std::ios::end);
1419 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1420 Fp->seekg(currentPosition, std::ios::beg);
1422 entry->SetReadLength(lengthUntilEOF);
1423 entry->SetLength(lengthUntilEOF);
1426 entry->SetReadLength(lengthOB);
1427 entry->SetLength(lengthOB);
1430 FixDocEntryFoundLength(entry, length32);
1434 // Length is encoded on 2 bytes.
1435 length16 = ReadInt16();
1437 // 0xffff means that we deal with 'No Length' Sequence
1438 // or 'No Length' SQItem
1439 if ( length16 == 0xffff)
1443 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1448 // Either implicit VR or a non DICOM conformal (see note below) explicit
1449 // VR that ommited the VR of (at least) this element. Farts happen.
1450 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1451 // on Data elements "Implicit and Explicit VR Data Elements shall
1452 // not coexist in a Data Set and Data Sets nested within it".]
1453 // Length is on 4 bytes.
1455 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1456 // even if Transfer Syntax is 'Implicit VR ...'
1457 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1459 FixDocEntryFoundLength( entry, ReadInt32() );
1465 * \brief Find the Length till the next sequence delimiter
1468 uint32_t Document::FindDocEntryLengthOBOrOW()
1469 throw( FormatUnexpected )
1471 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1472 long positionOnEntry = Fp->tellg();
1473 bool foundSequenceDelimiter = false;
1474 uint32_t totalLength = 0;
1476 while ( !foundSequenceDelimiter )
1482 group = ReadInt16();
1485 catch ( FormatError )
1487 throw FormatError("Unexpected end of file encountered during ",
1488 "Document::FindDocEntryLengthOBOrOW()");
1490 // We have to decount the group and element we just read
1492 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1494 long filePosition = Fp->tellg();
1496 "Neither an Item tag nor a Sequence delimiter tag on :"
1497 << std::hex << group << " , " << elem
1498 << ") -before- position x(" << filePosition << ")" );
1500 Fp->seekg(positionOnEntry, std::ios::beg);
1501 throw FormatUnexpected(
1502 "Neither an Item tag nor a Sequence delimiter tag.");
1504 if ( elem == 0xe0dd )
1506 foundSequenceDelimiter = true;
1508 uint32_t itemLength = ReadInt32();
1509 // We add 4 bytes since we just read the ItemLength with ReadInt32
1510 totalLength += itemLength + 4;
1511 SkipBytes(itemLength);
1513 if ( foundSequenceDelimiter )
1518 Fp->seekg( positionOnEntry, std::ios::beg);
1523 * \brief Find the Value Representation of the current Dicom Element.
1524 * @return Value Representation of the current Entry
1526 VRKey Document::FindDocEntryVR()
1528 if ( Filetype != ExplicitVR )
1529 return GDCM_VRUNKNOWN;
1531 long positionOnEntry = Fp->tellg();
1532 // Warning: we believe this is explicit VR (Value Representation) because
1533 // we used a heuristic that found "UL" in the first tag and/or
1534 // 'Transfer Syntax' told us it is.
1535 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1536 // In some cases one finds implicit VR tags mixed within an explicit VR file.
1537 // Hence we make sure the present tag is in explicit VR and try to fix things
1538 // if it happens not to be the case.
1541 Fp->read(&(vr[0]),(size_t)2);
1543 if ( !CheckDocEntryVR(vr) )
1545 // Don't warn user with useless messages
1546 // Often, delimiters (0xfffe), are not explicit VR ...
1547 if ( CurrentGroup != 0xfffe )
1548 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1549 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1550 << ") at offset :" << positionOnEntry );
1551 Fp->seekg(positionOnEntry, std::ios::beg);
1552 return GDCM_VRUNKNOWN;
1558 * \brief Check the correspondance between the VR of the header entry
1559 * and the taken VR. If they are different, the header entry is
1560 * updated with the new VR.
1561 * @param vr Dicom Value Representation
1562 * @return false if the VR is incorrect or if the VR isn't referenced
1563 * otherwise, it returns true
1565 bool Document::CheckDocEntryVR(const VRKey &vr)
1567 return Global::GetVR()->IsValidVR(vr);
1571 * \brief Skip a given Header Entry
1572 * @param entry entry to skip
1574 void Document::SkipDocEntry(DocEntry *entry)
1576 SkipBytes(entry->GetLength());
1580 * \brief Skips to the beginning of the next Header Entry
1581 * @param currentDocEntry entry to skip
1583 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1585 int l = currentDocEntry->GetReadLength();
1586 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1587 // ... but PMS imagers happen !
1589 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1590 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1592 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1597 * \brief When the length of an element value is obviously wrong (because
1598 * the parser went Jabberwocky) one can hope improving things by
1599 * applying some heuristics.
1600 * @param entry entry to check
1601 * @param foundLength first assumption about length
1603 void Document::FixDocEntryFoundLength(DocEntry *entry,
1604 uint32_t foundLength)
1606 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1607 if ( foundLength == 0xffffffff)
1612 uint16_t gr = entry->GetGroup();
1613 uint16_t elem = entry->GetElement();
1615 if ( foundLength % 2)
1617 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1618 << " in x(" << std::hex << gr << "," << elem <<")");
1621 //////// Fix for some naughty General Electric images.
1622 // Allthough not recent many such GE corrupted images are still present
1623 // on Creatis hard disks. Hence this fix shall remain when such images
1624 // are no longer in use (we are talking a few years, here)...
1625 // Note: XMedCon probably uses such a trick since it is able to read
1626 // those pesky GE images ...
1627 if ( foundLength == 13)
1629 // Only happens for this length !
1630 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1633 entry->SetReadLength(10); // a bug is to be fixed !?
1637 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1638 // Occurence of such images is quite low (unless one leaves close to a
1639 // 'Leonardo' source. Hence, one might consider commenting out the
1640 // following fix on efficiency reasons.
1641 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1644 entry->SetReadLength(4); // a bug is to be fixed !
1647 else if ( entry->GetVR() == "SQ" )
1649 foundLength = 0; // ReadLength is unchanged
1652 //////// We encountered a 'delimiter' element i.e. a tag of the form
1653 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1654 // taken into account.
1655 else if ( gr == 0xfffe )
1657 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1658 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1659 // causes extra troubles...
1660 if ( entry->GetElement() != 0x0000 )
1666 foundLength=12; // to skip the mess that follows this bugged Tag !
1669 entry->SetLength(foundLength);
1673 * \brief Apply some heuristics to predict whether the considered
1674 * element value contains/represents an integer or not.
1675 * @param entry The element value on which to apply the predicate.
1676 * @return The result of the heuristical predicate.
1678 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1680 uint16_t elem = entry->GetElement();
1681 uint16_t group = entry->GetGroup();
1682 const VRKey &vr = entry->GetVR();
1683 uint32_t length = entry->GetLength();
1685 // When we have some semantics on the element we just read, and if we
1686 // a priori know we are dealing with an integer, then we shall be
1687 // able to swap it's element value properly.
1688 if ( elem == 0 ) // This is the group length of the group
1696 // Although this should never happen, still some images have a
1697 // corrupted group length [e.g. have a glance at offset x(8336) of
1698 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1699 // Since for dicom compliant and well behaved headers, the present
1700 // test is useless (and might even look a bit paranoid), when we
1701 // encounter such an ill-formed image, we simply display a warning
1702 // message and proceed on parsing (while crossing fingers).
1703 long filePosition = Fp->tellg();
1704 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1705 << std::hex << group << " , " << elem
1706 << ") -before- position x(" << filePosition << ")"
1707 << "lgt : " << length );
1711 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1719 * \brief Discover what the swap code is (among little endian, big endian,
1720 * bad little endian, bad big endian).
1722 * @return false when we are absolutely sure
1723 * it's neither ACR-NEMA nor DICOM
1724 * true when we hope ours assuptions are OK
1726 bool Document::CheckSwap()
1733 // First, compare HostByteOrder and NetworkByteOrder in order to
1734 // determine if we shall need to swap bytes (i.e. the Endian type).
1735 bool net2host = Util::IsCurrentProcessorBigEndian();
1737 // The easiest case is the one of a 'true' DICOM header, we just have
1738 // to look for the string "DICM" inside the file preamble.
1741 char *entCur = deb + 128;
1742 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1744 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1746 // Group 0002 should always be VR, and the first element 0000
1747 // Let's be carefull (so many wrong headers ...)
1748 // and determine the value representation (VR) :
1749 // Let's skip to the first element (0002,0000) and check there if we find
1750 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1751 // in which case we (almost) know it is explicit VR.
1752 // WARNING: if it happens to be implicit VR then what we will read
1753 // is the length of the group. If this ascii representation of this
1754 // length happens to be "UL" then we shall believe it is explicit VR.
1755 // We need to skip :
1756 // * the 128 bytes of File Preamble (often padded with zeroes),
1757 // * the 4 bytes of "DICM" string,
1758 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1759 // i.e. a total of 136 bytes.
1762 // group 0x0002 *is always* Explicit VR Sometimes ,
1763 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1764 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1766 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1767 memcmp(entCur, "OB", (size_t)2) == 0 ||
1768 memcmp(entCur, "UI", (size_t)2) == 0 ||
1769 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1770 // when Write DCM *adds*
1772 // Use Document::dicom_vr to test all the possibilities
1773 // instead of just checking for UL, OB and UI !? group 0000
1775 Filetype = ExplicitVR;
1776 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1780 Filetype = ImplicitVR;
1781 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1782 << "Looks like a bugged Header!");
1788 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1793 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1796 // Position the file position indicator at first tag
1797 // (i.e. after the file preamble and the "DICM" string).
1799 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1801 Fp->seekg ( 132L, std::ios::beg);
1803 } // ------------------------------- End of DicomV3 ----------------
1805 // Alas, this is not a DicomV3 file and whatever happens there is no file
1806 // preamble. We can reset the file position indicator to where the data
1807 // is (i.e. the beginning of the file).
1809 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1811 Fp->seekg(0, std::ios::beg);
1813 // Let's check 'No Preamble Dicom File' :
1814 // Should start with group 0x0002
1815 // and be Explicit Value Representation
1817 s16 = *((uint16_t *)(deb));
1830 if ( SwapCode != 0 )
1832 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1833 memcmp(entCur, "OB", (size_t)2) == 0 ||
1834 memcmp(entCur, "UI", (size_t)2) == 0 ||
1835 memcmp(entCur, "SH", (size_t)2) == 0 ||
1836 memcmp(entCur, "AE", (size_t)2) == 0 ||
1837 memcmp(entCur, "OB", (size_t)2) == 0 )
1839 Filetype = ExplicitVR;
1840 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1844 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1846 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1847 // By clean we mean that the length of the first group is written down.
1848 // If this is the case and since the length of the first group HAS to be
1849 // four (bytes), then determining the proper swap code is straightforward.
1852 // We assume the array of char we are considering contains the binary
1853 // representation of a 32 bits integer. Hence the following dirty
1855 s32 = *((uint32_t *)(entCur));
1875 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1876 // It is time for despaired wild guesses.
1877 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1878 // i.e. the 'group length' element is not present :
1880 // check the supposed-to-be 'group number'
1881 // in ( 0x0001 .. 0x0008 )
1882 // to determine ' SwapCode' value .
1883 // Only 0 or 4321 will be possible
1884 // (no oportunity to check for the formerly well known
1885 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1886 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1887 // the file IS NOT ACR-NEMA nor DICOM V3
1888 // Find a trick to tell it the caller...
1890 s16 = *((uint16_t *)(deb));
1917 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1925 * \brief Change the Byte Swap code.
1927 void Document::SwitchByteSwapCode()
1929 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1930 << " at: 0x" << std::hex << Fp->tellg() );
1931 if ( SwapCode == 1234 )
1935 else if ( SwapCode == 4321 )
1939 else if ( SwapCode == 3412 )
1943 else if ( SwapCode == 2143 )
1947 gdcmDebugMacro( " Into: "<< SwapCode );
1951 * \brief during parsing, Header Elements too long are not loaded in memory
1952 * @param newSize new size
1954 void Document::SetMaxSizeLoadEntry(long newSize)
1960 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1962 MaxSizeLoadEntry = 0xffffffff;
1965 MaxSizeLoadEntry = newSize;
1969 * \brief Read the next tag WITHOUT loading it's value
1970 * (read the 'Group Number', the 'Element Number',
1971 * gets the Dict Entry
1972 * gets the VR, gets the length, gets the offset value)
1973 * @return On succes : the newly created DocEntry, NULL on failure.
1975 DocEntry *Document::ReadNextDocEntry()
1979 CurrentGroup = ReadInt16();
1980 CurrentElem = ReadInt16();
1982 catch ( FormatError )
1984 // We reached the EOF (or an error occured) therefore
1985 // header parsing has to be considered as finished.
1989 // Sometimes file contains groups of tags with reversed endianess.
1990 HandleBrokenEndian(CurrentGroup, CurrentElem);
1992 // In 'true DICOM' files Group 0002 is always little endian
1993 if ( HasDCMPreamble )
1994 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
1996 VRKey vr = FindDocEntryVR();
2000 if ( vr == GDCM_VRUNKNOWN )
2002 if ( CurrentElem == 0x0000 ) // Group Length
2004 realVR = "UL"; // must be UL
2006 else if (CurrentGroup%2 == 1 &&
2007 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2009 // DICOM PS 3-5 7.8.1 a) states that those
2010 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2015 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2018 realVR = dictEntry->GetVR();
2019 dictEntry->Unregister();
2023 // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2026 if ( Global::GetVR()->IsVROfSequence(realVR) )
2027 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2030 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2031 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2034 if ( vr == GDCM_VRUNKNOWN )
2036 if ( Filetype == ExplicitVR )
2038 // We thought this was explicit VR, but we end up with an
2039 // implicit VR tag. Let's backtrack.
2040 if ( newEntry->GetGroup() != 0xfffe )
2043 int offset = Fp->tellg();
2045 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2046 newEntry->GetGroup(), newEntry->GetElement(), offset );
2047 gdcmWarningMacro( msg.c_str() );
2050 newEntry->SetImplicitVR();
2055 FindDocEntryLength(newEntry);
2057 catch ( FormatError )
2064 newEntry->SetOffset(Fp->tellg());
2070 * \brief Handle broken private tag from Philips NTSCAN
2071 * where the endianess is being switched to BigEndian
2072 * for no apparent reason
2075 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2077 // Endian reversion.
2078 // Some files contain groups of tags with reversed endianess.
2079 static int reversedEndian = 0;
2080 // try to fix endian switching in the middle of headers
2081 if ((group == 0xfeff) && (elem == 0x00e0))
2083 // start endian swap mark for group found
2084 gdcmDebugMacro( "Start endian swap mark found." );
2086 SwitchByteSwapCode();
2091 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2093 // end of reversed endian group
2094 gdcmDebugMacro( "End of reversed endian." );
2096 SwitchByteSwapCode();
2098 else if (group == 0xfeff && elem == 0xdde0)
2100 // reversed Sequence Terminator found
2101 // probabely a bug in the header !
2102 // Do what you want, it breaks !
2104 //SwitchByteSwapCode();
2105 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2110 else if (group == 0xfffe && elem == 0xe0dd)
2112 gdcmDebugMacro( "Straight Sequence Terminator." );
2117 * \brief Group 0002 is always coded Little Endian
2118 * whatever Transfer Syntax is
2121 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2123 // Endian reversion.
2124 // Some files contain groups of tags with reversed endianess.
2125 if ( !Group0002Parsed && group != 0x0002)
2127 Group0002Parsed = true;
2128 // we just came out of group 0002
2129 // if Transfer Syntax is Big Endian we have to change CheckSwap
2131 std::string ts = GetTransferSyntax();
2132 if ( ts == GDCM_UNKNOWN )
2134 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2137 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2139 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2144 // Group 0002 is always 'Explicit ...'
2145 // even when Transfer Syntax says 'Implicit ..."
2147 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2148 TS::ImplicitVRLittleEndian )
2150 Filetype = ImplicitVR;
2153 // FIXME Strangely, this works with
2154 //'Implicit VR BigEndian Transfer Syntax (GE Private)
2156 // --> Probabely normal, since we considered we never have
2157 // to trust manufacturers.
2158 // (we find very often 'Implicit VR' tag,
2159 // even when Transfer Syntax tells us it's Explicit ...
2160 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2161 TS::ExplicitVRBigEndian )
2163 gdcmDebugMacro("Transfer Syntax Name = ["
2164 << GetTransferSyntaxName() << "]" );
2165 SwitchByteSwapCode();
2166 group = SwapShort(group);
2167 elem = SwapShort(elem);
2172 //-----------------------------------------------------------------------------
2175 //-----------------------------------------------------------------------------
2176 } // end namespace gdcm