1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/03/22 11:29:37 $
7 Version: $Revision: 1.233 $
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::SetFileName
51 * and \ref Document::Load.
59 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
62 Filetype = ExplicitVR;
63 Group0002Parsed = false;
64 LoadMode = 0x00000000; // Load everything
68 * \brief Constructor (not to break the API)
69 * @param filename 'Document' (File or DicomDir) to be opened for parsing
71 Document::Document( std::string const &filename )
76 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
79 Filetype = ExplicitVR;
80 Group0002Parsed = false;
81 LoadMode = 0x00000000; // Load everything
86 * \brief Canonical destructor.
88 Document::~Document ()
94 //-----------------------------------------------------------------------------
99 * @param filename 'Document' (File or DicomDir) to be opened for parsing
101 void Document::Load( std::string const &filename )
105 // We should clean out anything that already exists.
113 Group0002Parsed = false;
115 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
117 Fp->seekg(0, std::ios::end);
118 long lgt = Fp->tellg(); // total length of the file
120 Fp->seekg(0, std::ios::beg);
123 long beg = Fp->tellg(); // just after DICOM preamble (if any)
125 lgt -= beg; // remaining length to parse
127 ParseDES( this, beg, lgt, false); // Loading is done during parsing
129 Fp->seekg( 0, std::ios::beg);
131 // Load 'non string' values
133 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
134 if( PhotometricInterpretation == "PALETTE COLOR " )
136 LoadEntryBinArea(0x0028,0x1200); // gray LUT
137 /// FIXME FIXME FIXME
138 /// The tags refered by the three following lines used to be CORRECTLY
139 /// defined as having an US Value Representation in the public
140 /// dictionary. BUT the semantics implied by the three following
141 /// lines state that the corresponding tag contents are in fact
142 /// the ones of a BinEntry.
143 /// In order to fix things "Quick and Dirty" the dictionary was
144 /// altered on PURPOSE but now contains a WRONG value.
145 /// In order to fix things and restore the dictionary to its
146 /// correct value, one needs to decided of the semantics by deciding
147 /// whether the following tags are either:
148 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
149 /// also used as BinEntry, which requires the proper conversion,
150 /// - OW, and hence loaded as BinEntry, but afterwards also used
151 /// as ValEntry, which requires the proper conversion.
152 LoadEntryBinArea(0x0028,0x1201); // R LUT
153 LoadEntryBinArea(0x0028,0x1202); // G LUT
154 LoadEntryBinArea(0x0028,0x1203); // B LUT
156 // Segmented Red Palette Color LUT Data
157 LoadEntryBinArea(0x0028,0x1221);
158 // Segmented Green Palette Color LUT Data
159 LoadEntryBinArea(0x0028,0x1222);
160 // Segmented Blue Palette Color LUT Data
161 LoadEntryBinArea(0x0028,0x1223);
163 //FIXME later : how to use it?
164 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
168 // ----------------------------
169 // Specific code to allow gdcm to read ACR-LibIDO formated images
170 // Note: ACR-LibIDO is an extension of the ACR standard that was
171 // used at CREATIS. For the time being (say a couple years)
172 // we keep this kludge to allow CREATIS users
173 // reading their old images.
175 // if recognition code tells us we deal with a LibIDO image
176 // we switch lineNumber and columnNumber
179 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
180 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
181 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
182 // with "little-endian strings"
184 Filetype = ACR_LIBIDO;
185 std::string rows = GetEntryValue(0x0028, 0x0010);
186 std::string columns = GetEntryValue(0x0028, 0x0011);
187 SetValEntry(columns, 0x0028, 0x0010);
188 SetValEntry(rows , 0x0028, 0x0011);
190 // --- End of ACR-LibIDO kludge ---
194 * \brief Get the public dictionary used
196 Dict *Document::GetPubDict()
202 * \brief Get the shadow dictionary used
204 Dict *Document::GetShaDict()
210 * \brief Set the shadow dictionary used
211 * @param dict dictionary to use in shadow
213 bool Document::SetShaDict(Dict *dict)
220 * \brief Set the shadow dictionary used
221 * @param dictName name of the dictionary to use in shadow
223 bool Document::SetShaDict(DictKey const &dictName)
225 RefShaDict = Global::GetDicts()->GetDict(dictName);
230 * \brief This predicate, based on hopefully reasonable heuristics,
231 * decides whether or not the current Document was properly parsed
232 * and contains the mandatory information for being considered as
233 * a well formed and usable Dicom/Acr File.
234 * @return true when Document is the one of a reasonable Dicom/Acr file,
237 bool Document::IsReadable()
239 if( Filetype == Unknown)
241 gdcmWarningMacro( "Wrong filetype");
247 gdcmWarningMacro( "No tag in internal hash table.");
255 * \brief Predicate for dicom version 3 file.
256 * @return True when the file is a dicom version 3.
258 bool Document::IsDicomV3()
260 // Checking if Transfer Syntax exists is enough
261 // Anyway, it's to late check if the 'Preamble' was found ...
262 // And ... would it be a rich idea to check ?
263 // (some 'no Preamble' DICOM images exist !)
264 return GetDocEntry(0x0002, 0x0010) != NULL;
268 * \brief Predicate for Papyrus file
269 * Dedicated to whomsoever it may concern
270 * @return True when the file is a Papyrus file.
272 bool Document::IsPapyrus()
274 // check for Papyrus private Sequence
275 DocEntry *e = GetDocEntry(0x0041, 0x1050);
278 // check if it's actually a Sequence
279 if ( !dynamic_cast<SeqEntry*>(e) )
285 * \brief returns the File Type
286 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
287 * @return the FileType code
289 FileType Document::GetFileType()
295 * \brief Accessor to the Transfer Syntax (when present) of the
296 * current document (it internally handles reading the
297 * value from disk when only parsing occured).
298 * @return The encountered Transfer Syntax of the current document.
300 std::string Document::GetTransferSyntax()
302 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
308 // The entry might be present but not loaded (parsing and loading
309 // happen at different stages): try loading and proceed with check...
310 LoadDocEntrySafe(entry);
311 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
313 std::string transfer = valEntry->GetValue();
314 // The actual transfer (as read from disk) might be padded. We
315 // first need to remove the potential padding. We can make the
316 // weak assumption that padding was not executed with digits...
317 if ( transfer.length() == 0 )
319 // for brain damaged headers
322 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
324 transfer.erase(transfer.length()-1, 1);
332 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
333 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
335 std::string Document::GetTransferSyntaxName()
337 // use the TS (TS : Transfer Syntax)
338 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
340 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
342 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
343 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
344 return "Uncompressed ACR-NEMA";
346 if ( transferSyntax == GDCM_UNFOUND )
348 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
349 return "Uncompressed ACR-NEMA";
352 // we do it only when we need it
353 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
355 // Global::GetTS() is a global static you shall never try to delete it!
359 // --------------- Swap Code ------------------
361 * \brief Swaps the bytes so they agree with the processor order
362 * @return The properly swaped 16 bits integer.
364 uint16_t Document::SwapShort(uint16_t a)
366 if ( SwapCode == 4321 || SwapCode == 2143 )
368 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
370 a = ( a << 8 ) | ( a >> 8 );
376 * \brief Swaps back the bytes of 4-byte long integer accordingly to
378 * @return The properly swaped 32 bits integer.
380 uint32_t Document::SwapLong(uint32_t a)
387 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
388 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
390 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
391 ((a>>8) & 0x0000ff00) | (a>>24) );
394 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
395 a=( (a<<16) | (a>>16) );
398 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
401 gdcmErrorMacro( "Unset swap code:" << SwapCode );
408 // -----------------File I/O ---------------
410 * \brief Tries to open the file \ref Document::Filename and
411 * checks the preamble when existing.
412 * @return The FILE pointer on success.
414 std::ifstream *Document::OpenFile()
416 HasDCMPreamble = false;
417 if (Filename.length() == 0)
424 gdcmWarningMacro( "File already open: " << Filename.c_str());
428 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
431 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
438 Fp->read((char*)&zero, (size_t)2);
445 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
447 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
448 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
449 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
450 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
453 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
454 gdcmWarningMacro( msg.c_str() );
459 Fp->seekg(126L, std::ios::cur);
460 char dicm[4] = {' ',' ',' ',' '};
461 Fp->read(dicm, (size_t)4);
467 if( memcmp(dicm, "DICM", 4) == 0 )
469 HasDCMPreamble = true;
474 gdcmWarningMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
480 * \brief closes the file
481 * @return TRUE if the close was successfull
483 bool Document::CloseFile()
495 * \brief Writes in a file all the Header Entries (Dicom Elements)
496 * @param fp file pointer on an already open file (actually: Output File Stream)
497 * @param filetype Type of the File to be written
498 * (ACR-NEMA, ExplicitVR, ImplicitVR)
499 * @return Always true.
501 void Document::WriteContent(std::ofstream *fp, FileType filetype)
503 // \TODO move the following lines (and a lot of others, to be written)
504 // to a future function CheckAndCorrectHeader
506 // (necessary if user wants to write a DICOM V3 file
507 // starting from an ACR-NEMA (V2) Header
509 if ( filetype == ImplicitVR || filetype == ExplicitVR )
511 // writing Dicom File Preamble
512 char filePreamble[128];
513 memset(filePreamble, 0, 128);
514 fp->write(filePreamble, 128);
515 fp->write("DICM", 4);
519 * \todo rewrite later, if really usefull
520 * - 'Group Length' element is optional in DICOM
521 * - but un-updated odd groups lengthes can causes pb
524 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
525 * UpdateGroupLength(false,filetype);
526 * if ( filetype == ACR)
527 * UpdateGroupLength(true,ACR);
530 ElementSet::WriteContent(fp, filetype); // This one is recursive
533 // -----------------------------------------
536 * \brief Loads (from disk) the element content
537 * when a string is not suitable
538 * @param group group number of the Entry
539 * @param elem element number of the Entry
541 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
543 // Search the corresponding DocEntry
544 DocEntry *docElement = GetDocEntry(group, elem);
548 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
552 LoadEntryBinArea(binElement);
556 * \brief Loads (from disk) the element content
557 * when a string is not suitable
558 * @param elem Entry whose binArea is going to be loaded
560 void Document::LoadEntryBinArea(BinEntry *elem)
562 if(elem->GetBinArea())
569 size_t o =(size_t)elem->GetOffset();
570 Fp->seekg(o, std::ios::beg);
572 size_t l = elem->GetLength();
573 uint8_t *a = new uint8_t[l];
576 gdcmWarningMacro( "Cannot allocate BinEntry content");
580 Fp->read((char*)a, l);
581 if( Fp->fail() || Fp->eof())
594 * \brief Loads the element while preserving the current
595 * underlying file position indicator as opposed to
596 * LoadDocEntry that modifies it.
597 * @param entry DocEntry whose value will be loaded.
599 void Document::LoadDocEntrySafe(DocEntry *entry)
603 long PositionOnEntry = Fp->tellg();
605 Fp->seekg(PositionOnEntry, std::ios::beg);
610 * \brief Compares two documents, according to \ref DicomDir rules
611 * \warning Does NOT work with ACR-NEMA files
612 * \todo Find a trick to solve the pb (use RET fields ?)
613 * @param document to compare with current one
614 * @return true if 'smaller'
616 bool Document::operator<(Document &document)
619 std::string s1 = GetEntryValue(0x0010,0x0010);
620 std::string s2 = document.GetEntryValue(0x0010,0x0010);
632 s1 = GetEntryValue(0x0010,0x0020);
633 s2 = document.GetEntryValue(0x0010,0x0020);
644 // Study Instance UID
645 s1 = GetEntryValue(0x0020,0x000d);
646 s2 = document.GetEntryValue(0x0020,0x000d);
657 // Serie Instance UID
658 s1 = GetEntryValue(0x0020,0x000e);
659 s2 = document.GetEntryValue(0x0020,0x000e);
674 //-----------------------------------------------------------------------------
677 * \brief Reads a supposed to be 16 Bits integer
678 * (swaps it depending on processor endianness)
681 uint16_t Document::ReadInt16()
685 Fp->read ((char*)&g, (size_t)2);
688 throw FormatError( "Document::ReadInt16()", " file error." );
692 throw FormatError( "Document::ReadInt16()", "EOF." );
699 * \brief Reads a supposed to be 32 Bits integer
700 * (swaps it depending on processor endianness)
703 uint32_t Document::ReadInt32()
707 Fp->read ((char*)&g, (size_t)4);
710 throw FormatError( "Document::ReadInt32()", " file error." );
714 throw FormatError( "Document::ReadInt32()", "EOF." );
721 * \brief skips bytes inside the source file
722 * \warning NOT end user intended method !
725 void Document::SkipBytes(uint32_t nBytes)
727 //FIXME don't dump the returned value
728 Fp->seekg((long)nBytes, std::ios::cur);
732 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
733 * @param filetype Type of the File to be written
735 int Document::ComputeGroup0002Length( FileType filetype )
741 bool found0002 = false;
743 // for each zero-level Tag in the DCM Header
744 DocEntry *entry = GetFirstEntry();
747 gr = entry->GetGroup();
753 if( entry->GetElement() != 0x0000 )
757 if( filetype == ExplicitVR )
759 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
761 // explicit VR AND OB, OW, SQ : 4 more bytes
765 groupLength += 2 + 2 + 4 + entry->GetLength();
771 entry = GetNextEntry();
776 //-----------------------------------------------------------------------------
779 * \brief Loads all the needed Dictionaries
780 * \warning NOT end user intended method !
782 void Document::Initialize()
784 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
790 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
791 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
792 * @param offset start of parsing
793 * @param l_max length to parse
794 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
796 void Document::ParseDES(DocEntrySet *set, long offset,
797 long l_max, bool delim_mode)
799 DocEntry *newDocEntry;
800 ValEntry *newValEntry;
801 BinEntry *newBinEntry;
802 SeqEntry *newSeqEntry;
808 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
814 newDocEntry = ReadNextDocEntry( );
821 vr = newDocEntry->GetVR();
822 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
823 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
824 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
826 if ( newValEntry || newBinEntry )
830 if ( Filetype == ExplicitVR &&
831 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
833 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
834 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
835 << "|" << newDocEntry->GetElement()
836 << " : Neither Valentry, nor BinEntry."
837 "Probably unknown VR.");
840 //////////////////// BinEntry or UNKOWN VR:
841 // When "this" is a Document the Key is simply of the
842 // form ( group, elem )...
843 if ( dynamic_cast< Document* > ( set ) )
845 newBinEntry->SetKey( newBinEntry->GetKey() );
847 // but when "this" is a SQItem, we are inserting this new
848 // valEntry in a sequence item, and the key has the
849 // generalized form (refer to \ref BaseTagKey):
850 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
852 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
853 + newBinEntry->GetKey() );
856 LoadDocEntry( newBinEntry );
857 if( !set->AddEntry( newBinEntry ) )
859 //Expect big troubles if here
860 //delete newBinEntry;
866 /////////////////////// ValEntry
868 // When "set" is a Document, then we are at the top of the
869 // hierarchy and the Key is simply of the form ( group, elem )...
870 if ( dynamic_cast< Document* > ( set ) )
872 newValEntry->SetKey( newValEntry->GetKey() );
874 // ...but when "set" is a SQItem, we are inserting this new
875 // valEntry in a sequence item. Hence the key has the
876 // generalized form (refer to \ref BaseTagKey):
877 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
879 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
880 + newValEntry->GetKey() );
883 LoadDocEntry( newValEntry );
884 bool delimitor=newValEntry->IsItemDelimitor();
886 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
887 // shadow groups ( if possible :
888 // whether element 0x0000 exits)
890 if ( newValEntry->GetGroup()%2 != 0 )
892 if ( newValEntry->GetElement() == 0x0000 )
894 std::string strLgrGroup = newValEntry->GetValue();
896 if ( strLgrGroup != GDCM_UNFOUND)
898 lgrGroup = atoi(strLgrGroup.c_str());
899 Fp->seekg(lgrGroup , std::ios::cur);
907 if( !set->AddEntry( newValEntry ) )
909 // If here expect big troubles
910 // delete newValEntry; //otherwise mem leak
920 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
928 // Just to make sure we are at the beginning of next entry.
929 SkipToNextDocEntry(newDocEntry);
934 unsigned long l = newDocEntry->GetReadLength();
935 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
937 if ( l == 0xffffffff )
947 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
949 Fp->seekg( l, std::ios::cur);
954 // no other way to create it ...
955 newSeqEntry->SetDelimitorMode( delim_mode );
957 // At the top of the hierarchy, stands a Document. When "set"
958 // is a Document, then we are building the first depth level.
959 // Hence the SeqEntry we are building simply has a depth
961 if ( dynamic_cast< Document* > ( set ) )
963 newSeqEntry->SetDepthLevel( 1 );
964 newSeqEntry->SetKey( newSeqEntry->GetKey() );
966 // But when "set" is already a SQItem, we are building a nested
967 // sequence, and hence the depth level of the new SeqEntry
968 // we are building, is one level deeper:
969 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
971 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
972 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
973 + newSeqEntry->GetKey() );
977 { // Don't try to parse zero-length sequences
978 ParseSQ( newSeqEntry,
979 newDocEntry->GetOffset(),
982 if( !set->AddEntry( newSeqEntry ) )
987 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1001 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1002 * @return parsed length for this level
1004 void Document::ParseSQ( SeqEntry *seqEntry,
1005 long offset, long l_max, bool delim_mode)
1007 int SQItemNumber = 0;
1009 long offsetStartCurrentSQItem = offset;
1013 // the first time, we read the fff0,e000 of the first SQItem
1014 DocEntry *newDocEntry = ReadNextDocEntry();
1018 // FIXME Should warn user
1023 if ( newDocEntry->IsSequenceDelimitor() )
1025 seqEntry->SetDelimitationItem( newDocEntry );
1029 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1034 // create the current SQItem
1035 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1036 std::ostringstream newBase;
1037 newBase << seqEntry->GetKey()
1041 itemSQ->SetBaseTagKey( newBase.str() );
1042 unsigned int l = newDocEntry->GetReadLength();
1044 if ( l == 0xffffffff )
1053 // Let's try :------------
1054 // remove fff0,e000, created out of the SQItem
1056 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1057 // fill up the current SQItem, starting at the beginning of fff0,e000
1058 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1059 offsetStartCurrentSQItem = Fp->tellg();
1060 // end try -----------------
1062 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1064 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1072 * \brief Loads the element content if its length doesn't exceed
1073 * the value specified with Document::SetMaxSizeLoadEntry()
1074 * @param entry Header Entry (Dicom Element) to be dealt with
1076 void Document::LoadDocEntry(DocEntry *entry)
1078 uint16_t group = entry->GetGroup();
1079 std::string vr = entry->GetVR();
1080 uint32_t length = entry->GetLength();
1082 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1084 // A SeQuence "contains" a set of Elements.
1085 // (fffe e000) tells us an Element is beginning
1086 // (fffe e00d) tells us an Element just ended
1087 // (fffe e0dd) tells us the current SeQuence just ended
1088 if( group == 0xfffe )
1090 // NO more value field for SQ !
1094 // When the length is zero things are easy:
1097 ((ValEntry *)entry)->SetValue("");
1101 // The elements whose length is bigger than the specified upper bound
1102 // are not loaded. Instead we leave a short notice of the offset of
1103 // the element content and it's length.
1105 std::ostringstream s;
1106 if (length > MaxSizeLoadEntry)
1108 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1110 //s << "gdcm::NotLoaded (BinEntry)";
1111 s << GDCM_NOTLOADED;
1112 s << " Address:" << (long)entry->GetOffset();
1113 s << " Length:" << entry->GetLength();
1114 s << " x(" << std::hex << entry->GetLength() << ")";
1115 binEntryPtr->SetValue(s.str());
1117 // Be carefull : a BinEntry IS_A ValEntry ...
1118 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1120 // s << "gdcm::NotLoaded. (ValEntry)";
1121 s << GDCM_NOTLOADED;
1122 s << " Address:" << (long)entry->GetOffset();
1123 s << " Length:" << entry->GetLength();
1124 s << " x(" << std::hex << entry->GetLength() << ")";
1125 valEntryPtr->SetValue(s.str());
1130 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1131 << "nor a ValEntry ?! Should never print that !" );
1134 // to be sure we are at the end of the value ...
1135 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1140 // When we find a BinEntry not very much can be done :
1141 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1143 s << GDCM_BINLOADED;
1144 binEntryPtr->SetValue(s.str());
1145 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1149 if ( IsDocEntryAnInteger(entry) )
1153 // When short integer(s) are expected, read and convert the following
1154 // n *two characters properly i.e. consider them as short integers as
1155 // opposed to strings.
1156 // Elements with Value Multiplicity > 1
1157 // contain a set of integers (not a single one)
1158 if (vr == "US" || vr == "SS")
1161 NewInt = ReadInt16();
1165 for (int i=1; i < nbInt; i++)
1168 NewInt = ReadInt16();
1173 // See above comment on multiple integers (mutatis mutandis).
1174 else if (vr == "UL" || vr == "SL")
1177 NewInt = ReadInt32();
1181 for (int i=1; i < nbInt; i++)
1184 NewInt = ReadInt32();
1189 #ifdef GDCM_NO_ANSI_STRING_STREAM
1190 s << std::ends; // to avoid oddities on Solaris
1191 #endif //GDCM_NO_ANSI_STRING_STREAM
1193 ((ValEntry *)entry)->SetValue(s.str());
1197 // FIXME: We need an additional byte for storing \0 that is not on disk
1198 char *str = new char[length+1];
1199 Fp->read(str, (size_t)length);
1200 str[length] = '\0'; //this is only useful when length is odd
1201 // Special DicomString call to properly handle \0 and even length
1202 std::string newValue;
1205 newValue = Util::DicomString(str, length+1);
1206 gdcmWarningMacro("Warning: bad length: " << length <<
1207 ",For string :" << newValue.c_str());
1208 // Since we change the length of string update it length
1209 //entry->SetReadLength(length+1);
1213 newValue = Util::DicomString(str, length);
1217 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1219 if ( Fp->fail() || Fp->eof())
1221 gdcmWarningMacro("Unread element value");
1222 valEntry->SetValue(GDCM_UNREAD);
1228 // Because of correspondance with the VR dic
1229 valEntry->SetValue(newValue);
1233 valEntry->SetValue(newValue);
1238 gdcmErrorMacro( "Should have a ValEntry, here !");
1243 * \brief Find the value Length of the passed Header Entry
1244 * @param entry Header Entry whose length of the value shall be loaded.
1246 void Document::FindDocEntryLength( DocEntry *entry )
1247 throw ( FormatError )
1249 std::string vr = entry->GetVR();
1252 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1254 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1256 // The following reserved two bytes (see PS 3.5-2003, section
1257 // "7.1.2 Data element structure with explicit vr", p 27) must be
1258 // skipped before proceeding on reading the length on 4 bytes.
1259 Fp->seekg( 2L, std::ios::cur);
1260 uint32_t length32 = ReadInt32();
1262 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1267 lengthOB = FindDocEntryLengthOBOrOW();
1269 catch ( FormatUnexpected )
1271 // Computing the length failed (this happens with broken
1272 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1273 // chance to get the pixels by deciding the element goes
1274 // until the end of the file. Hence we artificially fix the
1275 // the length and proceed.
1276 long currentPosition = Fp->tellg();
1277 Fp->seekg(0L,std::ios::end);
1279 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1280 Fp->seekg(currentPosition, std::ios::beg);
1282 entry->SetReadLength(lengthUntilEOF);
1283 entry->SetLength(lengthUntilEOF);
1286 entry->SetReadLength(lengthOB);
1287 entry->SetLength(lengthOB);
1290 FixDocEntryFoundLength(entry, length32);
1294 // Length is encoded on 2 bytes.
1295 length16 = ReadInt16();
1297 // 0xffff means that we deal with 'No Length' Sequence
1298 // or 'No Length' SQItem
1299 if ( length16 == 0xffff)
1303 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1308 // Either implicit VR or a non DICOM conformal (see note below) explicit
1309 // VR that ommited the VR of (at least) this element. Farts happen.
1310 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1311 // on Data elements "Implicit and Explicit VR Data Elements shall
1312 // not coexist in a Data Set and Data Sets nested within it".]
1313 // Length is on 4 bytes.
1315 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1316 // even if Transfer Syntax is 'Implicit VR ...'
1318 FixDocEntryFoundLength( entry, ReadInt32() );
1324 * \brief Find the Length till the next sequence delimiter
1325 * \warning NOT end user intended method !
1328 uint32_t Document::FindDocEntryLengthOBOrOW()
1329 throw( FormatUnexpected )
1331 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1332 long positionOnEntry = Fp->tellg();
1333 bool foundSequenceDelimiter = false;
1334 uint32_t totalLength = 0;
1336 while ( !foundSequenceDelimiter )
1342 group = ReadInt16();
1345 catch ( FormatError )
1347 throw FormatError("Unexpected end of file encountered during ",
1348 "Document::FindDocEntryLengthOBOrOW()");
1350 // We have to decount the group and element we just read
1352 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1354 long filePosition = Fp->tellg();
1356 "Neither an Item tag nor a Sequence delimiter tag on :"
1357 << std::hex << group << " , " << elem
1358 << ") -before- position x(" << filePosition << ")" );
1360 Fp->seekg(positionOnEntry, std::ios::beg);
1361 throw FormatUnexpected(
1362 "Neither an Item tag nor a Sequence delimiter tag.");
1364 if ( elem == 0xe0dd )
1366 foundSequenceDelimiter = true;
1368 uint32_t itemLength = ReadInt32();
1369 // We add 4 bytes since we just read the ItemLength with ReadInt32
1370 totalLength += itemLength + 4;
1371 SkipBytes(itemLength);
1373 if ( foundSequenceDelimiter )
1378 Fp->seekg( positionOnEntry, std::ios::beg);
1383 * \brief Find the Value Representation of the current Dicom Element.
1384 * @return Value Representation of the current Entry
1386 std::string Document::FindDocEntryVR()
1388 if ( Filetype != ExplicitVR )
1389 return GDCM_UNKNOWN;
1391 long positionOnEntry = Fp->tellg();
1392 // Warning: we believe this is explicit VR (Value Representation) because
1393 // we used a heuristic that found "UL" in the first tag. Alas this
1394 // doesn't guarantee that all the tags will be in explicit VR. In some
1395 // cases (see e-film filtered files) one finds implicit VR tags mixed
1396 // within an explicit VR file. Hence we make sure the present tag
1397 // is in explicit VR and try to fix things if it happens not to be
1401 Fp->read (vr, (size_t)2);
1404 if( !CheckDocEntryVR(vr) )
1406 Fp->seekg(positionOnEntry, std::ios::beg);
1407 return GDCM_UNKNOWN;
1413 * \brief Check the correspondance between the VR of the header entry
1414 * and the taken VR. If they are different, the header entry is
1415 * updated with the new VR.
1416 * @param vr Dicom Value Representation
1417 * @return false if the VR is incorrect of if the VR isn't referenced
1418 * otherwise, it returns true
1420 bool Document::CheckDocEntryVR(VRKey vr)
1422 if ( !Global::GetVR()->IsValidVR(vr) )
1429 * \brief Get the transformed value of the header entry. The VR value
1430 * is used to define the transformation to operate on the value
1431 * \warning NOT end user intended method !
1432 * @param entry entry to tranform
1433 * @return Transformed entry value
1435 std::string Document::GetDocEntryValue(DocEntry *entry)
1437 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1439 std::string val = ((ValEntry *)entry)->GetValue();
1440 std::string vr = entry->GetVR();
1441 uint32_t length = entry->GetLength();
1442 std::ostringstream s;
1445 // When short integer(s) are expected, read and convert the following
1446 // n * 2 bytes properly i.e. as a multivaluated strings
1447 // (each single value is separated fromthe next one by '\'
1448 // as usual for standard multivaluated filels
1449 // Elements with Value Multiplicity > 1
1450 // contain a set of short integers (not a single one)
1452 if( vr == "US" || vr == "SS" )
1457 for (int i=0; i < nbInt; i++)
1463 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1464 newInt16 = SwapShort( newInt16 );
1469 // When integer(s) are expected, read and convert the following
1470 // n * 4 bytes properly i.e. as a multivaluated strings
1471 // (each single value is separated fromthe next one by '\'
1472 // as usual for standard multivaluated filels
1473 // Elements with Value Multiplicity > 1
1474 // contain a set of integers (not a single one)
1475 else if( vr == "UL" || vr == "SL" )
1480 for (int i=0; i < nbInt; i++)
1486 newInt32 = ( val[4*i+0] & 0xFF )
1487 + (( val[4*i+1] & 0xFF ) << 8 )
1488 + (( val[4*i+2] & 0xFF ) << 16 )
1489 + (( val[4*i+3] & 0xFF ) << 24 );
1490 newInt32 = SwapLong( newInt32 );
1494 #ifdef GDCM_NO_ANSI_STRING_STREAM
1495 s << std::ends; // to avoid oddities on Solaris
1496 #endif //GDCM_NO_ANSI_STRING_STREAM
1499 return ((ValEntry *)entry)->GetValue();
1503 * \brief Get the reverse transformed value of the header entry. The VR
1504 * value is used to define the reverse transformation to operate on
1506 * \warning NOT end user intended method !
1507 * @param entry Entry to reverse transform
1508 * @return Reverse transformed entry value
1510 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1512 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1514 std::string vr = entry->GetVR();
1515 std::vector<std::string> tokens;
1516 std::ostringstream s;
1518 if ( vr == "US" || vr == "SS" )
1522 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1523 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1524 for (unsigned int i=0; i<tokens.size(); i++)
1526 newInt16 = atoi(tokens[i].c_str());
1527 s << ( newInt16 & 0xFF )
1528 << (( newInt16 >> 8 ) & 0xFF );
1532 if ( vr == "UL" || vr == "SL")
1536 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1537 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1538 for (unsigned int i=0; i<tokens.size();i++)
1540 newInt32 = atoi(tokens[i].c_str());
1541 s << (char)( newInt32 & 0xFF )
1542 << (char)(( newInt32 >> 8 ) & 0xFF )
1543 << (char)(( newInt32 >> 16 ) & 0xFF )
1544 << (char)(( newInt32 >> 24 ) & 0xFF );
1549 #ifdef GDCM_NO_ANSI_STRING_STREAM
1550 s << std::ends; // to avoid oddities on Solaris
1551 #endif //GDCM_NO_ANSI_STRING_STREAM
1555 return ((ValEntry *)entry)->GetValue();
1559 * \brief Skip a given Header Entry
1560 * \warning NOT end user intended method !
1561 * @param entry entry to skip
1563 void Document::SkipDocEntry(DocEntry *entry)
1565 SkipBytes(entry->GetLength());
1569 * \brief Skips to the beginning of the next Header Entry
1570 * \warning NOT end user intended method !
1571 * @param currentDocEntry entry to skip
1573 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1575 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1576 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1577 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1581 * \brief When the length of an element value is obviously wrong (because
1582 * the parser went Jabberwocky) one can hope improving things by
1583 * applying some heuristics.
1584 * @param entry entry to check
1585 * @param foundLength first assumption about length
1587 void Document::FixDocEntryFoundLength(DocEntry *entry,
1588 uint32_t foundLength)
1590 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1591 if ( foundLength == 0xffffffff)
1596 uint16_t gr = entry->GetGroup();
1597 uint16_t elem = entry->GetElement();
1599 if ( foundLength % 2)
1601 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1602 << " in x(" << std::hex << gr << "," << elem <<")");
1605 //////// Fix for some naughty General Electric images.
1606 // Allthough not recent many such GE corrupted images are still present
1607 // on Creatis hard disks. Hence this fix shall remain when such images
1608 // are no longer in use (we are talking a few years, here)...
1609 // Note: XMedCom probably uses such a trick since it is able to read
1610 // those pesky GE images ...
1611 if ( foundLength == 13)
1613 // Only happens for this length !
1614 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1617 entry->SetReadLength(10); // a bug is to be fixed !?
1621 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1622 // Occurence of such images is quite low (unless one leaves close to a
1623 // 'Leonardo' source. Hence, one might consider commenting out the
1624 // following fix on efficiency reasons.
1625 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1628 entry->SetReadLength(4); // a bug is to be fixed !?
1631 else if ( entry->GetVR() == "SQ" )
1633 foundLength = 0; // ReadLength is unchanged
1636 //////// We encountered a 'delimiter' element i.e. a tag of the form
1637 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1638 // taken into account.
1639 else if( gr == 0xfffe )
1641 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1642 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1643 // causes extra troubles...
1644 if( entry->GetElement() != 0x0000 )
1649 entry->SetLength(foundLength);
1653 * \brief Apply some heuristics to predict whether the considered
1654 * element value contains/represents an integer or not.
1655 * @param entry The element value on which to apply the predicate.
1656 * @return The result of the heuristical predicate.
1658 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1660 uint16_t elem = entry->GetElement();
1661 uint16_t group = entry->GetGroup();
1662 const std::string &vr = entry->GetVR();
1663 uint32_t length = entry->GetLength();
1665 // When we have some semantics on the element we just read, and if we
1666 // a priori know we are dealing with an integer, then we shall be
1667 // able to swap it's element value properly.
1668 if ( elem == 0 ) // This is the group length of the group
1676 // Allthough this should never happen, still some images have a
1677 // corrupted group length [e.g. have a glance at offset x(8336) of
1678 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1679 // Since for dicom compliant and well behaved headers, the present
1680 // test is useless (and might even look a bit paranoid), when we
1681 // encounter such an ill-formed image, we simply display a warning
1682 // message and proceed on parsing (while crossing fingers).
1683 long filePosition = Fp->tellg();
1684 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1685 << std::hex << group << " , " << elem
1686 << ") -before- position x(" << filePosition << ")"
1687 << "lgt : " << length );
1691 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1699 * \brief Discover what the swap code is (among little endian, big endian,
1700 * bad little endian, bad big endian).
1702 * @return false when we are absolutely sure
1703 * it's neither ACR-NEMA nor DICOM
1704 * true when we hope ours assuptions are OK
1706 bool Document::CheckSwap()
1708 // The only guaranted way of finding the swap code is to find a
1709 // group tag since we know it's length has to be of four bytes i.e.
1710 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1711 // occurs when we can't find such group...
1718 // First, compare HostByteOrder and NetworkByteOrder in order to
1719 // determine if we shall need to swap bytes (i.e. the Endian type).
1720 bool net2host = Util::IsCurrentProcessorBigEndian();
1722 // The easiest case is the one of a 'true' DICOM header, we just have
1723 // to look for the string "DICM" inside the file preamble.
1726 char *entCur = deb + 128;
1727 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1729 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1731 // Group 0002 should always be VR, and the first element 0000
1732 // Let's be carefull (so many wrong headers ...)
1733 // and determine the value representation (VR) :
1734 // Let's skip to the first element (0002,0000) and check there if we find
1735 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1736 // in which case we (almost) know it is explicit VR.
1737 // WARNING: if it happens to be implicit VR then what we will read
1738 // is the length of the group. If this ascii representation of this
1739 // length happens to be "UL" then we shall believe it is explicit VR.
1740 // We need to skip :
1741 // * the 128 bytes of File Preamble (often padded with zeroes),
1742 // * the 4 bytes of "DICM" string,
1743 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1744 // i.e. a total of 136 bytes.
1747 // group 0x0002 *is always* Explicit VR Sometimes ,
1748 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1749 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1751 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1752 memcmp(entCur, "OB", (size_t)2) == 0 ||
1753 memcmp(entCur, "UI", (size_t)2) == 0 ||
1754 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1755 // when Write DCM *adds*
1757 // Use Document::dicom_vr to test all the possibilities
1758 // instead of just checking for UL, OB and UI !? group 0000
1760 Filetype = ExplicitVR;
1761 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1765 Filetype = ImplicitVR;
1766 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1767 << "Looks like a bugged Header!");
1773 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1778 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1781 // Position the file position indicator at first tag
1782 // (i.e. after the file preamble and the "DICM" string).
1783 Fp->seekg(0, std::ios::beg);
1784 Fp->seekg ( 132L, std::ios::beg);
1788 // Alas, this is not a DicomV3 file and whatever happens there is no file
1789 // preamble. We can reset the file position indicator to where the data
1790 // is (i.e. the beginning of the file).
1791 gdcmWarningMacro( "Not a DICOM Version3 file");
1792 Fp->seekg(0, std::ios::beg);
1794 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1795 // By clean we mean that the length of the first tag is written down.
1796 // If this is the case and since the length of the first group HAS to be
1797 // four (bytes), then determining the proper swap code is straightforward.
1800 // We assume the array of char we are considering contains the binary
1801 // representation of a 32 bits integer. Hence the following dirty
1803 s32 = *((uint32_t *)(entCur));
1824 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1825 // It is time for despaired wild guesses.
1826 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1827 // i.e. the 'group length' element is not present :
1829 // check the supposed-to-be 'group number'
1830 // in ( 0x0001 .. 0x0008 )
1831 // to determine ' SwapCode' value .
1832 // Only 0 or 4321 will be possible
1833 // (no oportunity to check for the formerly well known
1834 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1835 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1836 // the file IS NOT ACR-NEMA nor DICOM V3
1837 // Find a trick to tell it the caller...
1839 s16 = *((uint16_t *)(deb));
1866 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1874 * \brief Change the Byte Swap code.
1876 void Document::SwitchByteSwapCode()
1878 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1879 if ( SwapCode == 1234 )
1883 else if ( SwapCode == 4321 )
1887 else if ( SwapCode == 3412 )
1891 else if ( SwapCode == 2143 )
1898 * \brief during parsing, Header Elements too long are not loaded in memory
1899 * @param newSize new size
1901 void Document::SetMaxSizeLoadEntry(long newSize)
1907 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1909 MaxSizeLoadEntry = 0xffffffff;
1912 MaxSizeLoadEntry = newSize;
1916 * \brief Read the next tag but WITHOUT loading it's value
1917 * (read the 'Group Number', the 'Element Number',
1918 * gets the Dict Entry
1919 * gets the VR, gets the length, gets the offset value)
1920 * @return On succes the newly created DocEntry, NULL on failure.
1922 DocEntry *Document::ReadNextDocEntry()
1929 group = ReadInt16();
1932 catch ( FormatError e )
1934 // We reached the EOF (or an error occured) therefore
1935 // header parsing has to be considered as finished.
1939 // Sometimes file contains groups of tags with reversed endianess.
1940 HandleBrokenEndian(group, elem);
1942 // In 'true DICOM' files Group 0002 is always little endian
1943 if ( HasDCMPreamble )
1944 HandleOutOfGroup0002(group, elem);
1946 std::string vr = FindDocEntryVR();
1947 std::string realVR = vr;
1949 if( vr == GDCM_UNKNOWN)
1951 if ( elem == 0x0000 ) // Group Length
1952 realVR = "UL"; // must be UL
1955 DictEntry *dictEntry = GetDictEntry(group,elem);
1957 realVR = dictEntry->GetVR();
1962 if( Global::GetVR()->IsVROfSequence(realVR) )
1963 newEntry = NewSeqEntry(group, elem);
1964 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1965 newEntry = NewValEntry(group, elem,vr);
1967 newEntry = NewBinEntry(group, elem,vr);
1969 if( vr == GDCM_UNKNOWN )
1971 if( Filetype == ExplicitVR )
1973 // We thought this was explicit VR, but we end up with an
1974 // implicit VR tag. Let's backtrack.
1975 if ( newEntry->GetGroup() != 0xfffe )
1978 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
1979 newEntry->GetGroup(), newEntry->GetElement());
1980 gdcmWarningMacro( msg.c_str() );
1983 newEntry->SetImplicitVR();
1988 FindDocEntryLength(newEntry);
1990 catch ( FormatError e )
1997 newEntry->SetOffset(Fp->tellg());
2003 * \brief Handle broken private tag from Philips NTSCAN
2004 * where the endianess is being switch to BigEndian for no
2008 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2010 // Endian reversion. Some files contain groups of tags with reversed endianess.
2011 static int reversedEndian = 0;
2012 // try to fix endian switching in the middle of headers
2013 if ((group == 0xfeff) && (elem == 0x00e0))
2015 // start endian swap mark for group found
2017 SwitchByteSwapCode();
2022 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2024 // end of reversed endian group
2026 SwitchByteSwapCode();
2031 * \brief Group 0002 is always coded Little Endian
2032 * whatever Transfer Syntax is
2035 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2037 // Endian reversion. Some files contain groups of tags with reversed endianess.
2038 if ( !Group0002Parsed && group != 0x0002)
2040 Group0002Parsed = true;
2041 // we just came out of group 0002
2042 // if Transfer syntax is Big Endian we have to change CheckSwap
2044 std::string ts = GetTransferSyntax();
2045 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2047 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2051 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2053 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2055 Filetype = ImplicitVR;
2058 // FIXME Strangely, this works with
2059 //'Implicit VR Transfer Syntax (GE Private)
2060 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2062 gdcmWarningMacro("Transfer Syntax Name = ["
2063 << GetTransferSyntaxName() << "]" );
2064 SwitchByteSwapCode();
2065 group = SwapShort(group);
2066 elem = SwapShort(elem);
2071 //-----------------------------------------------------------------------------
2074 //-----------------------------------------------------------------------------
2075 } // end namespace gdcm