1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/04/05 10:20:53 $
7 Version: $Revision: 1.234 $
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 << " Address:" << (long)entry->GetOffset();
1112 s << " Length:" << entry->GetLength();
1113 s << " x(" << std::hex << entry->GetLength() << ")";
1114 binEntryPtr->SetValue(s.str());
1116 // Be carefull : a BinEntry IS_A ValEntry ...
1117 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1119 // s << "gdcm::NotLoaded. (ValEntry)";
1120 s << GDCM_NOTLOADED;
1121 s << " Address:" << (long)entry->GetOffset();
1122 s << " Length:" << entry->GetLength();
1123 s << " x(" << std::hex << entry->GetLength() << ")";
1124 valEntryPtr->SetValue(s.str());
1129 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1130 << "nor a ValEntry ?! Should never print that !" );
1133 // to be sure we are at the end of the value ...
1134 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1139 // When we find a BinEntry not very much can be done :
1140 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1142 s << GDCM_BINLOADED;
1143 binEntryPtr->SetValue(s.str());
1144 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1148 if ( IsDocEntryAnInteger(entry) )
1152 // When short integer(s) are expected, read and convert the following
1153 // n *two characters properly i.e. consider them as short integers as
1154 // opposed to strings.
1155 // Elements with Value Multiplicity > 1
1156 // contain a set of integers (not a single one)
1157 if (vr == "US" || vr == "SS")
1160 NewInt = ReadInt16();
1164 for (int i=1; i < nbInt; i++)
1167 NewInt = ReadInt16();
1172 // See above comment on multiple integers (mutatis mutandis).
1173 else if (vr == "UL" || vr == "SL")
1176 NewInt = ReadInt32();
1180 for (int i=1; i < nbInt; i++)
1183 NewInt = ReadInt32();
1188 #ifdef GDCM_NO_ANSI_STRING_STREAM
1189 s << std::ends; // to avoid oddities on Solaris
1190 #endif //GDCM_NO_ANSI_STRING_STREAM
1192 ((ValEntry *)entry)->SetValue(s.str());
1196 // FIXME: We need an additional byte for storing \0 that is not on disk
1197 char *str = new char[length+1];
1198 Fp->read(str, (size_t)length);
1199 str[length] = '\0'; //this is only useful when length is odd
1200 // Special DicomString call to properly handle \0 and even length
1201 std::string newValue;
1204 newValue = Util::DicomString(str, length+1);
1205 gdcmWarningMacro("Warning: bad length: " << length <<
1206 ",For string :" << newValue.c_str());
1207 // Since we change the length of string update it length
1208 //entry->SetReadLength(length+1);
1212 newValue = Util::DicomString(str, length);
1216 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1218 if ( Fp->fail() || Fp->eof())
1220 gdcmWarningMacro("Unread element value");
1221 valEntry->SetValue(GDCM_UNREAD);
1227 // Because of correspondance with the VR dic
1228 valEntry->SetValue(newValue);
1232 valEntry->SetValue(newValue);
1237 gdcmErrorMacro( "Should have a ValEntry, here !");
1242 * \brief Find the value Length of the passed Header Entry
1243 * @param entry Header Entry whose length of the value shall be loaded.
1245 void Document::FindDocEntryLength( DocEntry *entry )
1246 throw ( FormatError )
1248 std::string vr = entry->GetVR();
1251 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1253 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1255 // The following reserved two bytes (see PS 3.5-2003, section
1256 // "7.1.2 Data element structure with explicit vr", p 27) must be
1257 // skipped before proceeding on reading the length on 4 bytes.
1258 Fp->seekg( 2L, std::ios::cur);
1259 uint32_t length32 = ReadInt32();
1261 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1266 lengthOB = FindDocEntryLengthOBOrOW();
1268 catch ( FormatUnexpected )
1270 // Computing the length failed (this happens with broken
1271 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1272 // chance to get the pixels by deciding the element goes
1273 // until the end of the file. Hence we artificially fix the
1274 // the length and proceed.
1275 long currentPosition = Fp->tellg();
1276 Fp->seekg(0L,std::ios::end);
1278 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1279 Fp->seekg(currentPosition, std::ios::beg);
1281 entry->SetReadLength(lengthUntilEOF);
1282 entry->SetLength(lengthUntilEOF);
1285 entry->SetReadLength(lengthOB);
1286 entry->SetLength(lengthOB);
1289 FixDocEntryFoundLength(entry, length32);
1293 // Length is encoded on 2 bytes.
1294 length16 = ReadInt16();
1296 // 0xffff means that we deal with 'No Length' Sequence
1297 // or 'No Length' SQItem
1298 if ( length16 == 0xffff)
1302 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1307 // Either implicit VR or a non DICOM conformal (see note below) explicit
1308 // VR that ommited the VR of (at least) this element. Farts happen.
1309 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1310 // on Data elements "Implicit and Explicit VR Data Elements shall
1311 // not coexist in a Data Set and Data Sets nested within it".]
1312 // Length is on 4 bytes.
1314 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1315 // even if Transfer Syntax is 'Implicit VR ...'
1317 FixDocEntryFoundLength( entry, ReadInt32() );
1323 * \brief Find the Length till the next sequence delimiter
1324 * \warning NOT end user intended method !
1327 uint32_t Document::FindDocEntryLengthOBOrOW()
1328 throw( FormatUnexpected )
1330 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1331 long positionOnEntry = Fp->tellg();
1332 bool foundSequenceDelimiter = false;
1333 uint32_t totalLength = 0;
1335 while ( !foundSequenceDelimiter )
1341 group = ReadInt16();
1344 catch ( FormatError )
1346 throw FormatError("Unexpected end of file encountered during ",
1347 "Document::FindDocEntryLengthOBOrOW()");
1349 // We have to decount the group and element we just read
1351 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1353 long filePosition = Fp->tellg();
1355 "Neither an Item tag nor a Sequence delimiter tag on :"
1356 << std::hex << group << " , " << elem
1357 << ") -before- position x(" << filePosition << ")" );
1359 Fp->seekg(positionOnEntry, std::ios::beg);
1360 throw FormatUnexpected(
1361 "Neither an Item tag nor a Sequence delimiter tag.");
1363 if ( elem == 0xe0dd )
1365 foundSequenceDelimiter = true;
1367 uint32_t itemLength = ReadInt32();
1368 // We add 4 bytes since we just read the ItemLength with ReadInt32
1369 totalLength += itemLength + 4;
1370 SkipBytes(itemLength);
1372 if ( foundSequenceDelimiter )
1377 Fp->seekg( positionOnEntry, std::ios::beg);
1382 * \brief Find the Value Representation of the current Dicom Element.
1383 * @return Value Representation of the current Entry
1385 std::string Document::FindDocEntryVR()
1387 if ( Filetype != ExplicitVR )
1388 return GDCM_UNKNOWN;
1390 long positionOnEntry = Fp->tellg();
1391 // Warning: we believe this is explicit VR (Value Representation) because
1392 // we used a heuristic that found "UL" in the first tag. Alas this
1393 // doesn't guarantee that all the tags will be in explicit VR. In some
1394 // cases (see e-film filtered files) one finds implicit VR tags mixed
1395 // within an explicit VR file. Hence we make sure the present tag
1396 // is in explicit VR and try to fix things if it happens not to be
1400 Fp->read (vr, (size_t)2);
1403 if( !CheckDocEntryVR(vr) )
1405 Fp->seekg(positionOnEntry, std::ios::beg);
1406 return GDCM_UNKNOWN;
1412 * \brief Check the correspondance between the VR of the header entry
1413 * and the taken VR. If they are different, the header entry is
1414 * updated with the new VR.
1415 * @param vr Dicom Value Representation
1416 * @return false if the VR is incorrect of if the VR isn't referenced
1417 * otherwise, it returns true
1419 bool Document::CheckDocEntryVR(VRKey vr)
1421 if ( !Global::GetVR()->IsValidVR(vr) )
1428 * \brief Get the transformed value of the header entry. The VR value
1429 * is used to define the transformation to operate on the value
1430 * \warning NOT end user intended method !
1431 * @param entry entry to tranform
1432 * @return Transformed entry value
1434 std::string Document::GetDocEntryValue(DocEntry *entry)
1436 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1438 std::string val = ((ValEntry *)entry)->GetValue();
1439 std::string vr = entry->GetVR();
1440 uint32_t length = entry->GetLength();
1441 std::ostringstream s;
1444 // When short integer(s) are expected, read and convert the following
1445 // n * 2 bytes properly i.e. as a multivaluated strings
1446 // (each single value is separated fromthe next one by '\'
1447 // as usual for standard multivaluated filels
1448 // Elements with Value Multiplicity > 1
1449 // contain a set of short integers (not a single one)
1451 if( vr == "US" || vr == "SS" )
1456 for (int i=0; i < nbInt; i++)
1462 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1463 newInt16 = SwapShort( newInt16 );
1468 // When integer(s) are expected, read and convert the following
1469 // n * 4 bytes properly i.e. as a multivaluated strings
1470 // (each single value is separated fromthe next one by '\'
1471 // as usual for standard multivaluated filels
1472 // Elements with Value Multiplicity > 1
1473 // contain a set of integers (not a single one)
1474 else if( vr == "UL" || vr == "SL" )
1479 for (int i=0; i < nbInt; i++)
1485 newInt32 = ( val[4*i+0] & 0xFF )
1486 + (( val[4*i+1] & 0xFF ) << 8 )
1487 + (( val[4*i+2] & 0xFF ) << 16 )
1488 + (( val[4*i+3] & 0xFF ) << 24 );
1489 newInt32 = SwapLong( newInt32 );
1493 #ifdef GDCM_NO_ANSI_STRING_STREAM
1494 s << std::ends; // to avoid oddities on Solaris
1495 #endif //GDCM_NO_ANSI_STRING_STREAM
1498 return ((ValEntry *)entry)->GetValue();
1502 * \brief Get the reverse transformed value of the header entry. The VR
1503 * value is used to define the reverse transformation to operate on
1505 * \warning NOT end user intended method !
1506 * @param entry Entry to reverse transform
1507 * @return Reverse transformed entry value
1509 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1511 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1513 std::string vr = entry->GetVR();
1514 std::vector<std::string> tokens;
1515 std::ostringstream s;
1517 if ( vr == "US" || vr == "SS" )
1521 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1522 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1523 for (unsigned int i=0; i<tokens.size(); i++)
1525 newInt16 = atoi(tokens[i].c_str());
1526 s << ( newInt16 & 0xFF )
1527 << (( newInt16 >> 8 ) & 0xFF );
1531 if ( vr == "UL" || vr == "SL")
1535 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1536 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1537 for (unsigned int i=0; i<tokens.size();i++)
1539 newInt32 = atoi(tokens[i].c_str());
1540 s << (char)( newInt32 & 0xFF )
1541 << (char)(( newInt32 >> 8 ) & 0xFF )
1542 << (char)(( newInt32 >> 16 ) & 0xFF )
1543 << (char)(( newInt32 >> 24 ) & 0xFF );
1548 #ifdef GDCM_NO_ANSI_STRING_STREAM
1549 s << std::ends; // to avoid oddities on Solaris
1550 #endif //GDCM_NO_ANSI_STRING_STREAM
1554 return ((ValEntry *)entry)->GetValue();
1558 * \brief Skip a given Header Entry
1559 * \warning NOT end user intended method !
1560 * @param entry entry to skip
1562 void Document::SkipDocEntry(DocEntry *entry)
1564 SkipBytes(entry->GetLength());
1568 * \brief Skips to the beginning of the next Header Entry
1569 * \warning NOT end user intended method !
1570 * @param currentDocEntry entry to skip
1572 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1574 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1575 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1576 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1580 * \brief When the length of an element value is obviously wrong (because
1581 * the parser went Jabberwocky) one can hope improving things by
1582 * applying some heuristics.
1583 * @param entry entry to check
1584 * @param foundLength first assumption about length
1586 void Document::FixDocEntryFoundLength(DocEntry *entry,
1587 uint32_t foundLength)
1589 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1590 if ( foundLength == 0xffffffff)
1595 uint16_t gr = entry->GetGroup();
1596 uint16_t elem = entry->GetElement();
1598 if ( foundLength % 2)
1600 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1601 << " in x(" << std::hex << gr << "," << elem <<")");
1604 //////// Fix for some naughty General Electric images.
1605 // Allthough not recent many such GE corrupted images are still present
1606 // on Creatis hard disks. Hence this fix shall remain when such images
1607 // are no longer in use (we are talking a few years, here)...
1608 // Note: XMedCom probably uses such a trick since it is able to read
1609 // those pesky GE images ...
1610 if ( foundLength == 13)
1612 // Only happens for this length !
1613 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1616 entry->SetReadLength(10); // a bug is to be fixed !?
1620 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1621 // Occurence of such images is quite low (unless one leaves close to a
1622 // 'Leonardo' source. Hence, one might consider commenting out the
1623 // following fix on efficiency reasons.
1624 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1627 entry->SetReadLength(4); // a bug is to be fixed !?
1630 else if ( entry->GetVR() == "SQ" )
1632 foundLength = 0; // ReadLength is unchanged
1635 //////// We encountered a 'delimiter' element i.e. a tag of the form
1636 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1637 // taken into account.
1638 else if( gr == 0xfffe )
1640 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1641 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1642 // causes extra troubles...
1643 if( entry->GetElement() != 0x0000 )
1648 entry->SetLength(foundLength);
1652 * \brief Apply some heuristics to predict whether the considered
1653 * element value contains/represents an integer or not.
1654 * @param entry The element value on which to apply the predicate.
1655 * @return The result of the heuristical predicate.
1657 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1659 uint16_t elem = entry->GetElement();
1660 uint16_t group = entry->GetGroup();
1661 const std::string &vr = entry->GetVR();
1662 uint32_t length = entry->GetLength();
1664 // When we have some semantics on the element we just read, and if we
1665 // a priori know we are dealing with an integer, then we shall be
1666 // able to swap it's element value properly.
1667 if ( elem == 0 ) // This is the group length of the group
1675 // Allthough this should never happen, still some images have a
1676 // corrupted group length [e.g. have a glance at offset x(8336) of
1677 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1678 // Since for dicom compliant and well behaved headers, the present
1679 // test is useless (and might even look a bit paranoid), when we
1680 // encounter such an ill-formed image, we simply display a warning
1681 // message and proceed on parsing (while crossing fingers).
1682 long filePosition = Fp->tellg();
1683 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1684 << std::hex << group << " , " << elem
1685 << ") -before- position x(" << filePosition << ")"
1686 << "lgt : " << length );
1690 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1698 * \brief Discover what the swap code is (among little endian, big endian,
1699 * bad little endian, bad big endian).
1701 * @return false when we are absolutely sure
1702 * it's neither ACR-NEMA nor DICOM
1703 * true when we hope ours assuptions are OK
1705 bool Document::CheckSwap()
1707 // The only guaranted way of finding the swap code is to find a
1708 // group tag since we know it's length has to be of four bytes i.e.
1709 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1710 // occurs when we can't find such group...
1717 // First, compare HostByteOrder and NetworkByteOrder in order to
1718 // determine if we shall need to swap bytes (i.e. the Endian type).
1719 bool net2host = Util::IsCurrentProcessorBigEndian();
1721 // The easiest case is the one of a 'true' DICOM header, we just have
1722 // to look for the string "DICM" inside the file preamble.
1725 char *entCur = deb + 128;
1726 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1728 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1730 // Group 0002 should always be VR, and the first element 0000
1731 // Let's be carefull (so many wrong headers ...)
1732 // and determine the value representation (VR) :
1733 // Let's skip to the first element (0002,0000) and check there if we find
1734 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1735 // in which case we (almost) know it is explicit VR.
1736 // WARNING: if it happens to be implicit VR then what we will read
1737 // is the length of the group. If this ascii representation of this
1738 // length happens to be "UL" then we shall believe it is explicit VR.
1739 // We need to skip :
1740 // * the 128 bytes of File Preamble (often padded with zeroes),
1741 // * the 4 bytes of "DICM" string,
1742 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1743 // i.e. a total of 136 bytes.
1746 // group 0x0002 *is always* Explicit VR Sometimes ,
1747 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1748 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1750 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1751 memcmp(entCur, "OB", (size_t)2) == 0 ||
1752 memcmp(entCur, "UI", (size_t)2) == 0 ||
1753 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1754 // when Write DCM *adds*
1756 // Use Document::dicom_vr to test all the possibilities
1757 // instead of just checking for UL, OB and UI !? group 0000
1759 Filetype = ExplicitVR;
1760 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1764 Filetype = ImplicitVR;
1765 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1766 << "Looks like a bugged Header!");
1772 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1777 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1780 // Position the file position indicator at first tag
1781 // (i.e. after the file preamble and the "DICM" string).
1782 Fp->seekg(0, std::ios::beg);
1783 Fp->seekg ( 132L, std::ios::beg);
1787 // Alas, this is not a DicomV3 file and whatever happens there is no file
1788 // preamble. We can reset the file position indicator to where the data
1789 // is (i.e. the beginning of the file).
1790 gdcmWarningMacro( "Not a DICOM Version3 file");
1791 Fp->seekg(0, std::ios::beg);
1793 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1794 // By clean we mean that the length of the first tag is written down.
1795 // If this is the case and since the length of the first group HAS to be
1796 // four (bytes), then determining the proper swap code is straightforward.
1799 // We assume the array of char we are considering contains the binary
1800 // representation of a 32 bits integer. Hence the following dirty
1802 s32 = *((uint32_t *)(entCur));
1823 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1824 // It is time for despaired wild guesses.
1825 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1826 // i.e. the 'group length' element is not present :
1828 // check the supposed-to-be 'group number'
1829 // in ( 0x0001 .. 0x0008 )
1830 // to determine ' SwapCode' value .
1831 // Only 0 or 4321 will be possible
1832 // (no oportunity to check for the formerly well known
1833 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1834 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1835 // the file IS NOT ACR-NEMA nor DICOM V3
1836 // Find a trick to tell it the caller...
1838 s16 = *((uint16_t *)(deb));
1865 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1873 * \brief Change the Byte Swap code.
1875 void Document::SwitchByteSwapCode()
1877 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1878 if ( SwapCode == 1234 )
1882 else if ( SwapCode == 4321 )
1886 else if ( SwapCode == 3412 )
1890 else if ( SwapCode == 2143 )
1897 * \brief during parsing, Header Elements too long are not loaded in memory
1898 * @param newSize new size
1900 void Document::SetMaxSizeLoadEntry(long newSize)
1906 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1908 MaxSizeLoadEntry = 0xffffffff;
1911 MaxSizeLoadEntry = newSize;
1915 * \brief Read the next tag but WITHOUT loading it's value
1916 * (read the 'Group Number', the 'Element Number',
1917 * gets the Dict Entry
1918 * gets the VR, gets the length, gets the offset value)
1919 * @return On succes the newly created DocEntry, NULL on failure.
1921 DocEntry *Document::ReadNextDocEntry()
1928 group = ReadInt16();
1931 catch ( FormatError e )
1933 // We reached the EOF (or an error occured) therefore
1934 // header parsing has to be considered as finished.
1938 // Sometimes file contains groups of tags with reversed endianess.
1939 HandleBrokenEndian(group, elem);
1941 // In 'true DICOM' files Group 0002 is always little endian
1942 if ( HasDCMPreamble )
1943 HandleOutOfGroup0002(group, elem);
1945 std::string vr = FindDocEntryVR();
1946 std::string realVR = vr;
1948 if( vr == GDCM_UNKNOWN)
1950 if ( elem == 0x0000 ) // Group Length
1951 realVR = "UL"; // must be UL
1954 DictEntry *dictEntry = GetDictEntry(group,elem);
1956 realVR = dictEntry->GetVR();
1961 if( Global::GetVR()->IsVROfSequence(realVR) )
1962 newEntry = NewSeqEntry(group, elem);
1963 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1964 newEntry = NewValEntry(group, elem,vr);
1966 newEntry = NewBinEntry(group, elem,vr);
1968 if( vr == GDCM_UNKNOWN )
1970 if( Filetype == ExplicitVR )
1972 // We thought this was explicit VR, but we end up with an
1973 // implicit VR tag. Let's backtrack.
1974 if ( newEntry->GetGroup() != 0xfffe )
1977 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
1978 newEntry->GetGroup(), newEntry->GetElement());
1979 gdcmWarningMacro( msg.c_str() );
1982 newEntry->SetImplicitVR();
1987 FindDocEntryLength(newEntry);
1989 catch ( FormatError e )
1996 newEntry->SetOffset(Fp->tellg());
2002 * \brief Handle broken private tag from Philips NTSCAN
2003 * where the endianess is being switch to BigEndian for no
2007 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2009 // Endian reversion. Some files contain groups of tags with reversed endianess.
2010 static int reversedEndian = 0;
2011 // try to fix endian switching in the middle of headers
2012 if ((group == 0xfeff) && (elem == 0x00e0))
2014 // start endian swap mark for group found
2016 SwitchByteSwapCode();
2021 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2023 // end of reversed endian group
2025 SwitchByteSwapCode();
2030 * \brief Group 0002 is always coded Little Endian
2031 * whatever Transfer Syntax is
2034 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2036 // Endian reversion. Some files contain groups of tags with reversed endianess.
2037 if ( !Group0002Parsed && group != 0x0002)
2039 Group0002Parsed = true;
2040 // we just came out of group 0002
2041 // if Transfer syntax is Big Endian we have to change CheckSwap
2043 std::string ts = GetTransferSyntax();
2044 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2046 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2050 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2052 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2054 Filetype = ImplicitVR;
2057 // FIXME Strangely, this works with
2058 //'Implicit VR Transfer Syntax (GE Private)
2059 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2061 gdcmWarningMacro("Transfer Syntax Name = ["
2062 << GetTransferSyntaxName() << "]" );
2063 SwitchByteSwapCode();
2064 group = SwapShort(group);
2065 elem = SwapShort(elem);
2070 //-----------------------------------------------------------------------------
2073 //-----------------------------------------------------------------------------
2074 } // end namespace gdcm