1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/08/24 12:51:45 $
7 Version: $Revision: 1.268 $
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 = 0x00000000; // 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 = 0x00000000; // 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)
263 // ----------------------------
264 // Specific code to allow gdcm to read ACR-LibIDO formated images
265 // Note: ACR-LibIDO is an extension of the ACR standard that was
266 // used at CREATIS. For the time being (say a couple of years)
267 // we keep this kludge to allow CREATIS users
268 // reading their old images.
270 // if recognition code tells us we deal with a LibIDO image
271 // we switch lineNumber and columnNumber
274 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
275 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
276 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
277 // with "little-endian strings"
279 Filetype = ACR_LIBIDO;
280 std::string rows = GetEntryValue(0x0028, 0x0010);
281 std::string columns = GetEntryValue(0x0028, 0x0011);
282 SetValEntry(columns, 0x0028, 0x0010);
283 SetValEntry(rows , 0x0028, 0x0011);
285 // --- End of ACR-LibIDO kludge ---
291 * \brief Get the public dictionary used
293 Dict *Document::GetPubDict()
299 * \brief Get the shadow dictionary used
301 Dict *Document::GetShaDict()
307 * \brief Set the shadow dictionary used
308 * @param dict dictionary to use in shadow
310 bool Document::SetShaDict(Dict *dict)
317 * \brief Set the shadow dictionary used
318 * @param dictName name of the dictionary to use in shadow
320 bool Document::SetShaDict(DictKey const &dictName)
322 RefShaDict = Global::GetDicts()->GetDict(dictName);
327 * \brief This predicate tells us whether or not the current Document
328 * was properly parsed and contains at least *one* Dicom Element
329 * (and nothing more, sorry).
330 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
333 bool Document::IsReadable()
335 if ( Filetype == Unknown )
337 gdcmWarningMacro( "Wrong filetype");
343 gdcmWarningMacro( "No tag in internal hash table.");
351 * \brief Predicate for dicom version 3 file.
352 * @return True when the file is a dicom version 3.
354 bool Document::IsDicomV3()
356 // Checking if Transfer Syntax exists is enough
357 // Anyway, it's too late check if the 'Preamble' was found ...
358 // And ... would it be a rich idea to check ?
359 // (some 'no Preamble' DICOM images exist !)
360 return GetDocEntry(0x0002, 0x0010) != NULL;
364 * \brief Predicate for Papyrus file
365 * Dedicated to whomsoever it may concern
366 * @return True when the file is a Papyrus file.
368 bool Document::IsPapyrus()
370 // check for Papyrus private Sequence
371 DocEntry *e = GetDocEntry(0x0041, 0x1050);
374 // check if it's actually a Sequence
375 if ( !dynamic_cast<SeqEntry*>(e) )
381 * \brief returns the File Type
382 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
383 * @return the FileType code
385 FileType Document::GetFileType()
391 * \brief Accessor to the Transfer Syntax (when present) of the
392 * current document (it internally handles reading the
393 * value from disk when only parsing occured).
394 * @return The encountered Transfer Syntax of the current document.
396 std::string Document::GetTransferSyntax()
398 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
404 // The entry might be present but not loaded (parsing and loading
405 // happen at different stages): try loading and proceed with check...
406 LoadDocEntrySafe(entry);
407 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
409 std::string transfer = valEntry->GetValue();
410 // The actual transfer (as read from disk) might be padded. We
411 // first need to remove the potential padding. We can make the
412 // weak assumption that padding was not executed with digits...
413 if ( transfer.length() == 0 )
415 // for brain damaged headers
418 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
420 transfer.erase(transfer.length()-1, 1);
428 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
429 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
431 std::string Document::GetTransferSyntaxName()
433 // use the TS (TS : Transfer Syntax)
434 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
436 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
438 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
439 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
440 return "Uncompressed ACR-NEMA";
442 if ( transferSyntax == GDCM_UNFOUND )
444 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
445 return "Uncompressed ACR-NEMA";
448 // we do it only when we need it
449 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
451 // Global::GetTS() is a global static you shall never try to delete it!
455 // --------------- Swap Code ------------------
457 * \brief Swaps the bytes so they agree with the processor order
458 * @return The properly swaped 16 bits integer.
460 uint16_t Document::SwapShort(uint16_t a)
462 if ( SwapCode == 4321 || SwapCode == 2143 )
464 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
466 a = ( a << 8 ) | ( a >> 8 );
472 * \brief Swaps back the bytes of 4-byte long integer accordingly to
474 * @return The properly swaped 32 bits integer.
476 uint32_t Document::SwapLong(uint32_t a)
483 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
484 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
486 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
487 ((a>>8) & 0x0000ff00) | (a>>24) );
490 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
491 a=( (a<<16) | (a>>16) );
494 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
497 gdcmErrorMacro( "Unset swap code:" << SwapCode );
504 // -----------------File I/O ---------------
506 * \brief Tries to open the file \ref Document::Filename and
507 * checks the preamble when existing.
508 * @return The FILE pointer on success.
510 std::ifstream *Document::OpenFile()
512 HasDCMPreamble = false;
513 if (Filename.length() == 0)
520 gdcmWarningMacro( "File already open: " << Filename.c_str());
524 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
527 // Don't user gdcmErrorMacro :
528 // a spurious message will appear when you use, for instance
529 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
530 // to create outputFileName.
531 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
535 //exit(1); // No function is allowed to leave the application instead
536 // of warning the caller
540 Fp->read((char*)&zero, (size_t)2);
547 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
549 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
550 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
551 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
552 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
554 std::string msg = Util::Format(
555 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
556 gdcmWarningMacro( msg.c_str() );
561 Fp->seekg(126L, std::ios::cur);
562 char dicm[4] = {' ',' ',' ',' '};
563 Fp->read(dicm, (size_t)4);
569 if ( memcmp(dicm, "DICM", 4) == 0 )
571 HasDCMPreamble = true;
575 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
577 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
578 << Filename.c_str());
583 * \brief closes the file
584 * @return TRUE if the close was successfull
586 bool Document::CloseFile()
598 * \brief Writes in a file all the Header Entries (Dicom Elements)
599 * @param fp file pointer on an already open file (actually: Output File Stream)
600 * @param filetype Type of the File to be written
601 * (ACR-NEMA, ExplicitVR, ImplicitVR)
602 * @return Always true.
604 void Document::WriteContent(std::ofstream *fp, FileType filetype)
606 // \TODO move the following lines (and a lot of others, to be written)
607 // to a future function CheckAndCorrectHeader
609 // (necessary if user wants to write a DICOM V3 file
610 // starting from an ACR-NEMA (V2) Header
612 if ( filetype == ImplicitVR || filetype == ExplicitVR )
614 // writing Dicom File Preamble
615 char filePreamble[128];
616 memset(filePreamble, 0, 128);
617 fp->write(filePreamble, 128);
618 fp->write("DICM", 4);
622 * \todo rewrite later, if really usefull
623 * - 'Group Length' element is optional in DICOM
624 * - but un-updated odd groups lengthes can causes pb
627 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
628 * UpdateGroupLength(false,filetype);
629 * if ( filetype == ACR)
630 * UpdateGroupLength(true,ACR);
633 ElementSet::WriteContent(fp, filetype); // This one is recursive
636 // -----------------------------------------
639 * \brief Loads (from disk) the element content
640 * when a string is not suitable
641 * @param group group number of the Entry
642 * @param elem element number of the Entry
644 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
646 // Search the corresponding DocEntry
647 DocEntry *docElement = GetDocEntry(group, elem);
651 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
655 LoadEntryBinArea(binElement);
659 * \brief Loads (from disk) the element content
660 * when a string is not suitable
661 * @param elem Entry whose binArea is going to be loaded
663 void Document::LoadEntryBinArea(BinEntry *elem)
665 if (elem->GetBinArea() )
672 size_t o =(size_t)elem->GetOffset();
673 Fp->seekg(o, std::ios::beg);
675 size_t l = elem->GetLength();
676 uint8_t *a = new uint8_t[l];
679 gdcmWarningMacro( "Cannot allocate BinEntry content");
683 Fp->read((char*)a, l);
684 if ( Fp->fail() || Fp->eof() )
697 * \brief Loads the element while preserving the current
698 * underlying file position indicator as opposed to
699 * LoadDocEntry that modifies it.
700 * @param entry DocEntry whose value will be loaded.
702 void Document::LoadDocEntrySafe(DocEntry *entry)
706 long PositionOnEntry = Fp->tellg();
708 Fp->seekg(PositionOnEntry, std::ios::beg);
713 * \brief Compares two documents, according to \ref DicomDir rules
714 * \warning Does NOT work with ACR-NEMA files
715 * \todo Find a trick to solve the pb (use RET fields ?)
716 * @param document to compare with current one
717 * @return true if 'smaller'
719 bool Document::operator<(Document &document)
722 std::string s1 = GetEntryValue(0x0010,0x0010);
723 std::string s2 = document.GetEntryValue(0x0010,0x0010);
735 s1 = GetEntryValue(0x0010,0x0020);
736 s2 = document.GetEntryValue(0x0010,0x0020);
747 // Study Instance UID
748 s1 = GetEntryValue(0x0020,0x000d);
749 s2 = document.GetEntryValue(0x0020,0x000d);
760 // Serie Instance UID
761 s1 = GetEntryValue(0x0020,0x000e);
762 s2 = document.GetEntryValue(0x0020,0x000e);
777 //-----------------------------------------------------------------------------
780 * \brief Reads a supposed to be 16 Bits integer
781 * (swaps it depending on processor endianness)
784 uint16_t Document::ReadInt16()
788 Fp->read ((char*)&g, (size_t)2);
791 throw FormatError( "Document::ReadInt16()", " file error." );
795 throw FormatError( "Document::ReadInt16()", "EOF." );
802 * \brief Reads a supposed to be 32 Bits integer
803 * (swaps it depending on processor endianness)
806 uint32_t Document::ReadInt32()
810 Fp->read ((char*)&g, (size_t)4);
813 throw FormatError( "Document::ReadInt32()", " file error." );
817 throw FormatError( "Document::ReadInt32()", "EOF." );
824 * \brief skips bytes inside the source file
825 * \warning NOT end user intended method !
828 void Document::SkipBytes(uint32_t nBytes)
830 //FIXME don't dump the returned value
831 Fp->seekg((long)nBytes, std::ios::cur);
835 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
836 * @param filetype Type of the File to be written
838 int Document::ComputeGroup0002Length( FileType filetype )
844 bool found0002 = false;
846 // for each zero-level Tag in the DCM Header
847 DocEntry *entry = GetFirstEntry();
850 gr = entry->GetGroup();
856 if ( entry->GetElement() != 0x0000 )
860 if ( filetype == ExplicitVR )
862 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
864 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
868 groupLength += 2 + 2 + 4 + entry->GetLength();
874 entry = GetNextEntry();
879 //-----------------------------------------------------------------------------
882 * \brief Loads all the needed Dictionaries
883 * \warning NOT end user intended method !
885 void Document::Initialize()
887 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
893 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
894 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
895 * @param offset start of parsing
896 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
897 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
899 void Document::ParseDES(DocEntrySet *set, long offset,
900 long l_max, bool delim_mode)
902 DocEntry *newDocEntry;
903 ValEntry *newValEntry;
904 BinEntry *newBinEntry;
905 SeqEntry *newSeqEntry;
908 bool delim_mode_intern = delim_mode;
912 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
917 newDocEntry = ReadNextDocEntry( );
919 // Uncoment this printf line to be able to 'follow' the DocEntries
920 // when something *very* strange happens
922 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
923 // newDocEntry->GetElement(),
924 // newDocEntry->GetVR().c_str() );
931 // an Item Starter found elsewhere but the first postition
932 // of a SeqEntry means previous entry was a Sequence
933 // but we didn't get it (private Sequence + Implicit VR)
934 // we have to backtrack.
935 if ( !first && newDocEntry->IsItemStarter() )
937 newDocEntry = Backtrack(newDocEntry);
941 PreviousDocEntry = newDocEntry;
945 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
946 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
948 if ( newValEntry || newBinEntry )
950 //////////////////////////// ContentEntry
953 vr = newDocEntry->GetVR();
954 if ( Filetype == ExplicitVR &&
955 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
957 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
958 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
959 << "|" << newDocEntry->GetElement()
960 << " : Neither Valentry, nor BinEntry."
961 "Probably unknown VR.");
964 //////////////////// BinEntry or UNKOWN VR:
966 // When "this" is a Document the Key is simply of the
967 // form ( group, elem )...
968 if ( dynamic_cast< Document* > ( set ) )
970 newBinEntry->SetKey( newBinEntry->GetKey() );
972 // but when "this" is a SQItem, we are inserting this new
973 // valEntry in a sequence item, and the key has the
974 // generalized form (refer to \ref BaseTagKey):
976 // time waste hunting
977 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
979 // newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
980 // + newBinEntry->GetKey() );
983 if ( !set->AddEntry( newBinEntry ) )
985 gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
986 << newBinEntry->GetKey()
988 << newBinEntry->GetOffset() << " )" );
993 // Load only if we can add (not a duplicate key)
994 LoadDocEntry( newBinEntry );
999 /////////////////////// ValEntry
1001 // When "set" is a Document, then we are at the top of the
1002 // hierarchy and the Key is simply of the form ( group, elem )...
1003 if ( dynamic_cast< Document* > ( set ) )
1005 newValEntry->SetKey( newValEntry->GetKey() );
1007 // ...but when "set" is a SQItem, we are inserting this new
1008 // valEntry in a sequence item. Hence the key has the
1009 // generalized form (refer to \ref BaseTagKey):
1011 // time waste hunting
1012 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1014 // newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1015 // + newValEntry->GetKey() );
1018 if ( !set->AddEntry( newValEntry ) )
1020 gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
1021 << newValEntry->GetKey()
1023 << newValEntry->GetOffset() << " )" );
1028 // Load only if we can add (not a duplicate key)
1029 LoadDocEntry( newValEntry );
1032 if ( newValEntry->GetElement() == 0x0000 ) // if on group length
1034 if ( newValEntry->GetGroup()%2 != 0 ) // if Shadow Group
1036 if ( LoadMode & NO_SHADOW ) // if user asked to skip shad.gr
1038 std::string strLgrGroup = newValEntry->GetValue();
1040 if ( strLgrGroup != GDCM_UNFOUND)
1042 lgrGroup = atoi(strLgrGroup.c_str());
1043 Fp->seekg(lgrGroup, std::ios::cur);
1045 RemoveEntry( newDocEntry );
1053 bool delimitor=newValEntry->IsItemDelimitor();
1056 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1064 // Just to make sure we are at the beginning of next entry.
1065 SkipToNextDocEntry(newDocEntry);
1069 /////////////////////// SeqEntry : VR = "SQ"
1071 unsigned long l = newDocEntry->GetReadLength();
1072 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1074 if ( l == 0xffffffff )
1076 delim_mode_intern = true;
1080 delim_mode_intern = false;
1084 if ( (LoadMode & NO_SHADOWSEQ) && ! delim_mode_intern )
1086 // User asked to skip SeQuences *only* if they belong to Shadow Group
1087 if ( newDocEntry->GetGroup()%2 != 0 )
1089 Fp->seekg( l, std::ios::cur);
1094 if ( (LoadMode & NO_SEQ) && ! delim_mode_intern )
1096 // User asked to skip *any* SeQuence
1097 Fp->seekg( l, std::ios::cur);
1101 // delay the dynamic cast as late as possible
1102 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1104 // no other way to create the Delimitor ...
1105 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1107 // At the top of the hierarchy, stands a Document. When "set"
1108 // is a Document, then we are building the first depth level.
1109 // Hence the SeqEntry we are building simply has a depth
1111 if ( dynamic_cast< Document* > ( set ) )
1113 newSeqEntry->SetDepthLevel( 1 );
1114 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1116 // But when "set" is already a SQItem, we are building a nested
1117 // sequence, and hence the depth level of the new SeqEntry
1118 // we are building, is one level deeper:
1120 // time waste hunting
1121 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1123 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1125 // newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1126 // + newSeqEntry->GetKey() );
1130 { // Don't try to parse zero-length sequences
1131 ParseSQ( newSeqEntry,
1132 newDocEntry->GetOffset(),
1133 l, delim_mode_intern);
1135 if ( !set->AddEntry( newSeqEntry ) )
1137 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1138 << newSeqEntry->GetKey()
1140 << newSeqEntry->GetOffset() << " )" );
1144 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1150 } // end SeqEntry : VR = "SQ"
1161 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1162 * @return parsed length for this level
1164 void Document::ParseSQ( SeqEntry *seqEntry,
1165 long offset, long l_max, bool delim_mode)
1167 int SQItemNumber = 0;
1169 long offsetStartCurrentSQItem = offset;
1173 // the first time, we read the fff0,e000 of the first SQItem
1174 DocEntry *newDocEntry = ReadNextDocEntry();
1178 // FIXME Should warn user
1179 gdcmWarningMacro("in ParseSQ : should never get here!");
1184 if ( newDocEntry->IsSequenceDelimitor() )
1186 seqEntry->SetDelimitationItem( newDocEntry );
1190 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1195 // create the current SQItem
1196 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1198 std::ostringstream newBase;
1199 newBase << seqEntry->GetKey()
1203 itemSQ->SetBaseTagKey( newBase.str() );
1205 unsigned int l = newDocEntry->GetReadLength();
1207 if ( l == 0xffffffff )
1216 // Let's try :------------
1217 // remove fff0,e000, created out of the SQItem
1219 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1220 // fill up the current SQItem, starting at the beginning of fff0,e000
1222 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1224 offsetStartCurrentSQItem = Fp->tellg();
1225 // end try -----------------
1227 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1229 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1237 * \brief When a private Sequence + Implicit VR is encountered
1238 * we cannot guess it's a Sequence till we find the first
1239 * Item Starter. We then backtrack to do the job.
1240 * @param docEntry Item Starter that warned us
1242 DocEntry *Document::Backtrack(DocEntry *docEntry)
1244 // delete the Item Starter, built erroneously out of any Sequence
1245 // it's not yet in the HTable/chained list
1248 // Get all info we can from PreviousDocEntry
1249 uint16_t group = PreviousDocEntry->GetGroup();
1250 uint16_t elem = PreviousDocEntry->GetElement();
1251 uint32_t lgt = PreviousDocEntry->GetLength();
1252 long offset = PreviousDocEntry->GetOffset();
1254 gdcmWarningMacro( "Backtrack :" << std::hex << group
1256 << " at offset " << offset );
1257 RemoveEntry( PreviousDocEntry );
1259 // forge the Seq Entry
1260 DocEntry *newEntry = NewSeqEntry(group, elem);
1261 newEntry->SetLength(lgt);
1262 newEntry->SetOffset(offset);
1264 // Move back to the beginning of the Sequence
1265 Fp->seekg( 0, std::ios::beg);
1266 Fp->seekg(offset, std::ios::cur);
1272 * \brief Loads the element content if its length doesn't exceed
1273 * the value specified with Document::SetMaxSizeLoadEntry()
1274 * @param entry Header Entry (Dicom Element) to be dealt with
1276 void Document::LoadDocEntry(DocEntry *entry)
1278 uint16_t group = entry->GetGroup();
1279 std::string vr = entry->GetVR();
1280 uint32_t length = entry->GetLength();
1282 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1284 // A SeQuence "contains" a set of Elements.
1285 // (fffe e000) tells us an Element is beginning
1286 // (fffe e00d) tells us an Element just ended
1287 // (fffe e0dd) tells us the current SeQuence just ended
1288 if ( group == 0xfffe )
1290 // NO more value field for SQ !
1294 // When the length is zero things are easy:
1297 ((ValEntry *)entry)->SetValue("");
1301 // The elements whose length is bigger than the specified upper bound
1302 // are not loaded. Instead we leave a short notice on the offset of
1303 // the element content and it's length.
1305 std::ostringstream s;
1306 if (length > MaxSizeLoadEntry)
1308 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1310 s << GDCM_NOTLOADED;
1311 s << " Ad.:" << (long)entry->GetOffset();
1312 s << " x(" << std::hex << entry->GetOffset() << ")";
1314 s << " Lgt:" << entry->GetLength();
1315 s << " x(" << std::hex << entry->GetLength() << ")";
1316 binEntryPtr->SetValue(s.str());
1318 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1320 s << GDCM_NOTLOADED;
1321 s << " Address:" << (long)entry->GetOffset();
1322 s << " Length:" << entry->GetLength();
1323 s << " x(" << std::hex << entry->GetLength() << ")";
1324 valEntryPtr->SetValue(s.str());
1329 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1330 << "nor a ValEntry ?! Should never print that !" );
1333 // to be sure we are at the end of the value ...
1334 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1339 // When we find a BinEntry not very much can be done :
1340 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1342 s << GDCM_BINLOADED;
1343 binEntryPtr->SetValue(s.str());
1344 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1348 if ( IsDocEntryAnInteger(entry) )
1352 // When short integer(s) are expected, read and convert the following
1353 // (n * 2) characters properly i.e. consider them as short integers as
1354 // opposed to strings.
1355 // Elements with Value Multiplicity > 1
1356 // contain a set of integers (not a single one)
1357 if (vr == "US" || vr == "SS")
1360 NewInt = ReadInt16();
1364 for (int i=1; i < nbInt; i++)
1367 NewInt = ReadInt16();
1372 // See above comment on multiple integers (mutatis mutandis).
1373 else if (vr == "UL" || vr == "SL")
1376 NewInt = ReadInt32();
1380 for (int i=1; i < nbInt; i++)
1383 NewInt = ReadInt32();
1388 #ifdef GDCM_NO_ANSI_STRING_STREAM
1389 s << std::ends; // to avoid oddities on Solaris
1390 #endif //GDCM_NO_ANSI_STRING_STREAM
1392 ((ValEntry *)entry)->SetValue(s.str());
1396 // FIXME: We need an additional byte for storing \0 that is not on disk
1397 char *str = new char[length+1];
1398 Fp->read(str, (size_t)length);
1399 str[length] = '\0'; //this is only useful when length is odd
1400 // Special DicomString call to properly handle \0 and even length
1401 std::string newValue;
1404 newValue = Util::DicomString(str, length+1);
1405 gdcmWarningMacro("Warning: bad length: " << length <<
1406 " For string :" << newValue.c_str());
1407 // Since we change the length of string update it length
1408 //entry->SetReadLength(length+1);
1412 newValue = Util::DicomString(str, length);
1416 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1418 if ( Fp->fail() || Fp->eof())
1421 gdcmWarningMacro("--> fail");
1423 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1424 << " lgt : " << valEntry->GetReadLength()
1425 << " at " << std::hex << valEntry->GetOffset());
1426 valEntry->SetValue(GDCM_UNREAD);
1432 // Because of correspondance with the VR dic
1433 valEntry->SetValue(newValue);
1437 valEntry->SetValue(newValue);
1442 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1443 << " lgt : " << valEntry->GetReadLength()
1444 << " at " << std::hex << valEntry->GetOffset());
1449 * \brief Find the value Length of the passed Header Entry
1450 * @param entry Header Entry whose length of the value shall be loaded.
1452 void Document::FindDocEntryLength( DocEntry *entry )
1453 throw ( FormatError )
1455 std::string vr = entry->GetVR();
1458 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1460 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1462 // The following reserved two bytes (see PS 3.5-2003, section
1463 // "7.1.2 Data element structure with explicit vr", p 27) must be
1464 // skipped before proceeding on reading the length on 4 bytes.
1465 Fp->seekg( 2L, std::ios::cur);
1466 uint32_t length32 = ReadInt32();
1468 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1473 lengthOB = FindDocEntryLengthOBOrOW();
1475 catch ( FormatUnexpected )
1477 // Computing the length failed (this happens with broken
1478 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1479 // chance to get the pixels by deciding the element goes
1480 // until the end of the file. Hence we artificially fix the
1481 // the length and proceed.
1482 long currentPosition = Fp->tellg();
1483 Fp->seekg(0L,std::ios::end);
1485 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1486 Fp->seekg(currentPosition, std::ios::beg);
1488 entry->SetReadLength(lengthUntilEOF);
1489 entry->SetLength(lengthUntilEOF);
1492 entry->SetReadLength(lengthOB);
1493 entry->SetLength(lengthOB);
1496 FixDocEntryFoundLength(entry, length32);
1500 // Length is encoded on 2 bytes.
1501 length16 = ReadInt16();
1503 // 0xffff means that we deal with 'No Length' Sequence
1504 // or 'No Length' SQItem
1505 if ( length16 == 0xffff)
1509 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1514 // Either implicit VR or a non DICOM conformal (see note below) explicit
1515 // VR that ommited the VR of (at least) this element. Farts happen.
1516 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1517 // on Data elements "Implicit and Explicit VR Data Elements shall
1518 // not coexist in a Data Set and Data Sets nested within it".]
1519 // Length is on 4 bytes.
1521 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1522 // even if Transfer Syntax is 'Implicit VR ...'
1524 FixDocEntryFoundLength( entry, ReadInt32() );
1530 * \brief Find the Length till the next sequence delimiter
1531 * \warning NOT end user intended method !
1534 uint32_t Document::FindDocEntryLengthOBOrOW()
1535 throw( FormatUnexpected )
1537 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1538 long positionOnEntry = Fp->tellg();
1539 bool foundSequenceDelimiter = false;
1540 uint32_t totalLength = 0;
1542 while ( !foundSequenceDelimiter )
1548 group = ReadInt16();
1551 catch ( FormatError )
1553 throw FormatError("Unexpected end of file encountered during ",
1554 "Document::FindDocEntryLengthOBOrOW()");
1556 // We have to decount the group and element we just read
1558 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1560 long filePosition = Fp->tellg();
1562 "Neither an Item tag nor a Sequence delimiter tag on :"
1563 << std::hex << group << " , " << elem
1564 << ") -before- position x(" << filePosition << ")" );
1566 Fp->seekg(positionOnEntry, std::ios::beg);
1567 throw FormatUnexpected(
1568 "Neither an Item tag nor a Sequence delimiter tag.");
1570 if ( elem == 0xe0dd )
1572 foundSequenceDelimiter = true;
1574 uint32_t itemLength = ReadInt32();
1575 // We add 4 bytes since we just read the ItemLength with ReadInt32
1576 totalLength += itemLength + 4;
1577 SkipBytes(itemLength);
1579 if ( foundSequenceDelimiter )
1584 Fp->seekg( positionOnEntry, std::ios::beg);
1589 * \brief Find the Value Representation of the current Dicom Element.
1590 * @return Value Representation of the current Entry
1592 std::string Document::FindDocEntryVR()
1594 if ( Filetype != ExplicitVR )
1595 return GDCM_UNKNOWN;
1597 long positionOnEntry = Fp->tellg();
1598 // Warning: we believe this is explicit VR (Value Representation) because
1599 // we used a heuristic that found "UL" in the first tag. Alas this
1600 // doesn't guarantee that all the tags will be in explicit VR. In some
1601 // cases (see e-film filtered files) one finds implicit VR tags mixed
1602 // within an explicit VR file. Hence we make sure the present tag
1603 // is in explicit VR and try to fix things if it happens not to be
1607 Fp->read (vr, (size_t)2);
1610 if ( !CheckDocEntryVR(vr) )
1612 Fp->seekg(positionOnEntry, std::ios::beg);
1613 return GDCM_UNKNOWN;
1619 * \brief Check the correspondance between the VR of the header entry
1620 * and the taken VR. If they are different, the header entry is
1621 * updated with the new VR.
1622 * @param vr Dicom Value Representation
1623 * @return false if the VR is incorrect of if the VR isn't referenced
1624 * otherwise, it returns true
1626 bool Document::CheckDocEntryVR(VRKey vr)
1628 if ( !Global::GetVR()->IsValidVR(vr) )
1635 * \brief Get the transformed value of the header entry. The VR value
1636 * is used to define the transformation to operate on the value
1637 * \warning NOT end user intended method !
1638 * @param entry entry to tranform
1639 * @return Transformed entry value
1641 std::string Document::GetDocEntryValue(DocEntry *entry)
1643 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1645 std::string val = ((ValEntry *)entry)->GetValue();
1646 std::string vr = entry->GetVR();
1647 uint32_t length = entry->GetLength();
1648 std::ostringstream s;
1651 // When short integer(s) are expected, read and convert the following
1652 // n * 2 bytes properly i.e. as a multivaluated strings
1653 // (each single value is separated fromthe next one by '\'
1654 // as usual for standard multivaluated filels
1655 // Elements with Value Multiplicity > 1
1656 // contain a set of short integers (not a single one)
1658 if ( vr == "US" || vr == "SS" )
1663 for (int i=0; i < nbInt; i++)
1669 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1670 newInt16 = SwapShort( newInt16 );
1675 // When integer(s) are expected, read and convert the following
1676 // n * 4 bytes properly i.e. as a multivaluated strings
1677 // (each single value is separated fromthe next one by '\'
1678 // as usual for standard multivaluated filels
1679 // Elements with Value Multiplicity > 1
1680 // contain a set of integers (not a single one)
1681 else if ( vr == "UL" || vr == "SL" )
1686 for (int i=0; i < nbInt; i++)
1692 newInt32 = ( val[4*i+0] & 0xFF )
1693 + (( val[4*i+1] & 0xFF ) << 8 )
1694 + (( val[4*i+2] & 0xFF ) << 16 )
1695 + (( val[4*i+3] & 0xFF ) << 24 );
1696 newInt32 = SwapLong( newInt32 );
1700 #ifdef GDCM_NO_ANSI_STRING_STREAM
1701 s << std::ends; // to avoid oddities on Solaris
1702 #endif //GDCM_NO_ANSI_STRING_STREAM
1705 return ((ValEntry *)entry)->GetValue();
1709 * \brief Get the reverse transformed value of the header entry. The VR
1710 * value is used to define the reverse transformation to operate on
1712 * \warning NOT end user intended method !
1713 * @param entry Entry to reverse transform
1714 * @return Reverse transformed entry value
1716 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1718 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1720 std::string vr = entry->GetVR();
1721 std::vector<std::string> tokens;
1722 std::ostringstream s;
1724 if ( vr == "US" || vr == "SS" )
1728 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1729 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1730 for (unsigned int i=0; i<tokens.size(); i++)
1732 newInt16 = atoi(tokens[i].c_str());
1733 s << ( newInt16 & 0xFF )
1734 << (( newInt16 >> 8 ) & 0xFF );
1738 if ( vr == "UL" || vr == "SL")
1742 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1743 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1744 for (unsigned int i=0; i<tokens.size();i++)
1746 newInt32 = atoi(tokens[i].c_str());
1747 s << (char)( newInt32 & 0xFF )
1748 << (char)(( newInt32 >> 8 ) & 0xFF )
1749 << (char)(( newInt32 >> 16 ) & 0xFF )
1750 << (char)(( newInt32 >> 24 ) & 0xFF );
1755 #ifdef GDCM_NO_ANSI_STRING_STREAM
1756 s << std::ends; // to avoid oddities on Solaris
1757 #endif //GDCM_NO_ANSI_STRING_STREAM
1761 return ((ValEntry *)entry)->GetValue();
1765 * \brief Skip a given Header Entry
1766 * \warning NOT end user intended method !
1767 * @param entry entry to skip
1769 void Document::SkipDocEntry(DocEntry *entry)
1771 SkipBytes(entry->GetLength());
1775 * \brief Skips to the beginning of the next Header Entry
1776 * \warning NOT end user intended method !
1777 * @param currentDocEntry entry to skip
1779 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1781 int l = currentDocEntry->GetReadLength();
1782 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1783 // ... but PMS imagers happen !
1785 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1786 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1788 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1793 * \brief When the length of an element value is obviously wrong (because
1794 * the parser went Jabberwocky) one can hope improving things by
1795 * applying some heuristics.
1796 * @param entry entry to check
1797 * @param foundLength first assumption about length
1799 void Document::FixDocEntryFoundLength(DocEntry *entry,
1800 uint32_t foundLength)
1802 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1803 if ( foundLength == 0xffffffff)
1808 uint16_t gr = entry->GetGroup();
1809 uint16_t elem = entry->GetElement();
1811 if ( foundLength % 2)
1813 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1814 << " in x(" << std::hex << gr << "," << elem <<")");
1817 //////// Fix for some naughty General Electric images.
1818 // Allthough not recent many such GE corrupted images are still present
1819 // on Creatis hard disks. Hence this fix shall remain when such images
1820 // are no longer in use (we are talking a few years, here)...
1821 // Note: XMedCon probably uses such a trick since it is able to read
1822 // those pesky GE images ...
1823 if ( foundLength == 13)
1825 // Only happens for this length !
1826 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1829 entry->SetReadLength(10); // a bug is to be fixed !?
1833 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1834 // Occurence of such images is quite low (unless one leaves close to a
1835 // 'Leonardo' source. Hence, one might consider commenting out the
1836 // following fix on efficiency reasons.
1837 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1840 entry->SetReadLength(4); // a bug is to be fixed !?
1843 else if ( entry->GetVR() == "SQ" )
1845 foundLength = 0; // ReadLength is unchanged
1848 //////// We encountered a 'delimiter' element i.e. a tag of the form
1849 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1850 // taken into account.
1851 else if ( gr == 0xfffe )
1853 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1854 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1855 // causes extra troubles...
1856 if ( entry->GetElement() != 0x0000 )
1861 entry->SetLength(foundLength);
1865 * \brief Apply some heuristics to predict whether the considered
1866 * element value contains/represents an integer or not.
1867 * @param entry The element value on which to apply the predicate.
1868 * @return The result of the heuristical predicate.
1870 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1872 uint16_t elem = entry->GetElement();
1873 uint16_t group = entry->GetGroup();
1874 const std::string &vr = entry->GetVR();
1875 uint32_t length = entry->GetLength();
1877 // When we have some semantics on the element we just read, and if we
1878 // a priori know we are dealing with an integer, then we shall be
1879 // able to swap it's element value properly.
1880 if ( elem == 0 ) // This is the group length of the group
1888 // Allthough this should never happen, still some images have a
1889 // corrupted group length [e.g. have a glance at offset x(8336) of
1890 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1891 // Since for dicom compliant and well behaved headers, the present
1892 // test is useless (and might even look a bit paranoid), when we
1893 // encounter such an ill-formed image, we simply display a warning
1894 // message and proceed on parsing (while crossing fingers).
1895 long filePosition = Fp->tellg();
1896 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1897 << std::hex << group << " , " << elem
1898 << ") -before- position x(" << filePosition << ")"
1899 << "lgt : " << length );
1903 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1911 * \brief Discover what the swap code is (among little endian, big endian,
1912 * bad little endian, bad big endian).
1914 * @return false when we are absolutely sure
1915 * it's neither ACR-NEMA nor DICOM
1916 * true when we hope ours assuptions are OK
1918 bool Document::CheckSwap()
1925 // First, compare HostByteOrder and NetworkByteOrder in order to
1926 // determine if we shall need to swap bytes (i.e. the Endian type).
1927 bool net2host = Util::IsCurrentProcessorBigEndian();
1929 // The easiest case is the one of a 'true' DICOM header, we just have
1930 // to look for the string "DICM" inside the file preamble.
1933 char *entCur = deb + 128;
1934 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1936 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1938 // Group 0002 should always be VR, and the first element 0000
1939 // Let's be carefull (so many wrong headers ...)
1940 // and determine the value representation (VR) :
1941 // Let's skip to the first element (0002,0000) and check there if we find
1942 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1943 // in which case we (almost) know it is explicit VR.
1944 // WARNING: if it happens to be implicit VR then what we will read
1945 // is the length of the group. If this ascii representation of this
1946 // length happens to be "UL" then we shall believe it is explicit VR.
1947 // We need to skip :
1948 // * the 128 bytes of File Preamble (often padded with zeroes),
1949 // * the 4 bytes of "DICM" string,
1950 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1951 // i.e. a total of 136 bytes.
1954 // group 0x0002 *is always* Explicit VR Sometimes ,
1955 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1956 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1958 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1959 memcmp(entCur, "OB", (size_t)2) == 0 ||
1960 memcmp(entCur, "UI", (size_t)2) == 0 ||
1961 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1962 // when Write DCM *adds*
1964 // Use Document::dicom_vr to test all the possibilities
1965 // instead of just checking for UL, OB and UI !? group 0000
1967 Filetype = ExplicitVR;
1968 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1972 Filetype = ImplicitVR;
1973 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1974 << "Looks like a bugged Header!");
1980 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1985 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1988 // Position the file position indicator at first tag
1989 // (i.e. after the file preamble and the "DICM" string).
1991 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1993 Fp->seekg ( 132L, std::ios::beg);
1995 } // ------------------------------- End of DicomV3 ----------------
1997 // Alas, this is not a DicomV3 file and whatever happens there is no file
1998 // preamble. We can reset the file position indicator to where the data
1999 // is (i.e. the beginning of the file).
2001 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2003 Fp->seekg(0, std::ios::beg);
2005 // Let's check 'No Preamble Dicom File' :
2006 // Should start with group 0x0002
2007 // and be Explicit Value Representation
2009 s16 = *((uint16_t *)(deb));
2022 if ( SwapCode != 0 )
2024 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2025 memcmp(entCur, "OB", (size_t)2) == 0 ||
2026 memcmp(entCur, "UI", (size_t)2) == 0 ||
2027 memcmp(entCur, "SH", (size_t)2) == 0 ||
2028 memcmp(entCur, "AE", (size_t)2) == 0 ||
2029 memcmp(entCur, "OB", (size_t)2) == 0 )
2031 Filetype = ExplicitVR;
2032 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2036 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2038 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2039 // By clean we mean that the length of the first group is written down.
2040 // If this is the case and since the length of the first group HAS to be
2041 // four (bytes), then determining the proper swap code is straightforward.
2044 // We assume the array of char we are considering contains the binary
2045 // representation of a 32 bits integer. Hence the following dirty
2047 s32 = *((uint32_t *)(entCur));
2067 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2068 // It is time for despaired wild guesses.
2069 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2070 // i.e. the 'group length' element is not present :
2072 // check the supposed-to-be 'group number'
2073 // in ( 0x0001 .. 0x0008 )
2074 // to determine ' SwapCode' value .
2075 // Only 0 or 4321 will be possible
2076 // (no oportunity to check for the formerly well known
2077 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2078 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2079 // the file IS NOT ACR-NEMA nor DICOM V3
2080 // Find a trick to tell it the caller...
2082 s16 = *((uint16_t *)(deb));
2109 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2117 * \brief Change the Byte Swap code.
2119 void Document::SwitchByteSwapCode()
2121 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2122 << " at :" <<std::hex << Fp->tellg() );
2123 if ( SwapCode == 1234 )
2127 else if ( SwapCode == 4321 )
2131 else if ( SwapCode == 3412 )
2135 else if ( SwapCode == 2143 )
2142 * \brief during parsing, Header Elements too long are not loaded in memory
2143 * @param newSize new size
2145 void Document::SetMaxSizeLoadEntry(long newSize)
2151 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2153 MaxSizeLoadEntry = 0xffffffff;
2156 MaxSizeLoadEntry = newSize;
2160 * \brief Read the next tag WITHOUT loading it's value
2161 * (read the 'Group Number', the 'Element Number',
2162 * gets the Dict Entry
2163 * gets the VR, gets the length, gets the offset value)
2164 * @return On succes : the newly created DocEntry, NULL on failure.
2166 DocEntry *Document::ReadNextDocEntry()
2173 group = ReadInt16();
2176 catch ( FormatError e )
2178 // We reached the EOF (or an error occured) therefore
2179 // header parsing has to be considered as finished.
2183 // Sometimes file contains groups of tags with reversed endianess.
2184 HandleBrokenEndian(group, elem);
2186 // In 'true DICOM' files Group 0002 is always little endian
2187 if ( HasDCMPreamble )
2188 HandleOutOfGroup0002(group, elem);
2190 std::string vr = FindDocEntryVR();
2191 std::string realVR = vr;
2193 if ( vr == GDCM_UNKNOWN )
2195 if ( elem == 0x0000 ) // Group Length
2196 realVR = "UL"; // must be UL
2199 DictEntry *dictEntry = GetDictEntry(group,elem);
2202 realVR = dictEntry->GetVR();
2208 if ( Global::GetVR()->IsVROfSequence(realVR) )
2209 newEntry = NewSeqEntry(group, elem);
2210 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2211 newEntry = NewValEntry(group, elem,vr);
2213 newEntry = NewBinEntry(group, elem,vr);
2215 if ( vr == GDCM_UNKNOWN )
2217 if ( Filetype == ExplicitVR )
2219 // We thought this was explicit VR, but we end up with an
2220 // implicit VR tag. Let's backtrack.
2221 if ( newEntry->GetGroup() != 0xfffe )
2224 int offset = Fp->tellg();
2225 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2226 newEntry->GetGroup(), newEntry->GetElement(), offset );
2227 gdcmWarningMacro( msg.c_str() );
2230 newEntry->SetImplicitVR();
2235 FindDocEntryLength(newEntry);
2237 catch ( FormatError e )
2244 newEntry->SetOffset(Fp->tellg());
2250 * \brief Handle broken private tag from Philips NTSCAN
2251 * where the endianess is being switched to BigEndian
2252 * for no apparent reason
2255 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2257 // Endian reversion. Some files contain groups of tags with reversed endianess.
2258 static int reversedEndian = 0;
2259 // try to fix endian switching in the middle of headers
2260 if ((group == 0xfeff) && (elem == 0x00e0))
2262 // start endian swap mark for group found
2264 SwitchByteSwapCode();
2269 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2271 // end of reversed endian group
2273 SwitchByteSwapCode();
2278 * \brief Group 0002 is always coded Little Endian
2279 * whatever Transfer Syntax is
2282 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2284 // Endian reversion. Some files contain groups of tags with reversed endianess.
2285 if ( !Group0002Parsed && group != 0x0002)
2287 Group0002Parsed = true;
2288 // we just came out of group 0002
2289 // if Transfer syntax is Big Endian we have to change CheckSwap
2291 std::string ts = GetTransferSyntax();
2292 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2294 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2298 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2300 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2302 Filetype = ImplicitVR;
2305 // FIXME Strangely, this works with
2306 //'Implicit VR Transfer Syntax (GE Private)
2307 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2309 gdcmWarningMacro("Transfer Syntax Name = ["
2310 << GetTransferSyntaxName() << "]" );
2311 SwitchByteSwapCode();
2312 group = SwapShort(group);
2313 elem = SwapShort(elem);
2318 //-----------------------------------------------------------------------------
2321 //-----------------------------------------------------------------------------
2322 } // end namespace gdcm