1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/08/30 15:34:35 $
7 Version: $Revision: 1.274 $
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 begining 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 // \TODO move the following lines (and a lot of others, to be written)
649 // to a future function CheckAndCorrectHeader
651 // (necessary if user wants to write a DICOM V3 file
652 // starting from an ACR-NEMA (V2) Header
654 if ( filetype == ImplicitVR || filetype == ExplicitVR )
656 // writing Dicom File Preamble
657 char filePreamble[128];
658 memset(filePreamble, 0, 128);
659 fp->write(filePreamble, 128);
660 fp->write("DICM", 4);
664 * \todo rewrite later, if really usefull
665 * - 'Group Length' element is optional in DICOM
666 * - but un-updated odd groups lengthes can causes pb
669 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
670 * UpdateGroupLength(false,filetype);
671 * if ( filetype == ACR)
672 * UpdateGroupLength(true,ACR);
675 ElementSet::WriteContent(fp, filetype); // This one is recursive
678 // -----------------------------------------
681 * \brief Loads (from disk) the element content
682 * when a string is not suitable
683 * @param group group number of the Entry
684 * @param elem element number of the Entry
686 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
688 // Search the corresponding DocEntry
689 DocEntry *docElement = GetDocEntry(group, elem);
693 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
697 LoadEntryBinArea(binElement);
701 * \brief Loads (from disk) the element content
702 * when a string is not suitable
703 * @param elem Entry whose binArea is going to be loaded
705 void Document::LoadEntryBinArea(BinEntry *elem)
707 if (elem->GetBinArea() )
714 size_t o =(size_t)elem->GetOffset();
715 Fp->seekg(o, std::ios::beg);
717 size_t l = elem->GetLength();
718 uint8_t *a = new uint8_t[l];
721 gdcmWarningMacro( "Cannot allocate BinEntry content for : "
722 << std::hex << elem->GetGroup()
723 << "|" << elem->GetElement() );
727 Fp->read((char*)a, l);
728 if ( Fp->fail() || Fp->eof() )
741 * \brief Loads the element while preserving the current
742 * underlying file position indicator as opposed to
743 * LoadDocEntry that modifies it.
744 * @param entry DocEntry whose value will be loaded.
746 void Document::LoadDocEntrySafe(DocEntry *entry)
750 long PositionOnEntry = Fp->tellg();
752 Fp->seekg(PositionOnEntry, std::ios::beg);
757 * \brief Compares two documents, according to \ref DicomDir rules
758 * \warning Does NOT work with ACR-NEMA files
759 * \todo Find a trick to solve the pb (use RET fields ?)
760 * @param document to compare with current one
761 * @return true if 'smaller'
763 bool Document::operator<(Document &document)
766 std::string s1 = GetEntryValue(0x0010,0x0010);
767 std::string s2 = document.GetEntryValue(0x0010,0x0010);
779 s1 = GetEntryValue(0x0010,0x0020);
780 s2 = document.GetEntryValue(0x0010,0x0020);
791 // Study Instance UID
792 s1 = GetEntryValue(0x0020,0x000d);
793 s2 = document.GetEntryValue(0x0020,0x000d);
804 // Serie Instance UID
805 s1 = GetEntryValue(0x0020,0x000e);
806 s2 = document.GetEntryValue(0x0020,0x000e);
821 //-----------------------------------------------------------------------------
824 * \brief Reads a supposed to be 16 Bits integer
825 * (swaps it depending on processor endianness)
828 uint16_t Document::ReadInt16()
832 Fp->read ((char*)&g, (size_t)2);
835 throw FormatError( "Document::ReadInt16()", " file error." );
839 throw FormatError( "Document::ReadInt16()", "EOF." );
846 * \brief Reads a supposed to be 32 Bits integer
847 * (swaps it depending on processor endianness)
850 uint32_t Document::ReadInt32()
854 Fp->read ((char*)&g, (size_t)4);
857 throw FormatError( "Document::ReadInt32()", " file error." );
861 throw FormatError( "Document::ReadInt32()", "EOF." );
868 * \brief skips bytes inside the source file
869 * \warning NOT end user intended method !
872 void Document::SkipBytes(uint32_t nBytes)
874 //FIXME don't dump the returned value
875 Fp->seekg((long)nBytes, std::ios::cur);
879 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
880 * @param filetype Type of the File to be written
882 int Document::ComputeGroup0002Length( FileType filetype )
888 bool found0002 = false;
890 // for each zero-level Tag in the DCM Header
891 DocEntry *entry = GetFirstEntry();
894 gr = entry->GetGroup();
900 if ( entry->GetElement() != 0x0000 )
904 if ( filetype == ExplicitVR )
906 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
908 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
912 groupLength += 2 + 2 + 4 + entry->GetLength();
918 entry = GetNextEntry();
923 //-----------------------------------------------------------------------------
926 * \brief Loads all the needed Dictionaries
927 * \warning NOT end user intended method !
929 void Document::Initialize()
931 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
937 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
938 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
939 * @param offset start of parsing
940 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
941 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
943 void Document::ParseDES(DocEntrySet *set, long offset,
944 long l_max, bool delim_mode)
946 DocEntry *newDocEntry;
947 ValEntry *newValEntry;
948 BinEntry *newBinEntry;
949 SeqEntry *newSeqEntry;
952 bool delim_mode_intern = delim_mode;
956 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
961 newDocEntry = ReadNextDocEntry( );
963 // Uncoment this printf line to be able to 'follow' the DocEntries
964 // when something *very* strange happens
966 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
967 // newDocEntry->GetElement(),
968 // newDocEntry->GetVR().c_str() );
975 // an Item Starter found elsewhere but the first postition
976 // of a SeqEntry means previous entry was a Sequence
977 // but we didn't get it (private Sequence + Implicit VR)
978 // we have to backtrack.
979 if ( !first && newDocEntry->IsItemStarter() )
981 newDocEntry = Backtrack(newDocEntry);
985 PreviousDocEntry = newDocEntry;
989 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
990 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
992 if ( newValEntry || newBinEntry )
994 //////////////////////////// ContentEntry
997 vr = newDocEntry->GetVR();
998 if ( Filetype == ExplicitVR &&
999 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1001 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1002 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
1003 << "|" << newDocEntry->GetElement()
1004 << " : Neither Valentry, nor BinEntry."
1005 "Probably unknown VR.");
1008 //////////////////// BinEntry or UNKOWN VR:
1010 // When "this" is a Document the Key is simply of the
1011 // form ( group, elem )...
1012 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1014 // newBinEntry->SetKey( newBinEntry->GetKey() );
1016 // but when "this" is a SQItem, we are inserting this new
1017 // valEntry in a sequence item, and the key has the
1018 // generalized form (refer to \ref BaseTagKey):
1020 // time waste hunting
1021 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1023 // newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1024 // + newBinEntry->GetKey() );
1027 if ( !set->AddEntry( newBinEntry ) )
1029 gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
1030 << newBinEntry->GetKey()
1032 << newBinEntry->GetOffset() << " )" );
1037 // Load only if we can add (not a duplicate key)
1038 LoadDocEntry( newBinEntry );
1043 /////////////////////// ValEntry
1045 // When "set" is a Document, then we are at the top of the
1046 // hierarchy and the Key is simply of the form ( group, elem )...
1047 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1049 // newValEntry->SetKey( newValEntry->GetKey() );
1051 // ...but when "set" is a SQItem, we are inserting this new
1052 // valEntry in a sequence item. Hence the key has the
1053 // generalized form (refer to \ref BaseTagKey):
1055 // time waste hunting
1056 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1058 // newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1059 // + newValEntry->GetKey() );
1062 if ( !set->AddEntry( newValEntry ) )
1064 gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
1065 << newValEntry->GetKey()
1067 << newValEntry->GetOffset() << " )" );
1072 // Load only if we can add (not a duplicate key)
1073 LoadDocEntry( newValEntry );
1076 if ( newValEntry->GetElement() == 0x0000 ) // if on group length
1078 if ( newValEntry->GetGroup()%2 != 0 ) // if Shadow Group
1080 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1082 std::string strLgrGroup = newValEntry->GetValue();
1084 if ( strLgrGroup != GDCM_UNFOUND)
1086 lgrGroup = atoi(strLgrGroup.c_str());
1087 Fp->seekg(lgrGroup, std::ios::cur);
1089 RemoveEntry( newDocEntry );
1097 bool delimitor=newValEntry->IsItemDelimitor();
1100 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1108 // Just to make sure we are at the beginning of next entry.
1109 SkipToNextDocEntry(newDocEntry);
1113 /////////////////////// SeqEntry : VR = "SQ"
1115 unsigned long l = newDocEntry->GetReadLength();
1116 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1118 if ( l == 0xffffffff )
1120 delim_mode_intern = true;
1124 delim_mode_intern = false;
1128 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1130 // User asked to skip SeQuences *only* if they belong to Shadow Group
1131 if ( newDocEntry->GetGroup()%2 != 0 )
1133 Fp->seekg( l, std::ios::cur);
1138 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1140 // User asked to skip *any* SeQuence
1141 Fp->seekg( l, std::ios::cur);
1145 // delay the dynamic cast as late as possible
1146 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1148 // no other way to create the Delimitor ...
1149 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1151 // At the top of the hierarchy, stands a Document. When "set"
1152 // is a Document, then we are building the first depth level.
1153 // Hence the SeqEntry we are building simply has a depth
1155 // SQItem *parentSQItem = dynamic_cast< SQItem* > ( set );
1156 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1158 newSeqEntry->SetDepthLevel( 1 );
1159 // newSeqEntry->SetKey( newSeqEntry->GetKey() );
1161 // But when "set" is already a SQItem, we are building a nested
1162 // sequence, and hence the depth level of the new SeqEntry
1163 // we are building, is one level deeper:
1165 // time waste hunting
1166 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1168 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1170 // newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1171 // + newSeqEntry->GetKey() );
1175 { // Don't try to parse zero-length sequences
1176 ParseSQ( newSeqEntry,
1177 newDocEntry->GetOffset(),
1178 l, delim_mode_intern);
1180 if ( !set->AddEntry( newSeqEntry ) )
1182 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1183 << newSeqEntry->GetKey()
1185 << newSeqEntry->GetOffset() << " )" );
1189 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1195 } // end SeqEntry : VR = "SQ"
1206 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1207 * @return parsed length for this level
1209 void Document::ParseSQ( SeqEntry *seqEntry,
1210 long offset, long l_max, bool delim_mode)
1212 int SQItemNumber = 0;
1214 long offsetStartCurrentSQItem = offset;
1218 // the first time, we read the fff0,e000 of the first SQItem
1219 DocEntry *newDocEntry = ReadNextDocEntry();
1223 // FIXME Should warn user
1224 gdcmWarningMacro("in ParseSQ : should never get here!");
1229 if ( newDocEntry->IsSequenceDelimitor() )
1231 seqEntry->SetDelimitationItem( newDocEntry );
1235 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1240 // create the current SQItem
1241 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1243 std::ostringstream newBase;
1244 newBase << seqEntry->GetKey()
1248 itemSQ->SetBaseTagKey( newBase.str() );
1250 unsigned int l = newDocEntry->GetReadLength();
1252 if ( l == 0xffffffff )
1261 // Let's try :------------
1262 // remove fff0,e000, created out of the SQItem
1264 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1265 // fill up the current SQItem, starting at the beginning of fff0,e000
1267 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1269 offsetStartCurrentSQItem = Fp->tellg();
1270 // end try -----------------
1272 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1274 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1282 * \brief When a private Sequence + Implicit VR is encountered
1283 * we cannot guess it's a Sequence till we find the first
1284 * Item Starter. We then backtrack to do the job.
1285 * @param docEntry Item Starter that warned us
1287 DocEntry *Document::Backtrack(DocEntry *docEntry)
1289 // delete the Item Starter, built erroneously out of any Sequence
1290 // it's not yet in the HTable/chained list
1293 // Get all info we can from PreviousDocEntry
1294 uint16_t group = PreviousDocEntry->GetGroup();
1295 uint16_t elem = PreviousDocEntry->GetElement();
1296 uint32_t lgt = PreviousDocEntry->GetLength();
1297 long offset = PreviousDocEntry->GetOffset();
1299 gdcmWarningMacro( "Backtrack :" << std::hex << group
1301 << " at offset " << offset );
1302 RemoveEntry( PreviousDocEntry );
1304 // forge the Seq Entry
1305 DocEntry *newEntry = NewSeqEntry(group, elem);
1306 newEntry->SetLength(lgt);
1307 newEntry->SetOffset(offset);
1309 // Move back to the beginning of the Sequence
1310 Fp->seekg( 0, std::ios::beg);
1311 Fp->seekg(offset, std::ios::cur);
1317 * \brief Loads (or not) the element content depending if its length exceeds
1318 * or not the value specified with Document::SetMaxSizeLoadEntry()
1319 * @param entry Header Entry (Dicom Element) to be dealt with
1320 * @param forceLoad wheter we want to load its content even if its length
1321 * exceeds the value specified with Document::SetMaxSizeLoadEntry()
1323 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1325 uint16_t group = entry->GetGroup();
1326 std::string vr = entry->GetVR();
1327 uint32_t length = entry->GetLength();
1329 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1331 // A SeQuence "contains" a set of Elements.
1332 // (fffe e000) tells us an Element is beginning
1333 // (fffe e00d) tells us an Element just ended
1334 // (fffe e0dd) tells us the current SeQuence just ended
1335 if ( group == 0xfffe )
1337 // NO more value field for SQ !
1341 // When the length is zero things are easy:
1344 ((ValEntry *)entry)->SetValue("");
1348 // The elements whose length is bigger than the specified upper bound
1349 // are not loaded. Instead we leave a short notice on the offset of
1350 // the element content and it's length.
1352 std::ostringstream s;
1356 if (length > MaxSizeLoadEntry)
1358 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1360 s << GDCM_NOTLOADED;
1361 s << " Ad.:" << (long)entry->GetOffset();
1362 s << " x(" << std::hex << entry->GetOffset() << ")";
1364 s << " Lgt:" << entry->GetLength();
1365 s << " x(" << std::hex << entry->GetLength() << ")";
1366 binEntryPtr->SetValue(s.str());
1368 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1370 s << GDCM_NOTLOADED;
1371 s << " Address:" << (long)entry->GetOffset();
1372 s << " Length:" << entry->GetLength();
1373 s << " x(" << std::hex << entry->GetLength() << ")";
1374 valEntryPtr->SetValue(s.str());
1379 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1380 << "nor a ValEntry ?! Should never print that !" );
1383 // to be sure we are at the end of the value ...
1384 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1390 // When we find a BinEntry not very much can be done :
1391 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1393 s << GDCM_BINLOADED;
1394 binEntryPtr->SetValue(s.str());
1395 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1399 if ( IsDocEntryAnInteger(entry) )
1403 // When short integer(s) are expected, read and convert the following
1404 // (n * 2) characters properly i.e. consider them as short integers as
1405 // opposed to strings.
1406 // Elements with Value Multiplicity > 1
1407 // contain a set of integers (not a single one)
1408 if (vr == "US" || vr == "SS")
1411 NewInt = ReadInt16();
1415 for (int i=1; i < nbInt; i++)
1418 NewInt = ReadInt16();
1423 // See above comment on multiple integers (mutatis mutandis).
1424 else if (vr == "UL" || vr == "SL")
1427 NewInt = ReadInt32();
1431 for (int i=1; i < nbInt; i++)
1434 NewInt = ReadInt32();
1439 #ifdef GDCM_NO_ANSI_STRING_STREAM
1440 s << std::ends; // to avoid oddities on Solaris
1441 #endif //GDCM_NO_ANSI_STRING_STREAM
1443 ((ValEntry *)entry)->SetValue(s.str());
1447 // FIXME: We need an additional byte for storing \0 that is not on disk
1448 char *str = new char[length+1];
1449 Fp->read(str, (size_t)length);
1450 str[length] = '\0'; //this is only useful when length is odd
1451 // Special DicomString call to properly handle \0 and even length
1452 std::string newValue;
1455 newValue = Util::DicomString(str, length+1);
1456 gdcmWarningMacro("Warning: bad length: " << length <<
1457 " For string :" << newValue.c_str());
1458 // Since we change the length of string update it length
1459 //entry->SetReadLength(length+1);
1463 newValue = Util::DicomString(str, length);
1467 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1469 if ( Fp->fail() || Fp->eof())
1472 gdcmWarningMacro("--> fail");
1474 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1475 << " lgt : " << valEntry->GetReadLength()
1476 << " at " << std::hex << valEntry->GetOffset());
1477 valEntry->SetValue(GDCM_UNREAD);
1483 // Because of correspondance with the VR dic
1484 valEntry->SetValue(newValue);
1488 valEntry->SetValue(newValue);
1493 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1494 << " lgt : " << valEntry->GetReadLength()
1495 << " at " << std::hex << valEntry->GetOffset());
1500 * \brief Find the value Length of the passed Header Entry
1501 * @param entry Header Entry whose length of the value shall be loaded.
1503 void Document::FindDocEntryLength( DocEntry *entry )
1504 throw ( FormatError )
1506 std::string vr = entry->GetVR();
1509 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1511 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
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 long currentPosition = Fp->tellg();
1534 Fp->seekg(0L,std::ios::end);
1536 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1537 Fp->seekg(currentPosition, std::ios::beg);
1539 entry->SetReadLength(lengthUntilEOF);
1540 entry->SetLength(lengthUntilEOF);
1543 entry->SetReadLength(lengthOB);
1544 entry->SetLength(lengthOB);
1547 FixDocEntryFoundLength(entry, length32);
1551 // Length is encoded on 2 bytes.
1552 length16 = ReadInt16();
1554 // 0xffff means that we deal with 'No Length' Sequence
1555 // or 'No Length' SQItem
1556 if ( length16 == 0xffff)
1560 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1565 // Either implicit VR or a non DICOM conformal (see note below) explicit
1566 // VR that ommited the VR of (at least) this element. Farts happen.
1567 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1568 // on Data elements "Implicit and Explicit VR Data Elements shall
1569 // not coexist in a Data Set and Data Sets nested within it".]
1570 // Length is on 4 bytes.
1572 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1573 // even if Transfer Syntax is 'Implicit VR ...'
1575 FixDocEntryFoundLength( entry, ReadInt32() );
1581 * \brief Find the Length till the next sequence delimiter
1582 * \warning NOT end user intended method !
1585 uint32_t Document::FindDocEntryLengthOBOrOW()
1586 throw( FormatUnexpected )
1588 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1589 long positionOnEntry = Fp->tellg();
1590 bool foundSequenceDelimiter = false;
1591 uint32_t totalLength = 0;
1593 while ( !foundSequenceDelimiter )
1599 group = ReadInt16();
1602 catch ( FormatError )
1604 throw FormatError("Unexpected end of file encountered during ",
1605 "Document::FindDocEntryLengthOBOrOW()");
1607 // We have to decount the group and element we just read
1609 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1611 long filePosition = Fp->tellg();
1613 "Neither an Item tag nor a Sequence delimiter tag on :"
1614 << std::hex << group << " , " << elem
1615 << ") -before- position x(" << filePosition << ")" );
1617 Fp->seekg(positionOnEntry, std::ios::beg);
1618 throw FormatUnexpected(
1619 "Neither an Item tag nor a Sequence delimiter tag.");
1621 if ( elem == 0xe0dd )
1623 foundSequenceDelimiter = true;
1625 uint32_t itemLength = ReadInt32();
1626 // We add 4 bytes since we just read the ItemLength with ReadInt32
1627 totalLength += itemLength + 4;
1628 SkipBytes(itemLength);
1630 if ( foundSequenceDelimiter )
1635 Fp->seekg( positionOnEntry, std::ios::beg);
1640 * \brief Find the Value Representation of the current Dicom Element.
1641 * @return Value Representation of the current Entry
1643 std::string Document::FindDocEntryVR()
1645 if ( Filetype != ExplicitVR )
1646 return GDCM_UNKNOWN;
1648 long positionOnEntry = Fp->tellg();
1649 // Warning: we believe this is explicit VR (Value Representation) because
1650 // we used a heuristic that found "UL" in the first tag. Alas this
1651 // doesn't guarantee that all the tags will be in explicit VR. In some
1652 // cases (see e-film filtered files) one finds implicit VR tags mixed
1653 // within an explicit VR file. Hence we make sure the present tag
1654 // is in explicit VR and try to fix things if it happens not to be
1658 Fp->read (vr, (size_t)2);
1661 if ( !CheckDocEntryVR(vr) )
1663 Fp->seekg(positionOnEntry, std::ios::beg);
1664 return GDCM_UNKNOWN;
1670 * \brief Check the correspondance between the VR of the header entry
1671 * and the taken VR. If they are different, the header entry is
1672 * updated with the new VR.
1673 * @param vr Dicom Value Representation
1674 * @return false if the VR is incorrect of if the VR isn't referenced
1675 * otherwise, it returns true
1677 bool Document::CheckDocEntryVR(VRKey vr)
1679 if ( !Global::GetVR()->IsValidVR(vr) )
1686 * \brief Get the transformed value of the header entry. The VR value
1687 * is used to define the transformation to operate on the value
1688 * \warning NOT end user intended method !
1689 * @param entry entry to tranform
1690 * @return Transformed entry value
1692 std::string Document::GetDocEntryValue(DocEntry *entry)
1694 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1696 std::string val = ((ValEntry *)entry)->GetValue();
1697 std::string vr = entry->GetVR();
1698 uint32_t length = entry->GetLength();
1699 std::ostringstream s;
1702 // When short integer(s) are expected, read and convert the following
1703 // n * 2 bytes properly i.e. as a multivaluated strings
1704 // (each single value is separated fromthe next one by '\'
1705 // as usual for standard multivaluated filels
1706 // Elements with Value Multiplicity > 1
1707 // contain a set of short integers (not a single one)
1709 if ( vr == "US" || vr == "SS" )
1714 for (int i=0; i < nbInt; i++)
1720 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1721 newInt16 = SwapShort( newInt16 );
1726 // When integer(s) are expected, read and convert the following
1727 // n * 4 bytes properly i.e. as a multivaluated strings
1728 // (each single value is separated fromthe next one by '\'
1729 // as usual for standard multivaluated filels
1730 // Elements with Value Multiplicity > 1
1731 // contain a set of integers (not a single one)
1732 else if ( vr == "UL" || vr == "SL" )
1737 for (int i=0; i < nbInt; i++)
1743 newInt32 = ( val[4*i+0] & 0xFF )
1744 + (( val[4*i+1] & 0xFF ) << 8 )
1745 + (( val[4*i+2] & 0xFF ) << 16 )
1746 + (( val[4*i+3] & 0xFF ) << 24 );
1747 newInt32 = SwapLong( newInt32 );
1751 #ifdef GDCM_NO_ANSI_STRING_STREAM
1752 s << std::ends; // to avoid oddities on Solaris
1753 #endif //GDCM_NO_ANSI_STRING_STREAM
1756 return ((ValEntry *)entry)->GetValue();
1760 * \brief Get the reverse transformed value of the header entry. The VR
1761 * value is used to define the reverse transformation to operate on
1763 * \warning NOT end user intended method !
1764 * @param entry Entry to reverse transform
1765 * @return Reverse transformed entry value
1767 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1769 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1771 std::string vr = entry->GetVR();
1772 std::vector<std::string> tokens;
1773 std::ostringstream s;
1775 if ( vr == "US" || vr == "SS" )
1779 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1780 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1781 for (unsigned int i=0; i<tokens.size(); i++)
1783 newInt16 = atoi(tokens[i].c_str());
1784 s << ( newInt16 & 0xFF )
1785 << (( newInt16 >> 8 ) & 0xFF );
1789 if ( vr == "UL" || vr == "SL")
1793 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1794 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1795 for (unsigned int i=0; i<tokens.size();i++)
1797 newInt32 = atoi(tokens[i].c_str());
1798 s << (char)( newInt32 & 0xFF )
1799 << (char)(( newInt32 >> 8 ) & 0xFF )
1800 << (char)(( newInt32 >> 16 ) & 0xFF )
1801 << (char)(( newInt32 >> 24 ) & 0xFF );
1806 #ifdef GDCM_NO_ANSI_STRING_STREAM
1807 s << std::ends; // to avoid oddities on Solaris
1808 #endif //GDCM_NO_ANSI_STRING_STREAM
1812 return ((ValEntry *)entry)->GetValue();
1816 * \brief Skip a given Header Entry
1817 * \warning NOT end user intended method !
1818 * @param entry entry to skip
1820 void Document::SkipDocEntry(DocEntry *entry)
1822 SkipBytes(entry->GetLength());
1826 * \brief Skips to the beginning of the next Header Entry
1827 * \warning NOT end user intended method !
1828 * @param currentDocEntry entry to skip
1830 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1832 int l = currentDocEntry->GetReadLength();
1833 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1834 // ... but PMS imagers happen !
1836 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1837 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1839 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1844 * \brief When the length of an element value is obviously wrong (because
1845 * the parser went Jabberwocky) one can hope improving things by
1846 * applying some heuristics.
1847 * @param entry entry to check
1848 * @param foundLength first assumption about length
1850 void Document::FixDocEntryFoundLength(DocEntry *entry,
1851 uint32_t foundLength)
1853 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1854 if ( foundLength == 0xffffffff)
1859 uint16_t gr = entry->GetGroup();
1860 uint16_t elem = entry->GetElement();
1862 if ( foundLength % 2)
1864 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1865 << " in x(" << std::hex << gr << "," << elem <<")");
1868 //////// Fix for some naughty General Electric images.
1869 // Allthough not recent many such GE corrupted images are still present
1870 // on Creatis hard disks. Hence this fix shall remain when such images
1871 // are no longer in use (we are talking a few years, here)...
1872 // Note: XMedCon probably uses such a trick since it is able to read
1873 // those pesky GE images ...
1874 if ( foundLength == 13)
1876 // Only happens for this length !
1877 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1880 entry->SetReadLength(10); // a bug is to be fixed !?
1884 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1885 // Occurence of such images is quite low (unless one leaves close to a
1886 // 'Leonardo' source. Hence, one might consider commenting out the
1887 // following fix on efficiency reasons.
1888 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1891 entry->SetReadLength(4); // a bug is to be fixed !?
1894 else if ( entry->GetVR() == "SQ" )
1896 foundLength = 0; // ReadLength is unchanged
1899 //////// We encountered a 'delimiter' element i.e. a tag of the form
1900 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1901 // taken into account.
1902 else if ( gr == 0xfffe )
1904 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1905 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1906 // causes extra troubles...
1907 if ( entry->GetElement() != 0x0000 )
1912 entry->SetLength(foundLength);
1916 * \brief Apply some heuristics to predict whether the considered
1917 * element value contains/represents an integer or not.
1918 * @param entry The element value on which to apply the predicate.
1919 * @return The result of the heuristical predicate.
1921 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1923 uint16_t elem = entry->GetElement();
1924 uint16_t group = entry->GetGroup();
1925 const std::string &vr = entry->GetVR();
1926 uint32_t length = entry->GetLength();
1928 // When we have some semantics on the element we just read, and if we
1929 // a priori know we are dealing with an integer, then we shall be
1930 // able to swap it's element value properly.
1931 if ( elem == 0 ) // This is the group length of the group
1939 // Allthough this should never happen, still some images have a
1940 // corrupted group length [e.g. have a glance at offset x(8336) of
1941 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1942 // Since for dicom compliant and well behaved headers, the present
1943 // test is useless (and might even look a bit paranoid), when we
1944 // encounter such an ill-formed image, we simply display a warning
1945 // message and proceed on parsing (while crossing fingers).
1946 long filePosition = Fp->tellg();
1947 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1948 << std::hex << group << " , " << elem
1949 << ") -before- position x(" << filePosition << ")"
1950 << "lgt : " << length );
1954 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1962 * \brief Discover what the swap code is (among little endian, big endian,
1963 * bad little endian, bad big endian).
1965 * @return false when we are absolutely sure
1966 * it's neither ACR-NEMA nor DICOM
1967 * true when we hope ours assuptions are OK
1969 bool Document::CheckSwap()
1976 // First, compare HostByteOrder and NetworkByteOrder in order to
1977 // determine if we shall need to swap bytes (i.e. the Endian type).
1978 bool net2host = Util::IsCurrentProcessorBigEndian();
1980 // The easiest case is the one of a 'true' DICOM header, we just have
1981 // to look for the string "DICM" inside the file preamble.
1984 char *entCur = deb + 128;
1985 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1987 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1989 // Group 0002 should always be VR, and the first element 0000
1990 // Let's be carefull (so many wrong headers ...)
1991 // and determine the value representation (VR) :
1992 // Let's skip to the first element (0002,0000) and check there if we find
1993 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1994 // in which case we (almost) know it is explicit VR.
1995 // WARNING: if it happens to be implicit VR then what we will read
1996 // is the length of the group. If this ascii representation of this
1997 // length happens to be "UL" then we shall believe it is explicit VR.
1998 // We need to skip :
1999 // * the 128 bytes of File Preamble (often padded with zeroes),
2000 // * the 4 bytes of "DICM" string,
2001 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2002 // i.e. a total of 136 bytes.
2005 // group 0x0002 *is always* Explicit VR Sometimes ,
2006 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2007 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2009 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2010 memcmp(entCur, "OB", (size_t)2) == 0 ||
2011 memcmp(entCur, "UI", (size_t)2) == 0 ||
2012 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2013 // when Write DCM *adds*
2015 // Use Document::dicom_vr to test all the possibilities
2016 // instead of just checking for UL, OB and UI !? group 0000
2018 Filetype = ExplicitVR;
2019 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2023 Filetype = ImplicitVR;
2024 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
2025 << "Looks like a bugged Header!");
2031 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
2036 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
2039 // Position the file position indicator at first tag
2040 // (i.e. after the file preamble and the "DICM" string).
2042 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
2044 Fp->seekg ( 132L, std::ios::beg);
2046 } // ------------------------------- End of DicomV3 ----------------
2048 // Alas, this is not a DicomV3 file and whatever happens there is no file
2049 // preamble. We can reset the file position indicator to where the data
2050 // is (i.e. the beginning of the file).
2052 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2054 Fp->seekg(0, std::ios::beg);
2056 // Let's check 'No Preamble Dicom File' :
2057 // Should start with group 0x0002
2058 // and be Explicit Value Representation
2060 s16 = *((uint16_t *)(deb));
2073 if ( SwapCode != 0 )
2075 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2076 memcmp(entCur, "OB", (size_t)2) == 0 ||
2077 memcmp(entCur, "UI", (size_t)2) == 0 ||
2078 memcmp(entCur, "SH", (size_t)2) == 0 ||
2079 memcmp(entCur, "AE", (size_t)2) == 0 ||
2080 memcmp(entCur, "OB", (size_t)2) == 0 )
2082 Filetype = ExplicitVR;
2083 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2087 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2089 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2090 // By clean we mean that the length of the first group is written down.
2091 // If this is the case and since the length of the first group HAS to be
2092 // four (bytes), then determining the proper swap code is straightforward.
2095 // We assume the array of char we are considering contains the binary
2096 // representation of a 32 bits integer. Hence the following dirty
2098 s32 = *((uint32_t *)(entCur));
2118 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2119 // It is time for despaired wild guesses.
2120 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2121 // i.e. the 'group length' element is not present :
2123 // check the supposed-to-be 'group number'
2124 // in ( 0x0001 .. 0x0008 )
2125 // to determine ' SwapCode' value .
2126 // Only 0 or 4321 will be possible
2127 // (no oportunity to check for the formerly well known
2128 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2129 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2130 // the file IS NOT ACR-NEMA nor DICOM V3
2131 // Find a trick to tell it the caller...
2133 s16 = *((uint16_t *)(deb));
2160 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2168 * \brief Change the Byte Swap code.
2170 void Document::SwitchByteSwapCode()
2172 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2173 << " at :" <<std::hex << Fp->tellg() );
2174 if ( SwapCode == 1234 )
2178 else if ( SwapCode == 4321 )
2182 else if ( SwapCode == 3412 )
2186 else if ( SwapCode == 2143 )
2193 * \brief during parsing, Header Elements too long are not loaded in memory
2194 * @param newSize new size
2196 void Document::SetMaxSizeLoadEntry(long newSize)
2202 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2204 MaxSizeLoadEntry = 0xffffffff;
2207 MaxSizeLoadEntry = newSize;
2211 * \brief Read the next tag WITHOUT loading it's value
2212 * (read the 'Group Number', the 'Element Number',
2213 * gets the Dict Entry
2214 * gets the VR, gets the length, gets the offset value)
2215 * @return On succes : the newly created DocEntry, NULL on failure.
2217 DocEntry *Document::ReadNextDocEntry()
2224 group = ReadInt16();
2227 catch ( FormatError e )
2229 // We reached the EOF (or an error occured) therefore
2230 // header parsing has to be considered as finished.
2234 // Sometimes file contains groups of tags with reversed endianess.
2235 HandleBrokenEndian(group, elem);
2237 // In 'true DICOM' files Group 0002 is always little endian
2238 if ( HasDCMPreamble )
2239 HandleOutOfGroup0002(group, elem);
2241 std::string vr = FindDocEntryVR();
2242 std::string realVR = vr;
2244 if ( vr == GDCM_UNKNOWN )
2246 if ( elem == 0x0000 ) // Group Length
2247 realVR = "UL"; // must be UL
2250 DictEntry *dictEntry = GetDictEntry(group,elem);
2253 realVR = dictEntry->GetVR();
2259 if ( Global::GetVR()->IsVROfSequence(realVR) )
2260 newEntry = NewSeqEntry(group, elem);
2261 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2262 newEntry = NewValEntry(group, elem,vr);
2264 newEntry = NewBinEntry(group, elem,vr);
2266 if ( vr == GDCM_UNKNOWN )
2268 if ( Filetype == ExplicitVR )
2270 // We thought this was explicit VR, but we end up with an
2271 // implicit VR tag. Let's backtrack.
2272 if ( newEntry->GetGroup() != 0xfffe )
2275 int offset = Fp->tellg();
2276 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2277 newEntry->GetGroup(), newEntry->GetElement(), offset );
2278 gdcmWarningMacro( msg.c_str() );
2281 newEntry->SetImplicitVR();
2286 FindDocEntryLength(newEntry);
2288 catch ( FormatError e )
2295 newEntry->SetOffset(Fp->tellg());
2301 * \brief Handle broken private tag from Philips NTSCAN
2302 * where the endianess is being switched to BigEndian
2303 * for no apparent reason
2306 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2308 // Endian reversion. Some files contain groups of tags with reversed endianess.
2309 static int reversedEndian = 0;
2310 // try to fix endian switching in the middle of headers
2311 if ((group == 0xfeff) && (elem == 0x00e0))
2313 // start endian swap mark for group found
2315 SwitchByteSwapCode();
2320 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2322 // end of reversed endian group
2324 SwitchByteSwapCode();
2329 * \brief Group 0002 is always coded Little Endian
2330 * whatever Transfer Syntax is
2333 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2335 // Endian reversion. Some files contain groups of tags with reversed endianess.
2336 if ( !Group0002Parsed && group != 0x0002)
2338 Group0002Parsed = true;
2339 // we just came out of group 0002
2340 // if Transfer syntax is Big Endian we have to change CheckSwap
2342 std::string ts = GetTransferSyntax();
2343 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2345 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2349 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2351 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2353 Filetype = ImplicitVR;
2356 // FIXME Strangely, this works with
2357 //'Implicit VR Transfer Syntax (GE Private)
2358 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2360 gdcmWarningMacro("Transfer Syntax Name = ["
2361 << GetTransferSyntaxName() << "]" );
2362 SwitchByteSwapCode();
2363 group = SwapShort(group);
2364 elem = SwapShort(elem);
2369 //-----------------------------------------------------------------------------
2372 //-----------------------------------------------------------------------------
2373 } // end namespace gdcm