1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/04/26 16:18:23 $
7 Version: $Revision: 1.237 $
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 // Load will set it to true if sucessfull
63 Group0002Parsed = false;
64 IsDocumentAlreadyLoaded = false;
65 LoadMode = 0x00000000; // default : load everything, later
69 * \brief Constructor (not to break the API)
70 * @param filename 'Document' (File or DicomDir) to be opened for parsing
72 Document::Document( std::string const &filename )
77 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
80 Filetype = ExplicitVR;
81 Group0002Parsed = false;
82 LoadMode = 0x00000000; // Load everything
84 // Load will set it to true if sucessfull
85 IsDocumentAlreadyLoaded = false;
90 * \brief Canonical destructor.
92 Document::~Document ()
98 //-----------------------------------------------------------------------------
103 * @param filename 'Document' (File or DicomDir) to be opened for parsing
105 void Document::Load( std::string const &filename )
107 // We should clean out anything that already exists.
108 // Check IsDocumentAlreadyLoaded to be sure.
109 if( IsDocumentAlreadyLoaded )
111 gdcmWarningMacro( "A file was already parsed inside this " <<
112 "gdcm::Document (previous name was: "
113 << Filename.c_str() << ". New name is :"
115 // todo : clean out the 'Document'
116 // We should call ClearEntry() on the parent object ?!?
124 // warning already performed in OpenFile()
125 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
126 // << Filename.c_str() );
131 Group0002Parsed = false;
133 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
135 Fp->seekg(0, std::ios::end);
136 long lgt = Fp->tellg(); // total length of the file
138 Fp->seekg(0, std::ios::beg);
140 // CheckSwap returns a boolean
141 // (false if no swap info of any kind was found)
144 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
145 << Filename.c_str());
150 long beg = Fp->tellg(); // just after DICOM preamble (if any)
152 lgt -= beg; // remaining length to parse
154 ParseDES( this, beg, lgt, false); // Loading is done during parsing
158 gdcmWarningMacro( "No tag in internal hash table for: "
159 << Filename.c_str());
163 IsDocumentAlreadyLoaded = true;
165 Fp->seekg( 0, std::ios::beg);
167 // Load 'non string' values
169 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
170 if( PhotometricInterpretation == "PALETTE COLOR " )
172 LoadEntryBinArea(0x0028,0x1200); // gray LUT
173 /// FIXME FIXME FIXME
174 /// The tags refered by the three following lines used to be CORRECTLY
175 /// defined as having an US Value Representation in the public
176 /// dictionary. BUT the semantics implied by the three following
177 /// lines state that the corresponding tag contents are in fact
178 /// the ones of a BinEntry.
179 /// In order to fix things "Quick and Dirty" the dictionary was
180 /// altered on PURPOSE but now contains a WRONG value.
181 /// In order to fix things and restore the dictionary to its
182 /// correct value, one needs to decided of the semantics by deciding
183 /// whether the following tags are either:
184 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
185 /// also used as BinEntry, which requires the proper conversion,
186 /// - OW, and hence loaded as BinEntry, but afterwards also used
187 /// as ValEntry, which requires the proper conversion.
188 LoadEntryBinArea(0x0028,0x1201); // R LUT
189 LoadEntryBinArea(0x0028,0x1202); // G LUT
190 LoadEntryBinArea(0x0028,0x1203); // B LUT
192 // Segmented Red Palette Color LUT Data
193 LoadEntryBinArea(0x0028,0x1221);
194 // Segmented Green Palette Color LUT Data
195 LoadEntryBinArea(0x0028,0x1222);
196 // Segmented Blue Palette Color LUT Data
197 LoadEntryBinArea(0x0028,0x1223);
199 //FIXME later : how to use it?
200 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
204 // ----------------------------
205 // Specific code to allow gdcm to read ACR-LibIDO formated images
206 // Note: ACR-LibIDO is an extension of the ACR standard that was
207 // used at CREATIS. For the time being (say a couple years)
208 // we keep this kludge to allow CREATIS users
209 // reading their old images.
211 // if recognition code tells us we deal with a LibIDO image
212 // we switch lineNumber and columnNumber
215 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
216 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
217 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
218 // with "little-endian strings"
220 Filetype = ACR_LIBIDO;
221 std::string rows = GetEntryValue(0x0028, 0x0010);
222 std::string columns = GetEntryValue(0x0028, 0x0011);
223 SetValEntry(columns, 0x0028, 0x0010);
224 SetValEntry(rows , 0x0028, 0x0011);
226 // --- End of ACR-LibIDO kludge ---
230 * \brief Get the public dictionary used
232 Dict *Document::GetPubDict()
238 * \brief Get the shadow dictionary used
240 Dict *Document::GetShaDict()
246 * \brief Set the shadow dictionary used
247 * @param dict dictionary to use in shadow
249 bool Document::SetShaDict(Dict *dict)
256 * \brief Set the shadow dictionary used
257 * @param dictName name of the dictionary to use in shadow
259 bool Document::SetShaDict(DictKey const &dictName)
261 RefShaDict = Global::GetDicts()->GetDict(dictName);
266 * \brief This predicate tells us whether or not the current Document
267 * was properly parsed and contains at least *one* Dicom Element
268 * (and nothing more, sorry).
269 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
272 bool Document::IsReadable()
274 if( Filetype == Unknown)
276 gdcmWarningMacro( "Wrong filetype");
282 gdcmWarningMacro( "No tag in internal hash table.");
290 * \brief Predicate for dicom version 3 file.
291 * @return True when the file is a dicom version 3.
293 bool Document::IsDicomV3()
295 // Checking if Transfer Syntax exists is enough
296 // Anyway, it's too late check if the 'Preamble' was found ...
297 // And ... would it be a rich idea to check ?
298 // (some 'no Preamble' DICOM images exist !)
299 return GetDocEntry(0x0002, 0x0010) != NULL;
303 * \brief Predicate for Papyrus file
304 * Dedicated to whomsoever it may concern
305 * @return True when the file is a Papyrus file.
307 bool Document::IsPapyrus()
309 // check for Papyrus private Sequence
310 DocEntry *e = GetDocEntry(0x0041, 0x1050);
313 // check if it's actually a Sequence
314 if ( !dynamic_cast<SeqEntry*>(e) )
320 * \brief returns the File Type
321 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
322 * @return the FileType code
324 FileType Document::GetFileType()
330 * \brief Accessor to the Transfer Syntax (when present) of the
331 * current document (it internally handles reading the
332 * value from disk when only parsing occured).
333 * @return The encountered Transfer Syntax of the current document.
335 std::string Document::GetTransferSyntax()
337 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
343 // The entry might be present but not loaded (parsing and loading
344 // happen at different stages): try loading and proceed with check...
345 LoadDocEntrySafe(entry);
346 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
348 std::string transfer = valEntry->GetValue();
349 // The actual transfer (as read from disk) might be padded. We
350 // first need to remove the potential padding. We can make the
351 // weak assumption that padding was not executed with digits...
352 if ( transfer.length() == 0 )
354 // for brain damaged headers
357 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
359 transfer.erase(transfer.length()-1, 1);
367 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
368 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
370 std::string Document::GetTransferSyntaxName()
372 // use the TS (TS : Transfer Syntax)
373 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
375 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
377 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
378 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
379 return "Uncompressed ACR-NEMA";
381 if ( transferSyntax == GDCM_UNFOUND )
383 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
384 return "Uncompressed ACR-NEMA";
387 // we do it only when we need it
388 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
390 // Global::GetTS() is a global static you shall never try to delete it!
394 // --------------- Swap Code ------------------
396 * \brief Swaps the bytes so they agree with the processor order
397 * @return The properly swaped 16 bits integer.
399 uint16_t Document::SwapShort(uint16_t a)
401 if ( SwapCode == 4321 || SwapCode == 2143 )
403 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
405 a = ( a << 8 ) | ( a >> 8 );
411 * \brief Swaps back the bytes of 4-byte long integer accordingly to
413 * @return The properly swaped 32 bits integer.
415 uint32_t Document::SwapLong(uint32_t a)
422 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
423 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
425 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
426 ((a>>8) & 0x0000ff00) | (a>>24) );
429 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
430 a=( (a<<16) | (a>>16) );
433 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
436 gdcmErrorMacro( "Unset swap code:" << SwapCode );
443 // -----------------File I/O ---------------
445 * \brief Tries to open the file \ref Document::Filename and
446 * checks the preamble when existing.
447 * @return The FILE pointer on success.
449 std::ifstream *Document::OpenFile()
451 HasDCMPreamble = false;
452 if (Filename.length() == 0)
459 gdcmWarningMacro( "File already open: " << Filename.c_str());
463 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
466 gdcmErrorMacro( "Cannot open file: " << Filename.c_str());
470 //exit(1); // No function is allowed to leave the application instead
471 // of warning the caller
475 Fp->read((char*)&zero, (size_t)2);
482 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
484 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
485 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
486 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
487 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
489 std::string msg = Util::Format(
490 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
491 gdcmWarningMacro( msg.c_str() );
496 Fp->seekg(126L, std::ios::cur);
497 char dicm[4] = {' ',' ',' ',' '};
498 Fp->read(dicm, (size_t)4);
504 if( memcmp(dicm, "DICM", 4) == 0 )
506 HasDCMPreamble = true;
510 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
512 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
513 << Filename.c_str());
518 * \brief closes the file
519 * @return TRUE if the close was successfull
521 bool Document::CloseFile()
533 * \brief Writes in a file all the Header Entries (Dicom Elements)
534 * @param fp file pointer on an already open file (actually: Output File Stream)
535 * @param filetype Type of the File to be written
536 * (ACR-NEMA, ExplicitVR, ImplicitVR)
537 * @return Always true.
539 void Document::WriteContent(std::ofstream *fp, FileType filetype)
541 // \TODO move the following lines (and a lot of others, to be written)
542 // to a future function CheckAndCorrectHeader
544 // (necessary if user wants to write a DICOM V3 file
545 // starting from an ACR-NEMA (V2) Header
547 if ( filetype == ImplicitVR || filetype == ExplicitVR )
549 // writing Dicom File Preamble
550 char filePreamble[128];
551 memset(filePreamble, 0, 128);
552 fp->write(filePreamble, 128);
553 fp->write("DICM", 4);
557 * \todo rewrite later, if really usefull
558 * - 'Group Length' element is optional in DICOM
559 * - but un-updated odd groups lengthes can causes pb
562 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
563 * UpdateGroupLength(false,filetype);
564 * if ( filetype == ACR)
565 * UpdateGroupLength(true,ACR);
568 ElementSet::WriteContent(fp, filetype); // This one is recursive
571 // -----------------------------------------
574 * \brief Loads (from disk) the element content
575 * when a string is not suitable
576 * @param group group number of the Entry
577 * @param elem element number of the Entry
579 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
581 // Search the corresponding DocEntry
582 DocEntry *docElement = GetDocEntry(group, elem);
586 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
590 LoadEntryBinArea(binElement);
594 * \brief Loads (from disk) the element content
595 * when a string is not suitable
596 * @param elem Entry whose binArea is going to be loaded
598 void Document::LoadEntryBinArea(BinEntry *elem)
600 if(elem->GetBinArea())
607 size_t o =(size_t)elem->GetOffset();
608 Fp->seekg(o, std::ios::beg);
610 size_t l = elem->GetLength();
611 uint8_t *a = new uint8_t[l];
614 gdcmWarningMacro( "Cannot allocate BinEntry content");
618 Fp->read((char*)a, l);
619 if( Fp->fail() || Fp->eof())
632 * \brief Loads the element while preserving the current
633 * underlying file position indicator as opposed to
634 * LoadDocEntry that modifies it.
635 * @param entry DocEntry whose value will be loaded.
637 void Document::LoadDocEntrySafe(DocEntry *entry)
641 long PositionOnEntry = Fp->tellg();
643 Fp->seekg(PositionOnEntry, std::ios::beg);
648 * \brief Compares two documents, according to \ref DicomDir rules
649 * \warning Does NOT work with ACR-NEMA files
650 * \todo Find a trick to solve the pb (use RET fields ?)
651 * @param document to compare with current one
652 * @return true if 'smaller'
654 bool Document::operator<(Document &document)
657 std::string s1 = GetEntryValue(0x0010,0x0010);
658 std::string s2 = document.GetEntryValue(0x0010,0x0010);
670 s1 = GetEntryValue(0x0010,0x0020);
671 s2 = document.GetEntryValue(0x0010,0x0020);
682 // Study Instance UID
683 s1 = GetEntryValue(0x0020,0x000d);
684 s2 = document.GetEntryValue(0x0020,0x000d);
695 // Serie Instance UID
696 s1 = GetEntryValue(0x0020,0x000e);
697 s2 = document.GetEntryValue(0x0020,0x000e);
712 //-----------------------------------------------------------------------------
715 * \brief Reads a supposed to be 16 Bits integer
716 * (swaps it depending on processor endianness)
719 uint16_t Document::ReadInt16()
723 Fp->read ((char*)&g, (size_t)2);
726 throw FormatError( "Document::ReadInt16()", " file error." );
730 throw FormatError( "Document::ReadInt16()", "EOF." );
737 * \brief Reads a supposed to be 32 Bits integer
738 * (swaps it depending on processor endianness)
741 uint32_t Document::ReadInt32()
745 Fp->read ((char*)&g, (size_t)4);
748 throw FormatError( "Document::ReadInt32()", " file error." );
752 throw FormatError( "Document::ReadInt32()", "EOF." );
759 * \brief skips bytes inside the source file
760 * \warning NOT end user intended method !
763 void Document::SkipBytes(uint32_t nBytes)
765 //FIXME don't dump the returned value
766 Fp->seekg((long)nBytes, std::ios::cur);
770 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
771 * @param filetype Type of the File to be written
773 int Document::ComputeGroup0002Length( FileType filetype )
779 bool found0002 = false;
781 // for each zero-level Tag in the DCM Header
782 DocEntry *entry = GetFirstEntry();
785 gr = entry->GetGroup();
791 if( entry->GetElement() != 0x0000 )
795 if( filetype == ExplicitVR )
797 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
799 // explicit VR AND OB, OW, SQ : 4 more bytes
803 groupLength += 2 + 2 + 4 + entry->GetLength();
809 entry = GetNextEntry();
814 //-----------------------------------------------------------------------------
817 * \brief Loads all the needed Dictionaries
818 * \warning NOT end user intended method !
820 void Document::Initialize()
822 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
828 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
829 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
830 * @param offset start of parsing
831 * @param l_max length to parse
832 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
834 void Document::ParseDES(DocEntrySet *set, long offset,
835 long l_max, bool delim_mode)
837 DocEntry *newDocEntry;
838 ValEntry *newValEntry;
839 BinEntry *newBinEntry;
840 SeqEntry *newSeqEntry;
846 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
852 newDocEntry = ReadNextDocEntry( );
859 vr = newDocEntry->GetVR();
860 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
861 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
862 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
864 if ( newValEntry || newBinEntry )
868 if ( Filetype == ExplicitVR &&
869 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
871 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
872 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
873 << "|" << newDocEntry->GetElement()
874 << " : Neither Valentry, nor BinEntry."
875 "Probably unknown VR.");
878 //////////////////// BinEntry or UNKOWN VR:
879 // When "this" is a Document the Key is simply of the
880 // form ( group, elem )...
881 if ( dynamic_cast< Document* > ( set ) )
883 newBinEntry->SetKey( newBinEntry->GetKey() );
885 // but when "this" is a SQItem, we are inserting this new
886 // valEntry in a sequence item, and the key has the
887 // generalized form (refer to \ref BaseTagKey):
888 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
890 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
891 + newBinEntry->GetKey() );
894 LoadDocEntry( newBinEntry );
895 if( !set->AddEntry( newBinEntry ) )
897 //Expect big troubles if here
898 //delete newBinEntry;
904 /////////////////////// ValEntry
906 // When "set" is a Document, then we are at the top of the
907 // hierarchy and the Key is simply of the form ( group, elem )...
908 if ( dynamic_cast< Document* > ( set ) )
910 newValEntry->SetKey( newValEntry->GetKey() );
912 // ...but when "set" is a SQItem, we are inserting this new
913 // valEntry in a sequence item. Hence the key has the
914 // generalized form (refer to \ref BaseTagKey):
915 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
917 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
918 + newValEntry->GetKey() );
921 LoadDocEntry( newValEntry );
922 bool delimitor=newValEntry->IsItemDelimitor();
924 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
925 // shadow groups ( if possible :
926 // whether element 0x0000 exits)
928 if ( newValEntry->GetGroup()%2 != 0 )
930 if ( newValEntry->GetElement() == 0x0000 )
932 std::string strLgrGroup = newValEntry->GetValue();
934 if ( strLgrGroup != GDCM_UNFOUND)
936 lgrGroup = atoi(strLgrGroup.c_str());
937 Fp->seekg(lgrGroup , std::ios::cur);
945 if( !set->AddEntry( newValEntry ) )
947 // If here expect big troubles
948 // delete newValEntry; //otherwise mem leak
958 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
966 // Just to make sure we are at the beginning of next entry.
967 SkipToNextDocEntry(newDocEntry);
972 unsigned long l = newDocEntry->GetReadLength();
973 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
975 if ( l == 0xffffffff )
985 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
987 Fp->seekg( l, std::ios::cur);
992 // no other way to create it ...
993 newSeqEntry->SetDelimitorMode( delim_mode );
995 // At the top of the hierarchy, stands a Document. When "set"
996 // is a Document, then we are building the first depth level.
997 // Hence the SeqEntry we are building simply has a depth
999 if ( dynamic_cast< Document* > ( set ) )
1001 newSeqEntry->SetDepthLevel( 1 );
1002 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1004 // But when "set" is already a SQItem, we are building a nested
1005 // sequence, and hence the depth level of the new SeqEntry
1006 // we are building, is one level deeper:
1007 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1009 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1010 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1011 + newSeqEntry->GetKey() );
1015 { // Don't try to parse zero-length sequences
1016 ParseSQ( newSeqEntry,
1017 newDocEntry->GetOffset(),
1020 if( !set->AddEntry( newSeqEntry ) )
1025 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1039 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1040 * @return parsed length for this level
1042 void Document::ParseSQ( SeqEntry *seqEntry,
1043 long offset, long l_max, bool delim_mode)
1045 int SQItemNumber = 0;
1047 long offsetStartCurrentSQItem = offset;
1051 // the first time, we read the fff0,e000 of the first SQItem
1052 DocEntry *newDocEntry = ReadNextDocEntry();
1056 // FIXME Should warn user
1061 if ( newDocEntry->IsSequenceDelimitor() )
1063 seqEntry->SetDelimitationItem( newDocEntry );
1067 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1072 // create the current SQItem
1073 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1074 std::ostringstream newBase;
1075 newBase << seqEntry->GetKey()
1079 itemSQ->SetBaseTagKey( newBase.str() );
1080 unsigned int l = newDocEntry->GetReadLength();
1082 if ( l == 0xffffffff )
1091 // Let's try :------------
1092 // remove fff0,e000, created out of the SQItem
1094 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1095 // fill up the current SQItem, starting at the beginning of fff0,e000
1096 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1097 offsetStartCurrentSQItem = Fp->tellg();
1098 // end try -----------------
1100 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1102 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1110 * \brief Loads the element content if its length doesn't exceed
1111 * the value specified with Document::SetMaxSizeLoadEntry()
1112 * @param entry Header Entry (Dicom Element) to be dealt with
1114 void Document::LoadDocEntry(DocEntry *entry)
1116 uint16_t group = entry->GetGroup();
1117 std::string vr = entry->GetVR();
1118 uint32_t length = entry->GetLength();
1120 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1122 // A SeQuence "contains" a set of Elements.
1123 // (fffe e000) tells us an Element is beginning
1124 // (fffe e00d) tells us an Element just ended
1125 // (fffe e0dd) tells us the current SeQuence just ended
1126 if( group == 0xfffe )
1128 // NO more value field for SQ !
1132 // When the length is zero things are easy:
1135 ((ValEntry *)entry)->SetValue("");
1139 // The elements whose length is bigger than the specified upper bound
1140 // are not loaded. Instead we leave a short notice of the offset of
1141 // the element content and it's length.
1143 std::ostringstream s;
1144 if (length > MaxSizeLoadEntry)
1146 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1148 //s << "gdcm::NotLoaded (BinEntry)";
1149 s << GDCM_NOTLOADED;
1150 s << " Ad.:" << (long)entry->GetOffset();
1151 s << " x(" << std::hex << entry->GetOffset() << ")";
1153 s << " Lgt:" << entry->GetLength();
1154 s << " x(" << std::hex << entry->GetLength() << ")";
1155 binEntryPtr->SetValue(s.str());
1157 // Be carefull : a BinEntry IS_A ValEntry ...
1158 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1160 // s << "gdcm::NotLoaded. (ValEntry)";
1161 s << GDCM_NOTLOADED;
1162 s << " Address:" << (long)entry->GetOffset();
1163 s << " Length:" << entry->GetLength();
1164 s << " x(" << std::hex << entry->GetLength() << ")";
1165 valEntryPtr->SetValue(s.str());
1170 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1171 << "nor a ValEntry ?! Should never print that !" );
1174 // to be sure we are at the end of the value ...
1175 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1180 // When we find a BinEntry not very much can be done :
1181 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1183 s << GDCM_BINLOADED;
1184 binEntryPtr->SetValue(s.str());
1185 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1189 if ( IsDocEntryAnInteger(entry) )
1193 // When short integer(s) are expected, read and convert the following
1194 // n *two characters properly i.e. consider them as short integers as
1195 // opposed to strings.
1196 // Elements with Value Multiplicity > 1
1197 // contain a set of integers (not a single one)
1198 if (vr == "US" || vr == "SS")
1201 NewInt = ReadInt16();
1205 for (int i=1; i < nbInt; i++)
1208 NewInt = ReadInt16();
1213 // See above comment on multiple integers (mutatis mutandis).
1214 else if (vr == "UL" || vr == "SL")
1217 NewInt = ReadInt32();
1221 for (int i=1; i < nbInt; i++)
1224 NewInt = ReadInt32();
1229 #ifdef GDCM_NO_ANSI_STRING_STREAM
1230 s << std::ends; // to avoid oddities on Solaris
1231 #endif //GDCM_NO_ANSI_STRING_STREAM
1233 ((ValEntry *)entry)->SetValue(s.str());
1237 // FIXME: We need an additional byte for storing \0 that is not on disk
1238 char *str = new char[length+1];
1239 Fp->read(str, (size_t)length);
1240 str[length] = '\0'; //this is only useful when length is odd
1241 // Special DicomString call to properly handle \0 and even length
1242 std::string newValue;
1245 newValue = Util::DicomString(str, length+1);
1246 gdcmWarningMacro("Warning: bad length: " << length <<
1247 ",For string :" << newValue.c_str());
1248 // Since we change the length of string update it length
1249 //entry->SetReadLength(length+1);
1253 newValue = Util::DicomString(str, length);
1257 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1259 if ( Fp->fail() || Fp->eof())
1261 gdcmWarningMacro("Unread element value");
1262 valEntry->SetValue(GDCM_UNREAD);
1268 // Because of correspondance with the VR dic
1269 valEntry->SetValue(newValue);
1273 valEntry->SetValue(newValue);
1278 gdcmErrorMacro( "Should have a ValEntry, here !");
1283 * \brief Find the value Length of the passed Header Entry
1284 * @param entry Header Entry whose length of the value shall be loaded.
1286 void Document::FindDocEntryLength( DocEntry *entry )
1287 throw ( FormatError )
1289 std::string vr = entry->GetVR();
1292 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1294 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1296 // The following reserved two bytes (see PS 3.5-2003, section
1297 // "7.1.2 Data element structure with explicit vr", p 27) must be
1298 // skipped before proceeding on reading the length on 4 bytes.
1299 Fp->seekg( 2L, std::ios::cur);
1300 uint32_t length32 = ReadInt32();
1302 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1307 lengthOB = FindDocEntryLengthOBOrOW();
1309 catch ( FormatUnexpected )
1311 // Computing the length failed (this happens with broken
1312 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1313 // chance to get the pixels by deciding the element goes
1314 // until the end of the file. Hence we artificially fix the
1315 // the length and proceed.
1316 long currentPosition = Fp->tellg();
1317 Fp->seekg(0L,std::ios::end);
1319 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1320 Fp->seekg(currentPosition, std::ios::beg);
1322 entry->SetReadLength(lengthUntilEOF);
1323 entry->SetLength(lengthUntilEOF);
1326 entry->SetReadLength(lengthOB);
1327 entry->SetLength(lengthOB);
1330 FixDocEntryFoundLength(entry, length32);
1334 // Length is encoded on 2 bytes.
1335 length16 = ReadInt16();
1337 // 0xffff means that we deal with 'No Length' Sequence
1338 // or 'No Length' SQItem
1339 if ( length16 == 0xffff)
1343 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1348 // Either implicit VR or a non DICOM conformal (see note below) explicit
1349 // VR that ommited the VR of (at least) this element. Farts happen.
1350 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1351 // on Data elements "Implicit and Explicit VR Data Elements shall
1352 // not coexist in a Data Set and Data Sets nested within it".]
1353 // Length is on 4 bytes.
1355 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1356 // even if Transfer Syntax is 'Implicit VR ...'
1358 FixDocEntryFoundLength( entry, ReadInt32() );
1364 * \brief Find the Length till the next sequence delimiter
1365 * \warning NOT end user intended method !
1368 uint32_t Document::FindDocEntryLengthOBOrOW()
1369 throw( FormatUnexpected )
1371 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1372 long positionOnEntry = Fp->tellg();
1373 bool foundSequenceDelimiter = false;
1374 uint32_t totalLength = 0;
1376 while ( !foundSequenceDelimiter )
1382 group = ReadInt16();
1385 catch ( FormatError )
1387 throw FormatError("Unexpected end of file encountered during ",
1388 "Document::FindDocEntryLengthOBOrOW()");
1390 // We have to decount the group and element we just read
1392 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1394 long filePosition = Fp->tellg();
1396 "Neither an Item tag nor a Sequence delimiter tag on :"
1397 << std::hex << group << " , " << elem
1398 << ") -before- position x(" << filePosition << ")" );
1400 Fp->seekg(positionOnEntry, std::ios::beg);
1401 throw FormatUnexpected(
1402 "Neither an Item tag nor a Sequence delimiter tag.");
1404 if ( elem == 0xe0dd )
1406 foundSequenceDelimiter = true;
1408 uint32_t itemLength = ReadInt32();
1409 // We add 4 bytes since we just read the ItemLength with ReadInt32
1410 totalLength += itemLength + 4;
1411 SkipBytes(itemLength);
1413 if ( foundSequenceDelimiter )
1418 Fp->seekg( positionOnEntry, std::ios::beg);
1423 * \brief Find the Value Representation of the current Dicom Element.
1424 * @return Value Representation of the current Entry
1426 std::string Document::FindDocEntryVR()
1428 if ( Filetype != ExplicitVR )
1429 return GDCM_UNKNOWN;
1431 long positionOnEntry = Fp->tellg();
1432 // Warning: we believe this is explicit VR (Value Representation) because
1433 // we used a heuristic that found "UL" in the first tag. Alas this
1434 // doesn't guarantee that all the tags will be in explicit VR. In some
1435 // cases (see e-film filtered files) one finds implicit VR tags mixed
1436 // within an explicit VR file. Hence we make sure the present tag
1437 // is in explicit VR and try to fix things if it happens not to be
1441 Fp->read (vr, (size_t)2);
1444 if( !CheckDocEntryVR(vr) )
1446 Fp->seekg(positionOnEntry, std::ios::beg);
1447 return GDCM_UNKNOWN;
1453 * \brief Check the correspondance between the VR of the header entry
1454 * and the taken VR. If they are different, the header entry is
1455 * updated with the new VR.
1456 * @param vr Dicom Value Representation
1457 * @return false if the VR is incorrect of if the VR isn't referenced
1458 * otherwise, it returns true
1460 bool Document::CheckDocEntryVR(VRKey vr)
1462 if ( !Global::GetVR()->IsValidVR(vr) )
1469 * \brief Get the transformed value of the header entry. The VR value
1470 * is used to define the transformation to operate on the value
1471 * \warning NOT end user intended method !
1472 * @param entry entry to tranform
1473 * @return Transformed entry value
1475 std::string Document::GetDocEntryValue(DocEntry *entry)
1477 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1479 std::string val = ((ValEntry *)entry)->GetValue();
1480 std::string vr = entry->GetVR();
1481 uint32_t length = entry->GetLength();
1482 std::ostringstream s;
1485 // When short integer(s) are expected, read and convert the following
1486 // n * 2 bytes properly i.e. as a multivaluated strings
1487 // (each single value is separated fromthe next one by '\'
1488 // as usual for standard multivaluated filels
1489 // Elements with Value Multiplicity > 1
1490 // contain a set of short integers (not a single one)
1492 if( vr == "US" || vr == "SS" )
1497 for (int i=0; i < nbInt; i++)
1503 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1504 newInt16 = SwapShort( newInt16 );
1509 // When integer(s) are expected, read and convert the following
1510 // n * 4 bytes properly i.e. as a multivaluated strings
1511 // (each single value is separated fromthe next one by '\'
1512 // as usual for standard multivaluated filels
1513 // Elements with Value Multiplicity > 1
1514 // contain a set of integers (not a single one)
1515 else if( vr == "UL" || vr == "SL" )
1520 for (int i=0; i < nbInt; i++)
1526 newInt32 = ( val[4*i+0] & 0xFF )
1527 + (( val[4*i+1] & 0xFF ) << 8 )
1528 + (( val[4*i+2] & 0xFF ) << 16 )
1529 + (( val[4*i+3] & 0xFF ) << 24 );
1530 newInt32 = SwapLong( newInt32 );
1534 #ifdef GDCM_NO_ANSI_STRING_STREAM
1535 s << std::ends; // to avoid oddities on Solaris
1536 #endif //GDCM_NO_ANSI_STRING_STREAM
1539 return ((ValEntry *)entry)->GetValue();
1543 * \brief Get the reverse transformed value of the header entry. The VR
1544 * value is used to define the reverse transformation to operate on
1546 * \warning NOT end user intended method !
1547 * @param entry Entry to reverse transform
1548 * @return Reverse transformed entry value
1550 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1552 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1554 std::string vr = entry->GetVR();
1555 std::vector<std::string> tokens;
1556 std::ostringstream s;
1558 if ( vr == "US" || vr == "SS" )
1562 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1563 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1564 for (unsigned int i=0; i<tokens.size(); i++)
1566 newInt16 = atoi(tokens[i].c_str());
1567 s << ( newInt16 & 0xFF )
1568 << (( newInt16 >> 8 ) & 0xFF );
1572 if ( vr == "UL" || vr == "SL")
1576 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1577 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1578 for (unsigned int i=0; i<tokens.size();i++)
1580 newInt32 = atoi(tokens[i].c_str());
1581 s << (char)( newInt32 & 0xFF )
1582 << (char)(( newInt32 >> 8 ) & 0xFF )
1583 << (char)(( newInt32 >> 16 ) & 0xFF )
1584 << (char)(( newInt32 >> 24 ) & 0xFF );
1589 #ifdef GDCM_NO_ANSI_STRING_STREAM
1590 s << std::ends; // to avoid oddities on Solaris
1591 #endif //GDCM_NO_ANSI_STRING_STREAM
1595 return ((ValEntry *)entry)->GetValue();
1599 * \brief Skip a given Header Entry
1600 * \warning NOT end user intended method !
1601 * @param entry entry to skip
1603 void Document::SkipDocEntry(DocEntry *entry)
1605 SkipBytes(entry->GetLength());
1609 * \brief Skips to the beginning of the next Header Entry
1610 * \warning NOT end user intended method !
1611 * @param currentDocEntry entry to skip
1613 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1615 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1616 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1617 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1621 * \brief When the length of an element value is obviously wrong (because
1622 * the parser went Jabberwocky) one can hope improving things by
1623 * applying some heuristics.
1624 * @param entry entry to check
1625 * @param foundLength first assumption about length
1627 void Document::FixDocEntryFoundLength(DocEntry *entry,
1628 uint32_t foundLength)
1630 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1631 if ( foundLength == 0xffffffff)
1636 uint16_t gr = entry->GetGroup();
1637 uint16_t elem = entry->GetElement();
1639 if ( foundLength % 2)
1641 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1642 << " in x(" << std::hex << gr << "," << elem <<")");
1645 //////// Fix for some naughty General Electric images.
1646 // Allthough not recent many such GE corrupted images are still present
1647 // on Creatis hard disks. Hence this fix shall remain when such images
1648 // are no longer in use (we are talking a few years, here)...
1649 // Note: XMedCom probably uses such a trick since it is able to read
1650 // those pesky GE images ...
1651 if ( foundLength == 13)
1653 // Only happens for this length !
1654 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1657 entry->SetReadLength(10); // a bug is to be fixed !?
1661 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1662 // Occurence of such images is quite low (unless one leaves close to a
1663 // 'Leonardo' source. Hence, one might consider commenting out the
1664 // following fix on efficiency reasons.
1665 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1668 entry->SetReadLength(4); // a bug is to be fixed !?
1671 else if ( entry->GetVR() == "SQ" )
1673 foundLength = 0; // ReadLength is unchanged
1676 //////// We encountered a 'delimiter' element i.e. a tag of the form
1677 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1678 // taken into account.
1679 else if( gr == 0xfffe )
1681 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1682 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1683 // causes extra troubles...
1684 if( entry->GetElement() != 0x0000 )
1689 entry->SetLength(foundLength);
1693 * \brief Apply some heuristics to predict whether the considered
1694 * element value contains/represents an integer or not.
1695 * @param entry The element value on which to apply the predicate.
1696 * @return The result of the heuristical predicate.
1698 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1700 uint16_t elem = entry->GetElement();
1701 uint16_t group = entry->GetGroup();
1702 const std::string &vr = entry->GetVR();
1703 uint32_t length = entry->GetLength();
1705 // When we have some semantics on the element we just read, and if we
1706 // a priori know we are dealing with an integer, then we shall be
1707 // able to swap it's element value properly.
1708 if ( elem == 0 ) // This is the group length of the group
1716 // Allthough this should never happen, still some images have a
1717 // corrupted group length [e.g. have a glance at offset x(8336) of
1718 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1719 // Since for dicom compliant and well behaved headers, the present
1720 // test is useless (and might even look a bit paranoid), when we
1721 // encounter such an ill-formed image, we simply display a warning
1722 // message and proceed on parsing (while crossing fingers).
1723 long filePosition = Fp->tellg();
1724 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1725 << std::hex << group << " , " << elem
1726 << ") -before- position x(" << filePosition << ")"
1727 << "lgt : " << length );
1731 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1739 * \brief Discover what the swap code is (among little endian, big endian,
1740 * bad little endian, bad big endian).
1742 * @return false when we are absolutely sure
1743 * it's neither ACR-NEMA nor DICOM
1744 * true when we hope ours assuptions are OK
1746 bool Document::CheckSwap()
1748 // The only guaranted way of finding the swap code is to find a
1749 // group tag since we know it's length has to be of four bytes i.e.
1750 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1751 // occurs when we can't find such group...
1758 // First, compare HostByteOrder and NetworkByteOrder in order to
1759 // determine if we shall need to swap bytes (i.e. the Endian type).
1760 bool net2host = Util::IsCurrentProcessorBigEndian();
1762 // The easiest case is the one of a 'true' DICOM header, we just have
1763 // to look for the string "DICM" inside the file preamble.
1766 char *entCur = deb + 128;
1767 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1769 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1771 // Group 0002 should always be VR, and the first element 0000
1772 // Let's be carefull (so many wrong headers ...)
1773 // and determine the value representation (VR) :
1774 // Let's skip to the first element (0002,0000) and check there if we find
1775 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1776 // in which case we (almost) know it is explicit VR.
1777 // WARNING: if it happens to be implicit VR then what we will read
1778 // is the length of the group. If this ascii representation of this
1779 // length happens to be "UL" then we shall believe it is explicit VR.
1780 // We need to skip :
1781 // * the 128 bytes of File Preamble (often padded with zeroes),
1782 // * the 4 bytes of "DICM" string,
1783 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1784 // i.e. a total of 136 bytes.
1787 // group 0x0002 *is always* Explicit VR Sometimes ,
1788 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1789 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1791 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1792 memcmp(entCur, "OB", (size_t)2) == 0 ||
1793 memcmp(entCur, "UI", (size_t)2) == 0 ||
1794 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1795 // when Write DCM *adds*
1797 // Use Document::dicom_vr to test all the possibilities
1798 // instead of just checking for UL, OB and UI !? group 0000
1800 Filetype = ExplicitVR;
1801 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1805 Filetype = ImplicitVR;
1806 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1807 << "Looks like a bugged Header!");
1813 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1818 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1821 // Position the file position indicator at first tag
1822 // (i.e. after the file preamble and the "DICM" string).
1823 Fp->seekg(0, std::ios::beg);
1824 Fp->seekg ( 132L, std::ios::beg);
1826 } // ------------------------------- End of DicomV3 ----------------
1828 // Alas, this is not a DicomV3 file and whatever happens there is no file
1829 // preamble. We can reset the file position indicator to where the data
1830 // is (i.e. the beginning of the file).
1832 gdcmWarningMacro( "Not a DICOM Version3 file");
1834 Fp->seekg(0, std::ios::beg);
1836 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1837 // By clean we mean that the length of the first group is written down.
1838 // If this is the case and since the length of the first group HAS to be
1839 // four (bytes), then determining the proper swap code is straightforward.
1842 // We assume the array of char we are considering contains the binary
1843 // representation of a 32 bits integer. Hence the following dirty
1845 s32 = *((uint32_t *)(entCur));
1865 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1866 // It is time for despaired wild guesses.
1867 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1868 // i.e. the 'group length' element is not present :
1870 // check the supposed-to-be 'group number'
1871 // in ( 0x0001 .. 0x0008 )
1872 // to determine ' SwapCode' value .
1873 // Only 0 or 4321 will be possible
1874 // (no oportunity to check for the formerly well known
1875 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1876 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1877 // the file IS NOT ACR-NEMA nor DICOM V3
1878 // Find a trick to tell it the caller...
1880 s16 = *((uint16_t *)(deb));
1907 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1915 * \brief Change the Byte Swap code.
1917 void Document::SwitchByteSwapCode()
1919 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1920 if ( SwapCode == 1234 )
1924 else if ( SwapCode == 4321 )
1928 else if ( SwapCode == 3412 )
1932 else if ( SwapCode == 2143 )
1939 * \brief during parsing, Header Elements too long are not loaded in memory
1940 * @param newSize new size
1942 void Document::SetMaxSizeLoadEntry(long newSize)
1948 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1950 MaxSizeLoadEntry = 0xffffffff;
1953 MaxSizeLoadEntry = newSize;
1957 * \brief Read the next tag but WITHOUT loading it's value
1958 * (read the 'Group Number', the 'Element Number',
1959 * gets the Dict Entry
1960 * gets the VR, gets the length, gets the offset value)
1961 * @return On succes the newly created DocEntry, NULL on failure.
1963 DocEntry *Document::ReadNextDocEntry()
1970 group = ReadInt16();
1973 catch ( FormatError e )
1975 // We reached the EOF (or an error occured) therefore
1976 // header parsing has to be considered as finished.
1980 // Sometimes file contains groups of tags with reversed endianess.
1981 HandleBrokenEndian(group, elem);
1983 // In 'true DICOM' files Group 0002 is always little endian
1984 if ( HasDCMPreamble )
1985 HandleOutOfGroup0002(group, elem);
1987 std::string vr = FindDocEntryVR();
1988 std::string realVR = vr;
1990 if( vr == GDCM_UNKNOWN)
1992 if ( elem == 0x0000 ) // Group Length
1993 realVR = "UL"; // must be UL
1996 DictEntry *dictEntry = GetDictEntry(group,elem);
1998 realVR = dictEntry->GetVR();
2003 if( Global::GetVR()->IsVROfSequence(realVR) )
2004 newEntry = NewSeqEntry(group, elem);
2005 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2006 newEntry = NewValEntry(group, elem,vr);
2008 newEntry = NewBinEntry(group, elem,vr);
2010 if( vr == GDCM_UNKNOWN )
2012 if( Filetype == ExplicitVR )
2014 // We thought this was explicit VR, but we end up with an
2015 // implicit VR tag. Let's backtrack.
2016 if ( newEntry->GetGroup() != 0xfffe )
2019 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2020 newEntry->GetGroup(), newEntry->GetElement());
2021 gdcmWarningMacro( msg.c_str() );
2024 newEntry->SetImplicitVR();
2029 FindDocEntryLength(newEntry);
2031 catch ( FormatError e )
2038 newEntry->SetOffset(Fp->tellg());
2044 * \brief Handle broken private tag from Philips NTSCAN
2045 * where the endianess is being switch to BigEndian for no
2049 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2051 // Endian reversion. Some files contain groups of tags with reversed endianess.
2052 static int reversedEndian = 0;
2053 // try to fix endian switching in the middle of headers
2054 if ((group == 0xfeff) && (elem == 0x00e0))
2056 // start endian swap mark for group found
2058 SwitchByteSwapCode();
2063 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2065 // end of reversed endian group
2067 SwitchByteSwapCode();
2072 * \brief Group 0002 is always coded Little Endian
2073 * whatever Transfer Syntax is
2076 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2078 // Endian reversion. Some files contain groups of tags with reversed endianess.
2079 if ( !Group0002Parsed && group != 0x0002)
2081 Group0002Parsed = true;
2082 // we just came out of group 0002
2083 // if Transfer syntax is Big Endian we have to change CheckSwap
2085 std::string ts = GetTransferSyntax();
2086 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2088 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2092 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2094 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2096 Filetype = ImplicitVR;
2099 // FIXME Strangely, this works with
2100 //'Implicit VR Transfer Syntax (GE Private)
2101 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2103 gdcmWarningMacro("Transfer Syntax Name = ["
2104 << GetTransferSyntaxName() << "]" );
2105 SwitchByteSwapCode();
2106 group = SwapShort(group);
2107 elem = SwapShort(elem);
2112 //-----------------------------------------------------------------------------
2115 //-----------------------------------------------------------------------------
2116 } // end namespace gdcm