1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/10/18 08:35:49 $
7 Version: $Revision: 1.289 $
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 "gdcmSeqEntry.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmDebug.h"
25 #include "gdcmDictSet.h"
26 #include "gdcmDocEntrySet.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
33 #include <ctype.h> // for isdigit
34 #include <stdlib.h> // for atoi
38 //-----------------------------------------------------------------------------
40 // Refer to Document::SetMaxSizeLoadEntry()
41 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
43 //-----------------------------------------------------------------------------
44 // Constructor / Destructor
45 // Constructors and destructors are protected to avoid user to invoke directly
48 * \brief This default constructor neither loads nor parses the file.
49 * You should then invoke \ref Document::Load.
57 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
60 Filetype = ExplicitVR;
61 // Load will set it to true if sucessfull
62 Group0002Parsed = false;
63 IsDocumentAlreadyLoaded = false;
64 IsDocumentModified = true;
65 LoadMode = LD_ALL; // default : load everything, later
70 * \brief Constructor (DEPRECATED : not to break the API)
71 * @param fileName 'Document' (File or DicomDir) to be open for parsing
73 Document::Document( std::string const &fileName )
78 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
81 Filetype = ExplicitVR;
82 Group0002Parsed = false;
83 LoadMode = LD_ALL; // Load everything, later
85 // Load will set it to true if sucessfull
86 IsDocumentAlreadyLoaded = false;
87 IsDocumentModified = true;
89 SetFileName(fileName);
93 * \brief Canonical destructor.
95 Document::~Document ()
100 //-----------------------------------------------------------------------------
104 * \brief Loader. use SetLoadMode(), SetFileName() before !
105 * @return false if file cannot be open or no swap info was found,
106 * or no tag was found.
108 bool Document::Load( )
110 if ( GetFileName() == "" )
112 gdcmWarningMacro( "Use SetFileName, before !" );
115 return DoTheLoadingDocumentJob( );
118 * \brief Loader. (DEPRECATED : not to break the API)
119 * @param fileName 'Document' (File or DicomDir) to be open for parsing
120 * @return false if file cannot be open or no swap info was found,
121 * or no tag was found.
123 bool Document::Load( std::string const &fileName )
126 return DoTheLoadingDocumentJob( );
130 * \brief Performs the Loading Job (internal use only)
131 * @return false if file cannot be open or no swap info was found,
132 * or no tag was found.
134 bool Document::DoTheLoadingDocumentJob( )
136 if ( ! IsDocumentModified ) // Nothing to do !
144 // warning already performed in OpenFile()
145 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
146 // << Filename.c_str() );
151 Group0002Parsed = false;
153 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
155 Fp->seekg(0, std::ios::end);
156 long lgt = Fp->tellg(); // total length of the file
158 Fp->seekg(0, std::ios::beg);
160 // CheckSwap returns a boolean
161 // (false if no swap info of any kind was found)
164 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
165 << Filename.c_str());
170 long beg = Fp->tellg(); // just after DICOM preamble (if any)
172 lgt -= beg; // remaining length to parse
175 // Loading is done during parsing
176 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
180 gdcmWarningMacro( "No tag in internal hash table for: "
181 << Filename.c_str());
185 IsDocumentAlreadyLoaded = true;
187 Fp->seekg( 0, std::ios::beg);
189 // Load 'non string' values
191 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
192 if ( PhotometricInterpretation == "PALETTE COLOR " )
195 // Probabely this line should be outside the 'if'
196 // Try to find an image sample holding a 'gray LUT'
197 LoadEntryBinArea(0x0028,0x1200); // gray LUT
200 /// The tags refered by the three following lines used to be CORRECTLY
201 /// defined as having an US Value Representation in the public
202 /// dictionary. BUT the semantics implied by the three following
203 /// lines state that the corresponding tag contents are in fact
204 /// the ones of a DataEntry.
205 /// In order to fix things "Quick and Dirty" the dictionary was
206 /// altered on PURPOSE but now contains a WRONG value.
207 /// In order to fix things and restore the dictionary to its
208 /// correct value, one needs to decided of the semantics by deciding
209 /// whether the following tags are either :
210 /// - multivaluated US, and hence loaded as DataEntry, but afterwards
211 /// also used as DataEntry, which requires the proper conversion,
212 /// - OW, and hence loaded as DataEntry, but afterwards also used
213 /// as DataEntry, which requires the proper conversion.
214 LoadEntryBinArea(0x0028,0x1201); // R LUT
215 LoadEntryBinArea(0x0028,0x1202); // G LUT
216 LoadEntryBinArea(0x0028,0x1203); // B LUT
218 // Segmented Red Palette Color LUT Data
219 LoadEntryBinArea(0x0028,0x1221);
220 // Segmented Green Palette Color LUT Data
221 LoadEntryBinArea(0x0028,0x1222);
222 // Segmented Blue Palette Color LUT Data
223 LoadEntryBinArea(0x0028,0x1223);
226 //FIXME later : how to use it?
227 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
230 SQItem *sqi= modLutSeq->GetFirstSQItem();
233 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
234 if ( dataEntry != 0 )
236 if ( dataEntry->GetLength() != 0 )
238 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
244 // Force Loading some more elements if user asked to.
247 for (ListElements::iterator it = UserForceLoadList.begin();
248 it != UserForceLoadList.end();
251 gdcmWarningMacro( "Force Load " << std::hex
252 << (*it).Group << "|" <<(*it).Elem );
254 d = GetDocEntry( (*it).Group, (*it).Elem);
258 gdcmWarningMacro( "You asked toForce Load " << std::hex
259 << (*it).Group <<"|"<< (*it).Elem
260 << " that doesn't exist" );
264 LoadDocEntry(d, true);
269 // ----------------------------
270 // Specific code to allow gdcm to read ACR-LibIDO formated images
271 // Note: ACR-LibIDO is an extension of the ACR standard that was
272 // used at CREATIS. For the time being (say a couple of years)
273 // we keep this kludge to allow CREATIS users
274 // reading their old images.
276 // if recognition code tells us we deal with a LibIDO image
277 // we switch lineNumber and columnNumber
280 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
281 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
282 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
283 // with "little-endian strings"
285 Filetype = ACR_LIBIDO;
286 std::string rows = GetEntryString(0x0028, 0x0010);
287 std::string columns = GetEntryString(0x0028, 0x0011);
288 SetEntryString(columns, 0x0028, 0x0010);
289 SetEntryString(rows , 0x0028, 0x0011);
291 // --- End of ACR-LibIDO kludge ---
297 * \brief Adds a new element we want to load anyway
298 * @param group Group number of the target tag.
299 * @param elem Element number of the target tag.
301 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
306 UserForceLoadList.push_back(el);
309 * \brief Get the public dictionary used
311 Dict *Document::GetPubDict()
317 * \brief Get the shadow dictionary used
319 Dict *Document::GetShaDict()
325 * \brief Set the shadow dictionary used
326 * @param dict dictionary to use in shadow
328 bool Document::SetShaDict(Dict *dict)
335 * \brief Set the shadow dictionary used
336 * @param dictName name of the dictionary to use in shadow
338 bool Document::SetShaDict(DictKey const &dictName)
340 RefShaDict = Global::GetDicts()->GetDict(dictName);
345 * \brief This predicate tells us whether or not the current Document
346 * was properly parsed and contains at least *one* Dicom Element
347 * (and nothing more, sorry).
348 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
351 bool Document::IsReadable()
353 if ( Filetype == Unknown )
355 gdcmWarningMacro( "Wrong filetype");
361 gdcmWarningMacro( "No tag in internal hash table.");
369 * \brief Predicate for dicom version 3 file.
370 * @return True when the file is a dicom version 3.
372 bool Document::IsDicomV3()
374 // Checking if Transfer Syntax exists is enough
375 // Anyway, it's too late check if the 'Preamble' was found ...
376 // And ... would it be a rich idea to check ?
377 // (some 'no Preamble' DICOM images exist !)
378 return GetDocEntry(0x0002, 0x0010) != NULL;
382 * \brief Predicate for Papyrus file
383 * Dedicated to whomsoever it may concern
384 * @return True when the file is a Papyrus file.
386 bool Document::IsPapyrus()
388 // check for Papyrus private Sequence
389 DocEntry *e = GetDocEntry(0x0041, 0x1050);
392 // check if it's actually a Sequence
393 if ( !dynamic_cast<SeqEntry*>(e) )
399 * \brief returns the File Type
400 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
401 * @return the FileType code
403 FileType Document::GetFileType()
409 * \brief Accessor to the Transfer Syntax (when present) of the
410 * current document (it internally handles reading the
411 * value from disk when only parsing occured).
412 * @return The encountered Transfer Syntax of the current document.
414 std::string Document::GetTransferSyntax()
416 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
422 // The entry might be present but not loaded (parsing and loading
423 // happen at different stages): try loading and proceed with check...
424 LoadDocEntrySafe(entry);
425 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
427 std::string transfer = dataEntry->GetString();
428 // The actual transfer (as read from disk) might be padded. We
429 // first need to remove the potential padding. We can make the
430 // weak assumption that padding was not executed with digits...
431 if ( transfer.length() == 0 )
433 // for brain damaged headers
436 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
438 transfer.erase(transfer.length()-1, 1);
439 if ( transfer.length() == 0 )
441 // for brain damaged headers
451 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
452 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
454 std::string Document::GetTransferSyntaxName()
456 // use the TS (TS : Transfer Syntax)
457 std::string transferSyntax = GetEntryString(0x0002,0x0010);
459 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
461 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
462 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
463 return "Uncompressed ACR-NEMA";
465 if ( transferSyntax == GDCM_UNFOUND )
467 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
468 return "Uncompressed ACR-NEMA";
471 // we do it only when we need it
472 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
474 // Global::GetTS() is a global static you shall never try to delete it!
478 // --------------- Swap Code ------------------
480 * \brief Swaps the bytes so they agree with the processor order
481 * @return The properly swaped 16 bits integer.
483 uint16_t Document::SwapShort(uint16_t a)
485 if ( SwapCode == 4321 || SwapCode == 2143 )
487 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
489 a = ( a << 8 ) | ( a >> 8 );
495 * \brief Swaps back the bytes of 4-byte long integer accordingly to
497 * @return The properly swaped 32 bits integer.
499 uint32_t Document::SwapLong(uint32_t a)
506 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
507 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
509 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
510 ((a>>8) & 0x0000ff00) | (a>>24) );
513 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
514 a=( (a<<16) | (a>>16) );
517 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
520 gdcmErrorMacro( "Unset swap code:" << SwapCode );
527 // -----------------File I/O ---------------
529 * \brief Tries to open the file \ref Document::Filename and
530 * checks the preamble when existing.
531 * @return The FILE pointer on success.
533 std::ifstream *Document::OpenFile()
535 HasDCMPreamble = false;
536 if (Filename.length() == 0)
543 gdcmWarningMacro( "File already open: " << Filename.c_str());
547 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
550 // Don't user gdcmErrorMacro :
551 // a spurious message will appear when you use, for instance
552 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
553 // to create outputFileName.
554 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
558 //exit(1); // No function is allowed to leave the application instead
559 // of warning the caller
563 Fp->read((char*)&zero, (size_t)2);
570 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
572 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
573 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
574 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
575 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
577 std::string msg = Util::Format(
578 "ACR/DICOM starting at the beginning of the file:(%04x)\n", zero);
579 gdcmWarningMacro( msg.c_str() );
584 Fp->seekg(126L, std::ios::cur);
585 char dicm[4]; // = {' ',' ',' ',' '};
586 Fp->read(dicm, (size_t)4);
592 if ( memcmp(dicm, "DICM", 4) == 0 )
594 HasDCMPreamble = true;
598 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
600 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
601 << Filename.c_str());
606 * \brief closes the file
607 * @return TRUE if the close was successfull
609 bool Document::CloseFile()
621 * \brief Writes in a file all the Entries (Dicom Elements)
622 * @param fp file pointer on an already open file (actually: Output File Stream)
623 * @param filetype Type of the File to be written
624 * (ACR-NEMA, ExplicitVR, ImplicitVR)
626 void Document::WriteContent(std::ofstream *fp, FileType filetype)
628 // Skip if user wants to write an ACR-NEMA file
630 if ( filetype == ImplicitVR || filetype == ExplicitVR )
632 // writing Dicom File Preamble
633 char filePreamble[128];
634 memset(filePreamble, 0, 128);
635 fp->write(filePreamble, 128);
636 fp->write("DICM", 4);
640 * \todo rewrite later, if really usefull
641 * - 'Group Length' element is optional in DICOM
642 * - but un-updated odd groups lengthes can causes pb
645 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
646 * UpdateGroupLength(false,filetype);
647 * if ( filetype == ACR)
648 * UpdateGroupLength(true,ACR);
651 ElementSet::WriteContent(fp, filetype); // This one is recursive
654 // -----------------------------------------
657 * \brief Loads (from disk) the element content
658 * when a string is not suitable
659 * @param group group number of the Entry
660 * @param elem element number of the Entry
662 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
664 // Search the corresponding DocEntry
665 DocEntry *docEntry = GetDocEntry(group, elem);
668 gdcmWarningMacro(std::hex << group << "|" << elem
669 << "doesn't exist" );
672 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
675 gdcmWarningMacro(std::hex << group << "|" << elem
676 << "is NOT a DataEntry");
679 LoadEntryBinArea(dataEntry);
683 * \brief Loads (from disk) the element content
684 * when a string is not suitable
685 * @param elem Entry whose binArea is going to be loaded
687 void Document::LoadEntryBinArea(DataEntry *entry)
689 if( entry->GetBinArea() )
696 size_t o =(size_t)entry->GetOffset();
697 Fp->seekg(o, std::ios::beg);
699 size_t l = entry->GetLength();
700 uint8_t *data = new uint8_t[l];
703 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
704 << std::hex << entry->GetGroup()
705 << "|" << entry->GetElement() );
710 Fp->read((char*)data, l);
711 if ( Fp->fail() || Fp->eof() )
714 entry->SetState(DataEntry::STATE_UNREAD);
718 // Swap the data content if necessary
720 unsigned short vrLgth = Global::GetVR()->GetAtomicElementLength(entry->GetVR());
721 if( entry->GetVR() == "OW" )
728 uint16_t *data16 = (uint16_t *)data;
729 for(i=0;i<l/vrLgth;i++)
730 data16[i] = SwapShort(data16[i]);
735 uint32_t *data32 = (uint32_t *)data;
736 for(i=0;i<l/vrLgth;i++)
737 data32[i] = SwapLong(data32[i]);
742 gdcmWarningMacro("Can't swap 64 bits datas");
743 /* uint64_t *data64 = (uint64_t *)data;
744 for(i=0;i<l/vrLgth;i++)
745 data64[i] = SwapLongLong(data64[i]);*/
750 entry->SetBinArea(data);
757 * \brief Loads the element while preserving the current
758 * underlying file position indicator as opposed to
759 * LoadDocEntry that modifies it.
760 * @param entry DocEntry whose value will be loaded.
762 void Document::LoadDocEntrySafe(DocEntry *entry)
766 long PositionOnEntry = Fp->tellg();
768 Fp->seekg(PositionOnEntry, std::ios::beg);
773 * \brief Compares two documents, according to \ref DicomDir rules
774 * \warning Does NOT work with ACR-NEMA files
775 * \todo Find a trick to solve the pb (use RET fields ?)
776 * @param document to compare with current one
777 * @return true if 'smaller'
779 bool Document::operator<(Document &document)
782 std::string s1 = GetEntryString(0x0010,0x0010);
783 std::string s2 = document.GetEntryString(0x0010,0x0010);
795 s1 = GetEntryString(0x0010,0x0020);
796 s2 = document.GetEntryString(0x0010,0x0020);
807 // Study Instance UID
808 s1 = GetEntryString(0x0020,0x000d);
809 s2 = document.GetEntryString(0x0020,0x000d);
820 // Serie Instance UID
821 s1 = GetEntryString(0x0020,0x000e);
822 s2 = document.GetEntryString(0x0020,0x000e);
837 //-----------------------------------------------------------------------------
840 * \brief Reads a supposed to be 16 Bits integer
841 * (swaps it depending on processor endianness)
844 uint16_t Document::ReadInt16()
848 Fp->read ((char*)&g, (size_t)2);
851 throw FormatError( "Document::ReadInt16()", " file error." );
855 throw FormatError( "Document::ReadInt16()", "EOF." );
862 * \brief Reads a supposed to be 32 Bits integer
863 * (swaps it depending on processor endianness)
866 uint32_t Document::ReadInt32()
870 Fp->read ((char*)&g, (size_t)4);
873 throw FormatError( "Document::ReadInt32()", " file error." );
877 throw FormatError( "Document::ReadInt32()", "EOF." );
884 * \brief skips bytes inside the source file
885 * \warning NOT end user intended method !
888 void Document::SkipBytes(uint32_t nBytes)
890 //FIXME don't dump the returned value
891 Fp->seekg((long)nBytes, std::ios::cur);
895 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
897 int Document::ComputeGroup0002Length( /*FileType filetype*/ )
903 bool found0002 = false;
905 // for each zero-level Tag in the DCM Header
906 DocEntry *entry = GetFirstEntry();
909 gr = entry->GetGroup();
915 if ( entry->GetElement() != 0x0000 )
919 // FIXME : group 0x0002 is *always* Explicit VR!
921 //if ( filetype == ExplicitVR )
923 // if ( (vr == "OB") || (vr == "OW") || (vr == "UT") || (vr == "SQ") )
924 // (no SQ, OW, UT in group 0x0002;)
927 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
931 groupLength += 2 + 2 + 4 + entry->GetLength();
937 entry = GetNextEntry();
942 //-----------------------------------------------------------------------------
945 * \brief Loads all the needed Dictionaries
946 * \warning NOT end user intended method !
948 void Document::Initialize()
950 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
956 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
957 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
958 * @param offset start of parsing
959 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
960 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
962 void Document::ParseDES(DocEntrySet *set, long offset,
963 long l_max, bool delim_mode)
965 DocEntry *newDocEntry;
966 DataEntry *newDataEntry;
967 SeqEntry *newSeqEntry;
969 bool used; // will be set to false when something wrong happens to an Entry.
970 // (Entry will then be deleted)
971 bool delim_mode_intern = delim_mode;
973 gdcmWarningMacro( "Enter in ParseDES, delim-mode " << delim_mode
974 << " at offset " << std::hex << offset );
977 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
982 newDocEntry = ReadNextDocEntry( );
985 // Private tag, in IMplicit VR are defaulted as a DataEntry,
986 // Very often they are only composed of Printable characters,
987 // and could be defaulted as a DataEntry.
988 // It's too late to do the Job
989 // (we should check the value, but we know it after LoadDocEntry ...)
991 // Uncoment this printf line to be able to 'follow' the DocEntries
992 // when something *very* strange happens
994 //printf( "%04x|%04x %s\n",newDocEntry->GetGroup(),
995 // newDocEntry->GetElement(),
996 // newDocEntry->GetVR().c_str() );
1003 // an Item Starter found elsewhere but the first position
1004 // of a SeqEntry means previous entry was a Sequence
1005 // but we didn't get it (private Sequence + Implicit VR)
1006 // we have to backtrack.
1007 if ( !first && newDocEntry->IsItemStarter() )
1009 newDocEntry = Backtrack(newDocEntry);
1013 PreviousDocEntry = newDocEntry;
1017 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1021 //////////////////////////// DataEntry
1022 vr = newDocEntry->GetVR();
1023 if ( Filetype == ExplicitVR &&
1024 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1026 ////// No DataEntry: should mean UNKOWN VR
1027 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
1028 << "|" << newDocEntry->GetElement()
1029 << " : No DataEntry."
1030 "Probably unknown VR.");
1033 if ( !set->AddEntry( newDataEntry ) )
1035 gdcmWarningMacro( "in ParseDES : cannot add a DataEntry "
1036 << newDataEntry->GetKey()
1038 << newDataEntry->GetOffset() << " )" );
1043 // Load only if we can add (not a duplicate key)
1044 LoadDocEntry( newDataEntry );
1047 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1049 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1051 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1053 std::string strLgrGroup = newDataEntry->GetString();
1055 if ( newDataEntry->IsUnfound() )
1057 lgrGroup = atoi(strLgrGroup.c_str());
1058 Fp->seekg(lgrGroup, std::ios::cur);
1059 //used = false; // never used
1060 RemoveEntry( newDocEntry ); // Remove and delete
1061 // bcc 5.5 is right "assigned a value that's never used"
1069 bool delimitor = newDataEntry->IsItemDelimitor();
1072 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1079 // Just to make sure we are at the beginning of next entry.
1080 SkipToNextDocEntry(newDocEntry);
1084 /////////////////////// SeqEntry : VR = "SQ"
1086 unsigned long l = newDocEntry->GetReadLength();
1087 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1089 if ( l == 0xffffffff )
1091 delim_mode_intern = true;
1095 delim_mode_intern = false;
1099 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1101 // User asked to skip SeQuences *only* if they belong to Shadow Group
1102 if ( newDocEntry->GetGroup()%2 != 0 )
1104 Fp->seekg( l, std::ios::cur);
1105 RemoveEntry( newDocEntry ); // Remove and delete
1106 //used = false; // never used
1110 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1112 // User asked to skip *any* SeQuence
1113 Fp->seekg( l, std::ios::cur);
1114 //used = false; // never used
1115 RemoveEntry( newDocEntry ); // Remove and delete
1118 // delay the dynamic cast as late as possible
1119 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1121 // no other way to create the Delimitor ...
1122 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1124 // At the top of the hierarchy, stands a Document. When "set"
1125 // is a Document, then we are building the first depth level.
1126 // Hence the SeqEntry we are building simply has a depth
1128 // SQItem *parentSQItem = dynamic_cast< SQItem* > ( set );
1129 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1131 newSeqEntry->SetDepthLevel( 1 );
1132 // newSeqEntry->SetKey( newSeqEntry->GetKey() );
1134 // But when "set" is already a SQItem, we are building a nested
1135 // sequence, and hence the depth level of the new SeqEntry
1136 // we are building, is one level deeper:
1138 // time waste hunting
1139 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1141 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1143 // newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1144 // + newSeqEntry->GetKey() );
1148 { // Don't try to parse zero-length sequences
1150 gdcmWarningMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1151 << " at offset " << std::hex
1152 << newDocEntry->GetOffset() );
1154 ParseSQ( newSeqEntry,
1155 newDocEntry->GetOffset(),
1156 l, delim_mode_intern);
1158 gdcmWarningMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1161 if ( !set->AddEntry( newSeqEntry ) )
1163 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1164 << newSeqEntry->GetKey()
1166 << newSeqEntry->GetOffset() << " )" );
1170 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1176 } // end SeqEntry : VR = "SQ"
1184 gdcmWarningMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1188 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1189 * @return parsed length for this level
1191 void Document::ParseSQ( SeqEntry *seqEntry,
1192 long offset, long l_max, bool delim_mode)
1194 int SQItemNumber = 0;
1196 long offsetStartCurrentSQItem = offset;
1200 // the first time, we read the fff0,e000 of the first SQItem
1201 DocEntry *newDocEntry = ReadNextDocEntry();
1205 // FIXME Should warn user
1206 gdcmWarningMacro("in ParseSQ : should never get here!");
1211 if ( newDocEntry->IsSequenceDelimitor() )
1213 seqEntry->SetDelimitationItem( newDocEntry );
1217 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1222 // create the current SQItem
1223 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1224 unsigned int l = newDocEntry->GetReadLength();
1226 if ( l == 0xffffffff )
1235 // Let's try :------------
1236 // remove fff0,e000, created out of the SQItem
1238 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1239 // fill up the current SQItem, starting at the beginning of fff0,e000
1241 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1243 offsetStartCurrentSQItem = Fp->tellg();
1244 // end try -----------------
1246 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1248 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1256 * \brief When a private Sequence + Implicit VR is encountered
1257 * we cannot guess it's a Sequence till we find the first
1258 * Item Starter. We then backtrack to do the job.
1259 * @param docEntry Item Starter that warned us
1261 DocEntry *Document::Backtrack(DocEntry *docEntry)
1263 // delete the Item Starter, built erroneously out of any Sequence
1264 // it's not yet in the HTable/chained list
1267 // Get all info we can from PreviousDocEntry
1268 uint16_t group = PreviousDocEntry->GetGroup();
1269 uint16_t elem = PreviousDocEntry->GetElement();
1270 uint32_t lgt = PreviousDocEntry->GetLength();
1271 long offset = PreviousDocEntry->GetOffset();
1273 gdcmWarningMacro( "Backtrack :" << std::hex << group
1275 << " at offset " << offset );
1276 RemoveEntry( PreviousDocEntry );
1278 // forge the Seq Entry
1279 DocEntry *newEntry = NewSeqEntry(group, elem);
1280 newEntry->SetLength(lgt);
1281 newEntry->SetOffset(offset);
1283 // Move back to the beginning of the Sequence
1284 Fp->seekg( 0, std::ios::beg);
1285 Fp->seekg(offset, std::ios::cur);
1291 * \brief Loads (or not) the element content depending if its length exceeds
1292 * or not the value specified with Document::SetMaxSizeLoadEntry()
1293 * @param entry Header Entry (Dicom Element) to be dealt with
1294 * @param forceLoad whether you want to force loading of 'long' elements
1296 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1298 uint16_t group = entry->GetGroup();
1299 std::string vr = entry->GetVR();
1300 uint32_t length = entry->GetLength();
1302 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1304 // A SeQuence "contains" a set of Elements.
1305 // (fffe e000) tells us an Element is beginning
1306 // (fffe e00d) tells us an Element just ended
1307 // (fffe e0dd) tells us the current SeQuence just ended
1308 if ( group == 0xfffe || vr == "SQ" )
1310 // NO more value field for SQ !
1314 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1320 // When the length is zero things are easy:
1323 dataEntryPtr->SetBinArea(NULL,true);
1327 // The elements whose length is bigger than the specified upper bound
1328 // are not loaded. Instead we leave a short notice on the offset of
1329 // the element content and it's length.
1331 std::ostringstream s;
1335 if (length > MaxSizeLoadEntry)
1337 dataEntryPtr->SetBinArea(NULL,true);
1338 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1340 // to be sure we are at the end of the value ...
1341 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1347 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1351 * \brief Find the value Length of the passed Doc Entry
1352 * @param entry Header Entry whose length of the value shall be loaded.
1354 void Document::FindDocEntryLength( DocEntry *entry )
1355 throw ( FormatError )
1357 std::string vr = entry->GetVR();
1360 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1362 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1365 // The following reserved two bytes (see PS 3.5-2003, section
1366 // "7.1.2 Data element structure with explicit vr", p 27) must be
1367 // skipped before proceeding on reading the length on 4 bytes.
1368 Fp->seekg( 2L, std::ios::cur);
1369 uint32_t length32 = ReadInt32();
1371 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1376 lengthOB = FindDocEntryLengthOBOrOW();
1378 catch ( FormatUnexpected )
1380 // Computing the length failed (this happens with broken
1381 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1382 // chance to get the pixels by deciding the element goes
1383 // until the end of the file. Hence we artificially fix the
1384 // the length and proceed.
1385 gdcmWarningMacro( " Computing the length failed for " <<
1386 entry->GetKey() <<" in " <<GetFileName());
1388 long currentPosition = Fp->tellg();
1389 Fp->seekg(0L,std::ios::end);
1391 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1392 Fp->seekg(currentPosition, std::ios::beg);
1394 entry->SetReadLength(lengthUntilEOF);
1395 entry->SetLength(lengthUntilEOF);
1398 entry->SetReadLength(lengthOB);
1399 entry->SetLength(lengthOB);
1402 FixDocEntryFoundLength(entry, length32);
1406 // Length is encoded on 2 bytes.
1407 length16 = ReadInt16();
1409 // 0xffff means that we deal with 'No Length' Sequence
1410 // or 'No Length' SQItem
1411 if ( length16 == 0xffff)
1415 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1420 // Either implicit VR or a non DICOM conformal (see note below) explicit
1421 // VR that ommited the VR of (at least) this element. Farts happen.
1422 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1423 // on Data elements "Implicit and Explicit VR Data Elements shall
1424 // not coexist in a Data Set and Data Sets nested within it".]
1425 // Length is on 4 bytes.
1427 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1428 // even if Transfer Syntax is 'Implicit VR ...'
1430 FixDocEntryFoundLength( entry, ReadInt32() );
1436 * \brief Find the Length till the next sequence delimiter
1437 * \warning NOT end user intended method !
1440 uint32_t Document::FindDocEntryLengthOBOrOW()
1441 throw( FormatUnexpected )
1443 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1444 long positionOnEntry = Fp->tellg();
1445 bool foundSequenceDelimiter = false;
1446 uint32_t totalLength = 0;
1448 while ( !foundSequenceDelimiter )
1454 group = ReadInt16();
1457 catch ( FormatError )
1459 throw FormatError("Unexpected end of file encountered during ",
1460 "Document::FindDocEntryLengthOBOrOW()");
1462 // We have to decount the group and element we just read
1464 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1466 long filePosition = Fp->tellg();
1468 "Neither an Item tag nor a Sequence delimiter tag on :"
1469 << std::hex << group << " , " << elem
1470 << ") -before- position x(" << filePosition << ")" );
1472 Fp->seekg(positionOnEntry, std::ios::beg);
1473 throw FormatUnexpected(
1474 "Neither an Item tag nor a Sequence delimiter tag.");
1476 if ( elem == 0xe0dd )
1478 foundSequenceDelimiter = true;
1480 uint32_t itemLength = ReadInt32();
1481 // We add 4 bytes since we just read the ItemLength with ReadInt32
1482 totalLength += itemLength + 4;
1483 SkipBytes(itemLength);
1485 if ( foundSequenceDelimiter )
1490 Fp->seekg( positionOnEntry, std::ios::beg);
1495 * \brief Find the Value Representation of the current Dicom Element.
1496 * @return Value Representation of the current Entry
1498 std::string Document::FindDocEntryVR()
1500 if ( Filetype != ExplicitVR )
1501 return GDCM_UNKNOWN;
1503 long positionOnEntry = Fp->tellg();
1504 // Warning: we believe this is explicit VR (Value Representation) because
1505 // we used a heuristic that found "UL" in the first tag. Alas this
1506 // doesn't guarantee that all the tags will be in explicit VR. In some
1507 // cases (see e-film filtered files) one finds implicit VR tags mixed
1508 // within an explicit VR file. Hence we make sure the present tag
1509 // is in explicit VR and try to fix things if it happens not to be
1513 Fp->read (vr, (size_t)2);
1516 if ( !CheckDocEntryVR(vr) )
1518 Fp->seekg(positionOnEntry, std::ios::beg);
1519 return GDCM_UNKNOWN;
1525 * \brief Check the correspondance between the VR of the header entry
1526 * and the taken VR. If they are different, the header entry is
1527 * updated with the new VR.
1528 * @param vr Dicom Value Representation
1529 * @return false if the VR is incorrect or if the VR isn't referenced
1530 * otherwise, it returns true
1532 bool Document::CheckDocEntryVR(VRKey vr)
1534 if ( !Global::GetVR()->IsValidVR(vr) )
1541 * \brief Skip a given Header Entry
1542 * \warning NOT end user intended method !
1543 * @param entry entry to skip
1545 void Document::SkipDocEntry(DocEntry *entry)
1547 SkipBytes(entry->GetLength());
1551 * \brief Skips to the beginning of the next Header Entry
1552 * \warning NOT end user intended method !
1553 * @param currentDocEntry entry to skip
1555 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1557 int l = currentDocEntry->GetReadLength();
1558 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1559 // ... but PMS imagers happen !
1561 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1562 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1564 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1569 * \brief When the length of an element value is obviously wrong (because
1570 * the parser went Jabberwocky) one can hope improving things by
1571 * applying some heuristics.
1572 * @param entry entry to check
1573 * @param foundLength first assumption about length
1575 void Document::FixDocEntryFoundLength(DocEntry *entry,
1576 uint32_t foundLength)
1578 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1579 if ( foundLength == 0xffffffff)
1584 uint16_t gr = entry->GetGroup();
1585 uint16_t elem = entry->GetElement();
1587 if ( foundLength % 2)
1589 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1590 << " in x(" << std::hex << gr << "," << elem <<")");
1593 //////// Fix for some naughty General Electric images.
1594 // Allthough not recent many such GE corrupted images are still present
1595 // on Creatis hard disks. Hence this fix shall remain when such images
1596 // are no longer in use (we are talking a few years, here)...
1597 // Note: XMedCon probably uses such a trick since it is able to read
1598 // those pesky GE images ...
1599 if ( foundLength == 13)
1601 // Only happens for this length !
1602 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1605 entry->SetReadLength(10); // a bug is to be fixed !?
1609 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1610 // Occurence of such images is quite low (unless one leaves close to a
1611 // 'Leonardo' source. Hence, one might consider commenting out the
1612 // following fix on efficiency reasons.
1613 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1616 entry->SetReadLength(4); // a bug is to be fixed !?
1619 else if ( entry->GetVR() == "SQ" )
1621 foundLength = 0; // ReadLength is unchanged
1624 //////// We encountered a 'delimiter' element i.e. a tag of the form
1625 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1626 // taken into account.
1627 else if ( gr == 0xfffe )
1629 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1630 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1631 // causes extra troubles...
1632 if ( entry->GetElement() != 0x0000 )
1637 entry->SetLength(foundLength);
1641 * \brief Apply some heuristics to predict whether the considered
1642 * element value contains/represents an integer or not.
1643 * @param entry The element value on which to apply the predicate.
1644 * @return The result of the heuristical predicate.
1646 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1648 uint16_t elem = entry->GetElement();
1649 uint16_t group = entry->GetGroup();
1650 const std::string &vr = entry->GetVR();
1651 uint32_t length = entry->GetLength();
1653 // When we have some semantics on the element we just read, and if we
1654 // a priori know we are dealing with an integer, then we shall be
1655 // able to swap it's element value properly.
1656 if ( elem == 0 ) // This is the group length of the group
1664 // Allthough this should never happen, still some images have a
1665 // corrupted group length [e.g. have a glance at offset x(8336) of
1666 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1667 // Since for dicom compliant and well behaved headers, the present
1668 // test is useless (and might even look a bit paranoid), when we
1669 // encounter such an ill-formed image, we simply display a warning
1670 // message and proceed on parsing (while crossing fingers).
1671 long filePosition = Fp->tellg();
1672 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1673 << std::hex << group << " , " << elem
1674 << ") -before- position x(" << filePosition << ")"
1675 << "lgt : " << length );
1679 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1687 * \brief Discover what the swap code is (among little endian, big endian,
1688 * bad little endian, bad big endian).
1690 * @return false when we are absolutely sure
1691 * it's neither ACR-NEMA nor DICOM
1692 * true when we hope ours assuptions are OK
1694 bool Document::CheckSwap()
1701 // First, compare HostByteOrder and NetworkByteOrder in order to
1702 // determine if we shall need to swap bytes (i.e. the Endian type).
1703 bool net2host = Util::IsCurrentProcessorBigEndian();
1705 // The easiest case is the one of a 'true' DICOM header, we just have
1706 // to look for the string "DICM" inside the file preamble.
1709 char *entCur = deb + 128;
1710 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1712 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1714 // Group 0002 should always be VR, and the first element 0000
1715 // Let's be carefull (so many wrong headers ...)
1716 // and determine the value representation (VR) :
1717 // Let's skip to the first element (0002,0000) and check there if we find
1718 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1719 // in which case we (almost) know it is explicit VR.
1720 // WARNING: if it happens to be implicit VR then what we will read
1721 // is the length of the group. If this ascii representation of this
1722 // length happens to be "UL" then we shall believe it is explicit VR.
1723 // We need to skip :
1724 // * the 128 bytes of File Preamble (often padded with zeroes),
1725 // * the 4 bytes of "DICM" string,
1726 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1727 // i.e. a total of 136 bytes.
1730 // group 0x0002 *is always* Explicit VR Sometimes ,
1731 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1732 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1734 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1735 memcmp(entCur, "OB", (size_t)2) == 0 ||
1736 memcmp(entCur, "UI", (size_t)2) == 0 ||
1737 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1738 // when Write DCM *adds*
1740 // Use Document::dicom_vr to test all the possibilities
1741 // instead of just checking for UL, OB and UI !? group 0000
1743 Filetype = ExplicitVR;
1744 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1748 Filetype = ImplicitVR;
1749 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1750 << "Looks like a bugged Header!");
1756 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1761 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1764 // Position the file position indicator at first tag
1765 // (i.e. after the file preamble and the "DICM" string).
1767 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1769 Fp->seekg ( 132L, std::ios::beg);
1771 } // ------------------------------- End of DicomV3 ----------------
1773 // Alas, this is not a DicomV3 file and whatever happens there is no file
1774 // preamble. We can reset the file position indicator to where the data
1775 // is (i.e. the beginning of the file).
1777 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1779 Fp->seekg(0, std::ios::beg);
1781 // Let's check 'No Preamble Dicom File' :
1782 // Should start with group 0x0002
1783 // and be Explicit Value Representation
1785 s16 = *((uint16_t *)(deb));
1798 if ( SwapCode != 0 )
1800 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1801 memcmp(entCur, "OB", (size_t)2) == 0 ||
1802 memcmp(entCur, "UI", (size_t)2) == 0 ||
1803 memcmp(entCur, "SH", (size_t)2) == 0 ||
1804 memcmp(entCur, "AE", (size_t)2) == 0 ||
1805 memcmp(entCur, "OB", (size_t)2) == 0 )
1807 Filetype = ExplicitVR;
1808 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1812 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1814 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1815 // By clean we mean that the length of the first group is written down.
1816 // If this is the case and since the length of the first group HAS to be
1817 // four (bytes), then determining the proper swap code is straightforward.
1820 // We assume the array of char we are considering contains the binary
1821 // representation of a 32 bits integer. Hence the following dirty
1823 s32 = *((uint32_t *)(entCur));
1843 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1844 // It is time for despaired wild guesses.
1845 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1846 // i.e. the 'group length' element is not present :
1848 // check the supposed-to-be 'group number'
1849 // in ( 0x0001 .. 0x0008 )
1850 // to determine ' SwapCode' value .
1851 // Only 0 or 4321 will be possible
1852 // (no oportunity to check for the formerly well known
1853 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1854 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1855 // the file IS NOT ACR-NEMA nor DICOM V3
1856 // Find a trick to tell it the caller...
1858 s16 = *((uint16_t *)(deb));
1885 gdcmWarningMacro("ACR/NEMA unfound swap info (Really hopeless !)");
1893 * \brief Change the Byte Swap code.
1895 void Document::SwitchByteSwapCode()
1897 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
1898 << " at :" <<std::hex << Fp->tellg() );
1899 if ( SwapCode == 1234 )
1903 else if ( SwapCode == 4321 )
1907 else if ( SwapCode == 3412 )
1911 else if ( SwapCode == 2143 )
1918 * \brief during parsing, Header Elements too long are not loaded in memory
1919 * @param newSize new size
1921 void Document::SetMaxSizeLoadEntry(long newSize)
1927 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1929 MaxSizeLoadEntry = 0xffffffff;
1932 MaxSizeLoadEntry = newSize;
1936 * \brief Read the next tag WITHOUT loading it's value
1937 * (read the 'Group Number', the 'Element Number',
1938 * gets the Dict Entry
1939 * gets the VR, gets the length, gets the offset value)
1940 * @return On succes : the newly created DocEntry, NULL on failure.
1942 DocEntry *Document::ReadNextDocEntry()
1949 group = ReadInt16();
1952 catch ( FormatError )
1954 // We reached the EOF (or an error occured) therefore
1955 // header parsing has to be considered as finished.
1959 // Sometimes file contains groups of tags with reversed endianess.
1960 HandleBrokenEndian(group, elem);
1962 // In 'true DICOM' files Group 0002 is always little endian
1963 if ( HasDCMPreamble )
1964 HandleOutOfGroup0002(group, elem);
1966 std::string vr = FindDocEntryVR();
1967 std::string realVR = vr;
1969 if ( vr == GDCM_UNKNOWN )
1971 if ( elem == 0x0000 ) // Group Length
1973 realVR = "UL"; // must be UL
1975 else if (group%2 == 1 && (elem >= 0x0010 && elem <=0x00ff ))
1977 // DICOM PS 3-5 7.8.1 a) states that those
1978 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
1983 DictEntry *dictEntry = GetDictEntry(group,elem);
1986 realVR = dictEntry->GetVR();
1992 if ( Global::GetVR()->IsVROfSequence(realVR) )
1993 newEntry = NewSeqEntry(group, elem);
1996 newEntry = NewDataEntry(group, elem, realVR);
1997 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2000 if ( vr == GDCM_UNKNOWN )
2002 if ( Filetype == ExplicitVR )
2004 // We thought this was explicit VR, but we end up with an
2005 // implicit VR tag. Let's backtrack.
2006 if ( newEntry->GetGroup() != 0xfffe )
2009 int offset = Fp->tellg();
2010 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2011 newEntry->GetGroup(), newEntry->GetElement(), offset );
2012 gdcmWarningMacro( msg.c_str() );
2015 newEntry->SetImplicitVR();
2020 FindDocEntryLength(newEntry);
2022 catch ( FormatError )
2029 newEntry->SetOffset(Fp->tellg());
2035 * \brief Handle broken private tag from Philips NTSCAN
2036 * where the endianess is being switched to BigEndian
2037 * for no apparent reason
2040 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2042 // Endian reversion. Some files contain groups of tags with reversed endianess.
2043 static int reversedEndian = 0;
2044 // try to fix endian switching in the middle of headers
2045 if ((group == 0xfeff) && (elem == 0x00e0))
2047 // start endian swap mark for group found
2049 SwitchByteSwapCode();
2054 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2056 // end of reversed endian group
2058 SwitchByteSwapCode();
2060 else if (group == 0xfeff && elem == 0xdde0)
2062 // reversed Sequence Terminator found
2063 // probabely a bug in the header !
2064 // Do what you want, it breaks !
2066 //SwitchByteSwapCode();
2067 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2072 else if (group == 0xfffe && elem == 0xe0dd)
2074 gdcmWarningMacro( "Straight Sequence Terminator." );
2079 * \brief Group 0002 is always coded Little Endian
2080 * whatever Transfer Syntax is
2083 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2085 // Endian reversion. Some files contain groups of tags with reversed endianess.
2086 if ( !Group0002Parsed && group != 0x0002)
2088 Group0002Parsed = true;
2089 // we just came out of group 0002
2090 // if Transfer syntax is Big Endian we have to change CheckSwap
2092 std::string ts = GetTransferSyntax();
2093 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2095 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2099 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2101 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2103 Filetype = ImplicitVR;
2106 // FIXME Strangely, this works with
2107 //'Implicit VR Transfer Syntax (GE Private)
2108 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2110 gdcmWarningMacro("Transfer Syntax Name = ["
2111 << GetTransferSyntaxName() << "]" );
2112 SwitchByteSwapCode();
2113 group = SwapShort(group);
2114 elem = SwapShort(elem);
2119 //-----------------------------------------------------------------------------
2122 //-----------------------------------------------------------------------------
2123 } // end namespace gdcm