1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/09/07 08:55:22 $
7 Version: $Revision: 1.275 $
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 "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
34 #include <ctype.h> // for isdigit
35 #include <stdlib.h> // for atoi
39 //-----------------------------------------------------------------------------
41 // Refer to Document::SetMaxSizeLoadEntry()
42 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
46 // Constructors and destructors are protected to avoid user to invoke directly
49 * \brief This default constructor neither loads nor parses the file.
50 * You should then invoke \ref Document::Load.
58 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
61 Filetype = ExplicitVR;
62 // Load will set it to true if sucessfull
63 Group0002Parsed = false;
64 IsDocumentAlreadyLoaded = false;
65 IsDocumentModified = true;
66 LoadMode = LD_ALL; // default : load everything, later
71 * \brief Constructor (DEPRECATED : not to break the API)
72 * @param fileName 'Document' (File or DicomDir) to be open for parsing
74 Document::Document( std::string const &fileName )
79 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
82 Filetype = ExplicitVR;
83 Group0002Parsed = false;
84 LoadMode = LD_ALL; // Load everything, later
86 // Load will set it to true if sucessfull
87 IsDocumentAlreadyLoaded = false;
88 IsDocumentModified = true;
90 SetFileName(fileName);
94 * \brief Canonical destructor.
96 Document::~Document ()
101 //-----------------------------------------------------------------------------
105 * \brief Loader. use SetLoadMode(), SetFileName() before !
106 * @return false if file cannot be open or no swap info was found,
107 * or no tag was found.
109 bool Document::Load( )
111 if ( GetFileName() == "" )
113 gdcmWarningMacro( "Use SetFileName, before !" );
116 return DoTheLoadingDocumentJob( );
119 * \brief Loader. (DEPRECATED : not to break the API)
120 * @param fileName 'Document' (File or DicomDir) to be open for parsing
121 * @return false if file cannot be open or no swap info was found,
122 * or no tag was found.
124 bool Document::Load( std::string const &fileName )
127 return DoTheLoadingDocumentJob( );
131 * \brief Performs the Loading Job (internal use only)
132 * @return false if file cannot be open or no swap info was found,
133 * or no tag was found.
135 bool Document::DoTheLoadingDocumentJob( )
137 if ( ! IsDocumentModified ) // Nothing to do !
140 // if ( Filename == fileName )
142 // gdcmWarningMacro( "The file was already parsed inside this "
143 // << "gdcm::Document (its name is: "
144 // << Filename.c_str() );
148 //gdcmWarningMacro( "A file was already parsed inside this "
149 // << "gdcm::Document (previous name was: "
150 // << Filename.c_str() << ". New name is :"
152 // clean out the Entries, if already parsed
153 // (probabely a mistake from the user)
160 // warning already performed in OpenFile()
161 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
162 // << Filename.c_str() );
167 Group0002Parsed = false;
169 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
171 Fp->seekg(0, std::ios::end);
172 long lgt = Fp->tellg(); // total length of the file
174 Fp->seekg(0, std::ios::beg);
176 // CheckSwap returns a boolean
177 // (false if no swap info of any kind was found)
180 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
181 << Filename.c_str());
186 long beg = Fp->tellg(); // just after DICOM preamble (if any)
188 lgt -= beg; // remaining length to parse
191 // Loading is done during parsing
192 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
196 gdcmWarningMacro( "No tag in internal hash table for: "
197 << Filename.c_str());
201 IsDocumentAlreadyLoaded = true;
203 Fp->seekg( 0, std::ios::beg);
205 // Load 'non string' values
207 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
208 if ( PhotometricInterpretation == "PALETTE COLOR " )
211 // Probabely this line should be outside the 'if'
212 // Try to find an image sample holding a 'gray LUT'
213 LoadEntryBinArea(0x0028,0x1200); // gray LUT
216 /// The tags refered by the three following lines used to be CORRECTLY
217 /// defined as having an US Value Representation in the public
218 /// dictionary. BUT the semantics implied by the three following
219 /// lines state that the corresponding tag contents are in fact
220 /// the ones of a BinEntry.
221 /// In order to fix things "Quick and Dirty" the dictionary was
222 /// altered on PURPOSE but now contains a WRONG value.
223 /// In order to fix things and restore the dictionary to its
224 /// correct value, one needs to decided of the semantics by deciding
225 /// whether the following tags are either :
226 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
227 /// also used as BinEntry, which requires the proper conversion,
228 /// - OW, and hence loaded as BinEntry, but afterwards also used
229 /// as ValEntry, which requires the proper conversion.
230 LoadEntryBinArea(0x0028,0x1201); // R LUT
231 LoadEntryBinArea(0x0028,0x1202); // G LUT
232 LoadEntryBinArea(0x0028,0x1203); // B LUT
234 // Segmented Red Palette Color LUT Data
235 LoadEntryBinArea(0x0028,0x1221);
236 // Segmented Green Palette Color LUT Data
237 LoadEntryBinArea(0x0028,0x1222);
238 // Segmented Blue Palette Color LUT Data
239 LoadEntryBinArea(0x0028,0x1223);
242 //FIXME later : how to use it?
243 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
246 SQItem *sqi= modLutSeq->GetFirstSQItem();
249 BinEntry *b = sqi->GetBinEntry(0x0028,0x3006);
252 if ( b->GetLength() != 0 )
254 LoadEntryBinArea(b); //LUT Data (CTX dependent)
260 // Force Loading some more elements if user asked to.
263 for (ListElements::iterator it = UserForceLoadList.begin();
264 it != UserForceLoadList.end();
267 d = GetDocEntry( (*it).Group, (*it).Elem);
272 if ( dynamic_cast<BinEntry *>(d) )
274 LoadDocEntry(d, true);
278 if ( dynamic_cast<BinEntry *>(d) )
280 LoadEntryBinArea((*it).Group, (*it).Elem);
284 if ( dynamic_cast<SeqEntry *>(d) )
286 gdcmWarningMacro( "You cannot 'ForceLoad' a SeqEntry ");
293 // ----------------------------
294 // Specific code to allow gdcm to read ACR-LibIDO formated images
295 // Note: ACR-LibIDO is an extension of the ACR standard that was
296 // used at CREATIS. For the time being (say a couple of years)
297 // we keep this kludge to allow CREATIS users
298 // reading their old images.
300 // if recognition code tells us we deal with a LibIDO image
301 // we switch lineNumber and columnNumber
304 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
305 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
306 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
307 // with "little-endian strings"
309 Filetype = ACR_LIBIDO;
310 std::string rows = GetEntryValue(0x0028, 0x0010);
311 std::string columns = GetEntryValue(0x0028, 0x0011);
312 SetValEntry(columns, 0x0028, 0x0010);
313 SetValEntry(rows , 0x0028, 0x0011);
315 // --- End of ACR-LibIDO kludge ---
321 * \brief Adds a new element we want to load anyway
322 * @param group Group number of the target tag.
323 * @param elem Element number of the target tag.
325 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
330 UserForceLoadList.push_back(el);
333 * \brief Get the public dictionary used
335 Dict *Document::GetPubDict()
341 * \brief Get the shadow dictionary used
343 Dict *Document::GetShaDict()
349 * \brief Set the shadow dictionary used
350 * @param dict dictionary to use in shadow
352 bool Document::SetShaDict(Dict *dict)
359 * \brief Set the shadow dictionary used
360 * @param dictName name of the dictionary to use in shadow
362 bool Document::SetShaDict(DictKey const &dictName)
364 RefShaDict = Global::GetDicts()->GetDict(dictName);
369 * \brief This predicate tells us whether or not the current Document
370 * was properly parsed and contains at least *one* Dicom Element
371 * (and nothing more, sorry).
372 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
375 bool Document::IsReadable()
377 if ( Filetype == Unknown )
379 gdcmWarningMacro( "Wrong filetype");
385 gdcmWarningMacro( "No tag in internal hash table.");
393 * \brief Predicate for dicom version 3 file.
394 * @return True when the file is a dicom version 3.
396 bool Document::IsDicomV3()
398 // Checking if Transfer Syntax exists is enough
399 // Anyway, it's too late check if the 'Preamble' was found ...
400 // And ... would it be a rich idea to check ?
401 // (some 'no Preamble' DICOM images exist !)
402 return GetDocEntry(0x0002, 0x0010) != NULL;
406 * \brief Predicate for Papyrus file
407 * Dedicated to whomsoever it may concern
408 * @return True when the file is a Papyrus file.
410 bool Document::IsPapyrus()
412 // check for Papyrus private Sequence
413 DocEntry *e = GetDocEntry(0x0041, 0x1050);
416 // check if it's actually a Sequence
417 if ( !dynamic_cast<SeqEntry*>(e) )
423 * \brief returns the File Type
424 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
425 * @return the FileType code
427 FileType Document::GetFileType()
433 * \brief Accessor to the Transfer Syntax (when present) of the
434 * current document (it internally handles reading the
435 * value from disk when only parsing occured).
436 * @return The encountered Transfer Syntax of the current document.
438 std::string Document::GetTransferSyntax()
440 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
446 // The entry might be present but not loaded (parsing and loading
447 // happen at different stages): try loading and proceed with check...
448 LoadDocEntrySafe(entry);
449 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
451 std::string transfer = valEntry->GetValue();
452 // The actual transfer (as read from disk) might be padded. We
453 // first need to remove the potential padding. We can make the
454 // weak assumption that padding was not executed with digits...
455 if ( transfer.length() == 0 )
457 // for brain damaged headers
460 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
462 transfer.erase(transfer.length()-1, 1);
470 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
471 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
473 std::string Document::GetTransferSyntaxName()
475 // use the TS (TS : Transfer Syntax)
476 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
478 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
480 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
481 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
482 return "Uncompressed ACR-NEMA";
484 if ( transferSyntax == GDCM_UNFOUND )
486 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
487 return "Uncompressed ACR-NEMA";
490 // we do it only when we need it
491 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
493 // Global::GetTS() is a global static you shall never try to delete it!
497 // --------------- Swap Code ------------------
499 * \brief Swaps the bytes so they agree with the processor order
500 * @return The properly swaped 16 bits integer.
502 uint16_t Document::SwapShort(uint16_t a)
504 if ( SwapCode == 4321 || SwapCode == 2143 )
506 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
508 a = ( a << 8 ) | ( a >> 8 );
514 * \brief Swaps back the bytes of 4-byte long integer accordingly to
516 * @return The properly swaped 32 bits integer.
518 uint32_t Document::SwapLong(uint32_t a)
525 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
526 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
528 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
529 ((a>>8) & 0x0000ff00) | (a>>24) );
532 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
533 a=( (a<<16) | (a>>16) );
536 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
539 gdcmErrorMacro( "Unset swap code:" << SwapCode );
546 // -----------------File I/O ---------------
548 * \brief Tries to open the file \ref Document::Filename and
549 * checks the preamble when existing.
550 * @return The FILE pointer on success.
552 std::ifstream *Document::OpenFile()
554 HasDCMPreamble = false;
555 if (Filename.length() == 0)
562 gdcmWarningMacro( "File already open: " << Filename.c_str());
566 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
569 // Don't user gdcmErrorMacro :
570 // a spurious message will appear when you use, for instance
571 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
572 // to create outputFileName.
573 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
577 //exit(1); // No function is allowed to leave the application instead
578 // of warning the caller
582 Fp->read((char*)&zero, (size_t)2);
589 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
591 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
592 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
593 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
594 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
596 std::string msg = Util::Format(
597 "ACR/DICOM starting at the beginning of the file:(%04x)\n", zero);
598 gdcmWarningMacro( msg.c_str() );
603 Fp->seekg(126L, std::ios::cur);
604 char dicm[4]; // = {' ',' ',' ',' '};
605 Fp->read(dicm, (size_t)4);
611 if ( memcmp(dicm, "DICM", 4) == 0 )
613 HasDCMPreamble = true;
617 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
619 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
620 << Filename.c_str());
625 * \brief closes the file
626 * @return TRUE if the close was successfull
628 bool Document::CloseFile()
640 * \brief Writes in a file all the Header Entries (Dicom Elements)
641 * @param fp file pointer on an already open file (actually: Output File Stream)
642 * @param filetype Type of the File to be written
643 * (ACR-NEMA, ExplicitVR, ImplicitVR)
644 * @return Always true.
646 void Document::WriteContent(std::ofstream *fp, FileType filetype)
648 // Skip if user wants to write an ACR-NEMA file
650 if ( filetype == ImplicitVR || filetype == ExplicitVR )
652 // writing Dicom File Preamble
653 char filePreamble[128];
654 memset(filePreamble, 0, 128);
655 fp->write(filePreamble, 128);
656 fp->write("DICM", 4);
660 * \todo rewrite later, if really usefull
661 * - 'Group Length' element is optional in DICOM
662 * - but un-updated odd groups lengthes can causes pb
665 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
666 * UpdateGroupLength(false,filetype);
667 * if ( filetype == ACR)
668 * UpdateGroupLength(true,ACR);
671 ElementSet::WriteContent(fp, filetype); // This one is recursive
674 // -----------------------------------------
677 * \brief Loads (from disk) the element content
678 * when a string is not suitable
679 * @param group group number of the Entry
680 * @param elem element number of the Entry
682 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
684 // Search the corresponding DocEntry
685 DocEntry *docElement = GetDocEntry(group, elem);
689 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
693 LoadEntryBinArea(binElement);
697 * \brief Loads (from disk) the element content
698 * when a string is not suitable
699 * @param elem Entry whose binArea is going to be loaded
701 void Document::LoadEntryBinArea(BinEntry *elem)
703 if (elem->GetBinArea() )
710 size_t o =(size_t)elem->GetOffset();
711 Fp->seekg(o, std::ios::beg);
713 size_t l = elem->GetLength();
714 uint8_t *a = new uint8_t[l];
717 gdcmWarningMacro( "Cannot allocate BinEntry content for : "
718 << std::hex << elem->GetGroup()
719 << "|" << elem->GetElement() );
723 Fp->read((char*)a, l);
724 if ( Fp->fail() || Fp->eof() )
737 * \brief Loads the element while preserving the current
738 * underlying file position indicator as opposed to
739 * LoadDocEntry that modifies it.
740 * @param entry DocEntry whose value will be loaded.
742 void Document::LoadDocEntrySafe(DocEntry *entry)
746 long PositionOnEntry = Fp->tellg();
748 Fp->seekg(PositionOnEntry, std::ios::beg);
753 * \brief Compares two documents, according to \ref DicomDir rules
754 * \warning Does NOT work with ACR-NEMA files
755 * \todo Find a trick to solve the pb (use RET fields ?)
756 * @param document to compare with current one
757 * @return true if 'smaller'
759 bool Document::operator<(Document &document)
762 std::string s1 = GetEntryValue(0x0010,0x0010);
763 std::string s2 = document.GetEntryValue(0x0010,0x0010);
775 s1 = GetEntryValue(0x0010,0x0020);
776 s2 = document.GetEntryValue(0x0010,0x0020);
787 // Study Instance UID
788 s1 = GetEntryValue(0x0020,0x000d);
789 s2 = document.GetEntryValue(0x0020,0x000d);
800 // Serie Instance UID
801 s1 = GetEntryValue(0x0020,0x000e);
802 s2 = document.GetEntryValue(0x0020,0x000e);
817 //-----------------------------------------------------------------------------
820 * \brief Reads a supposed to be 16 Bits integer
821 * (swaps it depending on processor endianness)
824 uint16_t Document::ReadInt16()
828 Fp->read ((char*)&g, (size_t)2);
831 throw FormatError( "Document::ReadInt16()", " file error." );
835 throw FormatError( "Document::ReadInt16()", "EOF." );
842 * \brief Reads a supposed to be 32 Bits integer
843 * (swaps it depending on processor endianness)
846 uint32_t Document::ReadInt32()
850 Fp->read ((char*)&g, (size_t)4);
853 throw FormatError( "Document::ReadInt32()", " file error." );
857 throw FormatError( "Document::ReadInt32()", "EOF." );
864 * \brief skips bytes inside the source file
865 * \warning NOT end user intended method !
868 void Document::SkipBytes(uint32_t nBytes)
870 //FIXME don't dump the returned value
871 Fp->seekg((long)nBytes, std::ios::cur);
875 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
877 int Document::ComputeGroup0002Length( /*FileType filetype*/ )
883 bool found0002 = false;
885 // for each zero-level Tag in the DCM Header
886 DocEntry *entry = GetFirstEntry();
889 gr = entry->GetGroup();
895 if ( entry->GetElement() != 0x0000 )
899 // FIXME : group 0x0002 is *always* Explicit VR!
901 //if ( filetype == ExplicitVR )
903 // if ( (vr == "OB") || (vr == "OW") || (vr == "UT") || (vr == "SQ") )
904 // (no SQ, OW, UT in group 0x0002;)
907 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
911 groupLength += 2 + 2 + 4 + entry->GetLength();
917 entry = GetNextEntry();
922 //-----------------------------------------------------------------------------
925 * \brief Loads all the needed Dictionaries
926 * \warning NOT end user intended method !
928 void Document::Initialize()
930 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
936 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
937 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
938 * @param offset start of parsing
939 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
940 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
942 void Document::ParseDES(DocEntrySet *set, long offset,
943 long l_max, bool delim_mode)
945 DocEntry *newDocEntry;
946 ValEntry *newValEntry;
947 BinEntry *newBinEntry;
948 SeqEntry *newSeqEntry;
951 bool delim_mode_intern = delim_mode;
955 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
960 newDocEntry = ReadNextDocEntry( );
962 // Uncoment this printf line to be able to 'follow' the DocEntries
963 // when something *very* strange happens
965 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
966 // newDocEntry->GetElement(),
967 // newDocEntry->GetVR().c_str() );
974 // an Item Starter found elsewhere but the first postition
975 // of a SeqEntry means previous entry was a Sequence
976 // but we didn't get it (private Sequence + Implicit VR)
977 // we have to backtrack.
978 if ( !first && newDocEntry->IsItemStarter() )
980 newDocEntry = Backtrack(newDocEntry);
984 PreviousDocEntry = newDocEntry;
988 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
989 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
991 if ( newValEntry || newBinEntry )
993 //////////////////////////// ContentEntry
996 vr = newDocEntry->GetVR();
997 if ( Filetype == ExplicitVR &&
998 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1000 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1001 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
1002 << "|" << newDocEntry->GetElement()
1003 << " : Neither Valentry, nor BinEntry."
1004 "Probably unknown VR.");
1007 //////////////////// BinEntry or UNKOWN VR:
1009 // When "this" is a Document the Key is simply of the
1010 // form ( group, elem )...
1011 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1013 // newBinEntry->SetKey( newBinEntry->GetKey() );
1015 // but when "this" is a SQItem, we are inserting this new
1016 // valEntry in a sequence item, and the key has the
1017 // generalized form (refer to \ref BaseTagKey):
1019 // time waste hunting
1020 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1022 // newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1023 // + newBinEntry->GetKey() );
1026 if ( !set->AddEntry( newBinEntry ) )
1028 gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
1029 << newBinEntry->GetKey()
1031 << newBinEntry->GetOffset() << " )" );
1036 // Load only if we can add (not a duplicate key)
1037 LoadDocEntry( newBinEntry );
1042 /////////////////////// ValEntry
1044 // When "set" is a Document, then we are at the top of the
1045 // hierarchy and the Key is simply of the form ( group, elem )...
1046 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1048 // newValEntry->SetKey( newValEntry->GetKey() );
1050 // ...but when "set" is a SQItem, we are inserting this new
1051 // valEntry in a sequence item. Hence the key has the
1052 // generalized form (refer to \ref BaseTagKey):
1054 // time waste hunting
1055 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1057 // newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1058 // + newValEntry->GetKey() );
1061 if ( !set->AddEntry( newValEntry ) )
1063 gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
1064 << newValEntry->GetKey()
1066 << newValEntry->GetOffset() << " )" );
1071 // Load only if we can add (not a duplicate key)
1072 LoadDocEntry( newValEntry );
1075 if ( newValEntry->GetElement() == 0x0000 ) // if on group length
1077 if ( newValEntry->GetGroup()%2 != 0 ) // if Shadow Group
1079 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1081 std::string strLgrGroup = newValEntry->GetValue();
1083 if ( strLgrGroup != GDCM_UNFOUND)
1085 lgrGroup = atoi(strLgrGroup.c_str());
1086 Fp->seekg(lgrGroup, std::ios::cur);
1088 RemoveEntry( newDocEntry );
1096 bool delimitor=newValEntry->IsItemDelimitor();
1099 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
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);
1137 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1139 // User asked to skip *any* SeQuence
1140 Fp->seekg( l, std::ios::cur);
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 // SQItem *parentSQItem = dynamic_cast< SQItem* > ( set );
1155 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1157 newSeqEntry->SetDepthLevel( 1 );
1158 // newSeqEntry->SetKey( newSeqEntry->GetKey() );
1160 // But when "set" is already a SQItem, we are building a nested
1161 // sequence, and hence the depth level of the new SeqEntry
1162 // we are building, is one level deeper:
1164 // time waste hunting
1165 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1167 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1169 // newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1170 // + newSeqEntry->GetKey() );
1174 { // Don't try to parse zero-length sequences
1175 ParseSQ( newSeqEntry,
1176 newDocEntry->GetOffset(),
1177 l, delim_mode_intern);
1179 if ( !set->AddEntry( newSeqEntry ) )
1181 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1182 << newSeqEntry->GetKey()
1184 << newSeqEntry->GetOffset() << " )" );
1188 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1194 } // end SeqEntry : VR = "SQ"
1205 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1206 * @return parsed length for this level
1208 void Document::ParseSQ( SeqEntry *seqEntry,
1209 long offset, long l_max, bool delim_mode)
1211 int SQItemNumber = 0;
1213 long offsetStartCurrentSQItem = offset;
1217 // the first time, we read the fff0,e000 of the first SQItem
1218 DocEntry *newDocEntry = ReadNextDocEntry();
1222 // FIXME Should warn user
1223 gdcmWarningMacro("in ParseSQ : should never get here!");
1228 if ( newDocEntry->IsSequenceDelimitor() )
1230 seqEntry->SetDelimitationItem( newDocEntry );
1234 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1239 // create the current SQItem
1240 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1242 std::ostringstream newBase;
1243 newBase << seqEntry->GetKey()
1247 itemSQ->SetBaseTagKey( newBase.str() );
1249 unsigned int l = newDocEntry->GetReadLength();
1251 if ( l == 0xffffffff )
1260 // Let's try :------------
1261 // remove fff0,e000, created out of the SQItem
1263 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1264 // fill up the current SQItem, starting at the beginning of fff0,e000
1266 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1268 offsetStartCurrentSQItem = Fp->tellg();
1269 // end try -----------------
1271 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1273 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1281 * \brief When a private Sequence + Implicit VR is encountered
1282 * we cannot guess it's a Sequence till we find the first
1283 * Item Starter. We then backtrack to do the job.
1284 * @param docEntry Item Starter that warned us
1286 DocEntry *Document::Backtrack(DocEntry *docEntry)
1288 // delete the Item Starter, built erroneously out of any Sequence
1289 // it's not yet in the HTable/chained list
1292 // Get all info we can from PreviousDocEntry
1293 uint16_t group = PreviousDocEntry->GetGroup();
1294 uint16_t elem = PreviousDocEntry->GetElement();
1295 uint32_t lgt = PreviousDocEntry->GetLength();
1296 long offset = PreviousDocEntry->GetOffset();
1298 gdcmWarningMacro( "Backtrack :" << std::hex << group
1300 << " at offset " << offset );
1301 RemoveEntry( PreviousDocEntry );
1303 // forge the Seq Entry
1304 DocEntry *newEntry = NewSeqEntry(group, elem);
1305 newEntry->SetLength(lgt);
1306 newEntry->SetOffset(offset);
1308 // Move back to the beginning of the Sequence
1309 Fp->seekg( 0, std::ios::beg);
1310 Fp->seekg(offset, std::ios::cur);
1316 * \brief Loads (or not) the element content depending if its length exceeds
1317 * or not the value specified with Document::SetMaxSizeLoadEntry()
1318 * @param entry Header Entry (Dicom Element) to be dealt with
1319 * @param forceLoad wheter we want to load its content even if its length
1320 * exceeds the value specified with Document::SetMaxSizeLoadEntry()
1322 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1324 uint16_t group = entry->GetGroup();
1325 std::string vr = entry->GetVR();
1326 uint32_t length = entry->GetLength();
1328 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1330 // A SeQuence "contains" a set of Elements.
1331 // (fffe e000) tells us an Element is beginning
1332 // (fffe e00d) tells us an Element just ended
1333 // (fffe e0dd) tells us the current SeQuence just ended
1334 if ( group == 0xfffe )
1336 // NO more value field for SQ !
1340 // When the length is zero things are easy:
1343 ((ValEntry *)entry)->SetValue("");
1347 // The elements whose length is bigger than the specified upper bound
1348 // are not loaded. Instead we leave a short notice on the offset of
1349 // the element content and it's length.
1351 std::ostringstream s;
1355 if (length > MaxSizeLoadEntry)
1357 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1359 s << GDCM_NOTLOADED;
1360 s << " Ad.:" << (long)entry->GetOffset();
1361 s << " x(" << std::hex << entry->GetOffset() << ")";
1363 s << " Lgt:" << entry->GetLength();
1364 s << " x(" << std::hex << entry->GetLength() << ")";
1365 binEntryPtr->SetValue(s.str());
1367 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1369 s << GDCM_NOTLOADED;
1370 s << " Address:" << (long)entry->GetOffset();
1371 s << " Length:" << entry->GetLength();
1372 s << " x(" << std::hex << entry->GetLength() << ")";
1373 valEntryPtr->SetValue(s.str());
1378 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1379 << "nor a ValEntry ?! Should never print that !" );
1382 // to be sure we are at the end of the value ...
1383 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1389 // When we find a BinEntry not very much can be done :
1390 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1392 s << GDCM_BINLOADED;
1393 binEntryPtr->SetValue(s.str());
1394 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1398 if ( IsDocEntryAnInteger(entry) )
1402 // When short integer(s) are expected, read and convert the following
1403 // (n * 2) characters properly i.e. consider them as short integers as
1404 // opposed to strings.
1405 // Elements with Value Multiplicity > 1
1406 // contain a set of integers (not a single one)
1407 if (vr == "US" || vr == "SS")
1410 NewInt = ReadInt16();
1414 for (int i=1; i < nbInt; i++)
1417 NewInt = ReadInt16();
1422 // See above comment on multiple integers (mutatis mutandis).
1423 else if (vr == "UL" || vr == "SL")
1426 NewInt = ReadInt32();
1430 for (int i=1; i < nbInt; i++)
1433 NewInt = ReadInt32();
1438 #ifdef GDCM_NO_ANSI_STRING_STREAM
1439 s << std::ends; // to avoid oddities on Solaris
1440 #endif //GDCM_NO_ANSI_STRING_STREAM
1442 ((ValEntry *)entry)->SetValue(s.str());
1446 // FIXME: We need an additional byte for storing \0 that is not on disk
1447 char *str = new char[length+1];
1448 Fp->read(str, (size_t)length);
1449 str[length] = '\0'; //this is only useful when length is odd
1450 // Special DicomString call to properly handle \0 and even length
1451 std::string newValue;
1454 newValue = Util::DicomString(str, length+1);
1455 gdcmWarningMacro("Warning: bad length: " << length <<
1456 " For string :" << newValue.c_str());
1457 // Since we change the length of string update it length
1458 //entry->SetReadLength(length+1);
1462 newValue = Util::DicomString(str, length);
1466 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1468 if ( Fp->fail() || Fp->eof())
1471 gdcmWarningMacro("--> fail");
1473 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1474 << " lgt : " << valEntry->GetReadLength()
1475 << " at " << std::hex << valEntry->GetOffset());
1476 valEntry->SetValue(GDCM_UNREAD);
1482 // Because of correspondance with the VR dic
1483 valEntry->SetValue(newValue);
1487 valEntry->SetValue(newValue);
1492 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1493 << " lgt : " << valEntry->GetReadLength()
1494 << " at " << std::hex << valEntry->GetOffset());
1499 * \brief Find the value Length of the passed Doc Entry
1500 * @param entry Header Entry whose length of the value shall be loaded.
1502 void Document::FindDocEntryLength( DocEntry *entry )
1503 throw ( FormatError )
1505 std::string vr = entry->GetVR();
1508 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1510 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1513 // The following reserved two bytes (see PS 3.5-2003, section
1514 // "7.1.2 Data element structure with explicit vr", p 27) must be
1515 // skipped before proceeding on reading the length on 4 bytes.
1516 Fp->seekg( 2L, std::ios::cur);
1517 uint32_t length32 = ReadInt32();
1519 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1524 lengthOB = FindDocEntryLengthOBOrOW();
1526 catch ( FormatUnexpected )
1528 // Computing the length failed (this happens with broken
1529 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1530 // chance to get the pixels by deciding the element goes
1531 // until the end of the file. Hence we artificially fix the
1532 // the length and proceed.
1533 gdcmWarningMacro( " Computing the length failed for " <<
1534 entry->GetKey() <<" in " <<GetFileName());
1536 long currentPosition = Fp->tellg();
1537 Fp->seekg(0L,std::ios::end);
1539 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1540 Fp->seekg(currentPosition, std::ios::beg);
1542 entry->SetReadLength(lengthUntilEOF);
1543 entry->SetLength(lengthUntilEOF);
1546 entry->SetReadLength(lengthOB);
1547 entry->SetLength(lengthOB);
1550 FixDocEntryFoundLength(entry, length32);
1554 // Length is encoded on 2 bytes.
1555 length16 = ReadInt16();
1557 // 0xffff means that we deal with 'No Length' Sequence
1558 // or 'No Length' SQItem
1559 if ( length16 == 0xffff)
1563 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1568 // Either implicit VR or a non DICOM conformal (see note below) explicit
1569 // VR that ommited the VR of (at least) this element. Farts happen.
1570 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1571 // on Data elements "Implicit and Explicit VR Data Elements shall
1572 // not coexist in a Data Set and Data Sets nested within it".]
1573 // Length is on 4 bytes.
1575 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1576 // even if Transfer Syntax is 'Implicit VR ...'
1578 FixDocEntryFoundLength( entry, ReadInt32() );
1584 * \brief Find the Length till the next sequence delimiter
1585 * \warning NOT end user intended method !
1588 uint32_t Document::FindDocEntryLengthOBOrOW()
1589 throw( FormatUnexpected )
1591 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1592 long positionOnEntry = Fp->tellg();
1593 bool foundSequenceDelimiter = false;
1594 uint32_t totalLength = 0;
1596 while ( !foundSequenceDelimiter )
1602 group = ReadInt16();
1605 catch ( FormatError )
1607 throw FormatError("Unexpected end of file encountered during ",
1608 "Document::FindDocEntryLengthOBOrOW()");
1610 // We have to decount the group and element we just read
1612 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1614 long filePosition = Fp->tellg();
1616 "Neither an Item tag nor a Sequence delimiter tag on :"
1617 << std::hex << group << " , " << elem
1618 << ") -before- position x(" << filePosition << ")" );
1620 Fp->seekg(positionOnEntry, std::ios::beg);
1621 throw FormatUnexpected(
1622 "Neither an Item tag nor a Sequence delimiter tag.");
1624 if ( elem == 0xe0dd )
1626 foundSequenceDelimiter = true;
1628 uint32_t itemLength = ReadInt32();
1629 // We add 4 bytes since we just read the ItemLength with ReadInt32
1630 totalLength += itemLength + 4;
1631 SkipBytes(itemLength);
1633 if ( foundSequenceDelimiter )
1638 Fp->seekg( positionOnEntry, std::ios::beg);
1643 * \brief Find the Value Representation of the current Dicom Element.
1644 * @return Value Representation of the current Entry
1646 std::string Document::FindDocEntryVR()
1648 if ( Filetype != ExplicitVR )
1649 return GDCM_UNKNOWN;
1651 long positionOnEntry = Fp->tellg();
1652 // Warning: we believe this is explicit VR (Value Representation) because
1653 // we used a heuristic that found "UL" in the first tag. Alas this
1654 // doesn't guarantee that all the tags will be in explicit VR. In some
1655 // cases (see e-film filtered files) one finds implicit VR tags mixed
1656 // within an explicit VR file. Hence we make sure the present tag
1657 // is in explicit VR and try to fix things if it happens not to be
1661 Fp->read (vr, (size_t)2);
1664 if ( !CheckDocEntryVR(vr) )
1666 Fp->seekg(positionOnEntry, std::ios::beg);
1667 return GDCM_UNKNOWN;
1673 * \brief Check the correspondance between the VR of the header entry
1674 * and the taken VR. If they are different, the header entry is
1675 * updated with the new VR.
1676 * @param vr Dicom Value Representation
1677 * @return false if the VR is incorrect of if the VR isn't referenced
1678 * otherwise, it returns true
1680 bool Document::CheckDocEntryVR(VRKey vr)
1682 if ( !Global::GetVR()->IsValidVR(vr) )
1689 * \brief Get the transformed value of the header entry. The VR value
1690 * is used to define the transformation to operate on the value
1691 * \warning NOT end user intended method !
1692 * @param entry entry to tranform
1693 * @return Transformed entry value
1695 std::string Document::GetDocEntryValue(DocEntry *entry)
1697 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1699 std::string val = ((ValEntry *)entry)->GetValue();
1700 std::string vr = entry->GetVR();
1701 uint32_t length = entry->GetLength();
1702 std::ostringstream s;
1705 // When short integer(s) are expected, read and convert the following
1706 // n * 2 bytes properly i.e. as a multivaluated strings
1707 // (each single value is separated fromthe next one by '\'
1708 // as usual for standard multivaluated filels
1709 // Elements with Value Multiplicity > 1
1710 // contain a set of short integers (not a single one)
1712 if ( vr == "US" || vr == "SS" )
1717 for (int i=0; i < nbInt; i++)
1723 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1724 newInt16 = SwapShort( newInt16 );
1729 // When integer(s) are expected, read and convert the following
1730 // n * 4 bytes properly i.e. as a multivaluated strings
1731 // (each single value is separated fromthe next one by '\'
1732 // as usual for standard multivaluated filels
1733 // Elements with Value Multiplicity > 1
1734 // contain a set of integers (not a single one)
1735 else if ( vr == "UL" || vr == "SL" )
1740 for (int i=0; i < nbInt; i++)
1746 newInt32 = ( val[4*i+0] & 0xFF )
1747 + (( val[4*i+1] & 0xFF ) << 8 )
1748 + (( val[4*i+2] & 0xFF ) << 16 )
1749 + (( val[4*i+3] & 0xFF ) << 24 );
1750 newInt32 = SwapLong( newInt32 );
1754 #ifdef GDCM_NO_ANSI_STRING_STREAM
1755 s << std::ends; // to avoid oddities on Solaris
1756 #endif //GDCM_NO_ANSI_STRING_STREAM
1759 return ((ValEntry *)entry)->GetValue();
1763 * \brief Get the reverse transformed value of the header entry. The VR
1764 * value is used to define the reverse transformation to operate on
1766 * \warning NOT end user intended method !
1767 * @param entry Entry to reverse transform
1768 * @return Reverse transformed entry value
1770 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1772 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1774 std::string vr = entry->GetVR();
1775 std::vector<std::string> tokens;
1776 std::ostringstream s;
1778 if ( vr == "US" || vr == "SS" )
1782 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1783 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1784 for (unsigned int i=0; i<tokens.size(); i++)
1786 newInt16 = atoi(tokens[i].c_str());
1787 s << ( newInt16 & 0xFF )
1788 << (( newInt16 >> 8 ) & 0xFF );
1792 if ( vr == "UL" || vr == "SL")
1796 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1797 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1798 for (unsigned int i=0; i<tokens.size();i++)
1800 newInt32 = atoi(tokens[i].c_str());
1801 s << (char)( newInt32 & 0xFF )
1802 << (char)(( newInt32 >> 8 ) & 0xFF )
1803 << (char)(( newInt32 >> 16 ) & 0xFF )
1804 << (char)(( newInt32 >> 24 ) & 0xFF );
1809 #ifdef GDCM_NO_ANSI_STRING_STREAM
1810 s << std::ends; // to avoid oddities on Solaris
1811 #endif //GDCM_NO_ANSI_STRING_STREAM
1815 return ((ValEntry *)entry)->GetValue();
1819 * \brief Skip a given Header Entry
1820 * \warning NOT end user intended method !
1821 * @param entry entry to skip
1823 void Document::SkipDocEntry(DocEntry *entry)
1825 SkipBytes(entry->GetLength());
1829 * \brief Skips to the beginning of the next Header Entry
1830 * \warning NOT end user intended method !
1831 * @param currentDocEntry entry to skip
1833 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1835 int l = currentDocEntry->GetReadLength();
1836 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1837 // ... but PMS imagers happen !
1839 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1840 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1842 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1847 * \brief When the length of an element value is obviously wrong (because
1848 * the parser went Jabberwocky) one can hope improving things by
1849 * applying some heuristics.
1850 * @param entry entry to check
1851 * @param foundLength first assumption about length
1853 void Document::FixDocEntryFoundLength(DocEntry *entry,
1854 uint32_t foundLength)
1856 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1857 if ( foundLength == 0xffffffff)
1862 uint16_t gr = entry->GetGroup();
1863 uint16_t elem = entry->GetElement();
1865 if ( foundLength % 2)
1867 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1868 << " in x(" << std::hex << gr << "," << elem <<")");
1871 //////// Fix for some naughty General Electric images.
1872 // Allthough not recent many such GE corrupted images are still present
1873 // on Creatis hard disks. Hence this fix shall remain when such images
1874 // are no longer in use (we are talking a few years, here)...
1875 // Note: XMedCon probably uses such a trick since it is able to read
1876 // those pesky GE images ...
1877 if ( foundLength == 13)
1879 // Only happens for this length !
1880 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1883 entry->SetReadLength(10); // a bug is to be fixed !?
1887 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1888 // Occurence of such images is quite low (unless one leaves close to a
1889 // 'Leonardo' source. Hence, one might consider commenting out the
1890 // following fix on efficiency reasons.
1891 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1894 entry->SetReadLength(4); // a bug is to be fixed !?
1897 else if ( entry->GetVR() == "SQ" )
1899 foundLength = 0; // ReadLength is unchanged
1902 //////// We encountered a 'delimiter' element i.e. a tag of the form
1903 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1904 // taken into account.
1905 else if ( gr == 0xfffe )
1907 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1908 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1909 // causes extra troubles...
1910 if ( entry->GetElement() != 0x0000 )
1915 entry->SetLength(foundLength);
1919 * \brief Apply some heuristics to predict whether the considered
1920 * element value contains/represents an integer or not.
1921 * @param entry The element value on which to apply the predicate.
1922 * @return The result of the heuristical predicate.
1924 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1926 uint16_t elem = entry->GetElement();
1927 uint16_t group = entry->GetGroup();
1928 const std::string &vr = entry->GetVR();
1929 uint32_t length = entry->GetLength();
1931 // When we have some semantics on the element we just read, and if we
1932 // a priori know we are dealing with an integer, then we shall be
1933 // able to swap it's element value properly.
1934 if ( elem == 0 ) // This is the group length of the group
1942 // Allthough this should never happen, still some images have a
1943 // corrupted group length [e.g. have a glance at offset x(8336) of
1944 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1945 // Since for dicom compliant and well behaved headers, the present
1946 // test is useless (and might even look a bit paranoid), when we
1947 // encounter such an ill-formed image, we simply display a warning
1948 // message and proceed on parsing (while crossing fingers).
1949 long filePosition = Fp->tellg();
1950 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1951 << std::hex << group << " , " << elem
1952 << ") -before- position x(" << filePosition << ")"
1953 << "lgt : " << length );
1957 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1965 * \brief Discover what the swap code is (among little endian, big endian,
1966 * bad little endian, bad big endian).
1968 * @return false when we are absolutely sure
1969 * it's neither ACR-NEMA nor DICOM
1970 * true when we hope ours assuptions are OK
1972 bool Document::CheckSwap()
1979 // First, compare HostByteOrder and NetworkByteOrder in order to
1980 // determine if we shall need to swap bytes (i.e. the Endian type).
1981 bool net2host = Util::IsCurrentProcessorBigEndian();
1983 // The easiest case is the one of a 'true' DICOM header, we just have
1984 // to look for the string "DICM" inside the file preamble.
1987 char *entCur = deb + 128;
1988 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1990 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1992 // Group 0002 should always be VR, and the first element 0000
1993 // Let's be carefull (so many wrong headers ...)
1994 // and determine the value representation (VR) :
1995 // Let's skip to the first element (0002,0000) and check there if we find
1996 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1997 // in which case we (almost) know it is explicit VR.
1998 // WARNING: if it happens to be implicit VR then what we will read
1999 // is the length of the group. If this ascii representation of this
2000 // length happens to be "UL" then we shall believe it is explicit VR.
2001 // We need to skip :
2002 // * the 128 bytes of File Preamble (often padded with zeroes),
2003 // * the 4 bytes of "DICM" string,
2004 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2005 // i.e. a total of 136 bytes.
2008 // group 0x0002 *is always* Explicit VR Sometimes ,
2009 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2010 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2012 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2013 memcmp(entCur, "OB", (size_t)2) == 0 ||
2014 memcmp(entCur, "UI", (size_t)2) == 0 ||
2015 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2016 // when Write DCM *adds*
2018 // Use Document::dicom_vr to test all the possibilities
2019 // instead of just checking for UL, OB and UI !? group 0000
2021 Filetype = ExplicitVR;
2022 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2026 Filetype = ImplicitVR;
2027 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
2028 << "Looks like a bugged Header!");
2034 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
2039 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
2042 // Position the file position indicator at first tag
2043 // (i.e. after the file preamble and the "DICM" string).
2045 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
2047 Fp->seekg ( 132L, std::ios::beg);
2049 } // ------------------------------- End of DicomV3 ----------------
2051 // Alas, this is not a DicomV3 file and whatever happens there is no file
2052 // preamble. We can reset the file position indicator to where the data
2053 // is (i.e. the beginning of the file).
2055 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2057 Fp->seekg(0, std::ios::beg);
2059 // Let's check 'No Preamble Dicom File' :
2060 // Should start with group 0x0002
2061 // and be Explicit Value Representation
2063 s16 = *((uint16_t *)(deb));
2076 if ( SwapCode != 0 )
2078 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2079 memcmp(entCur, "OB", (size_t)2) == 0 ||
2080 memcmp(entCur, "UI", (size_t)2) == 0 ||
2081 memcmp(entCur, "SH", (size_t)2) == 0 ||
2082 memcmp(entCur, "AE", (size_t)2) == 0 ||
2083 memcmp(entCur, "OB", (size_t)2) == 0 )
2085 Filetype = ExplicitVR;
2086 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2090 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2092 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2093 // By clean we mean that the length of the first group is written down.
2094 // If this is the case and since the length of the first group HAS to be
2095 // four (bytes), then determining the proper swap code is straightforward.
2098 // We assume the array of char we are considering contains the binary
2099 // representation of a 32 bits integer. Hence the following dirty
2101 s32 = *((uint32_t *)(entCur));
2121 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2122 // It is time for despaired wild guesses.
2123 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2124 // i.e. the 'group length' element is not present :
2126 // check the supposed-to-be 'group number'
2127 // in ( 0x0001 .. 0x0008 )
2128 // to determine ' SwapCode' value .
2129 // Only 0 or 4321 will be possible
2130 // (no oportunity to check for the formerly well known
2131 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2132 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2133 // the file IS NOT ACR-NEMA nor DICOM V3
2134 // Find a trick to tell it the caller...
2136 s16 = *((uint16_t *)(deb));
2163 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2171 * \brief Change the Byte Swap code.
2173 void Document::SwitchByteSwapCode()
2175 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2176 << " at :" <<std::hex << Fp->tellg() );
2177 if ( SwapCode == 1234 )
2181 else if ( SwapCode == 4321 )
2185 else if ( SwapCode == 3412 )
2189 else if ( SwapCode == 2143 )
2196 * \brief during parsing, Header Elements too long are not loaded in memory
2197 * @param newSize new size
2199 void Document::SetMaxSizeLoadEntry(long newSize)
2205 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2207 MaxSizeLoadEntry = 0xffffffff;
2210 MaxSizeLoadEntry = newSize;
2214 * \brief Read the next tag WITHOUT loading it's value
2215 * (read the 'Group Number', the 'Element Number',
2216 * gets the Dict Entry
2217 * gets the VR, gets the length, gets the offset value)
2218 * @return On succes : the newly created DocEntry, NULL on failure.
2220 DocEntry *Document::ReadNextDocEntry()
2227 group = ReadInt16();
2230 catch ( FormatError e )
2232 // We reached the EOF (or an error occured) therefore
2233 // header parsing has to be considered as finished.
2237 // Sometimes file contains groups of tags with reversed endianess.
2238 HandleBrokenEndian(group, elem);
2240 // In 'true DICOM' files Group 0002 is always little endian
2241 if ( HasDCMPreamble )
2242 HandleOutOfGroup0002(group, elem);
2244 std::string vr = FindDocEntryVR();
2245 std::string realVR = vr;
2247 if ( vr == GDCM_UNKNOWN )
2249 if ( elem == 0x0000 ) // Group Length
2250 realVR = "UL"; // must be UL
2253 DictEntry *dictEntry = GetDictEntry(group,elem);
2256 realVR = dictEntry->GetVR();
2262 if ( Global::GetVR()->IsVROfSequence(realVR) )
2263 newEntry = NewSeqEntry(group, elem);
2264 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2265 newEntry = NewValEntry(group, elem,vr);
2267 newEntry = NewBinEntry(group, elem,vr);
2269 if ( vr == GDCM_UNKNOWN )
2271 if ( Filetype == ExplicitVR )
2273 // We thought this was explicit VR, but we end up with an
2274 // implicit VR tag. Let's backtrack.
2275 if ( newEntry->GetGroup() != 0xfffe )
2278 int offset = Fp->tellg();
2279 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2280 newEntry->GetGroup(), newEntry->GetElement(), offset );
2281 gdcmWarningMacro( msg.c_str() );
2284 newEntry->SetImplicitVR();
2289 FindDocEntryLength(newEntry);
2291 catch ( FormatError e )
2298 newEntry->SetOffset(Fp->tellg());
2304 * \brief Handle broken private tag from Philips NTSCAN
2305 * where the endianess is being switched to BigEndian
2306 * for no apparent reason
2309 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2311 // Endian reversion. Some files contain groups of tags with reversed endianess.
2312 static int reversedEndian = 0;
2313 // try to fix endian switching in the middle of headers
2314 if ((group == 0xfeff) && (elem == 0x00e0))
2316 // start endian swap mark for group found
2318 SwitchByteSwapCode();
2323 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2325 // end of reversed endian group
2327 SwitchByteSwapCode();
2332 * \brief Group 0002 is always coded Little Endian
2333 * whatever Transfer Syntax is
2336 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2338 // Endian reversion. Some files contain groups of tags with reversed endianess.
2339 if ( !Group0002Parsed && group != 0x0002)
2341 Group0002Parsed = true;
2342 // we just came out of group 0002
2343 // if Transfer syntax is Big Endian we have to change CheckSwap
2345 std::string ts = GetTransferSyntax();
2346 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2348 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2352 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2354 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2356 Filetype = ImplicitVR;
2359 // FIXME Strangely, this works with
2360 //'Implicit VR Transfer Syntax (GE Private)
2361 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2363 gdcmWarningMacro("Transfer Syntax Name = ["
2364 << GetTransferSyntaxName() << "]" );
2365 SwitchByteSwapCode();
2366 group = SwapShort(group);
2367 elem = SwapShort(elem);
2372 //-----------------------------------------------------------------------------
2375 //-----------------------------------------------------------------------------
2376 } // end namespace gdcm