1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/04/29 15:10:55 $
7 Version: $Revision: 1.238 $
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 // Don't user gdcmErrorMacro :
467 // a spurious message will appear when you use, for instance
468 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
469 // to create outputFileName.
470 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
474 //exit(1); // No function is allowed to leave the application instead
475 // of warning the caller
479 Fp->read((char*)&zero, (size_t)2);
486 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
488 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
489 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
490 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
491 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
493 std::string msg = Util::Format(
494 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
495 gdcmWarningMacro( msg.c_str() );
500 Fp->seekg(126L, std::ios::cur);
501 char dicm[4] = {' ',' ',' ',' '};
502 Fp->read(dicm, (size_t)4);
508 if( memcmp(dicm, "DICM", 4) == 0 )
510 HasDCMPreamble = true;
514 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
516 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
517 << Filename.c_str());
522 * \brief closes the file
523 * @return TRUE if the close was successfull
525 bool Document::CloseFile()
537 * \brief Writes in a file all the Header Entries (Dicom Elements)
538 * @param fp file pointer on an already open file (actually: Output File Stream)
539 * @param filetype Type of the File to be written
540 * (ACR-NEMA, ExplicitVR, ImplicitVR)
541 * @return Always true.
543 void Document::WriteContent(std::ofstream *fp, FileType filetype)
545 // \TODO move the following lines (and a lot of others, to be written)
546 // to a future function CheckAndCorrectHeader
548 // (necessary if user wants to write a DICOM V3 file
549 // starting from an ACR-NEMA (V2) Header
551 if ( filetype == ImplicitVR || filetype == ExplicitVR )
553 // writing Dicom File Preamble
554 char filePreamble[128];
555 memset(filePreamble, 0, 128);
556 fp->write(filePreamble, 128);
557 fp->write("DICM", 4);
561 * \todo rewrite later, if really usefull
562 * - 'Group Length' element is optional in DICOM
563 * - but un-updated odd groups lengthes can causes pb
566 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
567 * UpdateGroupLength(false,filetype);
568 * if ( filetype == ACR)
569 * UpdateGroupLength(true,ACR);
572 ElementSet::WriteContent(fp, filetype); // This one is recursive
575 // -----------------------------------------
578 * \brief Loads (from disk) the element content
579 * when a string is not suitable
580 * @param group group number of the Entry
581 * @param elem element number of the Entry
583 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
585 // Search the corresponding DocEntry
586 DocEntry *docElement = GetDocEntry(group, elem);
590 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
594 LoadEntryBinArea(binElement);
598 * \brief Loads (from disk) the element content
599 * when a string is not suitable
600 * @param elem Entry whose binArea is going to be loaded
602 void Document::LoadEntryBinArea(BinEntry *elem)
604 if(elem->GetBinArea())
611 size_t o =(size_t)elem->GetOffset();
612 Fp->seekg(o, std::ios::beg);
614 size_t l = elem->GetLength();
615 uint8_t *a = new uint8_t[l];
618 gdcmWarningMacro( "Cannot allocate BinEntry content");
622 Fp->read((char*)a, l);
623 if( Fp->fail() || Fp->eof())
636 * \brief Loads the element while preserving the current
637 * underlying file position indicator as opposed to
638 * LoadDocEntry that modifies it.
639 * @param entry DocEntry whose value will be loaded.
641 void Document::LoadDocEntrySafe(DocEntry *entry)
645 long PositionOnEntry = Fp->tellg();
647 Fp->seekg(PositionOnEntry, std::ios::beg);
652 * \brief Compares two documents, according to \ref DicomDir rules
653 * \warning Does NOT work with ACR-NEMA files
654 * \todo Find a trick to solve the pb (use RET fields ?)
655 * @param document to compare with current one
656 * @return true if 'smaller'
658 bool Document::operator<(Document &document)
661 std::string s1 = GetEntryValue(0x0010,0x0010);
662 std::string s2 = document.GetEntryValue(0x0010,0x0010);
674 s1 = GetEntryValue(0x0010,0x0020);
675 s2 = document.GetEntryValue(0x0010,0x0020);
686 // Study Instance UID
687 s1 = GetEntryValue(0x0020,0x000d);
688 s2 = document.GetEntryValue(0x0020,0x000d);
699 // Serie Instance UID
700 s1 = GetEntryValue(0x0020,0x000e);
701 s2 = document.GetEntryValue(0x0020,0x000e);
716 //-----------------------------------------------------------------------------
719 * \brief Reads a supposed to be 16 Bits integer
720 * (swaps it depending on processor endianness)
723 uint16_t Document::ReadInt16()
727 Fp->read ((char*)&g, (size_t)2);
730 throw FormatError( "Document::ReadInt16()", " file error." );
734 throw FormatError( "Document::ReadInt16()", "EOF." );
741 * \brief Reads a supposed to be 32 Bits integer
742 * (swaps it depending on processor endianness)
745 uint32_t Document::ReadInt32()
749 Fp->read ((char*)&g, (size_t)4);
752 throw FormatError( "Document::ReadInt32()", " file error." );
756 throw FormatError( "Document::ReadInt32()", "EOF." );
763 * \brief skips bytes inside the source file
764 * \warning NOT end user intended method !
767 void Document::SkipBytes(uint32_t nBytes)
769 //FIXME don't dump the returned value
770 Fp->seekg((long)nBytes, std::ios::cur);
774 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
775 * @param filetype Type of the File to be written
777 int Document::ComputeGroup0002Length( FileType filetype )
783 bool found0002 = false;
785 // for each zero-level Tag in the DCM Header
786 DocEntry *entry = GetFirstEntry();
789 gr = entry->GetGroup();
795 if( entry->GetElement() != 0x0000 )
799 if( filetype == ExplicitVR )
801 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
803 // explicit VR AND OB, OW, SQ : 4 more bytes
807 groupLength += 2 + 2 + 4 + entry->GetLength();
813 entry = GetNextEntry();
818 //-----------------------------------------------------------------------------
821 * \brief Loads all the needed Dictionaries
822 * \warning NOT end user intended method !
824 void Document::Initialize()
826 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
832 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
833 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
834 * @param offset start of parsing
835 * @param l_max length to parse
836 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
838 void Document::ParseDES(DocEntrySet *set, long offset,
839 long l_max, bool delim_mode)
841 DocEntry *newDocEntry;
842 ValEntry *newValEntry;
843 BinEntry *newBinEntry;
844 SeqEntry *newSeqEntry;
850 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
856 newDocEntry = ReadNextDocEntry( );
863 vr = newDocEntry->GetVR();
864 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
865 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
866 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
868 if ( newValEntry || newBinEntry )
872 if ( Filetype == ExplicitVR &&
873 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
875 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
876 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
877 << "|" << newDocEntry->GetElement()
878 << " : Neither Valentry, nor BinEntry."
879 "Probably unknown VR.");
882 //////////////////// BinEntry or UNKOWN VR:
883 // When "this" is a Document the Key is simply of the
884 // form ( group, elem )...
885 if ( dynamic_cast< Document* > ( set ) )
887 newBinEntry->SetKey( newBinEntry->GetKey() );
889 // but when "this" is a SQItem, we are inserting this new
890 // valEntry in a sequence item, and the key has the
891 // generalized form (refer to \ref BaseTagKey):
892 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
894 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
895 + newBinEntry->GetKey() );
898 LoadDocEntry( newBinEntry );
899 if( !set->AddEntry( newBinEntry ) )
901 //Expect big troubles if here
902 //delete newBinEntry;
908 /////////////////////// ValEntry
910 // When "set" is a Document, then we are at the top of the
911 // hierarchy and the Key is simply of the form ( group, elem )...
912 if ( dynamic_cast< Document* > ( set ) )
914 newValEntry->SetKey( newValEntry->GetKey() );
916 // ...but when "set" is a SQItem, we are inserting this new
917 // valEntry in a sequence item. Hence the key has the
918 // generalized form (refer to \ref BaseTagKey):
919 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
921 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
922 + newValEntry->GetKey() );
925 LoadDocEntry( newValEntry );
926 bool delimitor=newValEntry->IsItemDelimitor();
928 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
929 // shadow groups ( if possible :
930 // whether element 0x0000 exits)
932 if ( newValEntry->GetGroup()%2 != 0 )
934 if ( newValEntry->GetElement() == 0x0000 )
936 std::string strLgrGroup = newValEntry->GetValue();
938 if ( strLgrGroup != GDCM_UNFOUND)
940 lgrGroup = atoi(strLgrGroup.c_str());
941 Fp->seekg(lgrGroup , std::ios::cur);
949 if( !set->AddEntry( newValEntry ) )
951 // If here expect big troubles
952 // delete newValEntry; //otherwise mem leak
962 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
970 // Just to make sure we are at the beginning of next entry.
971 SkipToNextDocEntry(newDocEntry);
976 unsigned long l = newDocEntry->GetReadLength();
977 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
979 if ( l == 0xffffffff )
989 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
991 Fp->seekg( l, std::ios::cur);
996 // no other way to create it ...
997 newSeqEntry->SetDelimitorMode( delim_mode );
999 // At the top of the hierarchy, stands a Document. When "set"
1000 // is a Document, then we are building the first depth level.
1001 // Hence the SeqEntry we are building simply has a depth
1003 if ( dynamic_cast< Document* > ( set ) )
1005 newSeqEntry->SetDepthLevel( 1 );
1006 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1008 // But when "set" is already a SQItem, we are building a nested
1009 // sequence, and hence the depth level of the new SeqEntry
1010 // we are building, is one level deeper:
1011 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1013 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1014 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1015 + newSeqEntry->GetKey() );
1019 { // Don't try to parse zero-length sequences
1020 ParseSQ( newSeqEntry,
1021 newDocEntry->GetOffset(),
1024 if( !set->AddEntry( newSeqEntry ) )
1029 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1043 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1044 * @return parsed length for this level
1046 void Document::ParseSQ( SeqEntry *seqEntry,
1047 long offset, long l_max, bool delim_mode)
1049 int SQItemNumber = 0;
1051 long offsetStartCurrentSQItem = offset;
1055 // the first time, we read the fff0,e000 of the first SQItem
1056 DocEntry *newDocEntry = ReadNextDocEntry();
1060 // FIXME Should warn user
1065 if ( newDocEntry->IsSequenceDelimitor() )
1067 seqEntry->SetDelimitationItem( newDocEntry );
1071 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1076 // create the current SQItem
1077 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1078 std::ostringstream newBase;
1079 newBase << seqEntry->GetKey()
1083 itemSQ->SetBaseTagKey( newBase.str() );
1084 unsigned int l = newDocEntry->GetReadLength();
1086 if ( l == 0xffffffff )
1095 // Let's try :------------
1096 // remove fff0,e000, created out of the SQItem
1098 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1099 // fill up the current SQItem, starting at the beginning of fff0,e000
1100 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1101 offsetStartCurrentSQItem = Fp->tellg();
1102 // end try -----------------
1104 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1106 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1114 * \brief Loads the element content if its length doesn't exceed
1115 * the value specified with Document::SetMaxSizeLoadEntry()
1116 * @param entry Header Entry (Dicom Element) to be dealt with
1118 void Document::LoadDocEntry(DocEntry *entry)
1120 uint16_t group = entry->GetGroup();
1121 std::string vr = entry->GetVR();
1122 uint32_t length = entry->GetLength();
1124 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1126 // A SeQuence "contains" a set of Elements.
1127 // (fffe e000) tells us an Element is beginning
1128 // (fffe e00d) tells us an Element just ended
1129 // (fffe e0dd) tells us the current SeQuence just ended
1130 if( group == 0xfffe )
1132 // NO more value field for SQ !
1136 // When the length is zero things are easy:
1139 ((ValEntry *)entry)->SetValue("");
1143 // The elements whose length is bigger than the specified upper bound
1144 // are not loaded. Instead we leave a short notice of the offset of
1145 // the element content and it's length.
1147 std::ostringstream s;
1148 if (length > MaxSizeLoadEntry)
1150 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1152 //s << "gdcm::NotLoaded (BinEntry)";
1153 s << GDCM_NOTLOADED;
1154 s << " Ad.:" << (long)entry->GetOffset();
1155 s << " x(" << std::hex << entry->GetOffset() << ")";
1157 s << " Lgt:" << entry->GetLength();
1158 s << " x(" << std::hex << entry->GetLength() << ")";
1159 binEntryPtr->SetValue(s.str());
1161 // Be carefull : a BinEntry IS_A ValEntry ...
1162 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1164 // s << "gdcm::NotLoaded. (ValEntry)";
1165 s << GDCM_NOTLOADED;
1166 s << " Address:" << (long)entry->GetOffset();
1167 s << " Length:" << entry->GetLength();
1168 s << " x(" << std::hex << entry->GetLength() << ")";
1169 valEntryPtr->SetValue(s.str());
1174 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1175 << "nor a ValEntry ?! Should never print that !" );
1178 // to be sure we are at the end of the value ...
1179 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1184 // When we find a BinEntry not very much can be done :
1185 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1187 s << GDCM_BINLOADED;
1188 binEntryPtr->SetValue(s.str());
1189 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1193 if ( IsDocEntryAnInteger(entry) )
1197 // When short integer(s) are expected, read and convert the following
1198 // n *two characters properly i.e. consider them as short integers as
1199 // opposed to strings.
1200 // Elements with Value Multiplicity > 1
1201 // contain a set of integers (not a single one)
1202 if (vr == "US" || vr == "SS")
1205 NewInt = ReadInt16();
1209 for (int i=1; i < nbInt; i++)
1212 NewInt = ReadInt16();
1217 // See above comment on multiple integers (mutatis mutandis).
1218 else if (vr == "UL" || vr == "SL")
1221 NewInt = ReadInt32();
1225 for (int i=1; i < nbInt; i++)
1228 NewInt = ReadInt32();
1233 #ifdef GDCM_NO_ANSI_STRING_STREAM
1234 s << std::ends; // to avoid oddities on Solaris
1235 #endif //GDCM_NO_ANSI_STRING_STREAM
1237 ((ValEntry *)entry)->SetValue(s.str());
1241 // FIXME: We need an additional byte for storing \0 that is not on disk
1242 char *str = new char[length+1];
1243 Fp->read(str, (size_t)length);
1244 str[length] = '\0'; //this is only useful when length is odd
1245 // Special DicomString call to properly handle \0 and even length
1246 std::string newValue;
1249 newValue = Util::DicomString(str, length+1);
1250 gdcmWarningMacro("Warning: bad length: " << length <<
1251 ",For string :" << newValue.c_str());
1252 // Since we change the length of string update it length
1253 //entry->SetReadLength(length+1);
1257 newValue = Util::DicomString(str, length);
1261 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1263 if ( Fp->fail() || Fp->eof())
1265 gdcmWarningMacro("Unread element value");
1266 valEntry->SetValue(GDCM_UNREAD);
1272 // Because of correspondance with the VR dic
1273 valEntry->SetValue(newValue);
1277 valEntry->SetValue(newValue);
1282 gdcmErrorMacro( "Should have a ValEntry, here !");
1287 * \brief Find the value Length of the passed Header Entry
1288 * @param entry Header Entry whose length of the value shall be loaded.
1290 void Document::FindDocEntryLength( DocEntry *entry )
1291 throw ( FormatError )
1293 std::string vr = entry->GetVR();
1296 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1298 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1300 // The following reserved two bytes (see PS 3.5-2003, section
1301 // "7.1.2 Data element structure with explicit vr", p 27) must be
1302 // skipped before proceeding on reading the length on 4 bytes.
1303 Fp->seekg( 2L, std::ios::cur);
1304 uint32_t length32 = ReadInt32();
1306 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1311 lengthOB = FindDocEntryLengthOBOrOW();
1313 catch ( FormatUnexpected )
1315 // Computing the length failed (this happens with broken
1316 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1317 // chance to get the pixels by deciding the element goes
1318 // until the end of the file. Hence we artificially fix the
1319 // the length and proceed.
1320 long currentPosition = Fp->tellg();
1321 Fp->seekg(0L,std::ios::end);
1323 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1324 Fp->seekg(currentPosition, std::ios::beg);
1326 entry->SetReadLength(lengthUntilEOF);
1327 entry->SetLength(lengthUntilEOF);
1330 entry->SetReadLength(lengthOB);
1331 entry->SetLength(lengthOB);
1334 FixDocEntryFoundLength(entry, length32);
1338 // Length is encoded on 2 bytes.
1339 length16 = ReadInt16();
1341 // 0xffff means that we deal with 'No Length' Sequence
1342 // or 'No Length' SQItem
1343 if ( length16 == 0xffff)
1347 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1352 // Either implicit VR or a non DICOM conformal (see note below) explicit
1353 // VR that ommited the VR of (at least) this element. Farts happen.
1354 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1355 // on Data elements "Implicit and Explicit VR Data Elements shall
1356 // not coexist in a Data Set and Data Sets nested within it".]
1357 // Length is on 4 bytes.
1359 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1360 // even if Transfer Syntax is 'Implicit VR ...'
1362 FixDocEntryFoundLength( entry, ReadInt32() );
1368 * \brief Find the Length till the next sequence delimiter
1369 * \warning NOT end user intended method !
1372 uint32_t Document::FindDocEntryLengthOBOrOW()
1373 throw( FormatUnexpected )
1375 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1376 long positionOnEntry = Fp->tellg();
1377 bool foundSequenceDelimiter = false;
1378 uint32_t totalLength = 0;
1380 while ( !foundSequenceDelimiter )
1386 group = ReadInt16();
1389 catch ( FormatError )
1391 throw FormatError("Unexpected end of file encountered during ",
1392 "Document::FindDocEntryLengthOBOrOW()");
1394 // We have to decount the group and element we just read
1396 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1398 long filePosition = Fp->tellg();
1400 "Neither an Item tag nor a Sequence delimiter tag on :"
1401 << std::hex << group << " , " << elem
1402 << ") -before- position x(" << filePosition << ")" );
1404 Fp->seekg(positionOnEntry, std::ios::beg);
1405 throw FormatUnexpected(
1406 "Neither an Item tag nor a Sequence delimiter tag.");
1408 if ( elem == 0xe0dd )
1410 foundSequenceDelimiter = true;
1412 uint32_t itemLength = ReadInt32();
1413 // We add 4 bytes since we just read the ItemLength with ReadInt32
1414 totalLength += itemLength + 4;
1415 SkipBytes(itemLength);
1417 if ( foundSequenceDelimiter )
1422 Fp->seekg( positionOnEntry, std::ios::beg);
1427 * \brief Find the Value Representation of the current Dicom Element.
1428 * @return Value Representation of the current Entry
1430 std::string Document::FindDocEntryVR()
1432 if ( Filetype != ExplicitVR )
1433 return GDCM_UNKNOWN;
1435 long positionOnEntry = Fp->tellg();
1436 // Warning: we believe this is explicit VR (Value Representation) because
1437 // we used a heuristic that found "UL" in the first tag. Alas this
1438 // doesn't guarantee that all the tags will be in explicit VR. In some
1439 // cases (see e-film filtered files) one finds implicit VR tags mixed
1440 // within an explicit VR file. Hence we make sure the present tag
1441 // is in explicit VR and try to fix things if it happens not to be
1445 Fp->read (vr, (size_t)2);
1448 if( !CheckDocEntryVR(vr) )
1450 Fp->seekg(positionOnEntry, std::ios::beg);
1451 return GDCM_UNKNOWN;
1457 * \brief Check the correspondance between the VR of the header entry
1458 * and the taken VR. If they are different, the header entry is
1459 * updated with the new VR.
1460 * @param vr Dicom Value Representation
1461 * @return false if the VR is incorrect of if the VR isn't referenced
1462 * otherwise, it returns true
1464 bool Document::CheckDocEntryVR(VRKey vr)
1466 if ( !Global::GetVR()->IsValidVR(vr) )
1473 * \brief Get the transformed value of the header entry. The VR value
1474 * is used to define the transformation to operate on the value
1475 * \warning NOT end user intended method !
1476 * @param entry entry to tranform
1477 * @return Transformed entry value
1479 std::string Document::GetDocEntryValue(DocEntry *entry)
1481 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1483 std::string val = ((ValEntry *)entry)->GetValue();
1484 std::string vr = entry->GetVR();
1485 uint32_t length = entry->GetLength();
1486 std::ostringstream s;
1489 // When short integer(s) are expected, read and convert the following
1490 // n * 2 bytes properly i.e. as a multivaluated strings
1491 // (each single value is separated fromthe next one by '\'
1492 // as usual for standard multivaluated filels
1493 // Elements with Value Multiplicity > 1
1494 // contain a set of short integers (not a single one)
1496 if( vr == "US" || vr == "SS" )
1501 for (int i=0; i < nbInt; i++)
1507 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1508 newInt16 = SwapShort( newInt16 );
1513 // When integer(s) are expected, read and convert the following
1514 // n * 4 bytes properly i.e. as a multivaluated strings
1515 // (each single value is separated fromthe next one by '\'
1516 // as usual for standard multivaluated filels
1517 // Elements with Value Multiplicity > 1
1518 // contain a set of integers (not a single one)
1519 else if( vr == "UL" || vr == "SL" )
1524 for (int i=0; i < nbInt; i++)
1530 newInt32 = ( val[4*i+0] & 0xFF )
1531 + (( val[4*i+1] & 0xFF ) << 8 )
1532 + (( val[4*i+2] & 0xFF ) << 16 )
1533 + (( val[4*i+3] & 0xFF ) << 24 );
1534 newInt32 = SwapLong( newInt32 );
1538 #ifdef GDCM_NO_ANSI_STRING_STREAM
1539 s << std::ends; // to avoid oddities on Solaris
1540 #endif //GDCM_NO_ANSI_STRING_STREAM
1543 return ((ValEntry *)entry)->GetValue();
1547 * \brief Get the reverse transformed value of the header entry. The VR
1548 * value is used to define the reverse transformation to operate on
1550 * \warning NOT end user intended method !
1551 * @param entry Entry to reverse transform
1552 * @return Reverse transformed entry value
1554 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1556 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1558 std::string vr = entry->GetVR();
1559 std::vector<std::string> tokens;
1560 std::ostringstream s;
1562 if ( vr == "US" || vr == "SS" )
1566 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1567 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1568 for (unsigned int i=0; i<tokens.size(); i++)
1570 newInt16 = atoi(tokens[i].c_str());
1571 s << ( newInt16 & 0xFF )
1572 << (( newInt16 >> 8 ) & 0xFF );
1576 if ( vr == "UL" || vr == "SL")
1580 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1581 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1582 for (unsigned int i=0; i<tokens.size();i++)
1584 newInt32 = atoi(tokens[i].c_str());
1585 s << (char)( newInt32 & 0xFF )
1586 << (char)(( newInt32 >> 8 ) & 0xFF )
1587 << (char)(( newInt32 >> 16 ) & 0xFF )
1588 << (char)(( newInt32 >> 24 ) & 0xFF );
1593 #ifdef GDCM_NO_ANSI_STRING_STREAM
1594 s << std::ends; // to avoid oddities on Solaris
1595 #endif //GDCM_NO_ANSI_STRING_STREAM
1599 return ((ValEntry *)entry)->GetValue();
1603 * \brief Skip a given Header Entry
1604 * \warning NOT end user intended method !
1605 * @param entry entry to skip
1607 void Document::SkipDocEntry(DocEntry *entry)
1609 SkipBytes(entry->GetLength());
1613 * \brief Skips to the beginning of the next Header Entry
1614 * \warning NOT end user intended method !
1615 * @param currentDocEntry entry to skip
1617 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1619 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1620 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1621 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1625 * \brief When the length of an element value is obviously wrong (because
1626 * the parser went Jabberwocky) one can hope improving things by
1627 * applying some heuristics.
1628 * @param entry entry to check
1629 * @param foundLength first assumption about length
1631 void Document::FixDocEntryFoundLength(DocEntry *entry,
1632 uint32_t foundLength)
1634 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1635 if ( foundLength == 0xffffffff)
1640 uint16_t gr = entry->GetGroup();
1641 uint16_t elem = entry->GetElement();
1643 if ( foundLength % 2)
1645 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1646 << " in x(" << std::hex << gr << "," << elem <<")");
1649 //////// Fix for some naughty General Electric images.
1650 // Allthough not recent many such GE corrupted images are still present
1651 // on Creatis hard disks. Hence this fix shall remain when such images
1652 // are no longer in use (we are talking a few years, here)...
1653 // Note: XMedCom probably uses such a trick since it is able to read
1654 // those pesky GE images ...
1655 if ( foundLength == 13)
1657 // Only happens for this length !
1658 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1661 entry->SetReadLength(10); // a bug is to be fixed !?
1665 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1666 // Occurence of such images is quite low (unless one leaves close to a
1667 // 'Leonardo' source. Hence, one might consider commenting out the
1668 // following fix on efficiency reasons.
1669 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1672 entry->SetReadLength(4); // a bug is to be fixed !?
1675 else if ( entry->GetVR() == "SQ" )
1677 foundLength = 0; // ReadLength is unchanged
1680 //////// We encountered a 'delimiter' element i.e. a tag of the form
1681 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1682 // taken into account.
1683 else if( gr == 0xfffe )
1685 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1686 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1687 // causes extra troubles...
1688 if( entry->GetElement() != 0x0000 )
1693 entry->SetLength(foundLength);
1697 * \brief Apply some heuristics to predict whether the considered
1698 * element value contains/represents an integer or not.
1699 * @param entry The element value on which to apply the predicate.
1700 * @return The result of the heuristical predicate.
1702 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1704 uint16_t elem = entry->GetElement();
1705 uint16_t group = entry->GetGroup();
1706 const std::string &vr = entry->GetVR();
1707 uint32_t length = entry->GetLength();
1709 // When we have some semantics on the element we just read, and if we
1710 // a priori know we are dealing with an integer, then we shall be
1711 // able to swap it's element value properly.
1712 if ( elem == 0 ) // This is the group length of the group
1720 // Allthough this should never happen, still some images have a
1721 // corrupted group length [e.g. have a glance at offset x(8336) of
1722 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1723 // Since for dicom compliant and well behaved headers, the present
1724 // test is useless (and might even look a bit paranoid), when we
1725 // encounter such an ill-formed image, we simply display a warning
1726 // message and proceed on parsing (while crossing fingers).
1727 long filePosition = Fp->tellg();
1728 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1729 << std::hex << group << " , " << elem
1730 << ") -before- position x(" << filePosition << ")"
1731 << "lgt : " << length );
1735 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1743 * \brief Discover what the swap code is (among little endian, big endian,
1744 * bad little endian, bad big endian).
1746 * @return false when we are absolutely sure
1747 * it's neither ACR-NEMA nor DICOM
1748 * true when we hope ours assuptions are OK
1750 bool Document::CheckSwap()
1752 // The only guaranted way of finding the swap code is to find a
1753 // group tag since we know it's length has to be of four bytes i.e.
1754 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1755 // occurs when we can't find such group...
1762 // First, compare HostByteOrder and NetworkByteOrder in order to
1763 // determine if we shall need to swap bytes (i.e. the Endian type).
1764 bool net2host = Util::IsCurrentProcessorBigEndian();
1766 // The easiest case is the one of a 'true' DICOM header, we just have
1767 // to look for the string "DICM" inside the file preamble.
1770 char *entCur = deb + 128;
1771 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1773 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1775 // Group 0002 should always be VR, and the first element 0000
1776 // Let's be carefull (so many wrong headers ...)
1777 // and determine the value representation (VR) :
1778 // Let's skip to the first element (0002,0000) and check there if we find
1779 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1780 // in which case we (almost) know it is explicit VR.
1781 // WARNING: if it happens to be implicit VR then what we will read
1782 // is the length of the group. If this ascii representation of this
1783 // length happens to be "UL" then we shall believe it is explicit VR.
1784 // We need to skip :
1785 // * the 128 bytes of File Preamble (often padded with zeroes),
1786 // * the 4 bytes of "DICM" string,
1787 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1788 // i.e. a total of 136 bytes.
1791 // group 0x0002 *is always* Explicit VR Sometimes ,
1792 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1793 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1795 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1796 memcmp(entCur, "OB", (size_t)2) == 0 ||
1797 memcmp(entCur, "UI", (size_t)2) == 0 ||
1798 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1799 // when Write DCM *adds*
1801 // Use Document::dicom_vr to test all the possibilities
1802 // instead of just checking for UL, OB and UI !? group 0000
1804 Filetype = ExplicitVR;
1805 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1809 Filetype = ImplicitVR;
1810 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1811 << "Looks like a bugged Header!");
1817 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1822 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1825 // Position the file position indicator at first tag
1826 // (i.e. after the file preamble and the "DICM" string).
1827 Fp->seekg(0, std::ios::beg);
1828 Fp->seekg ( 132L, std::ios::beg);
1830 } // ------------------------------- End of DicomV3 ----------------
1832 // Alas, this is not a DicomV3 file and whatever happens there is no file
1833 // preamble. We can reset the file position indicator to where the data
1834 // is (i.e. the beginning of the file).
1836 gdcmWarningMacro( "Not a DICOM Version3 file");
1838 Fp->seekg(0, std::ios::beg);
1840 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1841 // By clean we mean that the length of the first group is written down.
1842 // If this is the case and since the length of the first group HAS to be
1843 // four (bytes), then determining the proper swap code is straightforward.
1846 // We assume the array of char we are considering contains the binary
1847 // representation of a 32 bits integer. Hence the following dirty
1849 s32 = *((uint32_t *)(entCur));
1869 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1870 // It is time for despaired wild guesses.
1871 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1872 // i.e. the 'group length' element is not present :
1874 // check the supposed-to-be 'group number'
1875 // in ( 0x0001 .. 0x0008 )
1876 // to determine ' SwapCode' value .
1877 // Only 0 or 4321 will be possible
1878 // (no oportunity to check for the formerly well known
1879 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1880 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1881 // the file IS NOT ACR-NEMA nor DICOM V3
1882 // Find a trick to tell it the caller...
1884 s16 = *((uint16_t *)(deb));
1911 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1919 * \brief Change the Byte Swap code.
1921 void Document::SwitchByteSwapCode()
1923 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1924 if ( SwapCode == 1234 )
1928 else if ( SwapCode == 4321 )
1932 else if ( SwapCode == 3412 )
1936 else if ( SwapCode == 2143 )
1943 * \brief during parsing, Header Elements too long are not loaded in memory
1944 * @param newSize new size
1946 void Document::SetMaxSizeLoadEntry(long newSize)
1952 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1954 MaxSizeLoadEntry = 0xffffffff;
1957 MaxSizeLoadEntry = newSize;
1961 * \brief Read the next tag but WITHOUT loading it's value
1962 * (read the 'Group Number', the 'Element Number',
1963 * gets the Dict Entry
1964 * gets the VR, gets the length, gets the offset value)
1965 * @return On succes the newly created DocEntry, NULL on failure.
1967 DocEntry *Document::ReadNextDocEntry()
1974 group = ReadInt16();
1977 catch ( FormatError e )
1979 // We reached the EOF (or an error occured) therefore
1980 // header parsing has to be considered as finished.
1984 // Sometimes file contains groups of tags with reversed endianess.
1985 HandleBrokenEndian(group, elem);
1987 // In 'true DICOM' files Group 0002 is always little endian
1988 if ( HasDCMPreamble )
1989 HandleOutOfGroup0002(group, elem);
1991 std::string vr = FindDocEntryVR();
1992 std::string realVR = vr;
1994 if( vr == GDCM_UNKNOWN)
1996 if ( elem == 0x0000 ) // Group Length
1997 realVR = "UL"; // must be UL
2000 DictEntry *dictEntry = GetDictEntry(group,elem);
2002 realVR = dictEntry->GetVR();
2007 if( Global::GetVR()->IsVROfSequence(realVR) )
2008 newEntry = NewSeqEntry(group, elem);
2009 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2010 newEntry = NewValEntry(group, elem,vr);
2012 newEntry = NewBinEntry(group, elem,vr);
2014 if( vr == GDCM_UNKNOWN )
2016 if( Filetype == ExplicitVR )
2018 // We thought this was explicit VR, but we end up with an
2019 // implicit VR tag. Let's backtrack.
2020 if ( newEntry->GetGroup() != 0xfffe )
2023 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2024 newEntry->GetGroup(), newEntry->GetElement());
2025 gdcmWarningMacro( msg.c_str() );
2028 newEntry->SetImplicitVR();
2033 FindDocEntryLength(newEntry);
2035 catch ( FormatError e )
2042 newEntry->SetOffset(Fp->tellg());
2048 * \brief Handle broken private tag from Philips NTSCAN
2049 * where the endianess is being switch to BigEndian for no
2053 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2055 // Endian reversion. Some files contain groups of tags with reversed endianess.
2056 static int reversedEndian = 0;
2057 // try to fix endian switching in the middle of headers
2058 if ((group == 0xfeff) && (elem == 0x00e0))
2060 // start endian swap mark for group found
2062 SwitchByteSwapCode();
2067 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2069 // end of reversed endian group
2071 SwitchByteSwapCode();
2076 * \brief Group 0002 is always coded Little Endian
2077 * whatever Transfer Syntax is
2080 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2082 // Endian reversion. Some files contain groups of tags with reversed endianess.
2083 if ( !Group0002Parsed && group != 0x0002)
2085 Group0002Parsed = true;
2086 // we just came out of group 0002
2087 // if Transfer syntax is Big Endian we have to change CheckSwap
2089 std::string ts = GetTransferSyntax();
2090 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2092 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2096 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2098 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2100 Filetype = ImplicitVR;
2103 // FIXME Strangely, this works with
2104 //'Implicit VR Transfer Syntax (GE Private)
2105 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2107 gdcmWarningMacro("Transfer Syntax Name = ["
2108 << GetTransferSyntaxName() << "]" );
2109 SwitchByteSwapCode();
2110 group = SwapShort(group);
2111 elem = SwapShort(elem);
2116 //-----------------------------------------------------------------------------
2119 //-----------------------------------------------------------------------------
2120 } // end namespace gdcm