1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/11/15 10:30:46 $
7 Version: $Revision: 1.328 $
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::IsParsable()
342 if ( Filetype == Unknown )
344 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
350 gdcmWarningMacro( "No tag in internal hash table.");
357 * \brief This predicate tells us whether or not the current Document
358 * was properly parsed and contains at least *one* Dicom Element
359 * (and nothing more, sorry).
360 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
363 bool Document::IsReadable()
369 * \brief Predicate for dicom version 3 file.
370 * @return True when the file is a dicom version 3.
372 bool Document::IsDicomV3()
374 // Checking if Transfer Syntax exists is enough
375 // Anyway, it's too late check if the 'Preamble' was found ...
376 // And ... would it be a rich idea to check ?
377 // (some 'no Preamble' DICOM images exist !)
378 return GetDocEntry(0x0002, 0x0010) != NULL;
382 * \brief Predicate for Papyrus file
383 * Dedicated to whomsoever it may concern
384 * @return True when the file is a Papyrus file.
386 bool Document::IsPapyrus()
388 // check for Papyrus private Sequence
389 DocEntry *e = GetDocEntry(0x0041, 0x1050);
392 // check if it's actually a Sequence
393 if ( !dynamic_cast<SeqEntry*>(e) )
399 * \brief returns the File Type
400 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
401 * @return the FileType code
403 FileType Document::GetFileType()
409 * \brief Accessor to the Transfer Syntax (when present) of the
410 * current document (it internally handles reading the
411 * value from disk when only parsing occured).
412 * @return The encountered Transfer Syntax of the current document, if DICOM.
413 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
415 std::string Document::GetTransferSyntax()
417 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
423 // The entry might be present but not loaded (parsing and loading
424 // happen at different stages): try loading and proceed with check...
425 LoadDocEntrySafe(entry);
426 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
428 std::string transfer = dataEntry->GetString();
429 // The actual transfer (as read from disk) might be padded. We
430 // first need to remove the potential padding. We can make the
431 // weak assumption that padding was not executed with digits...
432 if ( transfer.length() == 0 )
434 // for brain damaged headers
435 gdcmWarningMacro( "Transfer Syntax has length = 0.");
438 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
440 transfer.erase(transfer.length()-1, 1);
441 if ( transfer.length() == 0 )
443 // for brain damaged headers
444 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
454 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
455 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
457 std::string Document::GetTransferSyntaxName()
459 // use the TS (TS : Transfer Syntax)
460 std::string transferSyntax = GetEntryString(0x0002,0x0010);
462 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
464 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
465 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
466 return "Uncompressed ACR-NEMA";
468 if ( transferSyntax == GDCM_UNFOUND )
470 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
471 return "Uncompressed ACR-NEMA";
474 // we do it only when we need it
475 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
477 // Global::GetTS() is a global static you shall never try to delete it!
481 // --------------- Swap Code ------------------
483 * \brief Swaps the bytes so they agree with the processor order
484 * @return The properly swaped 16 bits integer.
486 uint16_t Document::SwapShort(uint16_t a)
488 if ( SwapCode == 4321 || SwapCode == 2143 )
490 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
492 a = ( a << 8 ) | ( a >> 8 );
498 * \brief Swaps back the bytes of 4-byte long integer accordingly to
500 * @return The properly swaped 32 bits integer.
502 uint32_t Document::SwapLong(uint32_t a)
509 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
510 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
512 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
513 ((a>>8) & 0x0000ff00) | (a>>24) );
516 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
517 a=( (a<<16) | (a>>16) );
520 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
523 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
530 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
532 * @return The properly swaped 64 bits double.
534 double Document::SwapDouble(double a)
538 // There were no 'double' at ACR-NEMA time.
539 // We just have to deal with 'straight Little Endian' and
540 // 'straight Big Endian'
545 char *beg = (char *)&a;
548 for (unsigned int i = 0; i<7; i++)
559 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
566 // -----------------File I/O ---------------
568 * \brief Tries to open the file \ref Document::Filename and
569 * checks the preamble when existing.
570 * @return The FILE pointer on success.
572 std::ifstream *Document::OpenFile()
574 HasDCMPreamble = false;
575 if (Filename.length() == 0)
582 gdcmDebugMacro( "File already open: " << Filename.c_str());
586 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
589 // Don't user gdcmErrorMacro :
590 // a spurious message will appear when you use, for instance
591 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
592 // to create outputFileName.
594 // FIXME : if the upper comment is still usefull
595 // --> the constructor is not so good ...
597 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
601 //exit(1); // No function is allowed to leave the application instead
602 // of warning the caller
606 Fp->read((char*)&zero, (size_t)2);
613 //-- Broken ACR or DICOM with no Preamble; may start with a Shadow Group --
615 // FIXME : We cannot be sure the preable is only zeroes..
616 // (see ACUSON-24-YBR_FULL-RLE.dcm )
618 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
619 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
620 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
621 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
623 std::string msg = Util::Format(
624 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
625 // FIXME : is it a Warning message, or a Debug message?
626 gdcmWarningMacro( msg.c_str() );
631 Fp->seekg(126L, std::ios::cur);
632 char dicm[4]; // = {' ',' ',' ',' '};
633 Fp->read(dicm, (size_t)4);
639 if ( memcmp(dicm, "DICM", 4) == 0 )
641 HasDCMPreamble = true;
645 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
647 // Don't user Warning nor Error, not to polute the output
648 // while directory recursive parsing ...
649 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
650 << Filename.c_str());
655 * \brief closes the file
656 * @return TRUE if the close was successfull
658 bool Document::CloseFile()
670 * \brief Writes in a file all the Entries (Dicom Elements)
671 * @param fp file pointer on an already open file (actually: Output File Stream)
672 * @param filetype Type of the File to be written
673 * (ACR-NEMA, ExplicitVR, ImplicitVR)
675 void Document::WriteContent(std::ofstream *fp, FileType filetype)
677 // Skip if user wants to write an ACR-NEMA file
679 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
682 // writing Dicom File Preamble
683 char filePreamble[128];
684 memset(filePreamble, 0, 128);
685 fp->write(filePreamble, 128);
686 fp->write("DICM", 4);
690 * \todo rewrite later, if really usefull
691 * - 'Group Length' element is optional in DICOM
692 * - but un-updated odd groups lengthes can causes pb
695 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
696 * UpdateGroupLength(false,filetype);
697 * if ( filetype == ACR)
698 * UpdateGroupLength(true,ACR);
700 * --> Computing group length for groups with embeded Sequences
701 * --> was too much tricky / we were [in a hurry / too lazy]
702 * --> We don't write the element 0x0000 (group length)
705 ElementSet::WriteContent(fp, filetype); // This one is recursive
708 // -----------------------------------------
711 * \brief Loads (from disk) the element content
712 * when a string is not suitable
713 * @param group group number of the Entry
714 * @param elem element number of the Entry
716 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
718 // Search the corresponding DocEntry
719 DocEntry *docEntry = GetDocEntry(group, elem);
722 gdcmDebugMacro(std::hex << group << "|" << elem
723 << " doesn't exist" );
726 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
729 gdcmWarningMacro(std::hex << group << "|" << elem
730 << " is NOT a DataEntry");
733 LoadEntryBinArea(dataEntry);
737 * \brief Loads (from disk) the element content
738 * when a string is not suitable
739 * @param entry Entry whose binArea is going to be loaded
741 void Document::LoadEntryBinArea(DataEntry *entry)
743 if( entry->GetBinArea() )
750 size_t o =(size_t)entry->GetOffset();
751 Fp->seekg(o, std::ios::beg);
753 size_t l = entry->GetLength();
754 uint8_t *data = new uint8_t[l];
757 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
758 << std::hex << entry->GetGroup()
759 << "|" << entry->GetElement() );
764 Fp->read((char*)data, l);
765 if ( Fp->fail() || Fp->eof() )
768 entry->SetState(DataEntry::STATE_UNREAD);
772 // Swap the data content if necessary
774 unsigned short vrLgth =
775 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
777 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
778 // if( entry->GetVR() == "OW" )
789 uint16_t *data16 = (uint16_t *)data;
790 for(i=0;i<l/vrLgth;i++)
791 data16[i] = SwapShort(data16[i]);
796 uint32_t *data32 = (uint32_t *)data;
797 for(i=0;i<l/vrLgth;i++)
798 data32[i] = SwapLong(data32[i]);
803 double *data64 = (double *)data;
804 for(i=0;i<l/vrLgth;i++)
805 data64[i] = SwapDouble(data64[i]);
810 entry->SetBinArea(data);
817 * \brief Loads the element while preserving the current
818 * underlying file position indicator as opposed to
819 * LoadDocEntry that modifies it.
820 * @param entry DocEntry whose value will be loaded.
822 void Document::LoadDocEntrySafe(DocEntry *entry)
826 long PositionOnEntry = Fp->tellg();
828 Fp->seekg(PositionOnEntry, std::ios::beg);
833 * \brief Compares two documents, according to \ref DicomDir rules
834 * \warning Does NOT work with ACR-NEMA files
835 * \todo Find a trick to solve the pb (use RET fields ?)
836 * @param document to compare with current one
837 * @return true if 'smaller'
839 bool Document::operator<(Document &document)
842 std::string s1 = GetEntryString(0x0010,0x0010);
843 std::string s2 = document.GetEntryString(0x0010,0x0010);
855 s1 = GetEntryString(0x0010,0x0020);
856 s2 = document.GetEntryString(0x0010,0x0020);
867 // Study Instance UID
868 s1 = GetEntryString(0x0020,0x000d);
869 s2 = document.GetEntryString(0x0020,0x000d);
880 // Serie Instance UID
881 s1 = GetEntryString(0x0020,0x000e);
882 s2 = document.GetEntryString(0x0020,0x000e);
897 //-----------------------------------------------------------------------------
900 * \brief Reads a supposed to be 16 Bits integer
901 * (swaps it depending on processor endianness)
904 uint16_t Document::ReadInt16()
908 Fp->read ((char*)&g, (size_t)2);
911 throw FormatError( "Document::ReadInt16()", " file error." );
915 throw FormatError( "Document::ReadInt16()", "EOF." );
922 * \brief Reads a supposed to be 32 Bits integer
923 * (swaps it depending on processor endianness)
926 uint32_t Document::ReadInt32()
930 Fp->read ((char*)&g, (size_t)4);
933 throw FormatError( "Document::ReadInt32()", " file error." );
937 throw FormatError( "Document::ReadInt32()", "EOF." );
944 * \brief skips bytes inside the source file
947 void Document::SkipBytes(uint32_t nBytes)
949 //FIXME don't dump the returned value
950 Fp->seekg((long)nBytes, std::ios::cur);
954 * \brief Re-computes the length of the Dicom group 0002.
956 int Document::ComputeGroup0002Length( )
962 bool found0002 = false;
964 // for each zero-level Tag in the DCM Header
965 DocEntry *entry = GetFirstEntry();
968 gr = entry->GetGroup();
974 if ( entry->GetElement() != 0x0000 )
978 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
979 // (no SQ, OW, UT in group 0x0002;)
982 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
986 groupLength += 2 + 2 + 4 + entry->GetLength();
992 entry = GetNextEntry();
997 //-----------------------------------------------------------------------------
1000 * \brief Loads all the needed Dictionaries
1002 void Document::Initialize()
1004 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1010 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1011 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1012 * @param offset start of parsing
1013 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1014 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1016 void Document::ParseDES(DocEntrySet *set, long offset,
1017 long l_max, bool delim_mode)
1019 DocEntry *newDocEntry;
1020 DataEntry *newDataEntry;
1021 SeqEntry *newSeqEntry;
1023 bool used; // will be set to false when something wrong happens to an Entry.
1024 // (Entry will then be deleted)
1025 bool delim_mode_intern = delim_mode;
1027 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1028 << " at offset " << std::hex << offset );
1031 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1036 newDocEntry = ReadNextDocEntry( );
1038 // Uncoment this cerr line to be able to 'follow' the DocEntries
1039 // when something *very* strange happens
1040 if( Debug::GetDebugFlag() )
1041 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1048 // an Item Starter found elsewhere but the first position
1049 // of a SeqEntry means previous entry was a Sequence
1050 // but we didn't get it (private Sequence + Implicit VR)
1051 // we have to backtrack.
1052 if ( !first && newDocEntry->IsItemStarter() )
1054 // Debug message within the method !
1055 newDocEntry = Backtrack(newDocEntry);
1059 PreviousDocEntry = newDocEntry;
1063 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1067 //////////////////////////// DataEntry
1069 vr = newDocEntry->GetVR();
1071 if ( !set->AddEntry( newDataEntry ) )
1073 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1074 << newDataEntry->GetKey()
1076 << newDataEntry->GetOffset() << " )" );
1081 newDataEntry->Delete();
1082 // Load only if we can add (not a duplicate key)
1083 LoadDocEntry( newDataEntry );
1086 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1088 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1090 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1092 std::string strLgrGroup = newDataEntry->GetString();
1094 if ( newDataEntry->IsUnfound() )
1096 lgrGroup = atoi(strLgrGroup.c_str());
1097 Fp->seekg(lgrGroup, std::ios::cur);
1098 //used = false; // never used
1099 RemoveEntry( newDocEntry ); // Remove and delete
1100 // bcc 5.5 is right "assigned a value that's never used"
1108 bool delimitor = newDataEntry->IsItemDelimitor();
1111 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1114 newDocEntry->Delete();
1118 // Just to make sure we are at the beginning of next entry.
1119 SkipToNextDocEntry(newDocEntry);
1123 /////////////////////// SeqEntry : VR = "SQ"
1125 unsigned long l = newDocEntry->GetReadLength();
1126 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1128 if ( l == 0xffffffff )
1130 delim_mode_intern = true;
1134 delim_mode_intern = false;
1138 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1140 // User asked to skip SeQuences *only* if they belong to Shadow Group
1141 if ( newDocEntry->GetGroup()%2 != 0 )
1143 Fp->seekg( l, std::ios::cur);
1144 newDocEntry->Delete(); // Delete, not in the set
1148 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1150 // User asked to skip *any* SeQuence
1151 Fp->seekg( l, std::ios::cur);
1152 newDocEntry->Delete(); // Delete, not in the set
1155 // delay the dynamic cast as late as possible
1156 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1158 // no other way to create the Delimitor ...
1159 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1161 // At the top of the hierarchy, stands a Document. When "set"
1162 // is a Document, then we are building the first depth level.
1163 // Hence the SeqEntry we are building simply has a depth
1165 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1167 newSeqEntry->SetDepthLevel( 1 );
1169 // But when "set" is already a SQItem, we are building a nested
1170 // sequence, and hence the depth level of the new SeqEntry
1171 // we are building, is one level deeper:
1173 // time waste hunting
1174 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1176 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1180 { // Don't try to parse zero-length sequences
1182 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1183 << " at offset " << std::hex
1184 << newDocEntry->GetOffset() );
1186 ParseSQ( newSeqEntry,
1187 newDocEntry->GetOffset(),
1188 l, delim_mode_intern);
1190 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1193 if ( !set->AddEntry( newSeqEntry ) )
1195 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1196 << newSeqEntry->GetKey()
1198 << newSeqEntry->GetOffset() << " )" );
1203 newDocEntry->Delete();
1206 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1209 newDocEntry->Delete();
1212 } // end SeqEntry : VR = "SQ"
1216 newDocEntry->Delete();
1220 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1224 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1225 * @return parsed length for this level
1227 void Document::ParseSQ( SeqEntry *seqEntry,
1228 long offset, long l_max, bool delim_mode)
1230 int SQItemNumber = 0;
1232 long offsetStartCurrentSQItem = offset;
1236 // the first time, we read the fff0,e000 of the first SQItem
1237 DocEntry *newDocEntry = ReadNextDocEntry();
1241 gdcmWarningMacro("in ParseSQ : should never get here!");
1246 if ( newDocEntry->IsSequenceDelimitor() )
1248 seqEntry->SetDelimitationItem( newDocEntry );
1249 newDocEntry->Delete();
1253 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1255 newDocEntry->Delete();
1258 // create the current SQItem
1259 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1260 unsigned int l = newDocEntry->GetReadLength();
1262 if ( l == 0xffffffff )
1271 // remove fff0,e000, created out of the SQItem
1272 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1273 // fill up the current SQItem, starting at the beginning of fff0,e000
1275 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1277 offsetStartCurrentSQItem = Fp->tellg();
1279 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1281 newDocEntry->Delete();
1283 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1291 * \brief When a private Sequence + Implicit VR is encountered
1292 * we cannot guess it's a Sequence till we find the first
1293 * Item Starter. We then backtrack to do the job.
1294 * @param docEntry Item Starter that warned us
1296 DocEntry *Document::Backtrack(DocEntry *docEntry)
1298 // delete the Item Starter, built erroneously out of any Sequence
1299 // it's not yet in the HTable/chained list
1302 // Get all info we can from PreviousDocEntry
1303 uint16_t group = PreviousDocEntry->GetGroup();
1304 uint16_t elem = PreviousDocEntry->GetElement();
1305 uint32_t lgt = PreviousDocEntry->GetLength();
1306 long offset = PreviousDocEntry->GetOffset();
1308 gdcmDebugMacro( "Backtrack :" << std::hex << group
1310 << " at offset " << offset );
1311 RemoveEntry( PreviousDocEntry );
1313 // forge the Seq Entry
1314 DocEntry *newEntry = NewSeqEntry(group, elem);
1315 newEntry->SetLength(lgt);
1316 newEntry->SetOffset(offset);
1318 // Move back to the beginning of the Sequence
1319 Fp->seekg( 0, std::ios::beg);
1320 Fp->seekg(offset, std::ios::cur);
1326 * \brief Loads (or not) the element content depending if its length exceeds
1327 * or not the value specified with Document::SetMaxSizeLoadEntry()
1328 * @param entry Header Entry (Dicom Element) to be dealt with
1329 * @param forceLoad whether you want to force loading of 'long' elements
1331 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1333 uint16_t group = entry->GetGroup();
1334 uint16_t elem = entry->GetElement();
1335 const VRKey &vr = entry->GetVR();
1336 uint32_t length = entry->GetLength();
1338 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1340 // A SeQuence "contains" a set of Elements.
1341 // (fffe e000) tells us an Element is beginning
1342 // (fffe e00d) tells us an Element just ended
1343 // (fffe e0dd) tells us the current SeQuence just ended
1345 // (fffe 0000) is an 'impossible' tag value,
1346 // found in MR-PHILIPS-16-Multi-Seq.dcm
1348 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1350 // NO more value field for SQ !
1354 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1360 // When the length is zero things are easy:
1363 dataEntryPtr->SetBinArea(NULL,true);
1367 // The elements whose length is bigger than the specified upper bound
1370 std::ostringstream s;
1374 if (length > MaxSizeLoadEntry)
1376 dataEntryPtr->SetBinArea(NULL,true);
1377 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1379 // to be sure we are at the end of the value ...
1380 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1386 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1390 * \brief Find the value Length of the passed Doc Entry
1391 * @param entry Header Entry whose length of the value shall be loaded.
1393 void Document::FindDocEntryLength( DocEntry *entry )
1394 throw ( FormatError )
1396 const VRKey &vr = entry->GetVR();
1399 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1401 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1404 // The following reserved two bytes (see PS 3.5-2003, section
1405 // "7.1.2 Data element structure with explicit vr", p 27) must be
1406 // skipped before proceeding on reading the length on 4 bytes.
1407 Fp->seekg( 2L, std::ios::cur);
1408 uint32_t length32 = ReadInt32();
1410 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1415 lengthOB = FindDocEntryLengthOBOrOW();
1417 catch ( FormatUnexpected )
1419 // Computing the length failed (this happens with broken
1420 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1421 // chance to get the pixels by deciding the element goes
1422 // until the end of the file. Hence we artificially fix the
1423 // the length and proceed.
1424 gdcmWarningMacro( " Computing the length failed for " <<
1425 entry->GetKey() <<" in " <<GetFileName());
1427 long currentPosition = Fp->tellg();
1428 Fp->seekg(0L,std::ios::end);
1430 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1431 Fp->seekg(currentPosition, std::ios::beg);
1433 entry->SetReadLength(lengthUntilEOF);
1434 entry->SetLength(lengthUntilEOF);
1437 entry->SetReadLength(lengthOB);
1438 entry->SetLength(lengthOB);
1441 FixDocEntryFoundLength(entry, length32);
1445 // Length is encoded on 2 bytes.
1446 length16 = ReadInt16();
1448 // 0xffff means that we deal with 'No Length' Sequence
1449 // or 'No Length' SQItem
1450 if ( length16 == 0xffff)
1454 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1459 // Either implicit VR or a non DICOM conformal (see note below) explicit
1460 // VR that ommited the VR of (at least) this element. Farts happen.
1461 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1462 // on Data elements "Implicit and Explicit VR Data Elements shall
1463 // not coexist in a Data Set and Data Sets nested within it".]
1464 // Length is on 4 bytes.
1466 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1467 // even if Transfer Syntax is 'Implicit VR ...'
1468 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1470 FixDocEntryFoundLength( entry, ReadInt32() );
1476 * \brief Find the Length till the next sequence delimiter
1479 uint32_t Document::FindDocEntryLengthOBOrOW()
1480 throw( FormatUnexpected )
1482 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1483 long positionOnEntry = Fp->tellg();
1484 bool foundSequenceDelimiter = false;
1485 uint32_t totalLength = 0;
1487 while ( !foundSequenceDelimiter )
1493 group = ReadInt16();
1496 catch ( FormatError )
1498 throw FormatError("Unexpected end of file encountered during ",
1499 "Document::FindDocEntryLengthOBOrOW()");
1501 // We have to decount the group and element we just read
1503 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1505 long filePosition = Fp->tellg();
1507 "Neither an Item tag nor a Sequence delimiter tag on :"
1508 << std::hex << group << " , " << elem
1509 << ") -before- position x(" << filePosition << ")" );
1511 Fp->seekg(positionOnEntry, std::ios::beg);
1512 throw FormatUnexpected(
1513 "Neither an Item tag nor a Sequence delimiter tag.");
1515 if ( elem == 0xe0dd )
1517 foundSequenceDelimiter = true;
1519 uint32_t itemLength = ReadInt32();
1520 // We add 4 bytes since we just read the ItemLength with ReadInt32
1521 totalLength += itemLength + 4;
1522 SkipBytes(itemLength);
1524 if ( foundSequenceDelimiter )
1529 Fp->seekg( positionOnEntry, std::ios::beg);
1534 * \brief Find the Value Representation of the current Dicom Element.
1535 * @return Value Representation of the current Entry
1537 VRKey Document::FindDocEntryVR()
1539 if ( Filetype != ExplicitVR )
1540 return GDCM_VRUNKNOWN;
1542 long positionOnEntry = Fp->tellg();
1543 // Warning: we believe this is explicit VR (Value Representation) because
1544 // we used a heuristic that found "UL" in the first tag and/or
1545 // 'Transfer Syntax' told us it is.
1546 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1547 // In some cases one finds implicit VR tags mixed within an explicit VR file.
1548 // Hence we make sure the present tag is in explicit VR and try to fix things
1549 // if it happens not to be the case.
1552 Fp->read(&(vr[0]),(size_t)2);
1554 if ( !CheckDocEntryVR(vr) )
1556 // Don't warn user with useless messages
1557 // Often, delimiters (0xfffe), are not explicit VR ...
1558 if ( CurrentGroup != 0xfffe )
1559 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1560 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1561 << ") at offset :" << positionOnEntry );
1562 Fp->seekg(positionOnEntry, std::ios::beg);
1563 return GDCM_VRUNKNOWN;
1569 * \brief Check the correspondance between the VR of the header entry
1570 * and the taken VR. If they are different, the header entry is
1571 * updated with the new VR.
1572 * @param vr Dicom Value Representation
1573 * @return false if the VR is incorrect or if the VR isn't referenced
1574 * otherwise, it returns true
1576 bool Document::CheckDocEntryVR(const VRKey &vr)
1578 return Global::GetVR()->IsValidVR(vr);
1582 * \brief Skip a given Header Entry
1583 * @param entry entry to skip
1585 void Document::SkipDocEntry(DocEntry *entry)
1587 SkipBytes(entry->GetLength());
1591 * \brief Skips to the beginning of the next Header Entry
1592 * @param currentDocEntry entry to skip
1594 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1596 int l = currentDocEntry->GetReadLength();
1597 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1598 // ... but PMS imagers happen !
1600 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1601 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1603 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1608 * \brief When the length of an element value is obviously wrong (because
1609 * the parser went Jabberwocky) one can hope improving things by
1610 * applying some heuristics.
1611 * @param entry entry to check
1612 * @param foundLength first assumption about length
1614 void Document::FixDocEntryFoundLength(DocEntry *entry,
1615 uint32_t foundLength)
1617 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1618 if ( foundLength == 0xffffffff)
1623 uint16_t gr = entry->GetGroup();
1624 uint16_t elem = entry->GetElement();
1626 if ( foundLength % 2)
1628 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1629 << " in x(" << std::hex << gr << "," << elem <<")");
1632 //////// Fix for some naughty General Electric images.
1633 // Allthough not recent many such GE corrupted images are still present
1634 // on Creatis hard disks. Hence this fix shall remain when such images
1635 // are no longer in use (we are talking a few years, here)...
1636 // Note: XMedCon probably uses such a trick since it is able to read
1637 // those pesky GE images ...
1638 if ( foundLength == 13)
1640 // Only happens for this length !
1641 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1644 entry->SetReadLength(10); // a bug is to be fixed !?
1648 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1649 // Occurence of such images is quite low (unless one leaves close to a
1650 // 'Leonardo' source. Hence, one might consider commenting out the
1651 // following fix on efficiency reasons.
1652 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1655 entry->SetReadLength(4); // a bug is to be fixed !
1658 else if ( entry->GetVR() == "SQ" )
1660 foundLength = 0; // ReadLength is unchanged
1663 //////// We encountered a 'delimiter' element i.e. a tag of the form
1664 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1665 // taken into account.
1666 else if ( gr == 0xfffe )
1668 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1669 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1670 // causes extra troubles...
1671 if ( entry->GetElement() != 0x0000 )
1677 foundLength=12; // to skip the mess that follows this bugged Tag !
1680 entry->SetLength(foundLength);
1684 * \brief Apply some heuristics to predict whether the considered
1685 * element value contains/represents an integer or not.
1686 * @param entry The element value on which to apply the predicate.
1687 * @return The result of the heuristical predicate.
1689 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1691 uint16_t elem = entry->GetElement();
1692 uint16_t group = entry->GetGroup();
1693 const VRKey &vr = entry->GetVR();
1694 uint32_t length = entry->GetLength();
1696 // When we have some semantics on the element we just read, and if we
1697 // a priori know we are dealing with an integer, then we shall be
1698 // able to swap it's element value properly.
1699 if ( elem == 0 ) // This is the group length of the group
1707 // Although this should never happen, still some images have a
1708 // corrupted group length [e.g. have a glance at offset x(8336) of
1709 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1710 // Since for dicom compliant and well behaved headers, the present
1711 // test is useless (and might even look a bit paranoid), when we
1712 // encounter such an ill-formed image, we simply display a warning
1713 // message and proceed on parsing (while crossing fingers).
1714 long filePosition = Fp->tellg();
1715 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1716 << std::hex << group << " , " << elem
1717 << ") -before- position x(" << filePosition << ")"
1718 << "lgt : " << length );
1722 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1730 * \brief Discover what the swap code is (among little endian, big endian,
1731 * bad little endian, bad big endian).
1733 * @return false when we are absolutely sure
1734 * it's neither ACR-NEMA nor DICOM
1735 * true when we hope ours assuptions are OK
1737 bool Document::CheckSwap()
1744 // First, compare HostByteOrder and NetworkByteOrder in order to
1745 // determine if we shall need to swap bytes (i.e. the Endian type).
1746 bool net2host = Util::IsCurrentProcessorBigEndian();
1748 // The easiest case is the one of a 'true' DICOM header, we just have
1749 // to look for the string "DICM" inside the file preamble.
1752 char *entCur = deb + 128;
1753 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1755 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1757 // Group 0002 should always be VR, and the first element 0000
1758 // Let's be carefull (so many wrong headers ...)
1759 // and determine the value representation (VR) :
1760 // Let's skip to the first element (0002,0000) and check there if we find
1761 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1762 // in which case we (almost) know it is explicit VR.
1763 // WARNING: if it happens to be implicit VR then what we will read
1764 // is the length of the group. If this ascii representation of this
1765 // length happens to be "UL" then we shall believe it is explicit VR.
1766 // We need to skip :
1767 // * the 128 bytes of File Preamble (often padded with zeroes),
1768 // * the 4 bytes of "DICM" string,
1769 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1770 // i.e. a total of 136 bytes.
1773 // group 0x0002 *is always* Explicit VR Sometimes ,
1774 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1775 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1777 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1778 memcmp(entCur, "OB", (size_t)2) == 0 ||
1779 memcmp(entCur, "UI", (size_t)2) == 0 ||
1780 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1781 // when Write DCM *adds*
1783 // Use Document::dicom_vr to test all the possibilities
1784 // instead of just checking for UL, OB and UI !? group 0000
1786 Filetype = ExplicitVR;
1787 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1791 Filetype = ImplicitVR;
1792 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1793 << "Looks like a bugged Header!");
1799 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1804 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1807 // Position the file position indicator at first tag
1808 // (i.e. after the file preamble and the "DICM" string).
1810 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1812 Fp->seekg ( 132L, std::ios::beg);
1814 } // ------------------------------- End of DicomV3 ----------------
1816 // Alas, this is not a DicomV3 file and whatever happens there is no file
1817 // preamble. We can reset the file position indicator to where the data
1818 // is (i.e. the beginning of the file).
1820 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1822 Fp->seekg(0, std::ios::beg);
1824 // Let's check 'No Preamble Dicom File' :
1825 // Should start with group 0x0002
1826 // and be Explicit Value Representation
1828 s16 = *((uint16_t *)(deb));
1841 if ( SwapCode != 0 )
1843 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1844 memcmp(entCur, "OB", (size_t)2) == 0 ||
1845 memcmp(entCur, "UI", (size_t)2) == 0 ||
1846 memcmp(entCur, "SH", (size_t)2) == 0 ||
1847 memcmp(entCur, "AE", (size_t)2) == 0 ||
1848 memcmp(entCur, "OB", (size_t)2) == 0 )
1850 Filetype = ExplicitVR;
1851 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1855 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1857 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1858 // By clean we mean that the length of the first group is written down.
1859 // If this is the case and since the length of the first group HAS to be
1860 // four (bytes), then determining the proper swap code is straightforward.
1863 // We assume the array of char we are considering contains the binary
1864 // representation of a 32 bits integer. Hence the following dirty
1866 s32 = *((uint32_t *)(entCur));
1886 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1887 // It is time for despaired wild guesses.
1888 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1889 // i.e. the 'group length' element is not present :
1891 // check the supposed-to-be 'group number'
1892 // in ( 0x0001 .. 0x0008 )
1893 // to determine ' SwapCode' value .
1894 // Only 0 or 4321 will be possible
1895 // (no oportunity to check for the formerly well known
1896 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1897 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1898 // the file IS NOT ACR-NEMA nor DICOM V3
1899 // Find a trick to tell it the caller...
1901 s16 = *((uint16_t *)(deb));
1928 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1936 * \brief Change the Byte Swap code.
1938 void Document::SwitchByteSwapCode()
1940 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1941 << " at: 0x" << std::hex << Fp->tellg() );
1942 if ( SwapCode == 1234 )
1946 else if ( SwapCode == 4321 )
1950 else if ( SwapCode == 3412 )
1954 else if ( SwapCode == 2143 )
1958 gdcmDebugMacro( " Into: "<< SwapCode );
1962 * \brief during parsing, Header Elements too long are not loaded in memory
1963 * @param newSize new size
1965 void Document::SetMaxSizeLoadEntry(long newSize)
1971 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1973 MaxSizeLoadEntry = 0xffffffff;
1976 MaxSizeLoadEntry = newSize;
1980 * \brief Read the next tag WITHOUT loading it's value
1981 * (read the 'Group Number', the 'Element Number',
1982 * gets the Dict Entry
1983 * gets the VR, gets the length, gets the offset value)
1984 * @return On succes : the newly created DocEntry, NULL on failure.
1986 DocEntry *Document::ReadNextDocEntry()
1990 CurrentGroup = ReadInt16();
1991 CurrentElem = ReadInt16();
1993 catch ( FormatError )
1995 // We reached the EOF (or an error occured) therefore
1996 // header parsing has to be considered as finished.
2000 // Sometimes file contains groups of tags with reversed endianess.
2001 HandleBrokenEndian(CurrentGroup, CurrentElem);
2003 // In 'true DICOM' files Group 0002 is always little endian
2004 if ( HasDCMPreamble )
2005 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2007 VRKey vr = FindDocEntryVR();
2011 if ( vr == GDCM_VRUNKNOWN )
2013 if ( CurrentElem == 0x0000 ) // Group Length
2015 realVR = "UL"; // must be UL
2017 else if (CurrentGroup%2 == 1 &&
2018 (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2020 // DICOM PS 3-5 7.8.1 a) states that those
2021 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2026 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2029 realVR = dictEntry->GetVR();
2030 dictEntry->Unregister();
2034 // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2037 if ( Global::GetVR()->IsVROfSequence(realVR) )
2038 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2041 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2042 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2045 if ( vr == GDCM_VRUNKNOWN )
2047 if ( Filetype == ExplicitVR )
2049 // We thought this was explicit VR, but we end up with an
2050 // implicit VR tag. Let's backtrack.
2051 if ( newEntry->GetGroup() != 0xfffe )
2054 int offset = Fp->tellg();
2056 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2057 newEntry->GetGroup(), newEntry->GetElement(), offset );
2058 gdcmWarningMacro( msg.c_str() );
2061 newEntry->SetImplicitVR();
2066 FindDocEntryLength(newEntry);
2068 catch ( FormatError )
2075 newEntry->SetOffset(Fp->tellg());
2081 * \brief Handle broken private tag from Philips NTSCAN
2082 * where the endianess is being switched to BigEndian
2083 * for no apparent reason
2086 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2088 // Endian reversion.
2089 // Some files contain groups of tags with reversed endianess.
2090 static int reversedEndian = 0;
2091 // try to fix endian switching in the middle of headers
2092 if ((group == 0xfeff) && (elem == 0x00e0))
2094 // start endian swap mark for group found
2095 gdcmDebugMacro( "Start endian swap mark found." );
2097 SwitchByteSwapCode();
2102 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2104 // end of reversed endian group
2105 gdcmDebugMacro( "End of reversed endian." );
2107 SwitchByteSwapCode();
2109 else if (group == 0xfeff && elem == 0xdde0)
2111 // reversed Sequence Terminator found
2112 // probabely a bug in the header !
2113 // Do what you want, it breaks !
2115 //SwitchByteSwapCode();
2116 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2121 else if (group == 0xfffe && elem == 0xe0dd)
2123 gdcmDebugMacro( "Straight Sequence Terminator." );
2128 * \brief Group 0002 is always coded Little Endian
2129 * whatever Transfer Syntax is
2132 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2134 // Endian reversion.
2135 // Some files contain groups of tags with reversed endianess.
2136 if ( !Group0002Parsed && group != 0x0002)
2138 Group0002Parsed = true;
2139 // we just came out of group 0002
2140 // if Transfer Syntax is Big Endian we have to change CheckSwap
2142 std::string ts = GetTransferSyntax();
2143 if ( ts == GDCM_UNKNOWN )
2145 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2148 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2150 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2155 // Group 0002 is always 'Explicit ...'
2156 // even when Transfer Syntax says 'Implicit ..."
2158 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2159 TS::ImplicitVRLittleEndian )
2161 Filetype = ImplicitVR;
2164 // FIXME Strangely, this works with
2165 //'Implicit VR BigEndian Transfer Syntax (GE Private)
2167 // --> Probabely normal, since we considered we never have
2168 // to trust manufacturers.
2169 // (we find very often 'Implicit VR' tag,
2170 // even when Transfer Syntax tells us it's Explicit ...
2171 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2172 TS::ExplicitVRBigEndian )
2174 gdcmDebugMacro("Transfer Syntax Name = ["
2175 << GetTransferSyntaxName() << "]" );
2176 SwitchByteSwapCode();
2177 group = SwapShort(group);
2178 elem = SwapShort(elem);
2183 //-----------------------------------------------------------------------------
2186 //-----------------------------------------------------------------------------
2187 } // end namespace gdcm