1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/09/21 09:42:19 $
7 Version: $Revision: 1.282 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
34 #include <ctype.h> // for isdigit
35 #include <stdlib.h> // for atoi
39 //-----------------------------------------------------------------------------
41 // Refer to Document::SetMaxSizeLoadEntry()
42 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
46 // Constructors and destructors are protected to avoid user to invoke directly
49 * \brief This default constructor neither loads nor parses the file.
50 * You should then invoke \ref Document::Load.
58 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
61 Filetype = ExplicitVR;
62 // Load will set it to true if sucessfull
63 Group0002Parsed = false;
64 IsDocumentAlreadyLoaded = false;
65 IsDocumentModified = true;
66 LoadMode = LD_ALL; // default : load everything, later
71 * \brief Constructor (DEPRECATED : not to break the API)
72 * @param fileName 'Document' (File or DicomDir) to be open for parsing
74 Document::Document( std::string const &fileName )
79 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
82 Filetype = ExplicitVR;
83 Group0002Parsed = false;
84 LoadMode = LD_ALL; // Load everything, later
86 // Load will set it to true if sucessfull
87 IsDocumentAlreadyLoaded = false;
88 IsDocumentModified = true;
90 SetFileName(fileName);
94 * \brief Canonical destructor.
96 Document::~Document ()
101 //-----------------------------------------------------------------------------
105 * \brief Loader. use SetLoadMode(), SetFileName() before !
106 * @return false if file cannot be open or no swap info was found,
107 * or no tag was found.
109 bool Document::Load( )
111 if ( GetFileName() == "" )
113 gdcmWarningMacro( "Use SetFileName, before !" );
116 return DoTheLoadingDocumentJob( );
119 * \brief Loader. (DEPRECATED : not to break the API)
120 * @param fileName 'Document' (File or DicomDir) to be open for parsing
121 * @return false if file cannot be open or no swap info was found,
122 * or no tag was found.
124 bool Document::Load( std::string const &fileName )
127 return DoTheLoadingDocumentJob( );
131 * \brief Performs the Loading Job (internal use only)
132 * @return false if file cannot be open or no swap info was found,
133 * or no tag was found.
135 bool Document::DoTheLoadingDocumentJob( )
137 if ( ! IsDocumentModified ) // Nothing to do !
140 // if ( Filename == fileName )
142 // gdcmWarningMacro( "The file was already parsed inside this "
143 // << "gdcm::Document (its name is: "
144 // << Filename.c_str() );
148 //gdcmWarningMacro( "A file was already parsed inside this "
149 // << "gdcm::Document (previous name was: "
150 // << Filename.c_str() << ". New name is :"
152 // clean out the Entries, if already parsed
153 // (probabely a mistake from the user)
160 // warning already performed in OpenFile()
161 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
162 // << Filename.c_str() );
167 Group0002Parsed = false;
169 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
171 Fp->seekg(0, std::ios::end);
172 long lgt = Fp->tellg(); // total length of the file
174 Fp->seekg(0, std::ios::beg);
176 // CheckSwap returns a boolean
177 // (false if no swap info of any kind was found)
180 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
181 << Filename.c_str());
186 long beg = Fp->tellg(); // just after DICOM preamble (if any)
188 lgt -= beg; // remaining length to parse
191 // Loading is done during parsing
192 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
196 gdcmWarningMacro( "No tag in internal hash table for: "
197 << Filename.c_str());
201 IsDocumentAlreadyLoaded = true;
203 Fp->seekg( 0, std::ios::beg);
205 // Load 'non string' values
207 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
208 if ( PhotometricInterpretation == "PALETTE COLOR " )
211 // Probabely this line should be outside the 'if'
212 // Try to find an image sample holding a 'gray LUT'
213 LoadEntryBinArea(0x0028,0x1200); // gray LUT
216 /// The tags refered by the three following lines used to be CORRECTLY
217 /// defined as having an US Value Representation in the public
218 /// dictionary. BUT the semantics implied by the three following
219 /// lines state that the corresponding tag contents are in fact
220 /// the ones of a BinEntry.
221 /// In order to fix things "Quick and Dirty" the dictionary was
222 /// altered on PURPOSE but now contains a WRONG value.
223 /// In order to fix things and restore the dictionary to its
224 /// correct value, one needs to decided of the semantics by deciding
225 /// whether the following tags are either :
226 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
227 /// also used as BinEntry, which requires the proper conversion,
228 /// - OW, and hence loaded as BinEntry, but afterwards also used
229 /// as ValEntry, which requires the proper conversion.
230 LoadEntryBinArea(0x0028,0x1201); // R LUT
231 LoadEntryBinArea(0x0028,0x1202); // G LUT
232 LoadEntryBinArea(0x0028,0x1203); // B LUT
234 // Segmented Red Palette Color LUT Data
235 LoadEntryBinArea(0x0028,0x1221);
236 // Segmented Green Palette Color LUT Data
237 LoadEntryBinArea(0x0028,0x1222);
238 // Segmented Blue Palette Color LUT Data
239 LoadEntryBinArea(0x0028,0x1223);
242 //FIXME later : how to use it?
243 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
246 SQItem *sqi= modLutSeq->GetFirstSQItem();
249 BinEntry *b = sqi->GetBinEntry(0x0028,0x3006);
252 if ( b->GetLength() != 0 )
254 LoadEntryBinArea(b); //LUT Data (CTX dependent)
260 // Force Loading some more elements if user asked to.
263 for (ListElements::iterator it = UserForceLoadList.begin();
264 it != UserForceLoadList.end();
267 gdcmWarningMacro( "Force Load " << std::hex
268 << (*it).Group << "|" <<(*it).Elem );
270 d = GetDocEntry( (*it).Group, (*it).Elem);
274 gdcmWarningMacro( "You asked toForce Load " << std::hex
275 << (*it).Group <<"|"<< (*it).Elem
276 << " that doesn't exist" );
280 if ( dynamic_cast<ValEntry *>(d) )
282 LoadDocEntry(d, true);
286 BinEntry *b = dynamic_cast<BinEntry *>(d);
290 b->SetValue(GDCM_BINLOADED);
294 if ( dynamic_cast<SeqEntry *>(d) )
296 gdcmWarningMacro( "You cannot 'ForceLoad' a SeqEntry :" << std::hex
297 << (*it).Group <<"|"<< (*it).Elem );
304 // ----------------------------
305 // Specific code to allow gdcm to read ACR-LibIDO formated images
306 // Note: ACR-LibIDO is an extension of the ACR standard that was
307 // used at CREATIS. For the time being (say a couple of years)
308 // we keep this kludge to allow CREATIS users
309 // reading their old images.
311 // if recognition code tells us we deal with a LibIDO image
312 // we switch lineNumber and columnNumber
315 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
316 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
317 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
318 // with "little-endian strings"
320 Filetype = ACR_LIBIDO;
321 std::string rows = GetEntryValue(0x0028, 0x0010);
322 std::string columns = GetEntryValue(0x0028, 0x0011);
323 SetValEntry(columns, 0x0028, 0x0010);
324 SetValEntry(rows , 0x0028, 0x0011);
326 // --- End of ACR-LibIDO kludge ---
332 * \brief Adds a new element we want to load anyway
333 * @param group Group number of the target tag.
334 * @param elem Element number of the target tag.
336 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
341 UserForceLoadList.push_back(el);
344 * \brief Get the public dictionary used
346 Dict *Document::GetPubDict()
352 * \brief Get the shadow dictionary used
354 Dict *Document::GetShaDict()
360 * \brief Set the shadow dictionary used
361 * @param dict dictionary to use in shadow
363 bool Document::SetShaDict(Dict *dict)
370 * \brief Set the shadow dictionary used
371 * @param dictName name of the dictionary to use in shadow
373 bool Document::SetShaDict(DictKey const &dictName)
375 RefShaDict = Global::GetDicts()->GetDict(dictName);
380 * \brief This predicate tells us whether or not the current Document
381 * was properly parsed and contains at least *one* Dicom Element
382 * (and nothing more, sorry).
383 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
386 bool Document::IsReadable()
388 if ( Filetype == Unknown )
390 gdcmWarningMacro( "Wrong filetype");
396 gdcmWarningMacro( "No tag in internal hash table.");
404 * \brief Predicate for dicom version 3 file.
405 * @return True when the file is a dicom version 3.
407 bool Document::IsDicomV3()
409 // Checking if Transfer Syntax exists is enough
410 // Anyway, it's too late check if the 'Preamble' was found ...
411 // And ... would it be a rich idea to check ?
412 // (some 'no Preamble' DICOM images exist !)
413 return GetDocEntry(0x0002, 0x0010) != NULL;
417 * \brief Predicate for Papyrus file
418 * Dedicated to whomsoever it may concern
419 * @return True when the file is a Papyrus file.
421 bool Document::IsPapyrus()
423 // check for Papyrus private Sequence
424 DocEntry *e = GetDocEntry(0x0041, 0x1050);
427 // check if it's actually a Sequence
428 if ( !dynamic_cast<SeqEntry*>(e) )
434 * \brief returns the File Type
435 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
436 * @return the FileType code
438 FileType Document::GetFileType()
444 * \brief Accessor to the Transfer Syntax (when present) of the
445 * current document (it internally handles reading the
446 * value from disk when only parsing occured).
447 * @return The encountered Transfer Syntax of the current document.
449 std::string Document::GetTransferSyntax()
451 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
457 // The entry might be present but not loaded (parsing and loading
458 // happen at different stages): try loading and proceed with check...
459 LoadDocEntrySafe(entry);
460 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
462 std::string transfer = valEntry->GetValue();
463 // The actual transfer (as read from disk) might be padded. We
464 // first need to remove the potential padding. We can make the
465 // weak assumption that padding was not executed with digits...
466 if ( transfer.length() == 0 )
468 // for brain damaged headers
471 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
473 transfer.erase(transfer.length()-1, 1);
481 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
482 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
484 std::string Document::GetTransferSyntaxName()
486 // use the TS (TS : Transfer Syntax)
487 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
489 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
491 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
492 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
493 return "Uncompressed ACR-NEMA";
495 if ( transferSyntax == GDCM_UNFOUND )
497 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
498 return "Uncompressed ACR-NEMA";
501 // we do it only when we need it
502 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
504 // Global::GetTS() is a global static you shall never try to delete it!
508 // --------------- Swap Code ------------------
510 * \brief Swaps the bytes so they agree with the processor order
511 * @return The properly swaped 16 bits integer.
513 uint16_t Document::SwapShort(uint16_t a)
515 if ( SwapCode == 4321 || SwapCode == 2143 )
517 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
519 a = ( a << 8 ) | ( a >> 8 );
525 * \brief Swaps back the bytes of 4-byte long integer accordingly to
527 * @return The properly swaped 32 bits integer.
529 uint32_t Document::SwapLong(uint32_t a)
536 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
537 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
539 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
540 ((a>>8) & 0x0000ff00) | (a>>24) );
543 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
544 a=( (a<<16) | (a>>16) );
547 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
550 gdcmErrorMacro( "Unset swap code:" << SwapCode );
557 // -----------------File I/O ---------------
559 * \brief Tries to open the file \ref Document::Filename and
560 * checks the preamble when existing.
561 * @return The FILE pointer on success.
563 std::ifstream *Document::OpenFile()
565 HasDCMPreamble = false;
566 if (Filename.length() == 0)
573 gdcmWarningMacro( "File already open: " << Filename.c_str());
577 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
580 // Don't user gdcmErrorMacro :
581 // a spurious message will appear when you use, for instance
582 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
583 // to create outputFileName.
584 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
588 //exit(1); // No function is allowed to leave the application instead
589 // of warning the caller
593 Fp->read((char*)&zero, (size_t)2);
600 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
602 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
603 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
604 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
605 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
607 std::string msg = Util::Format(
608 "ACR/DICOM starting at the beginning of the file:(%04x)\n", zero);
609 gdcmWarningMacro( msg.c_str() );
614 Fp->seekg(126L, std::ios::cur);
615 char dicm[4]; // = {' ',' ',' ',' '};
616 Fp->read(dicm, (size_t)4);
622 if ( memcmp(dicm, "DICM", 4) == 0 )
624 HasDCMPreamble = true;
628 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
630 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
631 << Filename.c_str());
636 * \brief closes the file
637 * @return TRUE if the close was successfull
639 bool Document::CloseFile()
651 * \brief Writes in a file all the Entries (Dicom Elements)
652 * @param fp file pointer on an already open file (actually: Output File Stream)
653 * @param filetype Type of the File to be written
654 * (ACR-NEMA, ExplicitVR, ImplicitVR)
656 void Document::WriteContent(std::ofstream *fp, FileType filetype)
658 // Skip if user wants to write an ACR-NEMA file
660 if ( filetype == ImplicitVR || filetype == ExplicitVR )
662 // writing Dicom File Preamble
663 char filePreamble[128];
664 memset(filePreamble, 0, 128);
665 fp->write(filePreamble, 128);
666 fp->write("DICM", 4);
670 * \todo rewrite later, if really usefull
671 * - 'Group Length' element is optional in DICOM
672 * - but un-updated odd groups lengthes can causes pb
675 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
676 * UpdateGroupLength(false,filetype);
677 * if ( filetype == ACR)
678 * UpdateGroupLength(true,ACR);
681 ElementSet::WriteContent(fp, filetype); // This one is recursive
684 // -----------------------------------------
687 * \brief Loads (from disk) the element content
688 * when a string is not suitable
689 * @param group group number of the Entry
690 * @param elem element number of the Entry
692 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
694 // Search the corresponding DocEntry
695 DocEntry *docElement = GetDocEntry(group, elem);
698 gdcmWarningMacro(std::hex << group << "|" << elem
699 << "doesn't exist" );
702 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
705 gdcmWarningMacro(std::hex << group << "|" << elem
706 << "is NOT a BinEntry");
709 LoadEntryBinArea(binElement);
713 * \brief Loads (from disk) the element content
714 * when a string is not suitable
715 * @param elem Entry whose binArea is going to be loaded
717 void Document::LoadEntryBinArea(BinEntry *elem)
719 if (elem->GetBinArea() )
726 size_t o =(size_t)elem->GetOffset();
727 Fp->seekg(o, std::ios::beg);
729 size_t l = elem->GetLength();
730 uint8_t *a = new uint8_t[l];
733 gdcmWarningMacro( "Cannot allocate BinEntry content for : "
734 << std::hex << elem->GetGroup()
735 << "|" << elem->GetElement() );
739 Fp->read((char*)a, l);
740 if ( Fp->fail() || Fp->eof() )
753 * \brief Loads the element while preserving the current
754 * underlying file position indicator as opposed to
755 * LoadDocEntry that modifies it.
756 * @param entry DocEntry whose value will be loaded.
758 void Document::LoadDocEntrySafe(DocEntry *entry)
762 long PositionOnEntry = Fp->tellg();
764 Fp->seekg(PositionOnEntry, std::ios::beg);
769 * \brief Compares two documents, according to \ref DicomDir rules
770 * \warning Does NOT work with ACR-NEMA files
771 * \todo Find a trick to solve the pb (use RET fields ?)
772 * @param document to compare with current one
773 * @return true if 'smaller'
775 bool Document::operator<(Document &document)
778 std::string s1 = GetEntryValue(0x0010,0x0010);
779 std::string s2 = document.GetEntryValue(0x0010,0x0010);
791 s1 = GetEntryValue(0x0010,0x0020);
792 s2 = document.GetEntryValue(0x0010,0x0020);
803 // Study Instance UID
804 s1 = GetEntryValue(0x0020,0x000d);
805 s2 = document.GetEntryValue(0x0020,0x000d);
816 // Serie Instance UID
817 s1 = GetEntryValue(0x0020,0x000e);
818 s2 = document.GetEntryValue(0x0020,0x000e);
833 //-----------------------------------------------------------------------------
836 * \brief Reads a supposed to be 16 Bits integer
837 * (swaps it depending on processor endianness)
840 uint16_t Document::ReadInt16()
844 Fp->read ((char*)&g, (size_t)2);
847 throw FormatError( "Document::ReadInt16()", " file error." );
851 throw FormatError( "Document::ReadInt16()", "EOF." );
858 * \brief Reads a supposed to be 32 Bits integer
859 * (swaps it depending on processor endianness)
862 uint32_t Document::ReadInt32()
866 Fp->read ((char*)&g, (size_t)4);
869 throw FormatError( "Document::ReadInt32()", " file error." );
873 throw FormatError( "Document::ReadInt32()", "EOF." );
880 * \brief skips bytes inside the source file
881 * \warning NOT end user intended method !
884 void Document::SkipBytes(uint32_t nBytes)
886 //FIXME don't dump the returned value
887 Fp->seekg((long)nBytes, std::ios::cur);
891 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
893 int Document::ComputeGroup0002Length( /*FileType filetype*/ )
899 bool found0002 = false;
901 // for each zero-level Tag in the DCM Header
902 DocEntry *entry = GetFirstEntry();
905 gr = entry->GetGroup();
911 if ( entry->GetElement() != 0x0000 )
915 // FIXME : group 0x0002 is *always* Explicit VR!
917 //if ( filetype == ExplicitVR )
919 // if ( (vr == "OB") || (vr == "OW") || (vr == "UT") || (vr == "SQ") )
920 // (no SQ, OW, UT in group 0x0002;)
923 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
927 groupLength += 2 + 2 + 4 + entry->GetLength();
933 entry = GetNextEntry();
938 //-----------------------------------------------------------------------------
941 * \brief Loads all the needed Dictionaries
942 * \warning NOT end user intended method !
944 void Document::Initialize()
946 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
952 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
953 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
954 * @param offset start of parsing
955 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
956 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
958 void Document::ParseDES(DocEntrySet *set, long offset,
959 long l_max, bool delim_mode)
961 DocEntry *newDocEntry;
962 ValEntry *newValEntry;
963 BinEntry *newBinEntry;
964 SeqEntry *newSeqEntry;
966 bool used; // will be set to false when something wrong happens to an Entry.
967 // (Entry will then be deleted)
968 bool delim_mode_intern = delim_mode;
972 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
977 newDocEntry = ReadNextDocEntry( );
980 // Private tag, in IMplicit VR are defaulted as a BinEntry,
981 // Very often they are only composed of Printable characters,
982 // and could be defaulted as a ValEntry.
983 // It's too late to do the Job
984 // (we should check the value, but we know it after LoadDocEntry ...)
985 // --> in next gdcm major release let's unify ValEntry and BinEntry !
987 // Uncoment this printf line to be able to 'follow' the DocEntries
988 // when something *very* strange happens
990 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
991 // newDocEntry->GetElement(),
992 // newDocEntry->GetVR().c_str() );
999 // an Item Starter found elsewhere but the first position
1000 // of a SeqEntry means previous entry was a Sequence
1001 // but we didn't get it (private Sequence + Implicit VR)
1002 // we have to backtrack.
1003 if ( !first && newDocEntry->IsItemStarter() )
1005 newDocEntry = Backtrack(newDocEntry);
1009 PreviousDocEntry = newDocEntry;
1013 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1014 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1016 if ( newValEntry || newBinEntry )
1018 //////////////////////////// ContentEntry
1021 vr = newDocEntry->GetVR();
1022 if ( Filetype == ExplicitVR &&
1023 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1025 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1026 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
1027 << "|" << newDocEntry->GetElement()
1028 << " : Neither Valentry, nor BinEntry."
1029 "Probably unknown VR.");
1032 //////////////////// BinEntry or UNKOWN VR:
1034 // When "this" is a Document the Key is simply of the
1035 // form ( group, elem )...
1036 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1038 // newBinEntry->SetKey( newBinEntry->GetKey() );
1040 // but when "this" is a SQItem, we are inserting this new
1041 // valEntry in a sequence item, and the key has the
1042 // generalized form (refer to \ref BaseTagKey):
1044 // time waste hunting
1045 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1047 // newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1048 // + newBinEntry->GetKey() );
1051 if ( !set->AddEntry( newBinEntry ) )
1053 gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
1054 << newBinEntry->GetKey()
1056 << newBinEntry->GetOffset() << " )" );
1061 // Load only if we can add (not a duplicate key)
1062 LoadDocEntry( newBinEntry );
1067 /////////////////////// ValEntry
1069 // When "set" is a Document, then we are at the top of the
1070 // hierarchy and the Key is simply of the form ( group, elem )...
1071 //if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1073 // newValEntry->SetKey( newValEntry->GetKey() );
1075 // ...but when "set" is a SQItem, we are inserting this new
1076 // valEntry in a sequence item. Hence the key has the
1077 // generalized form (refer to \ref BaseTagKey):
1079 // time waste hunting
1080 //if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1082 // newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1083 // + newValEntry->GetKey() );
1086 if ( !set->AddEntry( newValEntry ) )
1088 gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
1089 << newValEntry->GetKey()
1091 << newValEntry->GetOffset() << " )" );
1096 // Load only if we can add (not a duplicate key)
1097 LoadDocEntry( newValEntry );
1100 if ( newValEntry->GetElement() == 0x0000 ) // if on group length
1102 if ( newValEntry->GetGroup()%2 != 0 ) // if Shadow Group
1104 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1106 std::string strLgrGroup = newValEntry->GetValue();
1108 if ( strLgrGroup != GDCM_UNFOUND)
1110 lgrGroup = atoi(strLgrGroup.c_str());
1111 Fp->seekg(lgrGroup, std::ios::cur);
1113 RemoveEntry( newDocEntry );
1114 // bcc 5.5 is right "assigned a value that's never used"
1122 bool delimitor = newValEntry->IsItemDelimitor();
1125 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1133 // Just to make sure we are at the beginning of next entry.
1134 SkipToNextDocEntry(newDocEntry);
1138 /////////////////////// SeqEntry : VR = "SQ"
1140 unsigned long l = newDocEntry->GetReadLength();
1141 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1143 if ( l == 0xffffffff )
1145 delim_mode_intern = true;
1149 delim_mode_intern = false;
1153 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1155 // User asked to skip SeQuences *only* if they belong to Shadow Group
1156 if ( newDocEntry->GetGroup()%2 != 0 )
1158 Fp->seekg( l, std::ios::cur);
1163 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1165 // User asked to skip *any* SeQuence
1166 Fp->seekg( l, std::ios::cur);
1170 // delay the dynamic cast as late as possible
1171 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1173 // no other way to create the Delimitor ...
1174 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1176 // At the top of the hierarchy, stands a Document. When "set"
1177 // is a Document, then we are building the first depth level.
1178 // Hence the SeqEntry we are building simply has a depth
1180 // SQItem *parentSQItem = dynamic_cast< SQItem* > ( set );
1181 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1183 newSeqEntry->SetDepthLevel( 1 );
1184 // newSeqEntry->SetKey( newSeqEntry->GetKey() );
1186 // But when "set" is already a SQItem, we are building a nested
1187 // sequence, and hence the depth level of the new SeqEntry
1188 // we are building, is one level deeper:
1190 // time waste hunting
1191 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1193 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1195 // newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1196 // + newSeqEntry->GetKey() );
1200 { // Don't try to parse zero-length sequences
1201 ParseSQ( newSeqEntry,
1202 newDocEntry->GetOffset(),
1203 l, delim_mode_intern);
1205 if ( !set->AddEntry( newSeqEntry ) )
1207 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1208 << newSeqEntry->GetKey()
1210 << newSeqEntry->GetOffset() << " )" );
1214 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1220 } // end SeqEntry : VR = "SQ"
1231 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1232 * @return parsed length for this level
1234 void Document::ParseSQ( SeqEntry *seqEntry,
1235 long offset, long l_max, bool delim_mode)
1237 int SQItemNumber = 0;
1239 long offsetStartCurrentSQItem = offset;
1243 // the first time, we read the fff0,e000 of the first SQItem
1244 DocEntry *newDocEntry = ReadNextDocEntry();
1248 // FIXME Should warn user
1249 gdcmWarningMacro("in ParseSQ : should never get here!");
1254 if ( newDocEntry->IsSequenceDelimitor() )
1256 seqEntry->SetDelimitationItem( newDocEntry );
1260 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1265 // create the current SQItem
1266 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1268 std::ostringstream newBase;
1269 newBase << seqEntry->GetKey()
1273 itemSQ->SetBaseTagKey( newBase.str() );
1275 unsigned int l = newDocEntry->GetReadLength();
1277 if ( l == 0xffffffff )
1286 // Let's try :------------
1287 // remove fff0,e000, created out of the SQItem
1289 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1290 // fill up the current SQItem, starting at the beginning of fff0,e000
1292 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1294 offsetStartCurrentSQItem = Fp->tellg();
1295 // end try -----------------
1297 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1299 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1307 * \brief When a private Sequence + Implicit VR is encountered
1308 * we cannot guess it's a Sequence till we find the first
1309 * Item Starter. We then backtrack to do the job.
1310 * @param docEntry Item Starter that warned us
1312 DocEntry *Document::Backtrack(DocEntry *docEntry)
1314 // delete the Item Starter, built erroneously out of any Sequence
1315 // it's not yet in the HTable/chained list
1318 // Get all info we can from PreviousDocEntry
1319 uint16_t group = PreviousDocEntry->GetGroup();
1320 uint16_t elem = PreviousDocEntry->GetElement();
1321 uint32_t lgt = PreviousDocEntry->GetLength();
1322 long offset = PreviousDocEntry->GetOffset();
1324 gdcmWarningMacro( "Backtrack :" << std::hex << group
1326 << " at offset " << offset );
1327 RemoveEntry( PreviousDocEntry );
1329 // forge the Seq Entry
1330 DocEntry *newEntry = NewSeqEntry(group, elem);
1331 newEntry->SetLength(lgt);
1332 newEntry->SetOffset(offset);
1334 // Move back to the beginning of the Sequence
1335 Fp->seekg( 0, std::ios::beg);
1336 Fp->seekg(offset, std::ios::cur);
1342 * \brief Loads (or not) the element content depending if its length exceeds
1343 * or not the value specified with Document::SetMaxSizeLoadEntry()
1344 * @param entry Header Entry (Dicom Element) to be dealt with
1346 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1348 uint16_t group = entry->GetGroup();
1349 std::string vr = entry->GetVR();
1350 uint32_t length = entry->GetLength();
1352 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1354 // A SeQuence "contains" a set of Elements.
1355 // (fffe e000) tells us an Element is beginning
1356 // (fffe e00d) tells us an Element just ended
1357 // (fffe e0dd) tells us the current SeQuence just ended
1358 if ( group == 0xfffe )
1360 // NO more value field for SQ !
1364 // When the length is zero things are easy:
1367 ((ValEntry *)entry)->SetValue("");
1371 // The elements whose length is bigger than the specified upper bound
1372 // are not loaded. Instead we leave a short notice on the offset of
1373 // the element content and it's length.
1375 std::ostringstream s;
1379 if (length > MaxSizeLoadEntry)
1381 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1383 s << GDCM_NOTLOADED;
1384 s << " Ad.:" << (long)entry->GetOffset();
1385 s << " x(" << std::hex << entry->GetOffset() << ")";
1387 s << " Lgt:" << entry->GetLength();
1388 s << " x(" << std::hex << entry->GetLength() << ")";
1389 binEntryPtr->SetValue(s.str());
1391 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1393 s << GDCM_NOTLOADED;
1394 s << " Address:" << (long)entry->GetOffset();
1395 s << " Length:" << entry->GetLength();
1396 s << " x(" << std::hex << entry->GetLength() << ")";
1397 valEntryPtr->SetValue(s.str());
1402 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1403 << "nor a ValEntry ?! Should never print that !" );
1406 // to be sure we are at the end of the value ...
1407 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1413 // When we find a BinEntry not very much can be done :
1414 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1416 s << GDCM_BINLOADED;
1417 binEntryPtr->SetValue(s.str());
1418 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1422 if ( IsDocEntryAnInteger(entry) )
1426 // When short integer(s) are expected, read and convert the following
1427 // (n * 2) characters properly i.e. consider them as short integers as
1428 // opposed to strings.
1429 // Elements with Value Multiplicity > 1
1430 // contain a set of integers (not a single one)
1431 if (vr == "US" || vr == "SS")
1434 NewInt = ReadInt16();
1438 for (int i=1; i < nbInt; i++)
1441 NewInt = ReadInt16();
1446 // See above comment on multiple integers (mutatis mutandis).
1447 else if (vr == "UL" || vr == "SL")
1450 NewInt = ReadInt32();
1454 for (int i=1; i < nbInt; i++)
1457 NewInt = ReadInt32();
1462 #ifdef GDCM_NO_ANSI_STRING_STREAM
1463 s << std::ends; // to avoid oddities on Solaris
1464 #endif //GDCM_NO_ANSI_STRING_STREAM
1466 ((ValEntry *)entry)->SetValue(s.str());
1470 // FIXME: We need an additional byte for storing \0 that is not on disk
1471 char *str = new char[length+1];
1472 Fp->read(str, (size_t)length);
1473 str[length] = '\0'; //this is only useful when length is odd
1474 // Special DicomString call to properly handle \0 and even length
1475 std::string newValue;
1478 newValue = Util::DicomString(str, length+1);
1479 gdcmWarningMacro("Warning: bad length: " << length <<
1480 " For string :" << newValue.c_str());
1481 // Since we change the length of string update it length
1482 //entry->SetReadLength(length+1);
1486 newValue = Util::DicomString(str, length);
1490 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1492 if ( Fp->fail() || Fp->eof())
1495 gdcmWarningMacro("--> fail");
1497 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1498 << " lgt : " << valEntry->GetReadLength()
1499 << " at " << std::hex << valEntry->GetOffset());
1500 valEntry->SetValue(GDCM_UNREAD);
1506 // Because of correspondance with the VR dic
1507 valEntry->SetValue(newValue);
1511 valEntry->SetValue(newValue);
1516 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1517 << " lgt : " << valEntry->GetReadLength()
1518 << " at " << std::hex << valEntry->GetOffset());
1523 * \brief Find the value Length of the passed Doc Entry
1524 * @param entry Header Entry whose length of the value shall be loaded.
1526 void Document::FindDocEntryLength( DocEntry *entry )
1527 throw ( FormatError )
1529 std::string vr = entry->GetVR();
1532 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1534 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1537 // The following reserved two bytes (see PS 3.5-2003, section
1538 // "7.1.2 Data element structure with explicit vr", p 27) must be
1539 // skipped before proceeding on reading the length on 4 bytes.
1540 Fp->seekg( 2L, std::ios::cur);
1541 uint32_t length32 = ReadInt32();
1543 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1548 lengthOB = FindDocEntryLengthOBOrOW();
1550 catch ( FormatUnexpected )
1552 // Computing the length failed (this happens with broken
1553 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1554 // chance to get the pixels by deciding the element goes
1555 // until the end of the file. Hence we artificially fix the
1556 // the length and proceed.
1557 gdcmWarningMacro( " Computing the length failed for " <<
1558 entry->GetKey() <<" in " <<GetFileName());
1560 long currentPosition = Fp->tellg();
1561 Fp->seekg(0L,std::ios::end);
1563 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1564 Fp->seekg(currentPosition, std::ios::beg);
1566 entry->SetReadLength(lengthUntilEOF);
1567 entry->SetLength(lengthUntilEOF);
1570 entry->SetReadLength(lengthOB);
1571 entry->SetLength(lengthOB);
1574 FixDocEntryFoundLength(entry, length32);
1578 // Length is encoded on 2 bytes.
1579 length16 = ReadInt16();
1581 // 0xffff means that we deal with 'No Length' Sequence
1582 // or 'No Length' SQItem
1583 if ( length16 == 0xffff)
1587 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1592 // Either implicit VR or a non DICOM conformal (see note below) explicit
1593 // VR that ommited the VR of (at least) this element. Farts happen.
1594 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1595 // on Data elements "Implicit and Explicit VR Data Elements shall
1596 // not coexist in a Data Set and Data Sets nested within it".]
1597 // Length is on 4 bytes.
1599 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1600 // even if Transfer Syntax is 'Implicit VR ...'
1602 FixDocEntryFoundLength( entry, ReadInt32() );
1608 * \brief Find the Length till the next sequence delimiter
1609 * \warning NOT end user intended method !
1612 uint32_t Document::FindDocEntryLengthOBOrOW()
1613 throw( FormatUnexpected )
1615 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1616 long positionOnEntry = Fp->tellg();
1617 bool foundSequenceDelimiter = false;
1618 uint32_t totalLength = 0;
1620 while ( !foundSequenceDelimiter )
1626 group = ReadInt16();
1629 catch ( FormatError )
1631 throw FormatError("Unexpected end of file encountered during ",
1632 "Document::FindDocEntryLengthOBOrOW()");
1634 // We have to decount the group and element we just read
1636 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1638 long filePosition = Fp->tellg();
1640 "Neither an Item tag nor a Sequence delimiter tag on :"
1641 << std::hex << group << " , " << elem
1642 << ") -before- position x(" << filePosition << ")" );
1644 Fp->seekg(positionOnEntry, std::ios::beg);
1645 throw FormatUnexpected(
1646 "Neither an Item tag nor a Sequence delimiter tag.");
1648 if ( elem == 0xe0dd )
1650 foundSequenceDelimiter = true;
1652 uint32_t itemLength = ReadInt32();
1653 // We add 4 bytes since we just read the ItemLength with ReadInt32
1654 totalLength += itemLength + 4;
1655 SkipBytes(itemLength);
1657 if ( foundSequenceDelimiter )
1662 Fp->seekg( positionOnEntry, std::ios::beg);
1667 * \brief Find the Value Representation of the current Dicom Element.
1668 * @return Value Representation of the current Entry
1670 std::string Document::FindDocEntryVR()
1672 if ( Filetype != ExplicitVR )
1673 return GDCM_UNKNOWN;
1675 long positionOnEntry = Fp->tellg();
1676 // Warning: we believe this is explicit VR (Value Representation) because
1677 // we used a heuristic that found "UL" in the first tag. Alas this
1678 // doesn't guarantee that all the tags will be in explicit VR. In some
1679 // cases (see e-film filtered files) one finds implicit VR tags mixed
1680 // within an explicit VR file. Hence we make sure the present tag
1681 // is in explicit VR and try to fix things if it happens not to be
1685 Fp->read (vr, (size_t)2);
1688 if ( !CheckDocEntryVR(vr) )
1690 Fp->seekg(positionOnEntry, std::ios::beg);
1691 return GDCM_UNKNOWN;
1697 * \brief Check the correspondance between the VR of the header entry
1698 * and the taken VR. If they are different, the header entry is
1699 * updated with the new VR.
1700 * @param vr Dicom Value Representation
1701 * @return false if the VR is incorrect or if the VR isn't referenced
1702 * otherwise, it returns true
1704 bool Document::CheckDocEntryVR(VRKey vr)
1706 if ( !Global::GetVR()->IsValidVR(vr) )
1713 * \brief Get the transformed value of the header entry. The VR value
1714 * is used to define the transformation to operate on the value
1715 * \warning NOT end user intended method !
1716 * @param entry entry to tranform
1717 * @return Transformed entry value
1719 std::string Document::GetDocEntryValue(DocEntry *entry)
1721 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1723 std::string val = ((ValEntry *)entry)->GetValue();
1724 std::string vr = entry->GetVR();
1725 uint32_t length = entry->GetLength();
1726 std::ostringstream s;
1729 // When short integer(s) are expected, read and convert the following
1730 // n * 2 bytes properly i.e. as a multivaluated strings
1731 // (each single value is separated fromthe next one by '\'
1732 // as usual for standard multivaluated filels
1733 // Elements with Value Multiplicity > 1
1734 // contain a set of short integers (not a single one)
1736 if ( vr == "US" || vr == "SS" )
1741 for (int i=0; i < nbInt; i++)
1747 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1748 newInt16 = SwapShort( newInt16 );
1753 // When integer(s) are expected, read and convert the following
1754 // n * 4 bytes properly i.e. as a multivaluated strings
1755 // (each single value is separated fromthe next one by '\'
1756 // as usual for standard multivaluated filels
1757 // Elements with Value Multiplicity > 1
1758 // contain a set of integers (not a single one)
1759 else if ( vr == "UL" || vr == "SL" )
1764 for (int i=0; i < nbInt; i++)
1770 newInt32 = ( val[4*i+0] & 0xFF )
1771 + (( val[4*i+1] & 0xFF ) << 8 )
1772 + (( val[4*i+2] & 0xFF ) << 16 )
1773 + (( val[4*i+3] & 0xFF ) << 24 );
1774 newInt32 = SwapLong( newInt32 );
1778 #ifdef GDCM_NO_ANSI_STRING_STREAM
1779 s << std::ends; // to avoid oddities on Solaris
1780 #endif //GDCM_NO_ANSI_STRING_STREAM
1783 return ((ValEntry *)entry)->GetValue();
1787 * \brief Get the reverse transformed value of the header entry. The VR
1788 * value is used to define the reverse transformation to operate on
1790 * \warning NOT end user intended method !
1791 * @param entry Entry to reverse transform
1792 * @return Reverse transformed entry value
1794 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1796 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1798 std::string vr = entry->GetVR();
1799 std::vector<std::string> tokens;
1800 std::ostringstream s;
1802 if ( vr == "US" || vr == "SS" )
1806 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1807 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1808 for (unsigned int i=0; i<tokens.size(); i++)
1810 newInt16 = atoi(tokens[i].c_str());
1811 s << ( newInt16 & 0xFF )
1812 << (( newInt16 >> 8 ) & 0xFF );
1816 if ( vr == "UL" || vr == "SL")
1820 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1821 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1822 for (unsigned int i=0; i<tokens.size();i++)
1824 newInt32 = atoi(tokens[i].c_str());
1825 s << (char)( newInt32 & 0xFF )
1826 << (char)(( newInt32 >> 8 ) & 0xFF )
1827 << (char)(( newInt32 >> 16 ) & 0xFF )
1828 << (char)(( newInt32 >> 24 ) & 0xFF );
1833 #ifdef GDCM_NO_ANSI_STRING_STREAM
1834 s << std::ends; // to avoid oddities on Solaris
1835 #endif //GDCM_NO_ANSI_STRING_STREAM
1839 return ((ValEntry *)entry)->GetValue();
1843 * \brief Skip a given Header Entry
1844 * \warning NOT end user intended method !
1845 * @param entry entry to skip
1847 void Document::SkipDocEntry(DocEntry *entry)
1849 SkipBytes(entry->GetLength());
1853 * \brief Skips to the beginning of the next Header Entry
1854 * \warning NOT end user intended method !
1855 * @param currentDocEntry entry to skip
1857 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1859 int l = currentDocEntry->GetReadLength();
1860 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1861 // ... but PMS imagers happen !
1863 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1864 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1866 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1871 * \brief When the length of an element value is obviously wrong (because
1872 * the parser went Jabberwocky) one can hope improving things by
1873 * applying some heuristics.
1874 * @param entry entry to check
1875 * @param foundLength first assumption about length
1877 void Document::FixDocEntryFoundLength(DocEntry *entry,
1878 uint32_t foundLength)
1880 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1881 if ( foundLength == 0xffffffff)
1886 uint16_t gr = entry->GetGroup();
1887 uint16_t elem = entry->GetElement();
1889 if ( foundLength % 2)
1891 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1892 << " in x(" << std::hex << gr << "," << elem <<")");
1895 //////// Fix for some naughty General Electric images.
1896 // Allthough not recent many such GE corrupted images are still present
1897 // on Creatis hard disks. Hence this fix shall remain when such images
1898 // are no longer in use (we are talking a few years, here)...
1899 // Note: XMedCon probably uses such a trick since it is able to read
1900 // those pesky GE images ...
1901 if ( foundLength == 13)
1903 // Only happens for this length !
1904 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1907 entry->SetReadLength(10); // a bug is to be fixed !?
1911 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1912 // Occurence of such images is quite low (unless one leaves close to a
1913 // 'Leonardo' source. Hence, one might consider commenting out the
1914 // following fix on efficiency reasons.
1915 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1918 entry->SetReadLength(4); // a bug is to be fixed !?
1921 else if ( entry->GetVR() == "SQ" )
1923 foundLength = 0; // ReadLength is unchanged
1926 //////// We encountered a 'delimiter' element i.e. a tag of the form
1927 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1928 // taken into account.
1929 else if ( gr == 0xfffe )
1931 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1932 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1933 // causes extra troubles...
1934 if ( entry->GetElement() != 0x0000 )
1939 entry->SetLength(foundLength);
1943 * \brief Apply some heuristics to predict whether the considered
1944 * element value contains/represents an integer or not.
1945 * @param entry The element value on which to apply the predicate.
1946 * @return The result of the heuristical predicate.
1948 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1950 uint16_t elem = entry->GetElement();
1951 uint16_t group = entry->GetGroup();
1952 const std::string &vr = entry->GetVR();
1953 uint32_t length = entry->GetLength();
1955 // When we have some semantics on the element we just read, and if we
1956 // a priori know we are dealing with an integer, then we shall be
1957 // able to swap it's element value properly.
1958 if ( elem == 0 ) // This is the group length of the group
1966 // Allthough this should never happen, still some images have a
1967 // corrupted group length [e.g. have a glance at offset x(8336) of
1968 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1969 // Since for dicom compliant and well behaved headers, the present
1970 // test is useless (and might even look a bit paranoid), when we
1971 // encounter such an ill-formed image, we simply display a warning
1972 // message and proceed on parsing (while crossing fingers).
1973 long filePosition = Fp->tellg();
1974 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1975 << std::hex << group << " , " << elem
1976 << ") -before- position x(" << filePosition << ")"
1977 << "lgt : " << length );
1981 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1989 * \brief Discover what the swap code is (among little endian, big endian,
1990 * bad little endian, bad big endian).
1992 * @return false when we are absolutely sure
1993 * it's neither ACR-NEMA nor DICOM
1994 * true when we hope ours assuptions are OK
1996 bool Document::CheckSwap()
2003 // First, compare HostByteOrder and NetworkByteOrder in order to
2004 // determine if we shall need to swap bytes (i.e. the Endian type).
2005 bool net2host = Util::IsCurrentProcessorBigEndian();
2007 // The easiest case is the one of a 'true' DICOM header, we just have
2008 // to look for the string "DICM" inside the file preamble.
2011 char *entCur = deb + 128;
2012 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
2014 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2016 // Group 0002 should always be VR, and the first element 0000
2017 // Let's be carefull (so many wrong headers ...)
2018 // and determine the value representation (VR) :
2019 // Let's skip to the first element (0002,0000) and check there if we find
2020 // "UL" - or "OB" if the 1st one is (0002,0001) -,
2021 // in which case we (almost) know it is explicit VR.
2022 // WARNING: if it happens to be implicit VR then what we will read
2023 // is the length of the group. If this ascii representation of this
2024 // length happens to be "UL" then we shall believe it is explicit VR.
2025 // We need to skip :
2026 // * the 128 bytes of File Preamble (often padded with zeroes),
2027 // * the 4 bytes of "DICM" string,
2028 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2029 // i.e. a total of 136 bytes.
2032 // group 0x0002 *is always* Explicit VR Sometimes ,
2033 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2034 // *Implicit* VR (see former 'gdcmData/icone.dcm')
2036 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2037 memcmp(entCur, "OB", (size_t)2) == 0 ||
2038 memcmp(entCur, "UI", (size_t)2) == 0 ||
2039 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2040 // when Write DCM *adds*
2042 // Use Document::dicom_vr to test all the possibilities
2043 // instead of just checking for UL, OB and UI !? group 0000
2045 Filetype = ExplicitVR;
2046 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2050 Filetype = ImplicitVR;
2051 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
2052 << "Looks like a bugged Header!");
2058 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
2063 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
2066 // Position the file position indicator at first tag
2067 // (i.e. after the file preamble and the "DICM" string).
2069 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
2071 Fp->seekg ( 132L, std::ios::beg);
2073 } // ------------------------------- End of DicomV3 ----------------
2075 // Alas, this is not a DicomV3 file and whatever happens there is no file
2076 // preamble. We can reset the file position indicator to where the data
2077 // is (i.e. the beginning of the file).
2079 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2081 Fp->seekg(0, std::ios::beg);
2083 // Let's check 'No Preamble Dicom File' :
2084 // Should start with group 0x0002
2085 // and be Explicit Value Representation
2087 s16 = *((uint16_t *)(deb));
2100 if ( SwapCode != 0 )
2102 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2103 memcmp(entCur, "OB", (size_t)2) == 0 ||
2104 memcmp(entCur, "UI", (size_t)2) == 0 ||
2105 memcmp(entCur, "SH", (size_t)2) == 0 ||
2106 memcmp(entCur, "AE", (size_t)2) == 0 ||
2107 memcmp(entCur, "OB", (size_t)2) == 0 )
2109 Filetype = ExplicitVR;
2110 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
2114 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2116 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2117 // By clean we mean that the length of the first group is written down.
2118 // If this is the case and since the length of the first group HAS to be
2119 // four (bytes), then determining the proper swap code is straightforward.
2122 // We assume the array of char we are considering contains the binary
2123 // representation of a 32 bits integer. Hence the following dirty
2125 s32 = *((uint32_t *)(entCur));
2145 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2146 // It is time for despaired wild guesses.
2147 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2148 // i.e. the 'group length' element is not present :
2150 // check the supposed-to-be 'group number'
2151 // in ( 0x0001 .. 0x0008 )
2152 // to determine ' SwapCode' value .
2153 // Only 0 or 4321 will be possible
2154 // (no oportunity to check for the formerly well known
2155 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2156 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2157 // the file IS NOT ACR-NEMA nor DICOM V3
2158 // Find a trick to tell it the caller...
2160 s16 = *((uint16_t *)(deb));
2187 gdcmWarningMacro("ACR/NEMA unfound swap info (Really hopeless !)");
2195 * \brief Change the Byte Swap code.
2197 void Document::SwitchByteSwapCode()
2199 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2200 << " at :" <<std::hex << Fp->tellg() );
2201 if ( SwapCode == 1234 )
2205 else if ( SwapCode == 4321 )
2209 else if ( SwapCode == 3412 )
2213 else if ( SwapCode == 2143 )
2220 * \brief during parsing, Header Elements too long are not loaded in memory
2221 * @param newSize new size
2223 void Document::SetMaxSizeLoadEntry(long newSize)
2229 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2231 MaxSizeLoadEntry = 0xffffffff;
2234 MaxSizeLoadEntry = newSize;
2238 * \brief Read the next tag WITHOUT loading it's value
2239 * (read the 'Group Number', the 'Element Number',
2240 * gets the Dict Entry
2241 * gets the VR, gets the length, gets the offset value)
2242 * @return On succes : the newly created DocEntry, NULL on failure.
2244 DocEntry *Document::ReadNextDocEntry()
2251 group = ReadInt16();
2254 catch ( FormatError )
2256 // We reached the EOF (or an error occured) therefore
2257 // header parsing has to be considered as finished.
2261 // Sometimes file contains groups of tags with reversed endianess.
2262 HandleBrokenEndian(group, elem);
2264 // In 'true DICOM' files Group 0002 is always little endian
2265 if ( HasDCMPreamble )
2266 HandleOutOfGroup0002(group, elem);
2268 std::string vr = FindDocEntryVR();
2269 std::string realVR = vr;
2271 if ( vr == GDCM_UNKNOWN )
2273 if ( elem == 0x0000 ) // Group Length
2275 realVR = "UL"; // must be UL
2277 else if (group%2 == 1 && (elem >= 0x0010 && elem <=0x00ff ))
2279 // DICOM PS 3-5 7.8.1 a) states that those
2280 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2285 DictEntry *dictEntry = GetDictEntry(group,elem);
2288 realVR = dictEntry->GetVR();
2294 if ( Global::GetVR()->IsVROfSequence(realVR) )
2295 newEntry = NewSeqEntry(group, elem);
2296 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2297 newEntry = NewValEntry(group, elem, realVR);
2299 newEntry = NewBinEntry(group, elem, realVR);
2301 if ( vr == GDCM_UNKNOWN )
2303 if ( Filetype == ExplicitVR )
2305 // We thought this was explicit VR, but we end up with an
2306 // implicit VR tag. Let's backtrack.
2307 if ( newEntry->GetGroup() != 0xfffe )
2310 int offset = Fp->tellg();
2311 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2312 newEntry->GetGroup(), newEntry->GetElement(), offset );
2313 gdcmWarningMacro( msg.c_str() );
2316 newEntry->SetImplicitVR();
2321 FindDocEntryLength(newEntry);
2323 catch ( FormatError )
2330 newEntry->SetOffset(Fp->tellg());
2336 * \brief Handle broken private tag from Philips NTSCAN
2337 * where the endianess is being switched to BigEndian
2338 * for no apparent reason
2341 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2343 // Endian reversion. Some files contain groups of tags with reversed endianess.
2344 static int reversedEndian = 0;
2345 // try to fix endian switching in the middle of headers
2346 if ((group == 0xfeff) && (elem == 0x00e0))
2348 // start endian swap mark for group found
2350 SwitchByteSwapCode();
2355 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2357 // end of reversed endian group
2359 SwitchByteSwapCode();
2364 * \brief Group 0002 is always coded Little Endian
2365 * whatever Transfer Syntax is
2368 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2370 // Endian reversion. Some files contain groups of tags with reversed endianess.
2371 if ( !Group0002Parsed && group != 0x0002)
2373 Group0002Parsed = true;
2374 // we just came out of group 0002
2375 // if Transfer syntax is Big Endian we have to change CheckSwap
2377 std::string ts = GetTransferSyntax();
2378 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2380 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2384 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2386 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2388 Filetype = ImplicitVR;
2391 // FIXME Strangely, this works with
2392 //'Implicit VR Transfer Syntax (GE Private)
2393 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2395 gdcmWarningMacro("Transfer Syntax Name = ["
2396 << GetTransferSyntaxName() << "]" );
2397 SwitchByteSwapCode();
2398 group = SwapShort(group);
2399 elem = SwapShort(elem);
2404 //-----------------------------------------------------------------------------
2407 //-----------------------------------------------------------------------------
2408 } // end namespace gdcm