1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/08/30 14:40:33 $
7 Version: $Revision: 1.272 $
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 = GDCM_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 = GDCM_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 ()
102 //-----------------------------------------------------------------------------
106 * \brief Loader. use SetLoadMode(), SetFileName() before !
107 * @return false if file cannot be open or no swap info was found,
108 * or no tag was found.
110 bool Document::Load( )
112 if ( GetFileName() == "" )
114 gdcmWarningMacro( "Use SetFileName, before !" );
117 return DoTheLoadingDocumentJob( );
120 * \brief Loader. (DEPRECATED : not to break the API)
121 * @param fileName 'Document' (File or DicomDir) to be open for parsing
122 * @return false if file cannot be open or no swap info was found,
123 * or no tag was found.
125 bool Document::Load( std::string const &fileName )
128 return DoTheLoadingDocumentJob( );
132 * \brief Performs the Loading Job (internal use only)
133 * @return false if file cannot be open or no swap info was found,
134 * or no tag was found.
136 bool Document::DoTheLoadingDocumentJob( )
138 if ( ! IsDocumentModified ) // Nothing to do !
141 // if ( Filename == fileName )
143 // gdcmWarningMacro( "The file was already parsed inside this "
144 // << "gdcm::Document (its name is: "
145 // << Filename.c_str() );
149 //gdcmWarningMacro( "A file was already parsed inside this "
150 // << "gdcm::Document (previous name was: "
151 // << Filename.c_str() << ". New name is :"
153 // clean out the Entries, if already parsed
154 // (probabely a mistake from the user)
161 // warning already performed in OpenFile()
162 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
163 // << Filename.c_str() );
168 Group0002Parsed = false;
170 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
172 Fp->seekg(0, std::ios::end);
173 long lgt = Fp->tellg(); // total length of the file
175 Fp->seekg(0, std::ios::beg);
177 // CheckSwap returns a boolean
178 // (false if no swap info of any kind was found)
181 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
182 << Filename.c_str());
187 long beg = Fp->tellg(); // just after DICOM preamble (if any)
189 lgt -= beg; // remaining length to parse
192 // Loading is done during parsing
193 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
197 gdcmWarningMacro( "No tag in internal hash table for: "
198 << Filename.c_str());
202 IsDocumentAlreadyLoaded = true;
204 Fp->seekg( 0, std::ios::beg);
206 // Load 'non string' values
208 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
209 if ( PhotometricInterpretation == "PALETTE COLOR " )
212 // Probabely this line should be outside the 'if'
213 // Try to find an image sample holding a 'gray LUT'
214 LoadEntryBinArea(0x0028,0x1200); // gray LUT
217 /// The tags refered by the three following lines used to be CORRECTLY
218 /// defined as having an US Value Representation in the public
219 /// dictionary. BUT the semantics implied by the three following
220 /// lines state that the corresponding tag contents are in fact
221 /// the ones of a BinEntry.
222 /// In order to fix things "Quick and Dirty" the dictionary was
223 /// altered on PURPOSE but now contains a WRONG value.
224 /// In order to fix things and restore the dictionary to its
225 /// correct value, one needs to decided of the semantics by deciding
226 /// whether the following tags are either :
227 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
228 /// also used as BinEntry, which requires the proper conversion,
229 /// - OW, and hence loaded as BinEntry, but afterwards also used
230 /// as ValEntry, which requires the proper conversion.
231 LoadEntryBinArea(0x0028,0x1201); // R LUT
232 LoadEntryBinArea(0x0028,0x1202); // G LUT
233 LoadEntryBinArea(0x0028,0x1203); // B LUT
235 // Segmented Red Palette Color LUT Data
236 LoadEntryBinArea(0x0028,0x1221);
237 // Segmented Green Palette Color LUT Data
238 LoadEntryBinArea(0x0028,0x1222);
239 // Segmented Blue Palette Color LUT Data
240 LoadEntryBinArea(0x0028,0x1223);
243 //FIXME later : how to use it?
244 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
247 SQItem *sqi= modLutSeq->GetFirstSQItem();
250 BinEntry *b = sqi->GetBinEntry(0x0028,0x3006);
253 if ( b->GetLength() != 0 )
255 LoadEntryBinArea(b); //LUT Data (CTX dependent)
261 // Force Loading some more elements if user asked to.
264 for (ListElements::iterator it = UserForceLoadList.begin();
265 it != UserForceLoadList.end();
268 d = GetDocEntry( (*it).Group, (*it).Elem);
273 if ( dynamic_cast<BinEntry *>(d) )
275 LoadDocEntry(d, true);
279 if ( dynamic_cast<BinEntry *>(d) )
281 LoadEntryBinArea((*it).Group, (*it).Elem);
285 if ( dynamic_cast<SeqEntry *>(d) )
287 gdcmWarningMacro( "You cannot 'ForceLoad' a SeqEntry ");
294 // ----------------------------
295 // Specific code to allow gdcm to read ACR-LibIDO formated images
296 // Note: ACR-LibIDO is an extension of the ACR standard that was
297 // used at CREATIS. For the time being (say a couple of years)
298 // we keep this kludge to allow CREATIS users
299 // reading their old images.
301 // if recognition code tells us we deal with a LibIDO image
302 // we switch lineNumber and columnNumber
305 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
306 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
307 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
308 // with "little-endian strings"
310 Filetype = ACR_LIBIDO;
311 std::string rows = GetEntryValue(0x0028, 0x0010);
312 std::string columns = GetEntryValue(0x0028, 0x0011);
313 SetValEntry(columns, 0x0028, 0x0010);
314 SetValEntry(rows , 0x0028, 0x0011);
316 // --- End of ACR-LibIDO kludge ---
322 * \brief Adds a new element we want to load anyway
323 * @param group Group number of the target tag.
324 * @param elem Element number of the target tag.
326 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
331 UserForceLoadList.push_back(el);
334 * \brief Get the public dictionary used
336 Dict *Document::GetPubDict()
342 * \brief Get the shadow dictionary used
344 Dict *Document::GetShaDict()
350 * \brief Set the shadow dictionary used
351 * @param dict dictionary to use in shadow
353 bool Document::SetShaDict(Dict *dict)
360 * \brief Set the shadow dictionary used
361 * @param dictName name of the dictionary to use in shadow
363 bool Document::SetShaDict(DictKey const &dictName)
365 RefShaDict = Global::GetDicts()->GetDict(dictName);
370 * \brief This predicate tells us whether or not the current Document
371 * was properly parsed and contains at least *one* Dicom Element
372 * (and nothing more, sorry).
373 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
376 bool Document::IsReadable()
378 if ( Filetype == Unknown )
380 gdcmWarningMacro( "Wrong filetype");
386 gdcmWarningMacro( "No tag in internal hash table.");
394 * \brief Predicate for dicom version 3 file.
395 * @return True when the file is a dicom version 3.
397 bool Document::IsDicomV3()
399 // Checking if Transfer Syntax exists is enough
400 // Anyway, it's too late check if the 'Preamble' was found ...
401 // And ... would it be a rich idea to check ?
402 // (some 'no Preamble' DICOM images exist !)
403 return GetDocEntry(0x0002, 0x0010) != NULL;
407 * \brief Predicate for Papyrus file
408 * Dedicated to whomsoever it may concern
409 * @return True when the file is a Papyrus file.
411 bool Document::IsPapyrus()
413 // check for Papyrus private Sequence
414 DocEntry *e = GetDocEntry(0x0041, 0x1050);
417 // check if it's actually a Sequence
418 if ( !dynamic_cast<SeqEntry*>(e) )
424 * \brief returns the File Type
425 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
426 * @return the FileType code
428 FileType Document::GetFileType()
434 * \brief Accessor to the Transfer Syntax (when present) of the
435 * current document (it internally handles reading the
436 * value from disk when only parsing occured).
437 * @return The encountered Transfer Syntax of the current document.
439 std::string Document::GetTransferSyntax()
441 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
447 // The entry might be present but not loaded (parsing and loading
448 // happen at different stages): try loading and proceed with check...
449 LoadDocEntrySafe(entry);
450 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
452 std::string transfer = valEntry->GetValue();
453 // The actual transfer (as read from disk) might be padded. We
454 // first need to remove the potential padding. We can make the
455 // weak assumption that padding was not executed with digits...
456 if ( transfer.length() == 0 )
458 // for brain damaged headers
461 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
463 transfer.erase(transfer.length()-1, 1);
471 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
472 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
474 std::string Document::GetTransferSyntaxName()
476 // use the TS (TS : Transfer Syntax)
477 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
479 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
481 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
482 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
483 return "Uncompressed ACR-NEMA";
485 if ( transferSyntax == GDCM_UNFOUND )
487 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
488 return "Uncompressed ACR-NEMA";
491 // we do it only when we need it
492 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
494 // Global::GetTS() is a global static you shall never try to delete it!
498 // --------------- Swap Code ------------------
500 * \brief Swaps the bytes so they agree with the processor order
501 * @return The properly swaped 16 bits integer.
503 uint16_t Document::SwapShort(uint16_t a)
505 if ( SwapCode == 4321 || SwapCode == 2143 )
507 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
509 a = ( a << 8 ) | ( a >> 8 );
515 * \brief Swaps back the bytes of 4-byte long integer accordingly to
517 * @return The properly swaped 32 bits integer.
519 uint32_t Document::SwapLong(uint32_t a)
526 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
527 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
529 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
530 ((a>>8) & 0x0000ff00) | (a>>24) );
533 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
534 a=( (a<<16) | (a>>16) );
537 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
540 gdcmErrorMacro( "Unset swap code:" << SwapCode );
547 // -----------------File I/O ---------------
549 * \brief Tries to open the file \ref Document::Filename and
550 * checks the preamble when existing.
551 * @return The FILE pointer on success.
553 std::ifstream *Document::OpenFile()
555 HasDCMPreamble = false;
556 if (Filename.length() == 0)
563 gdcmWarningMacro( "File already open: " << Filename.c_str());
567 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
570 // Don't user gdcmErrorMacro :
571 // a spurious message will appear when you use, for instance
572 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
573 // to create outputFileName.
574 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
578 //exit(1); // No function is allowed to leave the application instead
579 // of warning the caller
583 Fp->read((char*)&zero, (size_t)2);
590 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
592 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
593 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
594 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
595 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
597 std::string msg = Util::Format(
598 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
599 gdcmWarningMacro( msg.c_str() );
604 Fp->seekg(126L, std::ios::cur);
605 char dicm[4] = {' ',' ',' ',' '};
606 Fp->read(dicm, (size_t)4);
612 if ( memcmp(dicm, "DICM", 4) == 0 )
614 HasDCMPreamble = true;
618 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
620 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
621 << Filename.c_str());
626 * \brief closes the file
627 * @return TRUE if the close was successfull
629 bool Document::CloseFile()
641 * \brief Writes in a file all the Header Entries (Dicom Elements)
642 * @param fp file pointer on an already open file (actually: Output File Stream)
643 * @param filetype Type of the File to be written
644 * (ACR-NEMA, ExplicitVR, ImplicitVR)
645 * @return Always true.
647 void Document::WriteContent(std::ofstream *fp, FileType filetype)
649 // \TODO move the following lines (and a lot of others, to be written)
650 // to a future function CheckAndCorrectHeader
652 // (necessary if user wants to write a DICOM V3 file
653 // starting from an ACR-NEMA (V2) Header
655 if ( filetype == ImplicitVR || filetype == ExplicitVR )
657 // writing Dicom File Preamble
658 char filePreamble[128];
659 memset(filePreamble, 0, 128);
660 fp->write(filePreamble, 128);
661 fp->write("DICM", 4);
665 * \todo rewrite later, if really usefull
666 * - 'Group Length' element is optional in DICOM
667 * - but un-updated odd groups lengthes can causes pb
670 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
671 * UpdateGroupLength(false,filetype);
672 * if ( filetype == ACR)
673 * UpdateGroupLength(true,ACR);
676 ElementSet::WriteContent(fp, filetype); // This one is recursive
679 // -----------------------------------------
682 * \brief Loads (from disk) the element content
683 * when a string is not suitable
684 * @param group group number of the Entry
685 * @param elem element number of the Entry
687 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
689 // Search the corresponding DocEntry
690 DocEntry *docElement = GetDocEntry(group, elem);
694 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
698 LoadEntryBinArea(binElement);
702 * \brief Loads (from disk) the element content
703 * when a string is not suitable
704 * @param elem Entry whose binArea is going to be loaded
706 void Document::LoadEntryBinArea(BinEntry *elem)
708 if (elem->GetBinArea() )
715 size_t o =(size_t)elem->GetOffset();
716 Fp->seekg(o, std::ios::beg);
718 size_t l = elem->GetLength();
719 uint8_t *a = new uint8_t[l];
722 gdcmWarningMacro( "Cannot allocate BinEntry content for : "
723 << std::hex << elem->GetGroup()
724 << "|" << elem->GetElement() );
728 Fp->read((char*)a, l);
729 if ( Fp->fail() || Fp->eof() )
742 * \brief Loads the element while preserving the current
743 * underlying file position indicator as opposed to
744 * LoadDocEntry that modifies it.
745 * @param entry DocEntry whose value will be loaded.
747 void Document::LoadDocEntrySafe(DocEntry *entry)
751 long PositionOnEntry = Fp->tellg();
753 Fp->seekg(PositionOnEntry, std::ios::beg);
758 * \brief Compares two documents, according to \ref DicomDir rules
759 * \warning Does NOT work with ACR-NEMA files
760 * \todo Find a trick to solve the pb (use RET fields ?)
761 * @param document to compare with current one
762 * @return true if 'smaller'
764 bool Document::operator<(Document &document)
767 std::string s1 = GetEntryValue(0x0010,0x0010);
768 std::string s2 = document.GetEntryValue(0x0010,0x0010);
780 s1 = GetEntryValue(0x0010,0x0020);
781 s2 = document.GetEntryValue(0x0010,0x0020);
792 // Study Instance UID
793 s1 = GetEntryValue(0x0020,0x000d);
794 s2 = document.GetEntryValue(0x0020,0x000d);
805 // Serie Instance UID
806 s1 = GetEntryValue(0x0020,0x000e);
807 s2 = document.GetEntryValue(0x0020,0x000e);
822 //-----------------------------------------------------------------------------
825 * \brief Reads a supposed to be 16 Bits integer
826 * (swaps it depending on processor endianness)
829 uint16_t Document::ReadInt16()
833 Fp->read ((char*)&g, (size_t)2);
836 throw FormatError( "Document::ReadInt16()", " file error." );
840 throw FormatError( "Document::ReadInt16()", "EOF." );
847 * \brief Reads a supposed to be 32 Bits integer
848 * (swaps it depending on processor endianness)
851 uint32_t Document::ReadInt32()
855 Fp->read ((char*)&g, (size_t)4);
858 throw FormatError( "Document::ReadInt32()", " file error." );
862 throw FormatError( "Document::ReadInt32()", "EOF." );
869 * \brief skips bytes inside the source file
870 * \warning NOT end user intended method !
873 void Document::SkipBytes(uint32_t nBytes)
875 //FIXME don't dump the returned value
876 Fp->seekg((long)nBytes, std::ios::cur);
880 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
881 * @param filetype Type of the File to be written
883 int Document::ComputeGroup0002Length( FileType filetype )
889 bool found0002 = false;
891 // for each zero-level Tag in the DCM Header
892 DocEntry *entry = GetFirstEntry();
895 gr = entry->GetGroup();
901 if ( entry->GetElement() != 0x0000 )
905 if ( filetype == ExplicitVR )
907 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
909 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
913 groupLength += 2 + 2 + 4 + entry->GetLength();
919 entry = GetNextEntry();
924 //-----------------------------------------------------------------------------
927 * \brief Loads all the needed Dictionaries
928 * \warning NOT end user intended method !
930 void Document::Initialize()
932 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
938 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
939 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
940 * @param offset start of parsing
941 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
942 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
944 void Document::ParseDES(DocEntrySet *set, long offset,
945 long l_max, bool delim_mode)
947 DocEntry *newDocEntry;
948 ValEntry *newValEntry;
949 BinEntry *newBinEntry;
950 SeqEntry *newSeqEntry;
953 bool delim_mode_intern = delim_mode;
957 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
962 newDocEntry = ReadNextDocEntry( );
964 // Uncoment this printf line to be able to 'follow' the DocEntries
965 // when something *very* strange happens
967 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
968 // newDocEntry->GetElement(),
969 // newDocEntry->GetVR().c_str() );
976 // an Item Starter found elsewhere but the first postition
977 // of a SeqEntry means previous entry was a Sequence
978 // but we didn't get it (private Sequence + Implicit VR)
979 // we have to backtrack.
980 if ( !first && newDocEntry->IsItemStarter() )
982 newDocEntry = Backtrack(newDocEntry);
986 PreviousDocEntry = newDocEntry;
990 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
991 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
993 if ( newValEntry || newBinEntry )
995 //////////////////////////// ContentEntry
998 vr = newDocEntry->GetVR();
999 if ( Filetype == ExplicitVR &&
1000 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1002 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1003 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
1004 << "|" << newDocEntry->GetElement()
1005 << " : Neither Valentry, nor BinEntry."
1006 "Probably unknown VR.");
1009 //////////////////// BinEntry or UNKOWN VR:
1011 // When "this" is a Document the Key is simply of the
1012 // form ( group, elem )...
1013 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1015 // newBinEntry->SetKey( newBinEntry->GetKey() );
1017 // but when "this" is a SQItem, we are inserting this new
1018 // valEntry in a sequence item, and the key has the
1019 // generalized form (refer to \ref BaseTagKey):
1021 // time waste hunting
1022 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1024 // newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1025 // + newBinEntry->GetKey() );
1028 if ( !set->AddEntry( newBinEntry ) )
1030 gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
1031 << newBinEntry->GetKey()
1033 << newBinEntry->GetOffset() << " )" );
1038 // Load only if we can add (not a duplicate key)
1039 LoadDocEntry( newBinEntry );
1044 /////////////////////// ValEntry
1046 // When "set" is a Document, then we are at the top of the
1047 // hierarchy and the Key is simply of the form ( group, elem )...
1048 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1050 // newValEntry->SetKey( newValEntry->GetKey() );
1052 // ...but when "set" is a SQItem, we are inserting this new
1053 // valEntry in a sequence item. Hence the key has the
1054 // generalized form (refer to \ref BaseTagKey):
1056 // time waste hunting
1057 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1059 // newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1060 // + newValEntry->GetKey() );
1063 if ( !set->AddEntry( newValEntry ) )
1065 gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
1066 << newValEntry->GetKey()
1068 << newValEntry->GetOffset() << " )" );
1073 // Load only if we can add (not a duplicate key)
1074 LoadDocEntry( newValEntry );
1077 if ( newValEntry->GetElement() == 0x0000 ) // if on group length
1079 if ( newValEntry->GetGroup()%2 != 0 ) // if Shadow Group
1081 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1083 std::string strLgrGroup = newValEntry->GetValue();
1085 if ( strLgrGroup != GDCM_UNFOUND)
1087 lgrGroup = atoi(strLgrGroup.c_str());
1088 Fp->seekg(lgrGroup, std::ios::cur);
1090 RemoveEntry( newDocEntry );
1098 bool delimitor=newValEntry->IsItemDelimitor();
1101 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1109 // Just to make sure we are at the beginning of next entry.
1110 SkipToNextDocEntry(newDocEntry);
1114 /////////////////////// SeqEntry : VR = "SQ"
1116 unsigned long l = newDocEntry->GetReadLength();
1117 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1119 if ( l == 0xffffffff )
1121 delim_mode_intern = true;
1125 delim_mode_intern = false;
1129 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1131 // User asked to skip SeQuences *only* if they belong to Shadow Group
1132 if ( newDocEntry->GetGroup()%2 != 0 )
1134 Fp->seekg( l, std::ios::cur);
1139 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1141 // User asked to skip *any* SeQuence
1142 Fp->seekg( l, std::ios::cur);
1146 // delay the dynamic cast as late as possible
1147 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1149 // no other way to create the Delimitor ...
1150 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1152 // At the top of the hierarchy, stands a Document. When "set"
1153 // is a Document, then we are building the first depth level.
1154 // Hence the SeqEntry we are building simply has a depth
1156 // SQItem *parentSQItem = dynamic_cast< SQItem* > ( set );
1157 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1159 newSeqEntry->SetDepthLevel( 1 );
1160 // newSeqEntry->SetKey( newSeqEntry->GetKey() );
1162 // But when "set" is already a SQItem, we are building a nested
1163 // sequence, and hence the depth level of the new SeqEntry
1164 // we are building, is one level deeper:
1166 // time waste hunting
1167 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1169 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1171 // newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1172 // + newSeqEntry->GetKey() );
1176 { // Don't try to parse zero-length sequences
1177 ParseSQ( newSeqEntry,
1178 newDocEntry->GetOffset(),
1179 l, delim_mode_intern);
1181 if ( !set->AddEntry( newSeqEntry ) )
1183 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1184 << newSeqEntry->GetKey()
1186 << newSeqEntry->GetOffset() << " )" );
1190 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1196 } // end SeqEntry : VR = "SQ"
1207 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1208 * @return parsed length for this level
1210 void Document::ParseSQ( SeqEntry *seqEntry,
1211 long offset, long l_max, bool delim_mode)
1213 int SQItemNumber = 0;
1215 long offsetStartCurrentSQItem = offset;
1219 // the first time, we read the fff0,e000 of the first SQItem
1220 DocEntry *newDocEntry = ReadNextDocEntry();
1224 // FIXME Should warn user
1225 gdcmWarningMacro("in ParseSQ : should never get here!");
1230 if ( newDocEntry->IsSequenceDelimitor() )
1232 seqEntry->SetDelimitationItem( newDocEntry );
1236 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1241 // create the current SQItem
1242 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1244 std::ostringstream newBase;
1245 newBase << seqEntry->GetKey()
1249 itemSQ->SetBaseTagKey( newBase.str() );
1251 unsigned int l = newDocEntry->GetReadLength();
1253 if ( l == 0xffffffff )
1262 // Let's try :------------
1263 // remove fff0,e000, created out of the SQItem
1265 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1266 // fill up the current SQItem, starting at the beginning of fff0,e000
1268 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1270 offsetStartCurrentSQItem = Fp->tellg();
1271 // end try -----------------
1273 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1275 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1283 * \brief When a private Sequence + Implicit VR is encountered
1284 * we cannot guess it's a Sequence till we find the first
1285 * Item Starter. We then backtrack to do the job.
1286 * @param docEntry Item Starter that warned us
1288 DocEntry *Document::Backtrack(DocEntry *docEntry)
1290 // delete the Item Starter, built erroneously out of any Sequence
1291 // it's not yet in the HTable/chained list
1294 // Get all info we can from PreviousDocEntry
1295 uint16_t group = PreviousDocEntry->GetGroup();
1296 uint16_t elem = PreviousDocEntry->GetElement();
1297 uint32_t lgt = PreviousDocEntry->GetLength();
1298 long offset = PreviousDocEntry->GetOffset();
1300 gdcmWarningMacro( "Backtrack :" << std::hex << group
1302 << " at offset " << offset );
1303 RemoveEntry( PreviousDocEntry );
1305 // forge the Seq Entry
1306 DocEntry *newEntry = NewSeqEntry(group, elem);
1307 newEntry->SetLength(lgt);
1308 newEntry->SetOffset(offset);
1310 // Move back to the beginning of the Sequence
1311 Fp->seekg( 0, std::ios::beg);
1312 Fp->seekg(offset, std::ios::cur);
1318 * \brief Loads (or not) the element content depending if its length exceeds
1319 * or not the value specified with Document::SetMaxSizeLoadEntry()
1320 * @param entry Header Entry (Dicom Element) to be dealt with
1321 * @param forceLoad wheter we want to load its content even if its length
1322 * exceeds the value specified with Document::SetMaxSizeLoadEntry()
1324 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1326 uint16_t group = entry->GetGroup();
1327 std::string vr = entry->GetVR();
1328 uint32_t length = entry->GetLength();
1330 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1332 // A SeQuence "contains" a set of Elements.
1333 // (fffe e000) tells us an Element is beginning
1334 // (fffe e00d) tells us an Element just ended
1335 // (fffe e0dd) tells us the current SeQuence just ended
1336 if ( group == 0xfffe )
1338 // NO more value field for SQ !
1342 // When the length is zero things are easy:
1345 ((ValEntry *)entry)->SetValue("");
1349 // The elements whose length is bigger than the specified upper bound
1350 // are not loaded. Instead we leave a short notice on the offset of
1351 // the element content and it's length.
1353 std::ostringstream s;
1357 if (length > MaxSizeLoadEntry)
1359 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1361 s << GDCM_NOTLOADED;
1362 s << " Ad.:" << (long)entry->GetOffset();
1363 s << " x(" << std::hex << entry->GetOffset() << ")";
1365 s << " Lgt:" << entry->GetLength();
1366 s << " x(" << std::hex << entry->GetLength() << ")";
1367 binEntryPtr->SetValue(s.str());
1369 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1371 s << GDCM_NOTLOADED;
1372 s << " Address:" << (long)entry->GetOffset();
1373 s << " Length:" << entry->GetLength();
1374 s << " x(" << std::hex << entry->GetLength() << ")";
1375 valEntryPtr->SetValue(s.str());
1380 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1381 << "nor a ValEntry ?! Should never print that !" );
1384 // to be sure we are at the end of the value ...
1385 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1391 // When we find a BinEntry not very much can be done :
1392 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1394 s << GDCM_BINLOADED;
1395 binEntryPtr->SetValue(s.str());
1396 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1400 if ( IsDocEntryAnInteger(entry) )
1404 // When short integer(s) are expected, read and convert the following
1405 // (n * 2) characters properly i.e. consider them as short integers as
1406 // opposed to strings.
1407 // Elements with Value Multiplicity > 1
1408 // contain a set of integers (not a single one)
1409 if (vr == "US" || vr == "SS")
1412 NewInt = ReadInt16();
1416 for (int i=1; i < nbInt; i++)
1419 NewInt = ReadInt16();
1424 // See above comment on multiple integers (mutatis mutandis).
1425 else if (vr == "UL" || vr == "SL")
1428 NewInt = ReadInt32();
1432 for (int i=1; i < nbInt; i++)
1435 NewInt = ReadInt32();
1440 #ifdef GDCM_NO_ANSI_STRING_STREAM
1441 s << std::ends; // to avoid oddities on Solaris
1442 #endif //GDCM_NO_ANSI_STRING_STREAM
1444 ((ValEntry *)entry)->SetValue(s.str());
1448 // FIXME: We need an additional byte for storing \0 that is not on disk
1449 char *str = new char[length+1];
1450 Fp->read(str, (size_t)length);
1451 str[length] = '\0'; //this is only useful when length is odd
1452 // Special DicomString call to properly handle \0 and even length
1453 std::string newValue;
1456 newValue = Util::DicomString(str, length+1);
1457 gdcmWarningMacro("Warning: bad length: " << length <<
1458 " For string :" << newValue.c_str());
1459 // Since we change the length of string update it length
1460 //entry->SetReadLength(length+1);
1464 newValue = Util::DicomString(str, length);
1468 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1470 if ( Fp->fail() || Fp->eof())
1473 gdcmWarningMacro("--> fail");
1475 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1476 << " lgt : " << valEntry->GetReadLength()
1477 << " at " << std::hex << valEntry->GetOffset());
1478 valEntry->SetValue(GDCM_UNREAD);
1484 // Because of correspondance with the VR dic
1485 valEntry->SetValue(newValue);
1489 valEntry->SetValue(newValue);
1494 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1495 << " lgt : " << valEntry->GetReadLength()
1496 << " at " << std::hex << valEntry->GetOffset());
1501 * \brief Find the value Length of the passed Header Entry
1502 * @param entry Header Entry whose length of the value shall be loaded.
1504 void Document::FindDocEntryLength( DocEntry *entry )
1505 throw ( FormatError )
1507 std::string vr = entry->GetVR();
1510 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1512 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1514 // The following reserved two bytes (see PS 3.5-2003, section
1515 // "7.1.2 Data element structure with explicit vr", p 27) must be
1516 // skipped before proceeding on reading the length on 4 bytes.
1517 Fp->seekg( 2L, std::ios::cur);
1518 uint32_t length32 = ReadInt32();
1520 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1525 lengthOB = FindDocEntryLengthOBOrOW();
1527 catch ( FormatUnexpected )
1529 // Computing the length failed (this happens with broken
1530 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1531 // chance to get the pixels by deciding the element goes
1532 // until the end of the file. Hence we artificially fix the
1533 // the length and proceed.
1534 long currentPosition = Fp->tellg();
1535 Fp->seekg(0L,std::ios::end);
1537 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1538 Fp->seekg(currentPosition, std::ios::beg);
1540 entry->SetReadLength(lengthUntilEOF);
1541 entry->SetLength(lengthUntilEOF);
1544 entry->SetReadLength(lengthOB);
1545 entry->SetLength(lengthOB);
1548 FixDocEntryFoundLength(entry, length32);
1552 // Length is encoded on 2 bytes.
1553 length16 = ReadInt16();
1555 // 0xffff means that we deal with 'No Length' Sequence
1556 // or 'No Length' SQItem
1557 if ( length16 == 0xffff)
1561 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1566 // Either implicit VR or a non DICOM conformal (see note below) explicit
1567 // VR that ommited the VR of (at least) this element. Farts happen.
1568 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1569 // on Data elements "Implicit and Explicit VR Data Elements shall
1570 // not coexist in a Data Set and Data Sets nested within it".]
1571 // Length is on 4 bytes.
1573 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1574 // even if Transfer Syntax is 'Implicit VR ...'
1576 FixDocEntryFoundLength( entry, ReadInt32() );
1582 * \brief Find the Length till the next sequence delimiter
1583 * \warning NOT end user intended method !
1586 uint32_t Document::FindDocEntryLengthOBOrOW()
1587 throw( FormatUnexpected )
1589 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1590 long positionOnEntry = Fp->tellg();
1591 bool foundSequenceDelimiter = false;
1592 uint32_t totalLength = 0;
1594 while ( !foundSequenceDelimiter )
1600 group = ReadInt16();
1603 catch ( FormatError )
1605 throw FormatError("Unexpected end of file encountered during ",
1606 "Document::FindDocEntryLengthOBOrOW()");
1608 // We have to decount the group and element we just read
1610 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1612 long filePosition = Fp->tellg();
1614 "Neither an Item tag nor a Sequence delimiter tag on :"
1615 << std::hex << group << " , " << elem
1616 << ") -before- position x(" << filePosition << ")" );
1618 Fp->seekg(positionOnEntry, std::ios::beg);
1619 throw FormatUnexpected(
1620 "Neither an Item tag nor a Sequence delimiter tag.");
1622 if ( elem == 0xe0dd )
1624 foundSequenceDelimiter = true;
1626 uint32_t itemLength = ReadInt32();
1627 // We add 4 bytes since we just read the ItemLength with ReadInt32
1628 totalLength += itemLength + 4;
1629 SkipBytes(itemLength);
1631 if ( foundSequenceDelimiter )
1636 Fp->seekg( positionOnEntry, std::ios::beg);
1641 * \brief Find the Value Representation of the current Dicom Element.
1642 * @return Value Representation of the current Entry
1644 std::string Document::FindDocEntryVR()
1646 if ( Filetype != ExplicitVR )
1647 return GDCM_UNKNOWN;
1649 long positionOnEntry = Fp->tellg();
1650 // Warning: we believe this is explicit VR (Value Representation) because
1651 // we used a heuristic that found "UL" in the first tag. Alas this
1652 // doesn't guarantee that all the tags will be in explicit VR. In some
1653 // cases (see e-film filtered files) one finds implicit VR tags mixed
1654 // within an explicit VR file. Hence we make sure the present tag
1655 // is in explicit VR and try to fix things if it happens not to be
1659 Fp->read (vr, (size_t)2);
1662 if ( !CheckDocEntryVR(vr) )
1664 Fp->seekg(positionOnEntry, std::ios::beg);
1665 return GDCM_UNKNOWN;
1671 * \brief Check the correspondance between the VR of the header entry
1672 * and the taken VR. If they are different, the header entry is
1673 * updated with the new VR.
1674 * @param vr Dicom Value Representation
1675 * @return false if the VR is incorrect of if the VR isn't referenced
1676 * otherwise, it returns true
1678 bool Document::CheckDocEntryVR(VRKey vr)
1680 if ( !Global::GetVR()->IsValidVR(vr) )
1687 * \brief Get the transformed value of the header entry. The VR value
1688 * is used to define the transformation to operate on the value
1689 * \warning NOT end user intended method !
1690 * @param entry entry to tranform
1691 * @return Transformed entry value
1693 std::string Document::GetDocEntryValue(DocEntry *entry)
1695 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1697 std::string val = ((ValEntry *)entry)->GetValue();
1698 std::string vr = entry->GetVR();
1699 uint32_t length = entry->GetLength();
1700 std::ostringstream s;
1703 // When short integer(s) are expected, read and convert the following
1704 // n * 2 bytes properly i.e. as a multivaluated strings
1705 // (each single value is separated fromthe next one by '\'
1706 // as usual for standard multivaluated filels
1707 // Elements with Value Multiplicity > 1
1708 // contain a set of short integers (not a single one)
1710 if ( vr == "US" || vr == "SS" )
1715 for (int i=0; i < nbInt; i++)
1721 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1722 newInt16 = SwapShort( newInt16 );
1727 // When integer(s) are expected, read and convert the following
1728 // n * 4 bytes properly i.e. as a multivaluated strings
1729 // (each single value is separated fromthe next one by '\'
1730 // as usual for standard multivaluated filels
1731 // Elements with Value Multiplicity > 1
1732 // contain a set of integers (not a single one)
1733 else if ( vr == "UL" || vr == "SL" )
1738 for (int i=0; i < nbInt; i++)
1744 newInt32 = ( val[4*i+0] & 0xFF )
1745 + (( val[4*i+1] & 0xFF ) << 8 )
1746 + (( val[4*i+2] & 0xFF ) << 16 )
1747 + (( val[4*i+3] & 0xFF ) << 24 );
1748 newInt32 = SwapLong( newInt32 );
1752 #ifdef GDCM_NO_ANSI_STRING_STREAM
1753 s << std::ends; // to avoid oddities on Solaris
1754 #endif //GDCM_NO_ANSI_STRING_STREAM
1757 return ((ValEntry *)entry)->GetValue();
1761 * \brief Get the reverse transformed value of the header entry. The VR
1762 * value is used to define the reverse transformation to operate on
1764 * \warning NOT end user intended method !
1765 * @param entry Entry to reverse transform
1766 * @return Reverse transformed entry value
1768 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1770 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1772 std::string vr = entry->GetVR();
1773 std::vector<std::string> tokens;
1774 std::ostringstream s;
1776 if ( vr == "US" || vr == "SS" )
1780 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1781 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1782 for (unsigned int i=0; i<tokens.size(); i++)
1784 newInt16 = atoi(tokens[i].c_str());
1785 s << ( newInt16 & 0xFF )
1786 << (( newInt16 >> 8 ) & 0xFF );
1790 if ( vr == "UL" || vr == "SL")
1794 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1795 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1796 for (unsigned int i=0; i<tokens.size();i++)
1798 newInt32 = atoi(tokens[i].c_str());
1799 s << (char)( newInt32 & 0xFF )
1800 << (char)(( newInt32 >> 8 ) & 0xFF )
1801 << (char)(( newInt32 >> 16 ) & 0xFF )
1802 << (char)(( newInt32 >> 24 ) & 0xFF );
1807 #ifdef GDCM_NO_ANSI_STRING_STREAM
1808 s << std::ends; // to avoid oddities on Solaris
1809 #endif //GDCM_NO_ANSI_STRING_STREAM
1813 return ((ValEntry *)entry)->GetValue();
1817 * \brief Skip a given Header Entry
1818 * \warning NOT end user intended method !
1819 * @param entry entry to skip
1821 void Document::SkipDocEntry(DocEntry *entry)
1823 SkipBytes(entry->GetLength());
1827 * \brief Skips to the beginning of the next Header Entry
1828 * \warning NOT end user intended method !
1829 * @param currentDocEntry entry to skip
1831 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1833 int l = currentDocEntry->GetReadLength();
1834 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1835 // ... but PMS imagers happen !
1837 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1838 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1840 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1845 * \brief When the length of an element value is obviously wrong (because
1846 * the parser went Jabberwocky) one can hope improving things by
1847 * applying some heuristics.
1848 * @param entry entry to check
1849 * @param foundLength first assumption about length
1851 void Document::FixDocEntryFoundLength(DocEntry *entry,
1852 uint32_t foundLength)
1854 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1855 if ( foundLength == 0xffffffff)
1860 uint16_t gr = entry->GetGroup();
1861 uint16_t elem = entry->GetElement();
1863 if ( foundLength % 2)
1865 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1866 << " in x(" << std::hex << gr << "," << elem <<")");
1869 //////// Fix for some naughty General Electric images.
1870 // Allthough not recent many such GE corrupted images are still present
1871 // on Creatis hard disks. Hence this fix shall remain when such images
1872 // are no longer in use (we are talking a few years, here)...
1873 // Note: XMedCon probably uses such a trick since it is able to read
1874 // those pesky GE images ...
1875 if ( foundLength == 13)
1877 // Only happens for this length !
1878 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1881 entry->SetReadLength(10); // a bug is to be fixed !?
1885 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1886 // Occurence of such images is quite low (unless one leaves close to a
1887 // 'Leonardo' source. Hence, one might consider commenting out the
1888 // following fix on efficiency reasons.
1889 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1892 entry->SetReadLength(4); // a bug is to be fixed !?
1895 else if ( entry->GetVR() == "SQ" )
1897 foundLength = 0; // ReadLength is unchanged
1900 //////// We encountered a 'delimiter' element i.e. a tag of the form
1901 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1902 // taken into account.
1903 else if ( gr == 0xfffe )
1905 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1906 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1907 // causes extra troubles...
1908 if ( entry->GetElement() != 0x0000 )
1913 entry->SetLength(foundLength);
1917 * \brief Apply some heuristics to predict whether the considered
1918 * element value contains/represents an integer or not.
1919 * @param entry The element value on which to apply the predicate.
1920 * @return The result of the heuristical predicate.
1922 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1924 uint16_t elem = entry->GetElement();
1925 uint16_t group = entry->GetGroup();
1926 const std::string &vr = entry->GetVR();
1927 uint32_t length = entry->GetLength();
1929 // When we have some semantics on the element we just read, and if we
1930 // a priori know we are dealing with an integer, then we shall be
1931 // able to swap it's element value properly.
1932 if ( elem == 0 ) // This is the group length of the group
1940 // Allthough this should never happen, still some images have a
1941 // corrupted group length [e.g. have a glance at offset x(8336) of
1942 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1943 // Since for dicom compliant and well behaved headers, the present
1944 // test is useless (and might even look a bit paranoid), when we
1945 // encounter such an ill-formed image, we simply display a warning
1946 // message and proceed on parsing (while crossing fingers).
1947 long filePosition = Fp->tellg();
1948 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1949 << std::hex << group << " , " << elem
1950 << ") -before- position x(" << filePosition << ")"
1951 << "lgt : " << length );
1955 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1963 * \brief Discover what the swap code is (among little endian, big endian,
1964 * bad little endian, bad big endian).
1966 * @return false when we are absolutely sure
1967 * it's neither ACR-NEMA nor DICOM
1968 * true when we hope ours assuptions are OK
1970 bool Document::CheckSwap()
1977 // First, compare HostByteOrder and NetworkByteOrder in order to
1978 // determine if we shall need to swap bytes (i.e. the Endian type).
1979 bool net2host = Util::IsCurrentProcessorBigEndian();
1981 // The easiest case is the one of a 'true' DICOM header, we just have
1982 // to look for the string "DICM" inside the file preamble.
1985 char *entCur = deb + 128;
1986 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1988 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1990 // Group 0002 should always be VR, and the first element 0000
1991 // Let's be carefull (so many wrong headers ...)
1992 // and determine the value representation (VR) :
1993 // Let's skip to the first element (0002,0000) and check there if we find
1994 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1995 // in which case we (almost) know it is explicit VR.
1996 // WARNING: if it happens to be implicit VR then what we will read
1997 // is the length of the group. If this ascii representation of this
1998 // length happens to be "UL" then we shall believe it is explicit VR.
1999 // We need to skip :
2000 // * the 128 bytes of File Preamble (often padded with zeroes),
2001 // * the 4 bytes of "DICM" string,
2002 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2003 // i.e. a total of 136 bytes.
2006 // group 0x0002 *is always* Explicit VR Sometimes ,
2007 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2008 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2010 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2011 memcmp(entCur, "OB", (size_t)2) == 0 ||
2012 memcmp(entCur, "UI", (size_t)2) == 0 ||
2013 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2014 // when Write DCM *adds*
2016 // Use Document::dicom_vr to test all the possibilities
2017 // instead of just checking for UL, OB and UI !? group 0000
2019 Filetype = ExplicitVR;
2020 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2024 Filetype = ImplicitVR;
2025 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
2026 << "Looks like a bugged Header!");
2032 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
2037 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
2040 // Position the file position indicator at first tag
2041 // (i.e. after the file preamble and the "DICM" string).
2043 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
2045 Fp->seekg ( 132L, std::ios::beg);
2047 } // ------------------------------- End of DicomV3 ----------------
2049 // Alas, this is not a DicomV3 file and whatever happens there is no file
2050 // preamble. We can reset the file position indicator to where the data
2051 // is (i.e. the beginning of the file).
2053 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2055 Fp->seekg(0, std::ios::beg);
2057 // Let's check 'No Preamble Dicom File' :
2058 // Should start with group 0x0002
2059 // and be Explicit Value Representation
2061 s16 = *((uint16_t *)(deb));
2074 if ( SwapCode != 0 )
2076 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2077 memcmp(entCur, "OB", (size_t)2) == 0 ||
2078 memcmp(entCur, "UI", (size_t)2) == 0 ||
2079 memcmp(entCur, "SH", (size_t)2) == 0 ||
2080 memcmp(entCur, "AE", (size_t)2) == 0 ||
2081 memcmp(entCur, "OB", (size_t)2) == 0 )
2083 Filetype = ExplicitVR;
2084 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2088 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2090 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2091 // By clean we mean that the length of the first group is written down.
2092 // If this is the case and since the length of the first group HAS to be
2093 // four (bytes), then determining the proper swap code is straightforward.
2096 // We assume the array of char we are considering contains the binary
2097 // representation of a 32 bits integer. Hence the following dirty
2099 s32 = *((uint32_t *)(entCur));
2119 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2120 // It is time for despaired wild guesses.
2121 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2122 // i.e. the 'group length' element is not present :
2124 // check the supposed-to-be 'group number'
2125 // in ( 0x0001 .. 0x0008 )
2126 // to determine ' SwapCode' value .
2127 // Only 0 or 4321 will be possible
2128 // (no oportunity to check for the formerly well known
2129 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2130 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2131 // the file IS NOT ACR-NEMA nor DICOM V3
2132 // Find a trick to tell it the caller...
2134 s16 = *((uint16_t *)(deb));
2161 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2169 * \brief Change the Byte Swap code.
2171 void Document::SwitchByteSwapCode()
2173 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2174 << " at :" <<std::hex << Fp->tellg() );
2175 if ( SwapCode == 1234 )
2179 else if ( SwapCode == 4321 )
2183 else if ( SwapCode == 3412 )
2187 else if ( SwapCode == 2143 )
2194 * \brief during parsing, Header Elements too long are not loaded in memory
2195 * @param newSize new size
2197 void Document::SetMaxSizeLoadEntry(long newSize)
2203 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2205 MaxSizeLoadEntry = 0xffffffff;
2208 MaxSizeLoadEntry = newSize;
2212 * \brief Read the next tag WITHOUT loading it's value
2213 * (read the 'Group Number', the 'Element Number',
2214 * gets the Dict Entry
2215 * gets the VR, gets the length, gets the offset value)
2216 * @return On succes : the newly created DocEntry, NULL on failure.
2218 DocEntry *Document::ReadNextDocEntry()
2225 group = ReadInt16();
2228 catch ( FormatError e )
2230 // We reached the EOF (or an error occured) therefore
2231 // header parsing has to be considered as finished.
2235 // Sometimes file contains groups of tags with reversed endianess.
2236 HandleBrokenEndian(group, elem);
2238 // In 'true DICOM' files Group 0002 is always little endian
2239 if ( HasDCMPreamble )
2240 HandleOutOfGroup0002(group, elem);
2242 std::string vr = FindDocEntryVR();
2243 std::string realVR = vr;
2245 if ( vr == GDCM_UNKNOWN )
2247 if ( elem == 0x0000 ) // Group Length
2248 realVR = "UL"; // must be UL
2251 DictEntry *dictEntry = GetDictEntry(group,elem);
2254 realVR = dictEntry->GetVR();
2260 if ( Global::GetVR()->IsVROfSequence(realVR) )
2261 newEntry = NewSeqEntry(group, elem);
2262 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2263 newEntry = NewValEntry(group, elem,vr);
2265 newEntry = NewBinEntry(group, elem,vr);
2267 if ( vr == GDCM_UNKNOWN )
2269 if ( Filetype == ExplicitVR )
2271 // We thought this was explicit VR, but we end up with an
2272 // implicit VR tag. Let's backtrack.
2273 if ( newEntry->GetGroup() != 0xfffe )
2276 int offset = Fp->tellg();
2277 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2278 newEntry->GetGroup(), newEntry->GetElement(), offset );
2279 gdcmWarningMacro( msg.c_str() );
2282 newEntry->SetImplicitVR();
2287 FindDocEntryLength(newEntry);
2289 catch ( FormatError e )
2296 newEntry->SetOffset(Fp->tellg());
2302 * \brief Handle broken private tag from Philips NTSCAN
2303 * where the endianess is being switched to BigEndian
2304 * for no apparent reason
2307 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2309 // Endian reversion. Some files contain groups of tags with reversed endianess.
2310 static int reversedEndian = 0;
2311 // try to fix endian switching in the middle of headers
2312 if ((group == 0xfeff) && (elem == 0x00e0))
2314 // start endian swap mark for group found
2316 SwitchByteSwapCode();
2321 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2323 // end of reversed endian group
2325 SwitchByteSwapCode();
2330 * \brief Group 0002 is always coded Little Endian
2331 * whatever Transfer Syntax is
2334 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2336 // Endian reversion. Some files contain groups of tags with reversed endianess.
2337 if ( !Group0002Parsed && group != 0x0002)
2339 Group0002Parsed = true;
2340 // we just came out of group 0002
2341 // if Transfer syntax is Big Endian we have to change CheckSwap
2343 std::string ts = GetTransferSyntax();
2344 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2346 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2350 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2352 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2354 Filetype = ImplicitVR;
2357 // FIXME Strangely, this works with
2358 //'Implicit VR Transfer Syntax (GE Private)
2359 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2361 gdcmWarningMacro("Transfer Syntax Name = ["
2362 << GetTransferSyntaxName() << "]" );
2363 SwitchByteSwapCode();
2364 group = SwapShort(group);
2365 elem = SwapShort(elem);
2370 //-----------------------------------------------------------------------------
2373 //-----------------------------------------------------------------------------
2374 } // end namespace gdcm