1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/07/06 15:18:42 $
7 Version: $Revision: 1.259 $
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"
34 #include <ctype.h> // for isdigit
35 #include <stdlib.h> // for atoi
39 //-----------------------------------------------------------------------------
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 open 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, later
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 open for parsing
104 * @return false if file cannot be open or no swap info was found,
105 * or no tag was found.
107 bool Document::Load( std::string const &fileName )
109 if ( IsDocumentAlreadyLoaded )
111 if ( Filename == fileName )
113 gdcmWarningMacro( "The file was already parsed inside this "
114 << "gdcm::Document (its name is: "
115 << Filename.c_str() );
119 gdcmWarningMacro( "A file was already parsed inside this "
120 << "gdcm::Document (previous name was: "
121 << Filename.c_str() << ". New name is :"
123 // clean out the Entries, if already parsed
124 // (probabely a mistake from the user)
134 // warning already performed in OpenFile()
135 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
136 // << Filename.c_str() );
141 Group0002Parsed = false;
143 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
145 Fp->seekg(0, std::ios::end);
146 long lgt = Fp->tellg(); // total length of the file
148 Fp->seekg(0, std::ios::beg);
150 // CheckSwap returns a boolean
151 // (false if no swap info of any kind was found)
154 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
155 << Filename.c_str());
160 long beg = Fp->tellg(); // just after DICOM preamble (if any)
162 lgt -= beg; // remaining length to parse
165 // Loading is done during parsing
166 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
170 gdcmWarningMacro( "No tag in internal hash table for: "
171 << Filename.c_str());
175 IsDocumentAlreadyLoaded = true;
177 Fp->seekg( 0, std::ios::beg);
179 // Load 'non string' values
181 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
182 if ( PhotometricInterpretation == "PALETTE COLOR " )
185 // Probabely this line should be outside the 'if'
186 // Try to find an image sample holding a 'gray LUT'
187 LoadEntryBinArea(0x0028,0x1200); // gray LUT
190 /// The tags refered by the three following lines used to be CORRECTLY
191 /// defined as having an US Value Representation in the public
192 /// dictionary. BUT the semantics implied by the three following
193 /// lines state that the corresponding tag contents are in fact
194 /// the ones of a BinEntry.
195 /// In order to fix things "Quick and Dirty" the dictionary was
196 /// altered on PURPOSE but now contains a WRONG value.
197 /// In order to fix things and restore the dictionary to its
198 /// correct value, one needs to decided of the semantics by deciding
199 /// whether the following tags are either :
200 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
201 /// also used as BinEntry, which requires the proper conversion,
202 /// - OW, and hence loaded as BinEntry, but afterwards also used
203 /// as ValEntry, which requires the proper conversion.
204 LoadEntryBinArea(0x0028,0x1201); // R LUT
205 LoadEntryBinArea(0x0028,0x1202); // G LUT
206 LoadEntryBinArea(0x0028,0x1203); // B LUT
208 // Segmented Red Palette Color LUT Data
209 LoadEntryBinArea(0x0028,0x1221);
210 // Segmented Green Palette Color LUT Data
211 LoadEntryBinArea(0x0028,0x1222);
212 // Segmented Blue Palette Color LUT Data
213 LoadEntryBinArea(0x0028,0x1223);
216 //FIXME later : how to use it?
217 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
220 SQItem *sqi= modLutSeq->GetFirstSQItem();
223 BinEntry *b = sqi->GetBinEntry(0x0028,0x3006);
226 if ( b->GetLength() != 0 )
228 LoadEntryBinArea(b); //LUT Data (CTX dependent)
236 // ----------------------------
237 // Specific code to allow gdcm to read ACR-LibIDO formated images
238 // Note: ACR-LibIDO is an extension of the ACR standard that was
239 // used at CREATIS. For the time being (say a couple of years)
240 // we keep this kludge to allow CREATIS users
241 // reading their old images.
243 // if recognition code tells us we deal with a LibIDO image
244 // we switch lineNumber and columnNumber
247 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
248 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
249 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
250 // with "little-endian strings"
252 Filetype = ACR_LIBIDO;
253 std::string rows = GetEntryValue(0x0028, 0x0010);
254 std::string columns = GetEntryValue(0x0028, 0x0011);
255 SetValEntry(columns, 0x0028, 0x0010);
256 SetValEntry(rows , 0x0028, 0x0011);
258 // --- End of ACR-LibIDO kludge ---
264 * \brief Get the public dictionary used
266 Dict *Document::GetPubDict()
272 * \brief Get the shadow dictionary used
274 Dict *Document::GetShaDict()
280 * \brief Set the shadow dictionary used
281 * @param dict dictionary to use in shadow
283 bool Document::SetShaDict(Dict *dict)
290 * \brief Set the shadow dictionary used
291 * @param dictName name of the dictionary to use in shadow
293 bool Document::SetShaDict(DictKey const &dictName)
295 RefShaDict = Global::GetDicts()->GetDict(dictName);
300 * \brief This predicate tells us whether or not the current Document
301 * was properly parsed and contains at least *one* Dicom Element
302 * (and nothing more, sorry).
303 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
306 bool Document::IsReadable()
308 if ( Filetype == Unknown )
310 gdcmWarningMacro( "Wrong filetype");
316 gdcmWarningMacro( "No tag in internal hash table.");
324 * \brief Predicate for dicom version 3 file.
325 * @return True when the file is a dicom version 3.
327 bool Document::IsDicomV3()
329 // Checking if Transfer Syntax exists is enough
330 // Anyway, it's too late check if the 'Preamble' was found ...
331 // And ... would it be a rich idea to check ?
332 // (some 'no Preamble' DICOM images exist !)
333 return GetDocEntry(0x0002, 0x0010) != NULL;
337 * \brief Predicate for Papyrus file
338 * Dedicated to whomsoever it may concern
339 * @return True when the file is a Papyrus file.
341 bool Document::IsPapyrus()
343 // check for Papyrus private Sequence
344 DocEntry *e = GetDocEntry(0x0041, 0x1050);
347 // check if it's actually a Sequence
348 if ( !dynamic_cast<SeqEntry*>(e) )
354 * \brief returns the File Type
355 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
356 * @return the FileType code
358 FileType Document::GetFileType()
364 * \brief Accessor to the Transfer Syntax (when present) of the
365 * current document (it internally handles reading the
366 * value from disk when only parsing occured).
367 * @return The encountered Transfer Syntax of the current document.
369 std::string Document::GetTransferSyntax()
371 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
377 // The entry might be present but not loaded (parsing and loading
378 // happen at different stages): try loading and proceed with check...
379 LoadDocEntrySafe(entry);
380 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
382 std::string transfer = valEntry->GetValue();
383 // The actual transfer (as read from disk) might be padded. We
384 // first need to remove the potential padding. We can make the
385 // weak assumption that padding was not executed with digits...
386 if ( transfer.length() == 0 )
388 // for brain damaged headers
391 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
393 transfer.erase(transfer.length()-1, 1);
401 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
402 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
404 std::string Document::GetTransferSyntaxName()
406 // use the TS (TS : Transfer Syntax)
407 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
409 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
411 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
412 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
413 return "Uncompressed ACR-NEMA";
415 if ( transferSyntax == GDCM_UNFOUND )
417 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
418 return "Uncompressed ACR-NEMA";
421 // we do it only when we need it
422 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
424 // Global::GetTS() is a global static you shall never try to delete it!
428 // --------------- Swap Code ------------------
430 * \brief Swaps the bytes so they agree with the processor order
431 * @return The properly swaped 16 bits integer.
433 uint16_t Document::SwapShort(uint16_t a)
435 if ( SwapCode == 4321 || SwapCode == 2143 )
437 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
439 a = ( a << 8 ) | ( a >> 8 );
445 * \brief Swaps back the bytes of 4-byte long integer accordingly to
447 * @return The properly swaped 32 bits integer.
449 uint32_t Document::SwapLong(uint32_t a)
456 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
457 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
459 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
460 ((a>>8) & 0x0000ff00) | (a>>24) );
463 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
464 a=( (a<<16) | (a>>16) );
467 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
470 gdcmErrorMacro( "Unset swap code:" << SwapCode );
477 // -----------------File I/O ---------------
479 * \brief Tries to open the file \ref Document::Filename and
480 * checks the preamble when existing.
481 * @return The FILE pointer on success.
483 std::ifstream *Document::OpenFile()
485 HasDCMPreamble = false;
486 if (Filename.length() == 0)
493 gdcmWarningMacro( "File already open: " << Filename.c_str());
497 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
500 // Don't user gdcmErrorMacro :
501 // a spurious message will appear when you use, for instance
502 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
503 // to create outputFileName.
504 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
508 //exit(1); // No function is allowed to leave the application instead
509 // of warning the caller
513 Fp->read((char*)&zero, (size_t)2);
520 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
522 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
523 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
524 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
525 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
527 std::string msg = Util::Format(
528 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
529 gdcmWarningMacro( msg.c_str() );
534 Fp->seekg(126L, std::ios::cur);
535 char dicm[4] = {' ',' ',' ',' '};
536 Fp->read(dicm, (size_t)4);
542 if ( memcmp(dicm, "DICM", 4) == 0 )
544 HasDCMPreamble = true;
548 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
550 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
551 << Filename.c_str());
556 * \brief closes the file
557 * @return TRUE if the close was successfull
559 bool Document::CloseFile()
571 * \brief Writes in a file all the Header Entries (Dicom Elements)
572 * @param fp file pointer on an already open file (actually: Output File Stream)
573 * @param filetype Type of the File to be written
574 * (ACR-NEMA, ExplicitVR, ImplicitVR)
575 * @return Always true.
577 void Document::WriteContent(std::ofstream *fp, FileType filetype)
579 // \TODO move the following lines (and a lot of others, to be written)
580 // to a future function CheckAndCorrectHeader
582 // (necessary if user wants to write a DICOM V3 file
583 // starting from an ACR-NEMA (V2) Header
585 if ( filetype == ImplicitVR || filetype == ExplicitVR )
587 // writing Dicom File Preamble
588 char filePreamble[128];
589 memset(filePreamble, 0, 128);
590 fp->write(filePreamble, 128);
591 fp->write("DICM", 4);
595 * \todo rewrite later, if really usefull
596 * - 'Group Length' element is optional in DICOM
597 * - but un-updated odd groups lengthes can causes pb
600 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
601 * UpdateGroupLength(false,filetype);
602 * if ( filetype == ACR)
603 * UpdateGroupLength(true,ACR);
606 ElementSet::WriteContent(fp, filetype); // This one is recursive
609 // -----------------------------------------
612 * \brief Loads (from disk) the element content
613 * when a string is not suitable
614 * @param group group number of the Entry
615 * @param elem element number of the Entry
617 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
619 // Search the corresponding DocEntry
620 DocEntry *docElement = GetDocEntry(group, elem);
624 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
628 LoadEntryBinArea(binElement);
632 * \brief Loads (from disk) the element content
633 * when a string is not suitable
634 * @param elem Entry whose binArea is going to be loaded
636 void Document::LoadEntryBinArea(BinEntry *elem)
638 if (elem->GetBinArea() )
645 size_t o =(size_t)elem->GetOffset();
646 Fp->seekg(o, std::ios::beg);
648 size_t l = elem->GetLength();
649 uint8_t *a = new uint8_t[l];
652 gdcmWarningMacro( "Cannot allocate BinEntry content");
656 Fp->read((char*)a, l);
657 if ( Fp->fail() || Fp->eof() )
670 * \brief Loads the element while preserving the current
671 * underlying file position indicator as opposed to
672 * LoadDocEntry that modifies it.
673 * @param entry DocEntry whose value will be loaded.
675 void Document::LoadDocEntrySafe(DocEntry *entry)
679 long PositionOnEntry = Fp->tellg();
681 Fp->seekg(PositionOnEntry, std::ios::beg);
686 * \brief Compares two documents, according to \ref DicomDir rules
687 * \warning Does NOT work with ACR-NEMA files
688 * \todo Find a trick to solve the pb (use RET fields ?)
689 * @param document to compare with current one
690 * @return true if 'smaller'
692 bool Document::operator<(Document &document)
695 std::string s1 = GetEntryValue(0x0010,0x0010);
696 std::string s2 = document.GetEntryValue(0x0010,0x0010);
708 s1 = GetEntryValue(0x0010,0x0020);
709 s2 = document.GetEntryValue(0x0010,0x0020);
720 // Study Instance UID
721 s1 = GetEntryValue(0x0020,0x000d);
722 s2 = document.GetEntryValue(0x0020,0x000d);
733 // Serie Instance UID
734 s1 = GetEntryValue(0x0020,0x000e);
735 s2 = document.GetEntryValue(0x0020,0x000e);
750 //-----------------------------------------------------------------------------
753 * \brief Reads a supposed to be 16 Bits integer
754 * (swaps it depending on processor endianness)
757 uint16_t Document::ReadInt16()
761 Fp->read ((char*)&g, (size_t)2);
764 throw FormatError( "Document::ReadInt16()", " file error." );
768 throw FormatError( "Document::ReadInt16()", "EOF." );
775 * \brief Reads a supposed to be 32 Bits integer
776 * (swaps it depending on processor endianness)
779 uint32_t Document::ReadInt32()
783 Fp->read ((char*)&g, (size_t)4);
786 throw FormatError( "Document::ReadInt32()", " file error." );
790 throw FormatError( "Document::ReadInt32()", "EOF." );
797 * \brief skips bytes inside the source file
798 * \warning NOT end user intended method !
801 void Document::SkipBytes(uint32_t nBytes)
803 //FIXME don't dump the returned value
804 Fp->seekg((long)nBytes, std::ios::cur);
808 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
809 * @param filetype Type of the File to be written
811 int Document::ComputeGroup0002Length( FileType filetype )
817 bool found0002 = false;
819 // for each zero-level Tag in the DCM Header
820 DocEntry *entry = GetFirstEntry();
823 gr = entry->GetGroup();
829 if ( entry->GetElement() != 0x0000 )
833 if ( filetype == ExplicitVR )
835 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
837 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
841 groupLength += 2 + 2 + 4 + entry->GetLength();
847 entry = GetNextEntry();
852 //-----------------------------------------------------------------------------
855 * \brief Loads all the needed Dictionaries
856 * \warning NOT end user intended method !
858 void Document::Initialize()
860 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
866 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
867 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
868 * @param offset start of parsing
869 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
870 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
872 void Document::ParseDES(DocEntrySet *set, long offset,
873 long l_max, bool delim_mode)
875 DocEntry *newDocEntry;
876 ValEntry *newValEntry;
877 BinEntry *newBinEntry;
878 SeqEntry *newSeqEntry;
881 bool delim_mode_intern = delim_mode;
885 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
890 newDocEntry = ReadNextDocEntry( );
898 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
899 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
901 if ( newValEntry || newBinEntry )
905 vr = newDocEntry->GetVR();
906 if ( Filetype == ExplicitVR &&
907 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
909 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
910 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
911 << "|" << newDocEntry->GetElement()
912 << " : Neither Valentry, nor BinEntry."
913 "Probably unknown VR.");
916 //////////////////// BinEntry or UNKOWN VR:
917 // When "this" is a Document the Key is simply of the
918 // form ( group, elem )...
919 if ( dynamic_cast< Document* > ( set ) )
921 newBinEntry->SetKey( newBinEntry->GetKey() );
923 // but when "this" is a SQItem, we are inserting this new
924 // valEntry in a sequence item, and the key has the
925 // generalized form (refer to \ref BaseTagKey):
926 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
928 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
929 + newBinEntry->GetKey() );
932 LoadDocEntry( newBinEntry );
933 if ( !set->AddEntry( newBinEntry ) )
935 gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
936 << newBinEntry->GetKey() );
942 /////////////////////// ValEntry
944 // When "set" is a Document, then we are at the top of the
945 // hierarchy and the Key is simply of the form ( group, elem )...
946 if ( dynamic_cast< Document* > ( set ) )
948 newValEntry->SetKey( newValEntry->GetKey() );
950 // ...but when "set" is a SQItem, we are inserting this new
951 // valEntry in a sequence item. Hence the key has the
952 // generalized form (refer to \ref BaseTagKey):
953 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
955 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
956 + newValEntry->GetKey() );
959 LoadDocEntry( newValEntry );
960 bool delimitor=newValEntry->IsItemDelimitor();
962 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
963 // shadow groups ( if possible :
964 // whether element 0x0000 exits)
966 if ( newValEntry->GetGroup()%2 != 0 )
968 if ( newValEntry->GetElement() == 0x0000 )
970 std::string strLgrGroup = newValEntry->GetValue();
972 if ( strLgrGroup != GDCM_UNFOUND)
974 lgrGroup = atoi(strLgrGroup.c_str());
975 Fp->seekg(lgrGroup, std::ios::cur);
983 if ( !set->AddEntry( newValEntry ) )
985 gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
986 << newValEntry->GetKey() );
996 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max )
1004 // Just to make sure we are at the beginning of next entry.
1005 SkipToNextDocEntry(newDocEntry);
1009 /////////////////////// SeqEntry : VR = "SQ"
1011 unsigned long l = newDocEntry->GetReadLength();
1012 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1014 if ( l == 0xffffffff )
1016 delim_mode_intern = true;
1020 delim_mode_intern = false;
1024 if ( (LoadMode & NO_SHADOWSEQ) && ! delim_mode_intern )
1026 // User asked to skip SeQuences *only* if they belong to Shadow Group
1027 if ( newDocEntry->GetGroup()%2 != 0 )
1029 Fp->seekg( l, std::ios::cur);
1034 if ( (LoadMode & NO_SEQ) && ! delim_mode_intern )
1036 // User asked to skip *any* SeQuence
1037 Fp->seekg( l, std::ios::cur);
1041 // delay the dynamic cast as late as possible
1042 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1044 // no other way to create the Delimitor ...
1045 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1047 // At the top of the hierarchy, stands a Document. When "set"
1048 // is a Document, then we are building the first depth level.
1049 // Hence the SeqEntry we are building simply has a depth
1051 if ( dynamic_cast< Document* > ( set ) )
1053 newSeqEntry->SetDepthLevel( 1 );
1054 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1056 // But when "set" is already a SQItem, we are building a nested
1057 // sequence, and hence the depth level of the new SeqEntry
1058 // we are building, is one level deeper:
1059 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1061 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1062 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1063 + newSeqEntry->GetKey() );
1067 { // Don't try to parse zero-length sequences
1068 ParseSQ( newSeqEntry,
1069 newDocEntry->GetOffset(),
1070 l, delim_mode_intern);
1072 if ( !set->AddEntry( newSeqEntry ) )
1074 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1075 << newSeqEntry->GetKey() );
1079 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1093 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1094 * @return parsed length for this level
1096 void Document::ParseSQ( SeqEntry *seqEntry,
1097 long offset, long l_max, bool delim_mode)
1099 int SQItemNumber = 0;
1101 long offsetStartCurrentSQItem = offset;
1105 // the first time, we read the fff0,e000 of the first SQItem
1106 DocEntry *newDocEntry = ReadNextDocEntry();
1110 // FIXME Should warn user
1111 gdcmWarningMacro("in ParseSQ : should never get here!");
1116 if ( newDocEntry->IsSequenceDelimitor() )
1118 seqEntry->SetDelimitationItem( newDocEntry );
1122 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1127 // create the current SQItem
1128 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1129 std::ostringstream newBase;
1130 newBase << seqEntry->GetKey()
1134 itemSQ->SetBaseTagKey( newBase.str() );
1135 unsigned int l = newDocEntry->GetReadLength();
1137 if ( l == 0xffffffff )
1146 // Let's try :------------
1147 // remove fff0,e000, created out of the SQItem
1149 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1150 // fill up the current SQItem, starting at the beginning of fff0,e000
1152 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1154 offsetStartCurrentSQItem = Fp->tellg();
1155 // end try -----------------
1157 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1159 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1167 * \brief Loads the element content if its length doesn't exceed
1168 * the value specified with Document::SetMaxSizeLoadEntry()
1169 * @param entry Header Entry (Dicom Element) to be dealt with
1171 void Document::LoadDocEntry(DocEntry *entry)
1173 uint16_t group = entry->GetGroup();
1174 std::string vr = entry->GetVR();
1175 uint32_t length = entry->GetLength();
1177 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1179 // A SeQuence "contains" a set of Elements.
1180 // (fffe e000) tells us an Element is beginning
1181 // (fffe e00d) tells us an Element just ended
1182 // (fffe e0dd) tells us the current SeQuence just ended
1183 if ( group == 0xfffe )
1185 // NO more value field for SQ !
1189 // When the length is zero things are easy:
1192 ((ValEntry *)entry)->SetValue("");
1196 // The elements whose length is bigger than the specified upper bound
1197 // are not loaded. Instead we leave a short notice on the offset of
1198 // the element content and it's length.
1200 std::ostringstream s;
1201 if (length > MaxSizeLoadEntry)
1203 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1205 s << GDCM_NOTLOADED;
1206 s << " Ad.:" << (long)entry->GetOffset();
1207 s << " x(" << std::hex << entry->GetOffset() << ")";
1209 s << " Lgt:" << entry->GetLength();
1210 s << " x(" << std::hex << entry->GetLength() << ")";
1211 binEntryPtr->SetValue(s.str());
1213 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1215 s << GDCM_NOTLOADED;
1216 s << " Address:" << (long)entry->GetOffset();
1217 s << " Length:" << entry->GetLength();
1218 s << " x(" << std::hex << entry->GetLength() << ")";
1219 valEntryPtr->SetValue(s.str());
1224 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1225 << "nor a ValEntry ?! Should never print that !" );
1228 // to be sure we are at the end of the value ...
1229 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1234 // When we find a BinEntry not very much can be done :
1235 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1237 s << GDCM_BINLOADED;
1238 binEntryPtr->SetValue(s.str());
1239 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1243 if ( IsDocEntryAnInteger(entry) )
1247 // When short integer(s) are expected, read and convert the following
1248 // (n * 2) characters properly i.e. consider them as short integers as
1249 // opposed to strings.
1250 // Elements with Value Multiplicity > 1
1251 // contain a set of integers (not a single one)
1252 if (vr == "US" || vr == "SS")
1255 NewInt = ReadInt16();
1259 for (int i=1; i < nbInt; i++)
1262 NewInt = ReadInt16();
1267 // See above comment on multiple integers (mutatis mutandis).
1268 else if (vr == "UL" || vr == "SL")
1271 NewInt = ReadInt32();
1275 for (int i=1; i < nbInt; i++)
1278 NewInt = ReadInt32();
1283 #ifdef GDCM_NO_ANSI_STRING_STREAM
1284 s << std::ends; // to avoid oddities on Solaris
1285 #endif //GDCM_NO_ANSI_STRING_STREAM
1287 ((ValEntry *)entry)->SetValue(s.str());
1291 // FIXME: We need an additional byte for storing \0 that is not on disk
1292 char *str = new char[length+1];
1293 Fp->read(str, (size_t)length);
1294 str[length] = '\0'; //this is only useful when length is odd
1295 // Special DicomString call to properly handle \0 and even length
1296 std::string newValue;
1299 newValue = Util::DicomString(str, length+1);
1300 gdcmWarningMacro("Warning: bad length: " << length <<
1301 " For string :" << newValue.c_str());
1302 // Since we change the length of string update it length
1303 //entry->SetReadLength(length+1);
1307 newValue = Util::DicomString(str, length);
1311 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1313 if ( Fp->fail() || Fp->eof())
1316 gdcmWarningMacro("--> fail");
1318 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1319 << " lgt : " << valEntry->GetReadLength()
1320 << " at " << std::hex << valEntry->GetOffset());
1321 valEntry->SetValue(GDCM_UNREAD);
1327 // Because of correspondance with the VR dic
1328 valEntry->SetValue(newValue);
1332 valEntry->SetValue(newValue);
1337 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1338 << " lgt : " << valEntry->GetReadLength()
1339 << " at " << std::hex << valEntry->GetOffset());
1344 * \brief Find the value Length of the passed Header Entry
1345 * @param entry Header Entry whose length of the value shall be loaded.
1347 void Document::FindDocEntryLength( DocEntry *entry )
1348 throw ( FormatError )
1350 std::string vr = entry->GetVR();
1353 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1355 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1357 // The following reserved two bytes (see PS 3.5-2003, section
1358 // "7.1.2 Data element structure with explicit vr", p 27) must be
1359 // skipped before proceeding on reading the length on 4 bytes.
1360 Fp->seekg( 2L, std::ios::cur);
1361 uint32_t length32 = ReadInt32();
1363 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1368 lengthOB = FindDocEntryLengthOBOrOW();
1370 catch ( FormatUnexpected )
1372 // Computing the length failed (this happens with broken
1373 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1374 // chance to get the pixels by deciding the element goes
1375 // until the end of the file. Hence we artificially fix the
1376 // the length and proceed.
1377 long currentPosition = Fp->tellg();
1378 Fp->seekg(0L,std::ios::end);
1380 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1381 Fp->seekg(currentPosition, std::ios::beg);
1383 entry->SetReadLength(lengthUntilEOF);
1384 entry->SetLength(lengthUntilEOF);
1387 entry->SetReadLength(lengthOB);
1388 entry->SetLength(lengthOB);
1391 FixDocEntryFoundLength(entry, length32);
1395 // Length is encoded on 2 bytes.
1396 length16 = ReadInt16();
1398 // 0xffff means that we deal with 'No Length' Sequence
1399 // or 'No Length' SQItem
1400 if ( length16 == 0xffff)
1404 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1409 // Either implicit VR or a non DICOM conformal (see note below) explicit
1410 // VR that ommited the VR of (at least) this element. Farts happen.
1411 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1412 // on Data elements "Implicit and Explicit VR Data Elements shall
1413 // not coexist in a Data Set and Data Sets nested within it".]
1414 // Length is on 4 bytes.
1416 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1417 // even if Transfer Syntax is 'Implicit VR ...'
1419 FixDocEntryFoundLength( entry, ReadInt32() );
1425 * \brief Find the Length till the next sequence delimiter
1426 * \warning NOT end user intended method !
1429 uint32_t Document::FindDocEntryLengthOBOrOW()
1430 throw( FormatUnexpected )
1432 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1433 long positionOnEntry = Fp->tellg();
1434 bool foundSequenceDelimiter = false;
1435 uint32_t totalLength = 0;
1437 while ( !foundSequenceDelimiter )
1443 group = ReadInt16();
1446 catch ( FormatError )
1448 throw FormatError("Unexpected end of file encountered during ",
1449 "Document::FindDocEntryLengthOBOrOW()");
1451 // We have to decount the group and element we just read
1453 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1455 long filePosition = Fp->tellg();
1457 "Neither an Item tag nor a Sequence delimiter tag on :"
1458 << std::hex << group << " , " << elem
1459 << ") -before- position x(" << filePosition << ")" );
1461 Fp->seekg(positionOnEntry, std::ios::beg);
1462 throw FormatUnexpected(
1463 "Neither an Item tag nor a Sequence delimiter tag.");
1465 if ( elem == 0xe0dd )
1467 foundSequenceDelimiter = true;
1469 uint32_t itemLength = ReadInt32();
1470 // We add 4 bytes since we just read the ItemLength with ReadInt32
1471 totalLength += itemLength + 4;
1472 SkipBytes(itemLength);
1474 if ( foundSequenceDelimiter )
1479 Fp->seekg( positionOnEntry, std::ios::beg);
1484 * \brief Find the Value Representation of the current Dicom Element.
1485 * @return Value Representation of the current Entry
1487 std::string Document::FindDocEntryVR()
1489 if ( Filetype != ExplicitVR )
1490 return GDCM_UNKNOWN;
1492 long positionOnEntry = Fp->tellg();
1493 // Warning: we believe this is explicit VR (Value Representation) because
1494 // we used a heuristic that found "UL" in the first tag. Alas this
1495 // doesn't guarantee that all the tags will be in explicit VR. In some
1496 // cases (see e-film filtered files) one finds implicit VR tags mixed
1497 // within an explicit VR file. Hence we make sure the present tag
1498 // is in explicit VR and try to fix things if it happens not to be
1502 Fp->read (vr, (size_t)2);
1505 if ( !CheckDocEntryVR(vr) )
1507 Fp->seekg(positionOnEntry, std::ios::beg);
1508 return GDCM_UNKNOWN;
1514 * \brief Check the correspondance between the VR of the header entry
1515 * and the taken VR. If they are different, the header entry is
1516 * updated with the new VR.
1517 * @param vr Dicom Value Representation
1518 * @return false if the VR is incorrect of if the VR isn't referenced
1519 * otherwise, it returns true
1521 bool Document::CheckDocEntryVR(VRKey vr)
1523 if ( !Global::GetVR()->IsValidVR(vr) )
1530 * \brief Get the transformed value of the header entry. The VR value
1531 * is used to define the transformation to operate on the value
1532 * \warning NOT end user intended method !
1533 * @param entry entry to tranform
1534 * @return Transformed entry value
1536 std::string Document::GetDocEntryValue(DocEntry *entry)
1538 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1540 std::string val = ((ValEntry *)entry)->GetValue();
1541 std::string vr = entry->GetVR();
1542 uint32_t length = entry->GetLength();
1543 std::ostringstream s;
1546 // When short integer(s) are expected, read and convert the following
1547 // n * 2 bytes properly i.e. as a multivaluated strings
1548 // (each single value is separated fromthe next one by '\'
1549 // as usual for standard multivaluated filels
1550 // Elements with Value Multiplicity > 1
1551 // contain a set of short integers (not a single one)
1553 if ( vr == "US" || vr == "SS" )
1558 for (int i=0; i < nbInt; i++)
1564 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1565 newInt16 = SwapShort( newInt16 );
1570 // When integer(s) are expected, read and convert the following
1571 // n * 4 bytes properly i.e. as a multivaluated strings
1572 // (each single value is separated fromthe next one by '\'
1573 // as usual for standard multivaluated filels
1574 // Elements with Value Multiplicity > 1
1575 // contain a set of integers (not a single one)
1576 else if ( vr == "UL" || vr == "SL" )
1581 for (int i=0; i < nbInt; i++)
1587 newInt32 = ( val[4*i+0] & 0xFF )
1588 + (( val[4*i+1] & 0xFF ) << 8 )
1589 + (( val[4*i+2] & 0xFF ) << 16 )
1590 + (( val[4*i+3] & 0xFF ) << 24 );
1591 newInt32 = SwapLong( newInt32 );
1595 #ifdef GDCM_NO_ANSI_STRING_STREAM
1596 s << std::ends; // to avoid oddities on Solaris
1597 #endif //GDCM_NO_ANSI_STRING_STREAM
1600 return ((ValEntry *)entry)->GetValue();
1604 * \brief Get the reverse transformed value of the header entry. The VR
1605 * value is used to define the reverse transformation to operate on
1607 * \warning NOT end user intended method !
1608 * @param entry Entry to reverse transform
1609 * @return Reverse transformed entry value
1611 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1613 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1615 std::string vr = entry->GetVR();
1616 std::vector<std::string> tokens;
1617 std::ostringstream s;
1619 if ( vr == "US" || vr == "SS" )
1623 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1624 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1625 for (unsigned int i=0; i<tokens.size(); i++)
1627 newInt16 = atoi(tokens[i].c_str());
1628 s << ( newInt16 & 0xFF )
1629 << (( newInt16 >> 8 ) & 0xFF );
1633 if ( vr == "UL" || vr == "SL")
1637 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1638 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1639 for (unsigned int i=0; i<tokens.size();i++)
1641 newInt32 = atoi(tokens[i].c_str());
1642 s << (char)( newInt32 & 0xFF )
1643 << (char)(( newInt32 >> 8 ) & 0xFF )
1644 << (char)(( newInt32 >> 16 ) & 0xFF )
1645 << (char)(( newInt32 >> 24 ) & 0xFF );
1650 #ifdef GDCM_NO_ANSI_STRING_STREAM
1651 s << std::ends; // to avoid oddities on Solaris
1652 #endif //GDCM_NO_ANSI_STRING_STREAM
1656 return ((ValEntry *)entry)->GetValue();
1660 * \brief Skip a given Header Entry
1661 * \warning NOT end user intended method !
1662 * @param entry entry to skip
1664 void Document::SkipDocEntry(DocEntry *entry)
1666 SkipBytes(entry->GetLength());
1670 * \brief Skips to the beginning of the next Header Entry
1671 * \warning NOT end user intended method !
1672 * @param currentDocEntry entry to skip
1674 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1676 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1677 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1678 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1682 * \brief When the length of an element value is obviously wrong (because
1683 * the parser went Jabberwocky) one can hope improving things by
1684 * applying some heuristics.
1685 * @param entry entry to check
1686 * @param foundLength first assumption about length
1688 void Document::FixDocEntryFoundLength(DocEntry *entry,
1689 uint32_t foundLength)
1691 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1692 if ( foundLength == 0xffffffff)
1697 uint16_t gr = entry->GetGroup();
1698 uint16_t elem = entry->GetElement();
1700 if ( foundLength % 2)
1702 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1703 << " in x(" << std::hex << gr << "," << elem <<")");
1706 //////// Fix for some naughty General Electric images.
1707 // Allthough not recent many such GE corrupted images are still present
1708 // on Creatis hard disks. Hence this fix shall remain when such images
1709 // are no longer in use (we are talking a few years, here)...
1710 // Note: XMedCon probably uses such a trick since it is able to read
1711 // those pesky GE images ...
1712 if ( foundLength == 13)
1714 // Only happens for this length !
1715 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1718 entry->SetReadLength(10); // a bug is to be fixed !?
1722 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1723 // Occurence of such images is quite low (unless one leaves close to a
1724 // 'Leonardo' source. Hence, one might consider commenting out the
1725 // following fix on efficiency reasons.
1726 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1729 entry->SetReadLength(4); // a bug is to be fixed !?
1732 else if ( entry->GetVR() == "SQ" )
1734 foundLength = 0; // ReadLength is unchanged
1737 //////// We encountered a 'delimiter' element i.e. a tag of the form
1738 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1739 // taken into account.
1740 else if ( gr == 0xfffe )
1742 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1743 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1744 // causes extra troubles...
1745 if ( entry->GetElement() != 0x0000 )
1750 entry->SetLength(foundLength);
1754 * \brief Apply some heuristics to predict whether the considered
1755 * element value contains/represents an integer or not.
1756 * @param entry The element value on which to apply the predicate.
1757 * @return The result of the heuristical predicate.
1759 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1761 uint16_t elem = entry->GetElement();
1762 uint16_t group = entry->GetGroup();
1763 const std::string &vr = entry->GetVR();
1764 uint32_t length = entry->GetLength();
1766 // When we have some semantics on the element we just read, and if we
1767 // a priori know we are dealing with an integer, then we shall be
1768 // able to swap it's element value properly.
1769 if ( elem == 0 ) // This is the group length of the group
1777 // Allthough this should never happen, still some images have a
1778 // corrupted group length [e.g. have a glance at offset x(8336) of
1779 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1780 // Since for dicom compliant and well behaved headers, the present
1781 // test is useless (and might even look a bit paranoid), when we
1782 // encounter such an ill-formed image, we simply display a warning
1783 // message and proceed on parsing (while crossing fingers).
1784 long filePosition = Fp->tellg();
1785 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1786 << std::hex << group << " , " << elem
1787 << ") -before- position x(" << filePosition << ")"
1788 << "lgt : " << length );
1792 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1800 * \brief Discover what the swap code is (among little endian, big endian,
1801 * bad little endian, bad big endian).
1803 * @return false when we are absolutely sure
1804 * it's neither ACR-NEMA nor DICOM
1805 * true when we hope ours assuptions are OK
1807 bool Document::CheckSwap()
1814 // First, compare HostByteOrder and NetworkByteOrder in order to
1815 // determine if we shall need to swap bytes (i.e. the Endian type).
1816 bool net2host = Util::IsCurrentProcessorBigEndian();
1818 // The easiest case is the one of a 'true' DICOM header, we just have
1819 // to look for the string "DICM" inside the file preamble.
1822 char *entCur = deb + 128;
1823 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1825 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1827 // Group 0002 should always be VR, and the first element 0000
1828 // Let's be carefull (so many wrong headers ...)
1829 // and determine the value representation (VR) :
1830 // Let's skip to the first element (0002,0000) and check there if we find
1831 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1832 // in which case we (almost) know it is explicit VR.
1833 // WARNING: if it happens to be implicit VR then what we will read
1834 // is the length of the group. If this ascii representation of this
1835 // length happens to be "UL" then we shall believe it is explicit VR.
1836 // We need to skip :
1837 // * the 128 bytes of File Preamble (often padded with zeroes),
1838 // * the 4 bytes of "DICM" string,
1839 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1840 // i.e. a total of 136 bytes.
1843 // group 0x0002 *is always* Explicit VR Sometimes ,
1844 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1845 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1847 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1848 memcmp(entCur, "OB", (size_t)2) == 0 ||
1849 memcmp(entCur, "UI", (size_t)2) == 0 ||
1850 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1851 // when Write DCM *adds*
1853 // Use Document::dicom_vr to test all the possibilities
1854 // instead of just checking for UL, OB and UI !? group 0000
1856 Filetype = ExplicitVR;
1857 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1861 Filetype = ImplicitVR;
1862 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1863 << "Looks like a bugged Header!");
1869 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1874 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1877 // Position the file position indicator at first tag
1878 // (i.e. after the file preamble and the "DICM" string).
1880 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1882 Fp->seekg ( 132L, std::ios::beg);
1884 } // ------------------------------- End of DicomV3 ----------------
1886 // Alas, this is not a DicomV3 file and whatever happens there is no file
1887 // preamble. We can reset the file position indicator to where the data
1888 // is (i.e. the beginning of the file).
1890 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1892 Fp->seekg(0, std::ios::beg);
1894 // Let's check 'No Preamble Dicom File' :
1895 // Should start with group 0x0002
1896 // and be Explicit Value Representation
1898 s16 = *((uint16_t *)(deb));
1911 if ( SwapCode != 0 )
1913 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1914 memcmp(entCur, "OB", (size_t)2) == 0 ||
1915 memcmp(entCur, "UI", (size_t)2) == 0 ||
1916 memcmp(entCur, "SH", (size_t)2) == 0 ||
1917 memcmp(entCur, "AE", (size_t)2) == 0 ||
1918 memcmp(entCur, "OB", (size_t)2) == 0 )
1920 Filetype = ExplicitVR;
1921 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1925 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1927 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1928 // By clean we mean that the length of the first group is written down.
1929 // If this is the case and since the length of the first group HAS to be
1930 // four (bytes), then determining the proper swap code is straightforward.
1933 // We assume the array of char we are considering contains the binary
1934 // representation of a 32 bits integer. Hence the following dirty
1936 s32 = *((uint32_t *)(entCur));
1956 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1957 // It is time for despaired wild guesses.
1958 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1959 // i.e. the 'group length' element is not present :
1961 // check the supposed-to-be 'group number'
1962 // in ( 0x0001 .. 0x0008 )
1963 // to determine ' SwapCode' value .
1964 // Only 0 or 4321 will be possible
1965 // (no oportunity to check for the formerly well known
1966 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1967 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1968 // the file IS NOT ACR-NEMA nor DICOM V3
1969 // Find a trick to tell it the caller...
1971 s16 = *((uint16_t *)(deb));
1998 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2006 * \brief Change the Byte Swap code.
2008 void Document::SwitchByteSwapCode()
2010 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2011 << " at :" <<std::hex << Fp->tellg() );
2012 if ( SwapCode == 1234 )
2016 else if ( SwapCode == 4321 )
2020 else if ( SwapCode == 3412 )
2024 else if ( SwapCode == 2143 )
2031 * \brief during parsing, Header Elements too long are not loaded in memory
2032 * @param newSize new size
2034 void Document::SetMaxSizeLoadEntry(long newSize)
2040 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2042 MaxSizeLoadEntry = 0xffffffff;
2045 MaxSizeLoadEntry = newSize;
2049 * \brief Read the next tag WITHOUT loading it's value
2050 * (read the 'Group Number', the 'Element Number',
2051 * gets the Dict Entry
2052 * gets the VR, gets the length, gets the offset value)
2053 * @return On succes : the newly created DocEntry, NULL on failure.
2055 DocEntry *Document::ReadNextDocEntry()
2062 group = ReadInt16();
2065 catch ( FormatError e )
2067 // We reached the EOF (or an error occured) therefore
2068 // header parsing has to be considered as finished.
2072 // Sometimes file contains groups of tags with reversed endianess.
2073 HandleBrokenEndian(group, elem);
2075 // In 'true DICOM' files Group 0002 is always little endian
2076 if ( HasDCMPreamble )
2077 HandleOutOfGroup0002(group, elem);
2079 std::string vr = FindDocEntryVR();
2080 std::string realVR = vr;
2082 if ( vr == GDCM_UNKNOWN )
2084 if ( elem == 0x0000 ) // Group Length
2085 realVR = "UL"; // must be UL
2088 DictEntry *dictEntry = GetDictEntry(group,elem);
2090 realVR = dictEntry->GetVR();
2095 if ( Global::GetVR()->IsVROfSequence(realVR) )
2096 newEntry = NewSeqEntry(group, elem);
2097 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2098 newEntry = NewValEntry(group, elem,vr);
2100 newEntry = NewBinEntry(group, elem,vr);
2102 if ( vr == GDCM_UNKNOWN )
2104 if ( Filetype == ExplicitVR )
2106 // We thought this was explicit VR, but we end up with an
2107 // implicit VR tag. Let's backtrack.
2108 if ( newEntry->GetGroup() != 0xfffe )
2111 int offset = Fp->tellg();
2112 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2113 newEntry->GetGroup(), newEntry->GetElement(), offset );
2114 gdcmWarningMacro( msg.c_str() );
2117 newEntry->SetImplicitVR();
2122 FindDocEntryLength(newEntry);
2124 catch ( FormatError e )
2131 newEntry->SetOffset(Fp->tellg());
2137 * \brief Handle broken private tag from Philips NTSCAN
2138 * where the endianess is being switched to BigEndian
2139 * for no apparent reason
2142 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2144 // Endian reversion. Some files contain groups of tags with reversed endianess.
2145 static int reversedEndian = 0;
2146 // try to fix endian switching in the middle of headers
2147 if ((group == 0xfeff) && (elem == 0x00e0))
2149 // start endian swap mark for group found
2151 SwitchByteSwapCode();
2156 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2158 // end of reversed endian group
2160 SwitchByteSwapCode();
2165 * \brief Group 0002 is always coded Little Endian
2166 * whatever Transfer Syntax is
2169 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2171 // Endian reversion. Some files contain groups of tags with reversed endianess.
2172 if ( !Group0002Parsed && group != 0x0002)
2174 Group0002Parsed = true;
2175 // we just came out of group 0002
2176 // if Transfer syntax is Big Endian we have to change CheckSwap
2178 std::string ts = GetTransferSyntax();
2179 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2181 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2185 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2187 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2189 Filetype = ImplicitVR;
2192 // FIXME Strangely, this works with
2193 //'Implicit VR Transfer Syntax (GE Private)
2194 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2196 gdcmWarningMacro("Transfer Syntax Name = ["
2197 << GetTransferSyntaxName() << "]" );
2198 SwitchByteSwapCode();
2199 group = SwapShort(group);
2200 elem = SwapShort(elem);
2205 //-----------------------------------------------------------------------------
2208 //-----------------------------------------------------------------------------
2209 } // end namespace gdcm