1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/04/22 12:59:58 $
7 Version: $Revision: 1.235 $
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"
37 //-----------------------------------------------------------------------------
38 // Refer to Document::CheckSwap()
39 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
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 Group0002Parsed = false;
63 LoadMode = 0x00000000; // default : load everything, later
67 * \brief Constructor (not to break the API)
68 * @param filename 'Document' (File or DicomDir) to be opened for parsing
70 Document::Document( std::string const &filename )
75 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
78 Filetype = ExplicitVR;
79 Group0002Parsed = false;
80 LoadMode = 0x00000000; // Load everything
85 * \brief Canonical destructor.
87 Document::~Document ()
93 //-----------------------------------------------------------------------------
98 * @param filename 'Document' (File or DicomDir) to be opened for parsing
100 void Document::Load( std::string const &filename )
104 // We should clean out anything that already exists.
112 Group0002Parsed = false;
114 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
116 Fp->seekg(0, std::ios::end);
117 long lgt = Fp->tellg(); // total length of the file
119 Fp->seekg(0, std::ios::beg);
122 long beg = Fp->tellg(); // just after DICOM preamble (if any)
124 lgt -= beg; // remaining length to parse
126 ParseDES( this, beg, lgt, false); // Loading is done during parsing
128 Fp->seekg( 0, std::ios::beg);
130 // Load 'non string' values
132 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
133 if( PhotometricInterpretation == "PALETTE COLOR " )
135 LoadEntryBinArea(0x0028,0x1200); // gray LUT
136 /// FIXME FIXME FIXME
137 /// The tags refered by the three following lines used to be CORRECTLY
138 /// defined as having an US Value Representation in the public
139 /// dictionary. BUT the semantics implied by the three following
140 /// lines state that the corresponding tag contents are in fact
141 /// the ones of a BinEntry.
142 /// In order to fix things "Quick and Dirty" the dictionary was
143 /// altered on PURPOSE but now contains a WRONG value.
144 /// In order to fix things and restore the dictionary to its
145 /// correct value, one needs to decided of the semantics by deciding
146 /// whether the following tags are either:
147 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
148 /// also used as BinEntry, which requires the proper conversion,
149 /// - OW, and hence loaded as BinEntry, but afterwards also used
150 /// as ValEntry, which requires the proper conversion.
151 LoadEntryBinArea(0x0028,0x1201); // R LUT
152 LoadEntryBinArea(0x0028,0x1202); // G LUT
153 LoadEntryBinArea(0x0028,0x1203); // B LUT
155 // Segmented Red Palette Color LUT Data
156 LoadEntryBinArea(0x0028,0x1221);
157 // Segmented Green Palette Color LUT Data
158 LoadEntryBinArea(0x0028,0x1222);
159 // Segmented Blue Palette Color LUT Data
160 LoadEntryBinArea(0x0028,0x1223);
162 //FIXME later : how to use it?
163 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
167 // ----------------------------
168 // Specific code to allow gdcm to read ACR-LibIDO formated images
169 // Note: ACR-LibIDO is an extension of the ACR standard that was
170 // used at CREATIS. For the time being (say a couple years)
171 // we keep this kludge to allow CREATIS users
172 // reading their old images.
174 // if recognition code tells us we deal with a LibIDO image
175 // we switch lineNumber and columnNumber
178 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
179 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
180 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
181 // with "little-endian strings"
183 Filetype = ACR_LIBIDO;
184 std::string rows = GetEntryValue(0x0028, 0x0010);
185 std::string columns = GetEntryValue(0x0028, 0x0011);
186 SetValEntry(columns, 0x0028, 0x0010);
187 SetValEntry(rows , 0x0028, 0x0011);
189 // --- End of ACR-LibIDO kludge ---
193 * \brief Get the public dictionary used
195 Dict *Document::GetPubDict()
201 * \brief Get the shadow dictionary used
203 Dict *Document::GetShaDict()
209 * \brief Set the shadow dictionary used
210 * @param dict dictionary to use in shadow
212 bool Document::SetShaDict(Dict *dict)
219 * \brief Set the shadow dictionary used
220 * @param dictName name of the dictionary to use in shadow
222 bool Document::SetShaDict(DictKey const &dictName)
224 RefShaDict = Global::GetDicts()->GetDict(dictName);
229 * \brief This predicate, based on hopefully reasonable heuristics,
230 * decides whether or not the current Document was properly parsed
231 * and contains the mandatory information for being considered as
232 * a well formed and usable Dicom/Acr File.
233 * @return true when Document is the one of a reasonable Dicom/Acr file,
236 bool Document::IsReadable()
238 if( Filetype == Unknown)
240 gdcmWarningMacro( "Wrong filetype");
246 gdcmWarningMacro( "No tag in internal hash table.");
254 * \brief Predicate for dicom version 3 file.
255 * @return True when the file is a dicom version 3.
257 bool Document::IsDicomV3()
259 // Checking if Transfer Syntax exists is enough
260 // Anyway, it's to late check if the 'Preamble' was found ...
261 // And ... would it be a rich idea to check ?
262 // (some 'no Preamble' DICOM images exist !)
263 return GetDocEntry(0x0002, 0x0010) != NULL;
267 * \brief Predicate for Papyrus file
268 * Dedicated to whomsoever it may concern
269 * @return True when the file is a Papyrus file.
271 bool Document::IsPapyrus()
273 // check for Papyrus private Sequence
274 DocEntry *e = GetDocEntry(0x0041, 0x1050);
277 // check if it's actually a Sequence
278 if ( !dynamic_cast<SeqEntry*>(e) )
284 * \brief returns the File Type
285 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
286 * @return the FileType code
288 FileType Document::GetFileType()
294 * \brief Accessor to the Transfer Syntax (when present) of the
295 * current document (it internally handles reading the
296 * value from disk when only parsing occured).
297 * @return The encountered Transfer Syntax of the current document.
299 std::string Document::GetTransferSyntax()
301 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
307 // The entry might be present but not loaded (parsing and loading
308 // happen at different stages): try loading and proceed with check...
309 LoadDocEntrySafe(entry);
310 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
312 std::string transfer = valEntry->GetValue();
313 // The actual transfer (as read from disk) might be padded. We
314 // first need to remove the potential padding. We can make the
315 // weak assumption that padding was not executed with digits...
316 if ( transfer.length() == 0 )
318 // for brain damaged headers
321 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
323 transfer.erase(transfer.length()-1, 1);
331 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
332 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
334 std::string Document::GetTransferSyntaxName()
336 // use the TS (TS : Transfer Syntax)
337 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
339 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
341 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
342 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
343 return "Uncompressed ACR-NEMA";
345 if ( transferSyntax == GDCM_UNFOUND )
347 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
348 return "Uncompressed ACR-NEMA";
351 // we do it only when we need it
352 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
354 // Global::GetTS() is a global static you shall never try to delete it!
358 // --------------- Swap Code ------------------
360 * \brief Swaps the bytes so they agree with the processor order
361 * @return The properly swaped 16 bits integer.
363 uint16_t Document::SwapShort(uint16_t a)
365 if ( SwapCode == 4321 || SwapCode == 2143 )
367 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
369 a = ( a << 8 ) | ( a >> 8 );
375 * \brief Swaps back the bytes of 4-byte long integer accordingly to
377 * @return The properly swaped 32 bits integer.
379 uint32_t Document::SwapLong(uint32_t a)
386 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
387 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
389 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
390 ((a>>8) & 0x0000ff00) | (a>>24) );
393 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
394 a=( (a<<16) | (a>>16) );
397 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
400 gdcmErrorMacro( "Unset swap code:" << SwapCode );
407 // -----------------File I/O ---------------
409 * \brief Tries to open the file \ref Document::Filename and
410 * checks the preamble when existing.
411 * @return The FILE pointer on success.
413 std::ifstream *Document::OpenFile()
415 HasDCMPreamble = false;
416 if (Filename.length() == 0)
423 gdcmWarningMacro( "File already open: " << Filename.c_str());
427 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
430 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
437 Fp->read((char*)&zero, (size_t)2);
444 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
446 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
447 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
448 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
449 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
452 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
453 gdcmWarningMacro( msg.c_str() );
458 Fp->seekg(126L, std::ios::cur);
459 char dicm[4] = {' ',' ',' ',' '};
460 Fp->read(dicm, (size_t)4);
466 if( memcmp(dicm, "DICM", 4) == 0 )
468 HasDCMPreamble = true;
473 gdcmWarningMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
479 * \brief closes the file
480 * @return TRUE if the close was successfull
482 bool Document::CloseFile()
494 * \brief Writes in a file all the Header Entries (Dicom Elements)
495 * @param fp file pointer on an already open file (actually: Output File Stream)
496 * @param filetype Type of the File to be written
497 * (ACR-NEMA, ExplicitVR, ImplicitVR)
498 * @return Always true.
500 void Document::WriteContent(std::ofstream *fp, FileType filetype)
502 // \TODO move the following lines (and a lot of others, to be written)
503 // to a future function CheckAndCorrectHeader
505 // (necessary if user wants to write a DICOM V3 file
506 // starting from an ACR-NEMA (V2) Header
508 if ( filetype == ImplicitVR || filetype == ExplicitVR )
510 // writing Dicom File Preamble
511 char filePreamble[128];
512 memset(filePreamble, 0, 128);
513 fp->write(filePreamble, 128);
514 fp->write("DICM", 4);
518 * \todo rewrite later, if really usefull
519 * - 'Group Length' element is optional in DICOM
520 * - but un-updated odd groups lengthes can causes pb
523 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
524 * UpdateGroupLength(false,filetype);
525 * if ( filetype == ACR)
526 * UpdateGroupLength(true,ACR);
529 ElementSet::WriteContent(fp, filetype); // This one is recursive
532 // -----------------------------------------
535 * \brief Loads (from disk) the element content
536 * when a string is not suitable
537 * @param group group number of the Entry
538 * @param elem element number of the Entry
540 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
542 // Search the corresponding DocEntry
543 DocEntry *docElement = GetDocEntry(group, elem);
547 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
551 LoadEntryBinArea(binElement);
555 * \brief Loads (from disk) the element content
556 * when a string is not suitable
557 * @param elem Entry whose binArea is going to be loaded
559 void Document::LoadEntryBinArea(BinEntry *elem)
561 if(elem->GetBinArea())
568 size_t o =(size_t)elem->GetOffset();
569 Fp->seekg(o, std::ios::beg);
571 size_t l = elem->GetLength();
572 uint8_t *a = new uint8_t[l];
575 gdcmWarningMacro( "Cannot allocate BinEntry content");
579 Fp->read((char*)a, l);
580 if( Fp->fail() || Fp->eof())
593 * \brief Loads the element while preserving the current
594 * underlying file position indicator as opposed to
595 * LoadDocEntry that modifies it.
596 * @param entry DocEntry whose value will be loaded.
598 void Document::LoadDocEntrySafe(DocEntry *entry)
602 long PositionOnEntry = Fp->tellg();
604 Fp->seekg(PositionOnEntry, std::ios::beg);
609 * \brief Compares two documents, according to \ref DicomDir rules
610 * \warning Does NOT work with ACR-NEMA files
611 * \todo Find a trick to solve the pb (use RET fields ?)
612 * @param document to compare with current one
613 * @return true if 'smaller'
615 bool Document::operator<(Document &document)
618 std::string s1 = GetEntryValue(0x0010,0x0010);
619 std::string s2 = document.GetEntryValue(0x0010,0x0010);
631 s1 = GetEntryValue(0x0010,0x0020);
632 s2 = document.GetEntryValue(0x0010,0x0020);
643 // Study Instance UID
644 s1 = GetEntryValue(0x0020,0x000d);
645 s2 = document.GetEntryValue(0x0020,0x000d);
656 // Serie Instance UID
657 s1 = GetEntryValue(0x0020,0x000e);
658 s2 = document.GetEntryValue(0x0020,0x000e);
673 //-----------------------------------------------------------------------------
676 * \brief Reads a supposed to be 16 Bits integer
677 * (swaps it depending on processor endianness)
680 uint16_t Document::ReadInt16()
684 Fp->read ((char*)&g, (size_t)2);
687 throw FormatError( "Document::ReadInt16()", " file error." );
691 throw FormatError( "Document::ReadInt16()", "EOF." );
698 * \brief Reads a supposed to be 32 Bits integer
699 * (swaps it depending on processor endianness)
702 uint32_t Document::ReadInt32()
706 Fp->read ((char*)&g, (size_t)4);
709 throw FormatError( "Document::ReadInt32()", " file error." );
713 throw FormatError( "Document::ReadInt32()", "EOF." );
720 * \brief skips bytes inside the source file
721 * \warning NOT end user intended method !
724 void Document::SkipBytes(uint32_t nBytes)
726 //FIXME don't dump the returned value
727 Fp->seekg((long)nBytes, std::ios::cur);
731 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
732 * @param filetype Type of the File to be written
734 int Document::ComputeGroup0002Length( FileType filetype )
740 bool found0002 = false;
742 // for each zero-level Tag in the DCM Header
743 DocEntry *entry = GetFirstEntry();
746 gr = entry->GetGroup();
752 if( entry->GetElement() != 0x0000 )
756 if( filetype == ExplicitVR )
758 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
760 // explicit VR AND OB, OW, SQ : 4 more bytes
764 groupLength += 2 + 2 + 4 + entry->GetLength();
770 entry = GetNextEntry();
775 //-----------------------------------------------------------------------------
778 * \brief Loads all the needed Dictionaries
779 * \warning NOT end user intended method !
781 void Document::Initialize()
783 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
789 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
790 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
791 * @param offset start of parsing
792 * @param l_max length to parse
793 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
795 void Document::ParseDES(DocEntrySet *set, long offset,
796 long l_max, bool delim_mode)
798 DocEntry *newDocEntry;
799 ValEntry *newValEntry;
800 BinEntry *newBinEntry;
801 SeqEntry *newSeqEntry;
807 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
813 newDocEntry = ReadNextDocEntry( );
820 vr = newDocEntry->GetVR();
821 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
822 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
823 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
825 if ( newValEntry || newBinEntry )
829 if ( Filetype == ExplicitVR &&
830 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
832 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
833 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
834 << "|" << newDocEntry->GetElement()
835 << " : Neither Valentry, nor BinEntry."
836 "Probably unknown VR.");
839 //////////////////// BinEntry or UNKOWN VR:
840 // When "this" is a Document the Key is simply of the
841 // form ( group, elem )...
842 if ( dynamic_cast< Document* > ( set ) )
844 newBinEntry->SetKey( newBinEntry->GetKey() );
846 // but when "this" is a SQItem, we are inserting this new
847 // valEntry in a sequence item, and the key has the
848 // generalized form (refer to \ref BaseTagKey):
849 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
851 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
852 + newBinEntry->GetKey() );
855 LoadDocEntry( newBinEntry );
856 if( !set->AddEntry( newBinEntry ) )
858 //Expect big troubles if here
859 //delete newBinEntry;
865 /////////////////////// ValEntry
867 // When "set" is a Document, then we are at the top of the
868 // hierarchy and the Key is simply of the form ( group, elem )...
869 if ( dynamic_cast< Document* > ( set ) )
871 newValEntry->SetKey( newValEntry->GetKey() );
873 // ...but when "set" is a SQItem, we are inserting this new
874 // valEntry in a sequence item. Hence the key has the
875 // generalized form (refer to \ref BaseTagKey):
876 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
878 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
879 + newValEntry->GetKey() );
882 LoadDocEntry( newValEntry );
883 bool delimitor=newValEntry->IsItemDelimitor();
885 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
886 // shadow groups ( if possible :
887 // whether element 0x0000 exits)
889 if ( newValEntry->GetGroup()%2 != 0 )
891 if ( newValEntry->GetElement() == 0x0000 )
893 std::string strLgrGroup = newValEntry->GetValue();
895 if ( strLgrGroup != GDCM_UNFOUND)
897 lgrGroup = atoi(strLgrGroup.c_str());
898 Fp->seekg(lgrGroup , std::ios::cur);
906 if( !set->AddEntry( newValEntry ) )
908 // If here expect big troubles
909 // delete newValEntry; //otherwise mem leak
919 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
927 // Just to make sure we are at the beginning of next entry.
928 SkipToNextDocEntry(newDocEntry);
933 unsigned long l = newDocEntry->GetReadLength();
934 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
936 if ( l == 0xffffffff )
946 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
948 Fp->seekg( l, std::ios::cur);
953 // no other way to create it ...
954 newSeqEntry->SetDelimitorMode( delim_mode );
956 // At the top of the hierarchy, stands a Document. When "set"
957 // is a Document, then we are building the first depth level.
958 // Hence the SeqEntry we are building simply has a depth
960 if ( dynamic_cast< Document* > ( set ) )
962 newSeqEntry->SetDepthLevel( 1 );
963 newSeqEntry->SetKey( newSeqEntry->GetKey() );
965 // But when "set" is already a SQItem, we are building a nested
966 // sequence, and hence the depth level of the new SeqEntry
967 // we are building, is one level deeper:
968 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
970 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
971 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
972 + newSeqEntry->GetKey() );
976 { // Don't try to parse zero-length sequences
977 ParseSQ( newSeqEntry,
978 newDocEntry->GetOffset(),
981 if( !set->AddEntry( newSeqEntry ) )
986 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1000 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1001 * @return parsed length for this level
1003 void Document::ParseSQ( SeqEntry *seqEntry,
1004 long offset, long l_max, bool delim_mode)
1006 int SQItemNumber = 0;
1008 long offsetStartCurrentSQItem = offset;
1012 // the first time, we read the fff0,e000 of the first SQItem
1013 DocEntry *newDocEntry = ReadNextDocEntry();
1017 // FIXME Should warn user
1022 if ( newDocEntry->IsSequenceDelimitor() )
1024 seqEntry->SetDelimitationItem( newDocEntry );
1028 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1033 // create the current SQItem
1034 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1035 std::ostringstream newBase;
1036 newBase << seqEntry->GetKey()
1040 itemSQ->SetBaseTagKey( newBase.str() );
1041 unsigned int l = newDocEntry->GetReadLength();
1043 if ( l == 0xffffffff )
1052 // Let's try :------------
1053 // remove fff0,e000, created out of the SQItem
1055 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1056 // fill up the current SQItem, starting at the beginning of fff0,e000
1057 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1058 offsetStartCurrentSQItem = Fp->tellg();
1059 // end try -----------------
1061 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1063 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1071 * \brief Loads the element content if its length doesn't exceed
1072 * the value specified with Document::SetMaxSizeLoadEntry()
1073 * @param entry Header Entry (Dicom Element) to be dealt with
1075 void Document::LoadDocEntry(DocEntry *entry)
1077 uint16_t group = entry->GetGroup();
1078 std::string vr = entry->GetVR();
1079 uint32_t length = entry->GetLength();
1081 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1083 // A SeQuence "contains" a set of Elements.
1084 // (fffe e000) tells us an Element is beginning
1085 // (fffe e00d) tells us an Element just ended
1086 // (fffe e0dd) tells us the current SeQuence just ended
1087 if( group == 0xfffe )
1089 // NO more value field for SQ !
1093 // When the length is zero things are easy:
1096 ((ValEntry *)entry)->SetValue("");
1100 // The elements whose length is bigger than the specified upper bound
1101 // are not loaded. Instead we leave a short notice of the offset of
1102 // the element content and it's length.
1104 std::ostringstream s;
1105 if (length > MaxSizeLoadEntry)
1107 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1109 //s << "gdcm::NotLoaded (BinEntry)";
1110 s << GDCM_NOTLOADED;
1111 s << " Ad.:" << (long)entry->GetOffset();
1112 s << " x(" << std::hex << entry->GetOffset() << ")";
1114 s << " Lgt:" << entry->GetLength();
1115 s << " x(" << std::hex << entry->GetLength() << ")";
1116 binEntryPtr->SetValue(s.str());
1118 // Be carefull : a BinEntry IS_A ValEntry ...
1119 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1121 // s << "gdcm::NotLoaded. (ValEntry)";
1122 s << GDCM_NOTLOADED;
1123 s << " Address:" << (long)entry->GetOffset();
1124 s << " Length:" << entry->GetLength();
1125 s << " x(" << std::hex << entry->GetLength() << ")";
1126 valEntryPtr->SetValue(s.str());
1131 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1132 << "nor a ValEntry ?! Should never print that !" );
1135 // to be sure we are at the end of the value ...
1136 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1141 // When we find a BinEntry not very much can be done :
1142 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1144 s << GDCM_BINLOADED;
1145 binEntryPtr->SetValue(s.str());
1146 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1150 if ( IsDocEntryAnInteger(entry) )
1154 // When short integer(s) are expected, read and convert the following
1155 // n *two characters properly i.e. consider them as short integers as
1156 // opposed to strings.
1157 // Elements with Value Multiplicity > 1
1158 // contain a set of integers (not a single one)
1159 if (vr == "US" || vr == "SS")
1162 NewInt = ReadInt16();
1166 for (int i=1; i < nbInt; i++)
1169 NewInt = ReadInt16();
1174 // See above comment on multiple integers (mutatis mutandis).
1175 else if (vr == "UL" || vr == "SL")
1178 NewInt = ReadInt32();
1182 for (int i=1; i < nbInt; i++)
1185 NewInt = ReadInt32();
1190 #ifdef GDCM_NO_ANSI_STRING_STREAM
1191 s << std::ends; // to avoid oddities on Solaris
1192 #endif //GDCM_NO_ANSI_STRING_STREAM
1194 ((ValEntry *)entry)->SetValue(s.str());
1198 // FIXME: We need an additional byte for storing \0 that is not on disk
1199 char *str = new char[length+1];
1200 Fp->read(str, (size_t)length);
1201 str[length] = '\0'; //this is only useful when length is odd
1202 // Special DicomString call to properly handle \0 and even length
1203 std::string newValue;
1206 newValue = Util::DicomString(str, length+1);
1207 gdcmWarningMacro("Warning: bad length: " << length <<
1208 ",For string :" << newValue.c_str());
1209 // Since we change the length of string update it length
1210 //entry->SetReadLength(length+1);
1214 newValue = Util::DicomString(str, length);
1218 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1220 if ( Fp->fail() || Fp->eof())
1222 gdcmWarningMacro("Unread element value");
1223 valEntry->SetValue(GDCM_UNREAD);
1229 // Because of correspondance with the VR dic
1230 valEntry->SetValue(newValue);
1234 valEntry->SetValue(newValue);
1239 gdcmErrorMacro( "Should have a ValEntry, here !");
1244 * \brief Find the value Length of the passed Header Entry
1245 * @param entry Header Entry whose length of the value shall be loaded.
1247 void Document::FindDocEntryLength( DocEntry *entry )
1248 throw ( FormatError )
1250 std::string vr = entry->GetVR();
1253 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1255 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1257 // The following reserved two bytes (see PS 3.5-2003, section
1258 // "7.1.2 Data element structure with explicit vr", p 27) must be
1259 // skipped before proceeding on reading the length on 4 bytes.
1260 Fp->seekg( 2L, std::ios::cur);
1261 uint32_t length32 = ReadInt32();
1263 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1268 lengthOB = FindDocEntryLengthOBOrOW();
1270 catch ( FormatUnexpected )
1272 // Computing the length failed (this happens with broken
1273 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1274 // chance to get the pixels by deciding the element goes
1275 // until the end of the file. Hence we artificially fix the
1276 // the length and proceed.
1277 long currentPosition = Fp->tellg();
1278 Fp->seekg(0L,std::ios::end);
1280 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1281 Fp->seekg(currentPosition, std::ios::beg);
1283 entry->SetReadLength(lengthUntilEOF);
1284 entry->SetLength(lengthUntilEOF);
1287 entry->SetReadLength(lengthOB);
1288 entry->SetLength(lengthOB);
1291 FixDocEntryFoundLength(entry, length32);
1295 // Length is encoded on 2 bytes.
1296 length16 = ReadInt16();
1298 // 0xffff means that we deal with 'No Length' Sequence
1299 // or 'No Length' SQItem
1300 if ( length16 == 0xffff)
1304 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1309 // Either implicit VR or a non DICOM conformal (see note below) explicit
1310 // VR that ommited the VR of (at least) this element. Farts happen.
1311 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1312 // on Data elements "Implicit and Explicit VR Data Elements shall
1313 // not coexist in a Data Set and Data Sets nested within it".]
1314 // Length is on 4 bytes.
1316 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1317 // even if Transfer Syntax is 'Implicit VR ...'
1319 FixDocEntryFoundLength( entry, ReadInt32() );
1325 * \brief Find the Length till the next sequence delimiter
1326 * \warning NOT end user intended method !
1329 uint32_t Document::FindDocEntryLengthOBOrOW()
1330 throw( FormatUnexpected )
1332 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1333 long positionOnEntry = Fp->tellg();
1334 bool foundSequenceDelimiter = false;
1335 uint32_t totalLength = 0;
1337 while ( !foundSequenceDelimiter )
1343 group = ReadInt16();
1346 catch ( FormatError )
1348 throw FormatError("Unexpected end of file encountered during ",
1349 "Document::FindDocEntryLengthOBOrOW()");
1351 // We have to decount the group and element we just read
1353 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1355 long filePosition = Fp->tellg();
1357 "Neither an Item tag nor a Sequence delimiter tag on :"
1358 << std::hex << group << " , " << elem
1359 << ") -before- position x(" << filePosition << ")" );
1361 Fp->seekg(positionOnEntry, std::ios::beg);
1362 throw FormatUnexpected(
1363 "Neither an Item tag nor a Sequence delimiter tag.");
1365 if ( elem == 0xe0dd )
1367 foundSequenceDelimiter = true;
1369 uint32_t itemLength = ReadInt32();
1370 // We add 4 bytes since we just read the ItemLength with ReadInt32
1371 totalLength += itemLength + 4;
1372 SkipBytes(itemLength);
1374 if ( foundSequenceDelimiter )
1379 Fp->seekg( positionOnEntry, std::ios::beg);
1384 * \brief Find the Value Representation of the current Dicom Element.
1385 * @return Value Representation of the current Entry
1387 std::string Document::FindDocEntryVR()
1389 if ( Filetype != ExplicitVR )
1390 return GDCM_UNKNOWN;
1392 long positionOnEntry = Fp->tellg();
1393 // Warning: we believe this is explicit VR (Value Representation) because
1394 // we used a heuristic that found "UL" in the first tag. Alas this
1395 // doesn't guarantee that all the tags will be in explicit VR. In some
1396 // cases (see e-film filtered files) one finds implicit VR tags mixed
1397 // within an explicit VR file. Hence we make sure the present tag
1398 // is in explicit VR and try to fix things if it happens not to be
1402 Fp->read (vr, (size_t)2);
1405 if( !CheckDocEntryVR(vr) )
1407 Fp->seekg(positionOnEntry, std::ios::beg);
1408 return GDCM_UNKNOWN;
1414 * \brief Check the correspondance between the VR of the header entry
1415 * and the taken VR. If they are different, the header entry is
1416 * updated with the new VR.
1417 * @param vr Dicom Value Representation
1418 * @return false if the VR is incorrect of if the VR isn't referenced
1419 * otherwise, it returns true
1421 bool Document::CheckDocEntryVR(VRKey vr)
1423 if ( !Global::GetVR()->IsValidVR(vr) )
1430 * \brief Get the transformed value of the header entry. The VR value
1431 * is used to define the transformation to operate on the value
1432 * \warning NOT end user intended method !
1433 * @param entry entry to tranform
1434 * @return Transformed entry value
1436 std::string Document::GetDocEntryValue(DocEntry *entry)
1438 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1440 std::string val = ((ValEntry *)entry)->GetValue();
1441 std::string vr = entry->GetVR();
1442 uint32_t length = entry->GetLength();
1443 std::ostringstream s;
1446 // When short integer(s) are expected, read and convert the following
1447 // n * 2 bytes properly i.e. as a multivaluated strings
1448 // (each single value is separated fromthe next one by '\'
1449 // as usual for standard multivaluated filels
1450 // Elements with Value Multiplicity > 1
1451 // contain a set of short integers (not a single one)
1453 if( vr == "US" || vr == "SS" )
1458 for (int i=0; i < nbInt; i++)
1464 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1465 newInt16 = SwapShort( newInt16 );
1470 // When integer(s) are expected, read and convert the following
1471 // n * 4 bytes properly i.e. as a multivaluated strings
1472 // (each single value is separated fromthe next one by '\'
1473 // as usual for standard multivaluated filels
1474 // Elements with Value Multiplicity > 1
1475 // contain a set of integers (not a single one)
1476 else if( vr == "UL" || vr == "SL" )
1481 for (int i=0; i < nbInt; i++)
1487 newInt32 = ( val[4*i+0] & 0xFF )
1488 + (( val[4*i+1] & 0xFF ) << 8 )
1489 + (( val[4*i+2] & 0xFF ) << 16 )
1490 + (( val[4*i+3] & 0xFF ) << 24 );
1491 newInt32 = SwapLong( newInt32 );
1495 #ifdef GDCM_NO_ANSI_STRING_STREAM
1496 s << std::ends; // to avoid oddities on Solaris
1497 #endif //GDCM_NO_ANSI_STRING_STREAM
1500 return ((ValEntry *)entry)->GetValue();
1504 * \brief Get the reverse transformed value of the header entry. The VR
1505 * value is used to define the reverse transformation to operate on
1507 * \warning NOT end user intended method !
1508 * @param entry Entry to reverse transform
1509 * @return Reverse transformed entry value
1511 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1513 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1515 std::string vr = entry->GetVR();
1516 std::vector<std::string> tokens;
1517 std::ostringstream s;
1519 if ( vr == "US" || vr == "SS" )
1523 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1524 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1525 for (unsigned int i=0; i<tokens.size(); i++)
1527 newInt16 = atoi(tokens[i].c_str());
1528 s << ( newInt16 & 0xFF )
1529 << (( newInt16 >> 8 ) & 0xFF );
1533 if ( vr == "UL" || vr == "SL")
1537 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1538 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1539 for (unsigned int i=0; i<tokens.size();i++)
1541 newInt32 = atoi(tokens[i].c_str());
1542 s << (char)( newInt32 & 0xFF )
1543 << (char)(( newInt32 >> 8 ) & 0xFF )
1544 << (char)(( newInt32 >> 16 ) & 0xFF )
1545 << (char)(( newInt32 >> 24 ) & 0xFF );
1550 #ifdef GDCM_NO_ANSI_STRING_STREAM
1551 s << std::ends; // to avoid oddities on Solaris
1552 #endif //GDCM_NO_ANSI_STRING_STREAM
1556 return ((ValEntry *)entry)->GetValue();
1560 * \brief Skip a given Header Entry
1561 * \warning NOT end user intended method !
1562 * @param entry entry to skip
1564 void Document::SkipDocEntry(DocEntry *entry)
1566 SkipBytes(entry->GetLength());
1570 * \brief Skips to the beginning of the next Header Entry
1571 * \warning NOT end user intended method !
1572 * @param currentDocEntry entry to skip
1574 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1576 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1577 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1578 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1582 * \brief When the length of an element value is obviously wrong (because
1583 * the parser went Jabberwocky) one can hope improving things by
1584 * applying some heuristics.
1585 * @param entry entry to check
1586 * @param foundLength first assumption about length
1588 void Document::FixDocEntryFoundLength(DocEntry *entry,
1589 uint32_t foundLength)
1591 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1592 if ( foundLength == 0xffffffff)
1597 uint16_t gr = entry->GetGroup();
1598 uint16_t elem = entry->GetElement();
1600 if ( foundLength % 2)
1602 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1603 << " in x(" << std::hex << gr << "," << elem <<")");
1606 //////// Fix for some naughty General Electric images.
1607 // Allthough not recent many such GE corrupted images are still present
1608 // on Creatis hard disks. Hence this fix shall remain when such images
1609 // are no longer in use (we are talking a few years, here)...
1610 // Note: XMedCom probably uses such a trick since it is able to read
1611 // those pesky GE images ...
1612 if ( foundLength == 13)
1614 // Only happens for this length !
1615 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1618 entry->SetReadLength(10); // a bug is to be fixed !?
1622 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1623 // Occurence of such images is quite low (unless one leaves close to a
1624 // 'Leonardo' source. Hence, one might consider commenting out the
1625 // following fix on efficiency reasons.
1626 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1629 entry->SetReadLength(4); // a bug is to be fixed !?
1632 else if ( entry->GetVR() == "SQ" )
1634 foundLength = 0; // ReadLength is unchanged
1637 //////// We encountered a 'delimiter' element i.e. a tag of the form
1638 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1639 // taken into account.
1640 else if( gr == 0xfffe )
1642 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1643 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1644 // causes extra troubles...
1645 if( entry->GetElement() != 0x0000 )
1650 entry->SetLength(foundLength);
1654 * \brief Apply some heuristics to predict whether the considered
1655 * element value contains/represents an integer or not.
1656 * @param entry The element value on which to apply the predicate.
1657 * @return The result of the heuristical predicate.
1659 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1661 uint16_t elem = entry->GetElement();
1662 uint16_t group = entry->GetGroup();
1663 const std::string &vr = entry->GetVR();
1664 uint32_t length = entry->GetLength();
1666 // When we have some semantics on the element we just read, and if we
1667 // a priori know we are dealing with an integer, then we shall be
1668 // able to swap it's element value properly.
1669 if ( elem == 0 ) // This is the group length of the group
1677 // Allthough this should never happen, still some images have a
1678 // corrupted group length [e.g. have a glance at offset x(8336) of
1679 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1680 // Since for dicom compliant and well behaved headers, the present
1681 // test is useless (and might even look a bit paranoid), when we
1682 // encounter such an ill-formed image, we simply display a warning
1683 // message and proceed on parsing (while crossing fingers).
1684 long filePosition = Fp->tellg();
1685 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1686 << std::hex << group << " , " << elem
1687 << ") -before- position x(" << filePosition << ")"
1688 << "lgt : " << length );
1692 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1700 * \brief Discover what the swap code is (among little endian, big endian,
1701 * bad little endian, bad big endian).
1703 * @return false when we are absolutely sure
1704 * it's neither ACR-NEMA nor DICOM
1705 * true when we hope ours assuptions are OK
1707 bool Document::CheckSwap()
1709 // The only guaranted way of finding the swap code is to find a
1710 // group tag since we know it's length has to be of four bytes i.e.
1711 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1712 // occurs when we can't find such group...
1719 // First, compare HostByteOrder and NetworkByteOrder in order to
1720 // determine if we shall need to swap bytes (i.e. the Endian type).
1721 bool net2host = Util::IsCurrentProcessorBigEndian();
1723 // The easiest case is the one of a 'true' DICOM header, we just have
1724 // to look for the string "DICM" inside the file preamble.
1727 char *entCur = deb + 128;
1728 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1730 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1732 // Group 0002 should always be VR, and the first element 0000
1733 // Let's be carefull (so many wrong headers ...)
1734 // and determine the value representation (VR) :
1735 // Let's skip to the first element (0002,0000) and check there if we find
1736 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1737 // in which case we (almost) know it is explicit VR.
1738 // WARNING: if it happens to be implicit VR then what we will read
1739 // is the length of the group. If this ascii representation of this
1740 // length happens to be "UL" then we shall believe it is explicit VR.
1741 // We need to skip :
1742 // * the 128 bytes of File Preamble (often padded with zeroes),
1743 // * the 4 bytes of "DICM" string,
1744 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1745 // i.e. a total of 136 bytes.
1748 // group 0x0002 *is always* Explicit VR Sometimes ,
1749 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1750 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1752 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1753 memcmp(entCur, "OB", (size_t)2) == 0 ||
1754 memcmp(entCur, "UI", (size_t)2) == 0 ||
1755 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1756 // when Write DCM *adds*
1758 // Use Document::dicom_vr to test all the possibilities
1759 // instead of just checking for UL, OB and UI !? group 0000
1761 Filetype = ExplicitVR;
1762 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1766 Filetype = ImplicitVR;
1767 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1768 << "Looks like a bugged Header!");
1774 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1779 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1782 // Position the file position indicator at first tag
1783 // (i.e. after the file preamble and the "DICM" string).
1784 Fp->seekg(0, std::ios::beg);
1785 Fp->seekg ( 132L, std::ios::beg);
1789 // Alas, this is not a DicomV3 file and whatever happens there is no file
1790 // preamble. We can reset the file position indicator to where the data
1791 // is (i.e. the beginning of the file).
1792 gdcmWarningMacro( "Not a DICOM Version3 file");
1793 Fp->seekg(0, std::ios::beg);
1795 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1796 // By clean we mean that the length of the first tag is written down.
1797 // If this is the case and since the length of the first group HAS to be
1798 // four (bytes), then determining the proper swap code is straightforward.
1801 // We assume the array of char we are considering contains the binary
1802 // representation of a 32 bits integer. Hence the following dirty
1804 s32 = *((uint32_t *)(entCur));
1825 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1826 // It is time for despaired wild guesses.
1827 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1828 // i.e. the 'group length' element is not present :
1830 // check the supposed-to-be 'group number'
1831 // in ( 0x0001 .. 0x0008 )
1832 // to determine ' SwapCode' value .
1833 // Only 0 or 4321 will be possible
1834 // (no oportunity to check for the formerly well known
1835 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1836 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1837 // the file IS NOT ACR-NEMA nor DICOM V3
1838 // Find a trick to tell it the caller...
1840 s16 = *((uint16_t *)(deb));
1867 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1875 * \brief Change the Byte Swap code.
1877 void Document::SwitchByteSwapCode()
1879 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1880 if ( SwapCode == 1234 )
1884 else if ( SwapCode == 4321 )
1888 else if ( SwapCode == 3412 )
1892 else if ( SwapCode == 2143 )
1899 * \brief during parsing, Header Elements too long are not loaded in memory
1900 * @param newSize new size
1902 void Document::SetMaxSizeLoadEntry(long newSize)
1908 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1910 MaxSizeLoadEntry = 0xffffffff;
1913 MaxSizeLoadEntry = newSize;
1917 * \brief Read the next tag but WITHOUT loading it's value
1918 * (read the 'Group Number', the 'Element Number',
1919 * gets the Dict Entry
1920 * gets the VR, gets the length, gets the offset value)
1921 * @return On succes the newly created DocEntry, NULL on failure.
1923 DocEntry *Document::ReadNextDocEntry()
1930 group = ReadInt16();
1933 catch ( FormatError e )
1935 // We reached the EOF (or an error occured) therefore
1936 // header parsing has to be considered as finished.
1940 // Sometimes file contains groups of tags with reversed endianess.
1941 HandleBrokenEndian(group, elem);
1943 // In 'true DICOM' files Group 0002 is always little endian
1944 if ( HasDCMPreamble )
1945 HandleOutOfGroup0002(group, elem);
1947 std::string vr = FindDocEntryVR();
1948 std::string realVR = vr;
1950 if( vr == GDCM_UNKNOWN)
1952 if ( elem == 0x0000 ) // Group Length
1953 realVR = "UL"; // must be UL
1956 DictEntry *dictEntry = GetDictEntry(group,elem);
1958 realVR = dictEntry->GetVR();
1963 if( Global::GetVR()->IsVROfSequence(realVR) )
1964 newEntry = NewSeqEntry(group, elem);
1965 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1966 newEntry = NewValEntry(group, elem,vr);
1968 newEntry = NewBinEntry(group, elem,vr);
1970 if( vr == GDCM_UNKNOWN )
1972 if( Filetype == ExplicitVR )
1974 // We thought this was explicit VR, but we end up with an
1975 // implicit VR tag. Let's backtrack.
1976 if ( newEntry->GetGroup() != 0xfffe )
1979 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
1980 newEntry->GetGroup(), newEntry->GetElement());
1981 gdcmWarningMacro( msg.c_str() );
1984 newEntry->SetImplicitVR();
1989 FindDocEntryLength(newEntry);
1991 catch ( FormatError e )
1998 newEntry->SetOffset(Fp->tellg());
2004 * \brief Handle broken private tag from Philips NTSCAN
2005 * where the endianess is being switch to BigEndian for no
2009 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2011 // Endian reversion. Some files contain groups of tags with reversed endianess.
2012 static int reversedEndian = 0;
2013 // try to fix endian switching in the middle of headers
2014 if ((group == 0xfeff) && (elem == 0x00e0))
2016 // start endian swap mark for group found
2018 SwitchByteSwapCode();
2023 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2025 // end of reversed endian group
2027 SwitchByteSwapCode();
2032 * \brief Group 0002 is always coded Little Endian
2033 * whatever Transfer Syntax is
2036 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2038 // Endian reversion. Some files contain groups of tags with reversed endianess.
2039 if ( !Group0002Parsed && group != 0x0002)
2041 Group0002Parsed = true;
2042 // we just came out of group 0002
2043 // if Transfer syntax is Big Endian we have to change CheckSwap
2045 std::string ts = GetTransferSyntax();
2046 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2048 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2052 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2054 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2056 Filetype = ImplicitVR;
2059 // FIXME Strangely, this works with
2060 //'Implicit VR Transfer Syntax (GE Private)
2061 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2063 gdcmWarningMacro("Transfer Syntax Name = ["
2064 << GetTransferSyntaxName() << "]" );
2065 SwitchByteSwapCode();
2066 group = SwapShort(group);
2067 elem = SwapShort(elem);
2072 //-----------------------------------------------------------------------------
2075 //-----------------------------------------------------------------------------
2076 } // end namespace gdcm