1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/07/06 08:42:33 $
7 Version: $Revision: 1.257 $
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 // We should clean out anything that already exists.
110 // Check IsDocumentAlreadyLoaded to be sure.
111 if ( IsDocumentAlreadyLoaded )
113 gdcmWarningMacro( "A file was already parsed inside this "
114 << "gdcm::Document (previous name was: "
115 << Filename.c_str() << ". New name is :"
117 // todo : clean out the 'Document'
118 // Should we call ClearEntry() on the parent object ?!?
126 // warning already performed in OpenFile()
127 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
128 // << Filename.c_str() );
133 Group0002Parsed = false;
135 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
137 Fp->seekg(0, std::ios::end);
138 long lgt = Fp->tellg(); // total length of the file
140 Fp->seekg(0, std::ios::beg);
142 // CheckSwap returns a boolean
143 // (false if no swap info of any kind was found)
146 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
147 << Filename.c_str());
152 long beg = Fp->tellg(); // just after DICOM preamble (if any)
154 lgt -= beg; // remaining length to parse
157 // Loading is done during parsing
158 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
162 gdcmWarningMacro( "No tag in internal hash table for: "
163 << Filename.c_str());
167 IsDocumentAlreadyLoaded = true;
169 Fp->seekg( 0, std::ios::beg);
171 // Load 'non string' values
173 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
174 if ( PhotometricInterpretation == "PALETTE COLOR " )
177 // Probabely this line should be outside the 'if'
178 // Try to find an image sample holding a 'gray LUT'
179 LoadEntryBinArea(0x0028,0x1200); // gray LUT
182 /// The tags refered by the three following lines used to be CORRECTLY
183 /// defined as having an US Value Representation in the public
184 /// dictionary. BUT the semantics implied by the three following
185 /// lines state that the corresponding tag contents are in fact
186 /// the ones of a BinEntry.
187 /// In order to fix things "Quick and Dirty" the dictionary was
188 /// altered on PURPOSE but now contains a WRONG value.
189 /// In order to fix things and restore the dictionary to its
190 /// correct value, one needs to decided of the semantics by deciding
191 /// whether the following tags are either :
192 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
193 /// also used as BinEntry, which requires the proper conversion,
194 /// - OW, and hence loaded as BinEntry, but afterwards also used
195 /// as ValEntry, which requires the proper conversion.
196 LoadEntryBinArea(0x0028,0x1201); // R LUT
197 LoadEntryBinArea(0x0028,0x1202); // G LUT
198 LoadEntryBinArea(0x0028,0x1203); // B LUT
200 // Segmented Red Palette Color LUT Data
201 LoadEntryBinArea(0x0028,0x1221);
202 // Segmented Green Palette Color LUT Data
203 LoadEntryBinArea(0x0028,0x1222);
204 // Segmented Blue Palette Color LUT Data
205 LoadEntryBinArea(0x0028,0x1223);
208 //FIXME later : how to use it?
209 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
212 SQItem *sqi= modLutSeq->GetFirstSQItem();
215 BinEntry *b = sqi->GetBinEntry(0x0028,0x3006);
218 if ( b->GetLength() != 0 )
220 LoadEntryBinArea(b); //LUT Data (CTX dependent)
228 // ----------------------------
229 // Specific code to allow gdcm to read ACR-LibIDO formated images
230 // Note: ACR-LibIDO is an extension of the ACR standard that was
231 // used at CREATIS. For the time being (say a couple of years)
232 // we keep this kludge to allow CREATIS users
233 // reading their old images.
235 // if recognition code tells us we deal with a LibIDO image
236 // we switch lineNumber and columnNumber
239 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
240 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
241 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
242 // with "little-endian strings"
244 Filetype = ACR_LIBIDO;
245 std::string rows = GetEntryValue(0x0028, 0x0010);
246 std::string columns = GetEntryValue(0x0028, 0x0011);
247 SetValEntry(columns, 0x0028, 0x0010);
248 SetValEntry(rows , 0x0028, 0x0011);
250 // --- End of ACR-LibIDO kludge ---
256 * \brief Get the public dictionary used
258 Dict *Document::GetPubDict()
264 * \brief Get the shadow dictionary used
266 Dict *Document::GetShaDict()
272 * \brief Set the shadow dictionary used
273 * @param dict dictionary to use in shadow
275 bool Document::SetShaDict(Dict *dict)
282 * \brief Set the shadow dictionary used
283 * @param dictName name of the dictionary to use in shadow
285 bool Document::SetShaDict(DictKey const &dictName)
287 RefShaDict = Global::GetDicts()->GetDict(dictName);
292 * \brief This predicate tells us whether or not the current Document
293 * was properly parsed and contains at least *one* Dicom Element
294 * (and nothing more, sorry).
295 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
298 bool Document::IsReadable()
300 if ( Filetype == Unknown )
302 gdcmWarningMacro( "Wrong filetype");
308 gdcmWarningMacro( "No tag in internal hash table.");
316 * \brief Predicate for dicom version 3 file.
317 * @return True when the file is a dicom version 3.
319 bool Document::IsDicomV3()
321 // Checking if Transfer Syntax exists is enough
322 // Anyway, it's too late check if the 'Preamble' was found ...
323 // And ... would it be a rich idea to check ?
324 // (some 'no Preamble' DICOM images exist !)
325 return GetDocEntry(0x0002, 0x0010) != NULL;
329 * \brief Predicate for Papyrus file
330 * Dedicated to whomsoever it may concern
331 * @return True when the file is a Papyrus file.
333 bool Document::IsPapyrus()
335 // check for Papyrus private Sequence
336 DocEntry *e = GetDocEntry(0x0041, 0x1050);
339 // check if it's actually a Sequence
340 if ( !dynamic_cast<SeqEntry*>(e) )
346 * \brief returns the File Type
347 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
348 * @return the FileType code
350 FileType Document::GetFileType()
356 * \brief Accessor to the Transfer Syntax (when present) of the
357 * current document (it internally handles reading the
358 * value from disk when only parsing occured).
359 * @return The encountered Transfer Syntax of the current document.
361 std::string Document::GetTransferSyntax()
363 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
369 // The entry might be present but not loaded (parsing and loading
370 // happen at different stages): try loading and proceed with check...
371 LoadDocEntrySafe(entry);
372 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
374 std::string transfer = valEntry->GetValue();
375 // The actual transfer (as read from disk) might be padded. We
376 // first need to remove the potential padding. We can make the
377 // weak assumption that padding was not executed with digits...
378 if ( transfer.length() == 0 )
380 // for brain damaged headers
383 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
385 transfer.erase(transfer.length()-1, 1);
393 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
394 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
396 std::string Document::GetTransferSyntaxName()
398 // use the TS (TS : Transfer Syntax)
399 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
401 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
403 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
404 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
405 return "Uncompressed ACR-NEMA";
407 if ( transferSyntax == GDCM_UNFOUND )
409 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
410 return "Uncompressed ACR-NEMA";
413 // we do it only when we need it
414 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
416 // Global::GetTS() is a global static you shall never try to delete it!
420 // --------------- Swap Code ------------------
422 * \brief Swaps the bytes so they agree with the processor order
423 * @return The properly swaped 16 bits integer.
425 uint16_t Document::SwapShort(uint16_t a)
427 if ( SwapCode == 4321 || SwapCode == 2143 )
429 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
431 a = ( a << 8 ) | ( a >> 8 );
437 * \brief Swaps back the bytes of 4-byte long integer accordingly to
439 * @return The properly swaped 32 bits integer.
441 uint32_t Document::SwapLong(uint32_t a)
448 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
449 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
451 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
452 ((a>>8) & 0x0000ff00) | (a>>24) );
455 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
456 a=( (a<<16) | (a>>16) );
459 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
462 gdcmErrorMacro( "Unset swap code:" << SwapCode );
469 // -----------------File I/O ---------------
471 * \brief Tries to open the file \ref Document::Filename and
472 * checks the preamble when existing.
473 * @return The FILE pointer on success.
475 std::ifstream *Document::OpenFile()
477 HasDCMPreamble = false;
478 if (Filename.length() == 0)
485 gdcmWarningMacro( "File already open: " << Filename.c_str());
489 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
492 // Don't user gdcmErrorMacro :
493 // a spurious message will appear when you use, for instance
494 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
495 // to create outputFileName.
496 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
500 //exit(1); // No function is allowed to leave the application instead
501 // of warning the caller
505 Fp->read((char*)&zero, (size_t)2);
512 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
514 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
515 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
516 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
517 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
519 std::string msg = Util::Format(
520 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
521 gdcmWarningMacro( msg.c_str() );
526 Fp->seekg(126L, std::ios::cur);
527 char dicm[4] = {' ',' ',' ',' '};
528 Fp->read(dicm, (size_t)4);
534 if ( memcmp(dicm, "DICM", 4) == 0 )
536 HasDCMPreamble = true;
540 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
542 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
543 << Filename.c_str());
548 * \brief closes the file
549 * @return TRUE if the close was successfull
551 bool Document::CloseFile()
563 * \brief Writes in a file all the Header Entries (Dicom Elements)
564 * @param fp file pointer on an already open file (actually: Output File Stream)
565 * @param filetype Type of the File to be written
566 * (ACR-NEMA, ExplicitVR, ImplicitVR)
567 * @return Always true.
569 void Document::WriteContent(std::ofstream *fp, FileType filetype)
571 // \TODO move the following lines (and a lot of others, to be written)
572 // to a future function CheckAndCorrectHeader
574 // (necessary if user wants to write a DICOM V3 file
575 // starting from an ACR-NEMA (V2) Header
577 if ( filetype == ImplicitVR || filetype == ExplicitVR )
579 // writing Dicom File Preamble
580 char filePreamble[128];
581 memset(filePreamble, 0, 128);
582 fp->write(filePreamble, 128);
583 fp->write("DICM", 4);
587 * \todo rewrite later, if really usefull
588 * - 'Group Length' element is optional in DICOM
589 * - but un-updated odd groups lengthes can causes pb
592 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
593 * UpdateGroupLength(false,filetype);
594 * if ( filetype == ACR)
595 * UpdateGroupLength(true,ACR);
598 ElementSet::WriteContent(fp, filetype); // This one is recursive
601 // -----------------------------------------
604 * \brief Loads (from disk) the element content
605 * when a string is not suitable
606 * @param group group number of the Entry
607 * @param elem element number of the Entry
609 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
611 // Search the corresponding DocEntry
612 DocEntry *docElement = GetDocEntry(group, elem);
616 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
620 LoadEntryBinArea(binElement);
624 * \brief Loads (from disk) the element content
625 * when a string is not suitable
626 * @param elem Entry whose binArea is going to be loaded
628 void Document::LoadEntryBinArea(BinEntry *elem)
630 if (elem->GetBinArea() )
637 size_t o =(size_t)elem->GetOffset();
638 Fp->seekg(o, std::ios::beg);
640 size_t l = elem->GetLength();
641 uint8_t *a = new uint8_t[l];
644 gdcmWarningMacro( "Cannot allocate BinEntry content");
648 Fp->read((char*)a, l);
649 if ( Fp->fail() || Fp->eof() )
662 * \brief Loads the element while preserving the current
663 * underlying file position indicator as opposed to
664 * LoadDocEntry that modifies it.
665 * @param entry DocEntry whose value will be loaded.
667 void Document::LoadDocEntrySafe(DocEntry *entry)
671 long PositionOnEntry = Fp->tellg();
673 Fp->seekg(PositionOnEntry, std::ios::beg);
678 * \brief Compares two documents, according to \ref DicomDir rules
679 * \warning Does NOT work with ACR-NEMA files
680 * \todo Find a trick to solve the pb (use RET fields ?)
681 * @param document to compare with current one
682 * @return true if 'smaller'
684 bool Document::operator<(Document &document)
687 std::string s1 = GetEntryValue(0x0010,0x0010);
688 std::string s2 = document.GetEntryValue(0x0010,0x0010);
700 s1 = GetEntryValue(0x0010,0x0020);
701 s2 = document.GetEntryValue(0x0010,0x0020);
712 // Study Instance UID
713 s1 = GetEntryValue(0x0020,0x000d);
714 s2 = document.GetEntryValue(0x0020,0x000d);
725 // Serie Instance UID
726 s1 = GetEntryValue(0x0020,0x000e);
727 s2 = document.GetEntryValue(0x0020,0x000e);
742 //-----------------------------------------------------------------------------
745 * \brief Reads a supposed to be 16 Bits integer
746 * (swaps it depending on processor endianness)
749 uint16_t Document::ReadInt16()
753 Fp->read ((char*)&g, (size_t)2);
756 throw FormatError( "Document::ReadInt16()", " file error." );
760 throw FormatError( "Document::ReadInt16()", "EOF." );
767 * \brief Reads a supposed to be 32 Bits integer
768 * (swaps it depending on processor endianness)
771 uint32_t Document::ReadInt32()
775 Fp->read ((char*)&g, (size_t)4);
778 throw FormatError( "Document::ReadInt32()", " file error." );
782 throw FormatError( "Document::ReadInt32()", "EOF." );
789 * \brief skips bytes inside the source file
790 * \warning NOT end user intended method !
793 void Document::SkipBytes(uint32_t nBytes)
795 //FIXME don't dump the returned value
796 Fp->seekg((long)nBytes, std::ios::cur);
800 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
801 * @param filetype Type of the File to be written
803 int Document::ComputeGroup0002Length( FileType filetype )
809 bool found0002 = false;
811 // for each zero-level Tag in the DCM Header
812 DocEntry *entry = GetFirstEntry();
815 gr = entry->GetGroup();
821 if ( entry->GetElement() != 0x0000 )
825 if ( filetype == ExplicitVR )
827 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
829 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
833 groupLength += 2 + 2 + 4 + entry->GetLength();
839 entry = GetNextEntry();
844 //-----------------------------------------------------------------------------
847 * \brief Loads all the needed Dictionaries
848 * \warning NOT end user intended method !
850 void Document::Initialize()
852 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
858 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
859 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
860 * @param offset start of parsing
861 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
862 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
864 void Document::ParseDES(DocEntrySet *set, long offset,
865 long l_max, bool delim_mode)
867 DocEntry *newDocEntry;
868 ValEntry *newValEntry;
869 BinEntry *newBinEntry;
870 SeqEntry *newSeqEntry;
873 bool delim_mode_intern = delim_mode;
877 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
882 newDocEntry = ReadNextDocEntry( );
890 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
891 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
893 if ( newValEntry || newBinEntry )
897 vr = newDocEntry->GetVR();
898 if ( Filetype == ExplicitVR &&
899 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
901 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
902 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
903 << "|" << newDocEntry->GetElement()
904 << " : Neither Valentry, nor BinEntry."
905 "Probably unknown VR.");
908 //////////////////// BinEntry or UNKOWN VR:
909 // When "this" is a Document the Key is simply of the
910 // form ( group, elem )...
911 if ( dynamic_cast< Document* > ( set ) )
913 newBinEntry->SetKey( newBinEntry->GetKey() );
915 // but when "this" is a SQItem, we are inserting this new
916 // valEntry in a sequence item, and the key has the
917 // generalized form (refer to \ref BaseTagKey):
918 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
920 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
921 + newBinEntry->GetKey() );
924 LoadDocEntry( newBinEntry );
925 if ( !set->AddEntry( newBinEntry ) )
927 //gdcmWarningMacro( "in ParseDES : cannot add a BinEntry "
928 // << newBinEntry->GetKey() );
934 /////////////////////// ValEntry
936 // When "set" is a Document, then we are at the top of the
937 // hierarchy and the Key is simply of the form ( group, elem )...
938 if ( dynamic_cast< Document* > ( set ) )
940 newValEntry->SetKey( newValEntry->GetKey() );
942 // ...but when "set" is a SQItem, we are inserting this new
943 // valEntry in a sequence item. Hence the key has the
944 // generalized form (refer to \ref BaseTagKey):
945 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
947 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
948 + newValEntry->GetKey() );
951 LoadDocEntry( newValEntry );
952 bool delimitor=newValEntry->IsItemDelimitor();
954 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
955 // shadow groups ( if possible :
956 // whether element 0x0000 exits)
958 if ( newValEntry->GetGroup()%2 != 0 )
960 if ( newValEntry->GetElement() == 0x0000 )
962 std::string strLgrGroup = newValEntry->GetValue();
964 if ( strLgrGroup != GDCM_UNFOUND)
966 lgrGroup = atoi(strLgrGroup.c_str());
967 Fp->seekg(lgrGroup, std::ios::cur);
975 if ( !set->AddEntry( newValEntry ) )
977 //gdcmWarningMacro( "in ParseDES : cannot add a ValEntry "
978 // << newValEntry->GetKey() );
988 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max )
996 // Just to make sure we are at the beginning of next entry.
997 SkipToNextDocEntry(newDocEntry);
1001 /////////////////////// SeqEntry : VR = "SQ"
1003 unsigned long l = newDocEntry->GetReadLength();
1004 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1006 if ( l == 0xffffffff )
1008 delim_mode_intern = true;
1012 delim_mode_intern = false;
1016 if ( (LoadMode & NO_SHADOWSEQ) && ! delim_mode_intern )
1018 // User asked to skip SeQuences *only* if they belong to Shadow Group
1019 if ( newDocEntry->GetGroup()%2 != 0 )
1021 Fp->seekg( l, std::ios::cur);
1026 if ( (LoadMode & NO_SEQ) && ! delim_mode_intern )
1028 // User asked to skip *any* SeQuence
1029 Fp->seekg( l, std::ios::cur);
1033 // delay the dynamic cast as late as possible
1034 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1036 // no other way to create the Delimitor ...
1037 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1039 // At the top of the hierarchy, stands a Document. When "set"
1040 // is a Document, then we are building the first depth level.
1041 // Hence the SeqEntry we are building simply has a depth
1043 if ( dynamic_cast< Document* > ( set ) )
1045 newSeqEntry->SetDepthLevel( 1 );
1046 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1048 // But when "set" is already a SQItem, we are building a nested
1049 // sequence, and hence the depth level of the new SeqEntry
1050 // we are building, is one level deeper:
1051 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1053 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1054 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1055 + newSeqEntry->GetKey() );
1059 { // Don't try to parse zero-length sequences
1060 ParseSQ( newSeqEntry,
1061 newDocEntry->GetOffset(),
1062 l, delim_mode_intern);
1064 if ( !set->AddEntry( newSeqEntry ) )
1066 //gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1067 // << newSeqEntry->GetKey() );
1071 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1085 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1086 * @return parsed length for this level
1088 void Document::ParseSQ( SeqEntry *seqEntry,
1089 long offset, long l_max, bool delim_mode)
1091 int SQItemNumber = 0;
1093 long offsetStartCurrentSQItem = offset;
1097 // the first time, we read the fff0,e000 of the first SQItem
1098 DocEntry *newDocEntry = ReadNextDocEntry();
1102 // FIXME Should warn user
1103 gdcmWarningMacro("in ParseSQ : should never get here!");
1108 if ( newDocEntry->IsSequenceDelimitor() )
1110 seqEntry->SetDelimitationItem( newDocEntry );
1114 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1119 // create the current SQItem
1120 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1121 std::ostringstream newBase;
1122 newBase << seqEntry->GetKey()
1126 itemSQ->SetBaseTagKey( newBase.str() );
1127 unsigned int l = newDocEntry->GetReadLength();
1129 if ( l == 0xffffffff )
1138 // Let's try :------------
1139 // remove fff0,e000, created out of the SQItem
1141 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1142 // fill up the current SQItem, starting at the beginning of fff0,e000
1144 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1146 offsetStartCurrentSQItem = Fp->tellg();
1147 // end try -----------------
1149 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1151 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1159 * \brief Loads the element content if its length doesn't exceed
1160 * the value specified with Document::SetMaxSizeLoadEntry()
1161 * @param entry Header Entry (Dicom Element) to be dealt with
1163 void Document::LoadDocEntry(DocEntry *entry)
1165 uint16_t group = entry->GetGroup();
1166 std::string vr = entry->GetVR();
1167 uint32_t length = entry->GetLength();
1169 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1171 // A SeQuence "contains" a set of Elements.
1172 // (fffe e000) tells us an Element is beginning
1173 // (fffe e00d) tells us an Element just ended
1174 // (fffe e0dd) tells us the current SeQuence just ended
1175 if ( group == 0xfffe )
1177 // NO more value field for SQ !
1181 // When the length is zero things are easy:
1184 ((ValEntry *)entry)->SetValue("");
1188 // The elements whose length is bigger than the specified upper bound
1189 // are not loaded. Instead we leave a short notice on the offset of
1190 // the element content and it's length.
1192 std::ostringstream s;
1193 if (length > MaxSizeLoadEntry)
1195 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1197 s << GDCM_NOTLOADED;
1198 s << " Ad.:" << (long)entry->GetOffset();
1199 s << " x(" << std::hex << entry->GetOffset() << ")";
1201 s << " Lgt:" << entry->GetLength();
1202 s << " x(" << std::hex << entry->GetLength() << ")";
1203 binEntryPtr->SetValue(s.str());
1205 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1207 s << GDCM_NOTLOADED;
1208 s << " Address:" << (long)entry->GetOffset();
1209 s << " Length:" << entry->GetLength();
1210 s << " x(" << std::hex << entry->GetLength() << ")";
1211 valEntryPtr->SetValue(s.str());
1216 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1217 << "nor a ValEntry ?! Should never print that !" );
1220 // to be sure we are at the end of the value ...
1221 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1226 // When we find a BinEntry not very much can be done :
1227 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1229 s << GDCM_BINLOADED;
1230 binEntryPtr->SetValue(s.str());
1231 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1235 if ( IsDocEntryAnInteger(entry) )
1239 // When short integer(s) are expected, read and convert the following
1240 // (n * 2) characters properly i.e. consider them as short integers as
1241 // opposed to strings.
1242 // Elements with Value Multiplicity > 1
1243 // contain a set of integers (not a single one)
1244 if (vr == "US" || vr == "SS")
1247 NewInt = ReadInt16();
1251 for (int i=1; i < nbInt; i++)
1254 NewInt = ReadInt16();
1259 // See above comment on multiple integers (mutatis mutandis).
1260 else if (vr == "UL" || vr == "SL")
1263 NewInt = ReadInt32();
1267 for (int i=1; i < nbInt; i++)
1270 NewInt = ReadInt32();
1275 #ifdef GDCM_NO_ANSI_STRING_STREAM
1276 s << std::ends; // to avoid oddities on Solaris
1277 #endif //GDCM_NO_ANSI_STRING_STREAM
1279 ((ValEntry *)entry)->SetValue(s.str());
1283 // FIXME: We need an additional byte for storing \0 that is not on disk
1284 char *str = new char[length+1];
1285 Fp->read(str, (size_t)length);
1286 str[length] = '\0'; //this is only useful when length is odd
1287 // Special DicomString call to properly handle \0 and even length
1288 std::string newValue;
1291 newValue = Util::DicomString(str, length+1);
1292 gdcmWarningMacro("Warning: bad length: " << length <<
1293 " For string :" << newValue.c_str());
1294 // Since we change the length of string update it length
1295 //entry->SetReadLength(length+1);
1299 newValue = Util::DicomString(str, length);
1303 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1305 if ( Fp->fail() || Fp->eof())
1308 gdcmWarningMacro("--> fail");
1310 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1311 << " lgt : " << valEntry->GetReadLength()
1312 << " at " << std::hex << valEntry->GetOffset());
1313 valEntry->SetValue(GDCM_UNREAD);
1319 // Because of correspondance with the VR dic
1320 valEntry->SetValue(newValue);
1324 valEntry->SetValue(newValue);
1329 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1330 << " lgt : " << valEntry->GetReadLength()
1331 << " at " << std::hex << valEntry->GetOffset());
1336 * \brief Find the value Length of the passed Header Entry
1337 * @param entry Header Entry whose length of the value shall be loaded.
1339 void Document::FindDocEntryLength( DocEntry *entry )
1340 throw ( FormatError )
1342 std::string vr = entry->GetVR();
1345 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1347 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1349 // The following reserved two bytes (see PS 3.5-2003, section
1350 // "7.1.2 Data element structure with explicit vr", p 27) must be
1351 // skipped before proceeding on reading the length on 4 bytes.
1352 Fp->seekg( 2L, std::ios::cur);
1353 uint32_t length32 = ReadInt32();
1355 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1360 lengthOB = FindDocEntryLengthOBOrOW();
1362 catch ( FormatUnexpected )
1364 // Computing the length failed (this happens with broken
1365 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1366 // chance to get the pixels by deciding the element goes
1367 // until the end of the file. Hence we artificially fix the
1368 // the length and proceed.
1369 long currentPosition = Fp->tellg();
1370 Fp->seekg(0L,std::ios::end);
1372 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1373 Fp->seekg(currentPosition, std::ios::beg);
1375 entry->SetReadLength(lengthUntilEOF);
1376 entry->SetLength(lengthUntilEOF);
1379 entry->SetReadLength(lengthOB);
1380 entry->SetLength(lengthOB);
1383 FixDocEntryFoundLength(entry, length32);
1387 // Length is encoded on 2 bytes.
1388 length16 = ReadInt16();
1390 // 0xffff means that we deal with 'No Length' Sequence
1391 // or 'No Length' SQItem
1392 if ( length16 == 0xffff)
1396 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1401 // Either implicit VR or a non DICOM conformal (see note below) explicit
1402 // VR that ommited the VR of (at least) this element. Farts happen.
1403 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1404 // on Data elements "Implicit and Explicit VR Data Elements shall
1405 // not coexist in a Data Set and Data Sets nested within it".]
1406 // Length is on 4 bytes.
1408 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1409 // even if Transfer Syntax is 'Implicit VR ...'
1411 FixDocEntryFoundLength( entry, ReadInt32() );
1417 * \brief Find the Length till the next sequence delimiter
1418 * \warning NOT end user intended method !
1421 uint32_t Document::FindDocEntryLengthOBOrOW()
1422 throw( FormatUnexpected )
1424 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1425 long positionOnEntry = Fp->tellg();
1426 bool foundSequenceDelimiter = false;
1427 uint32_t totalLength = 0;
1429 while ( !foundSequenceDelimiter )
1435 group = ReadInt16();
1438 catch ( FormatError )
1440 throw FormatError("Unexpected end of file encountered during ",
1441 "Document::FindDocEntryLengthOBOrOW()");
1443 // We have to decount the group and element we just read
1445 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1447 long filePosition = Fp->tellg();
1449 "Neither an Item tag nor a Sequence delimiter tag on :"
1450 << std::hex << group << " , " << elem
1451 << ") -before- position x(" << filePosition << ")" );
1453 Fp->seekg(positionOnEntry, std::ios::beg);
1454 throw FormatUnexpected(
1455 "Neither an Item tag nor a Sequence delimiter tag.");
1457 if ( elem == 0xe0dd )
1459 foundSequenceDelimiter = true;
1461 uint32_t itemLength = ReadInt32();
1462 // We add 4 bytes since we just read the ItemLength with ReadInt32
1463 totalLength += itemLength + 4;
1464 SkipBytes(itemLength);
1466 if ( foundSequenceDelimiter )
1471 Fp->seekg( positionOnEntry, std::ios::beg);
1476 * \brief Find the Value Representation of the current Dicom Element.
1477 * @return Value Representation of the current Entry
1479 std::string Document::FindDocEntryVR()
1481 if ( Filetype != ExplicitVR )
1482 return GDCM_UNKNOWN;
1484 long positionOnEntry = Fp->tellg();
1485 // Warning: we believe this is explicit VR (Value Representation) because
1486 // we used a heuristic that found "UL" in the first tag. Alas this
1487 // doesn't guarantee that all the tags will be in explicit VR. In some
1488 // cases (see e-film filtered files) one finds implicit VR tags mixed
1489 // within an explicit VR file. Hence we make sure the present tag
1490 // is in explicit VR and try to fix things if it happens not to be
1494 Fp->read (vr, (size_t)2);
1497 if ( !CheckDocEntryVR(vr) )
1499 Fp->seekg(positionOnEntry, std::ios::beg);
1500 return GDCM_UNKNOWN;
1506 * \brief Check the correspondance between the VR of the header entry
1507 * and the taken VR. If they are different, the header entry is
1508 * updated with the new VR.
1509 * @param vr Dicom Value Representation
1510 * @return false if the VR is incorrect of if the VR isn't referenced
1511 * otherwise, it returns true
1513 bool Document::CheckDocEntryVR(VRKey vr)
1515 if ( !Global::GetVR()->IsValidVR(vr) )
1522 * \brief Get the transformed value of the header entry. The VR value
1523 * is used to define the transformation to operate on the value
1524 * \warning NOT end user intended method !
1525 * @param entry entry to tranform
1526 * @return Transformed entry value
1528 std::string Document::GetDocEntryValue(DocEntry *entry)
1530 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1532 std::string val = ((ValEntry *)entry)->GetValue();
1533 std::string vr = entry->GetVR();
1534 uint32_t length = entry->GetLength();
1535 std::ostringstream s;
1538 // When short integer(s) are expected, read and convert the following
1539 // n * 2 bytes properly i.e. as a multivaluated strings
1540 // (each single value is separated fromthe next one by '\'
1541 // as usual for standard multivaluated filels
1542 // Elements with Value Multiplicity > 1
1543 // contain a set of short integers (not a single one)
1545 if ( vr == "US" || vr == "SS" )
1550 for (int i=0; i < nbInt; i++)
1556 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1557 newInt16 = SwapShort( newInt16 );
1562 // When integer(s) are expected, read and convert the following
1563 // n * 4 bytes properly i.e. as a multivaluated strings
1564 // (each single value is separated fromthe next one by '\'
1565 // as usual for standard multivaluated filels
1566 // Elements with Value Multiplicity > 1
1567 // contain a set of integers (not a single one)
1568 else if ( vr == "UL" || vr == "SL" )
1573 for (int i=0; i < nbInt; i++)
1579 newInt32 = ( val[4*i+0] & 0xFF )
1580 + (( val[4*i+1] & 0xFF ) << 8 )
1581 + (( val[4*i+2] & 0xFF ) << 16 )
1582 + (( val[4*i+3] & 0xFF ) << 24 );
1583 newInt32 = SwapLong( newInt32 );
1587 #ifdef GDCM_NO_ANSI_STRING_STREAM
1588 s << std::ends; // to avoid oddities on Solaris
1589 #endif //GDCM_NO_ANSI_STRING_STREAM
1592 return ((ValEntry *)entry)->GetValue();
1596 * \brief Get the reverse transformed value of the header entry. The VR
1597 * value is used to define the reverse transformation to operate on
1599 * \warning NOT end user intended method !
1600 * @param entry Entry to reverse transform
1601 * @return Reverse transformed entry value
1603 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1605 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1607 std::string vr = entry->GetVR();
1608 std::vector<std::string> tokens;
1609 std::ostringstream s;
1611 if ( vr == "US" || vr == "SS" )
1615 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1616 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1617 for (unsigned int i=0; i<tokens.size(); i++)
1619 newInt16 = atoi(tokens[i].c_str());
1620 s << ( newInt16 & 0xFF )
1621 << (( newInt16 >> 8 ) & 0xFF );
1625 if ( vr == "UL" || vr == "SL")
1629 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1630 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1631 for (unsigned int i=0; i<tokens.size();i++)
1633 newInt32 = atoi(tokens[i].c_str());
1634 s << (char)( newInt32 & 0xFF )
1635 << (char)(( newInt32 >> 8 ) & 0xFF )
1636 << (char)(( newInt32 >> 16 ) & 0xFF )
1637 << (char)(( newInt32 >> 24 ) & 0xFF );
1642 #ifdef GDCM_NO_ANSI_STRING_STREAM
1643 s << std::ends; // to avoid oddities on Solaris
1644 #endif //GDCM_NO_ANSI_STRING_STREAM
1648 return ((ValEntry *)entry)->GetValue();
1652 * \brief Skip a given Header Entry
1653 * \warning NOT end user intended method !
1654 * @param entry entry to skip
1656 void Document::SkipDocEntry(DocEntry *entry)
1658 SkipBytes(entry->GetLength());
1662 * \brief Skips to the beginning of the next Header Entry
1663 * \warning NOT end user intended method !
1664 * @param currentDocEntry entry to skip
1666 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1668 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1669 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1670 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1674 * \brief When the length of an element value is obviously wrong (because
1675 * the parser went Jabberwocky) one can hope improving things by
1676 * applying some heuristics.
1677 * @param entry entry to check
1678 * @param foundLength first assumption about length
1680 void Document::FixDocEntryFoundLength(DocEntry *entry,
1681 uint32_t foundLength)
1683 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1684 if ( foundLength == 0xffffffff)
1689 uint16_t gr = entry->GetGroup();
1690 uint16_t elem = entry->GetElement();
1692 if ( foundLength % 2)
1694 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1695 << " in x(" << std::hex << gr << "," << elem <<")");
1698 //////// Fix for some naughty General Electric images.
1699 // Allthough not recent many such GE corrupted images are still present
1700 // on Creatis hard disks. Hence this fix shall remain when such images
1701 // are no longer in use (we are talking a few years, here)...
1702 // Note: XMedCon probably uses such a trick since it is able to read
1703 // those pesky GE images ...
1704 if ( foundLength == 13)
1706 // Only happens for this length !
1707 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1710 entry->SetReadLength(10); // a bug is to be fixed !?
1714 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1715 // Occurence of such images is quite low (unless one leaves close to a
1716 // 'Leonardo' source. Hence, one might consider commenting out the
1717 // following fix on efficiency reasons.
1718 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1721 entry->SetReadLength(4); // a bug is to be fixed !?
1724 else if ( entry->GetVR() == "SQ" )
1726 foundLength = 0; // ReadLength is unchanged
1729 //////// We encountered a 'delimiter' element i.e. a tag of the form
1730 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1731 // taken into account.
1732 else if ( gr == 0xfffe )
1734 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1735 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1736 // causes extra troubles...
1737 if ( entry->GetElement() != 0x0000 )
1742 entry->SetLength(foundLength);
1746 * \brief Apply some heuristics to predict whether the considered
1747 * element value contains/represents an integer or not.
1748 * @param entry The element value on which to apply the predicate.
1749 * @return The result of the heuristical predicate.
1751 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1753 uint16_t elem = entry->GetElement();
1754 uint16_t group = entry->GetGroup();
1755 const std::string &vr = entry->GetVR();
1756 uint32_t length = entry->GetLength();
1758 // When we have some semantics on the element we just read, and if we
1759 // a priori know we are dealing with an integer, then we shall be
1760 // able to swap it's element value properly.
1761 if ( elem == 0 ) // This is the group length of the group
1769 // Allthough this should never happen, still some images have a
1770 // corrupted group length [e.g. have a glance at offset x(8336) of
1771 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1772 // Since for dicom compliant and well behaved headers, the present
1773 // test is useless (and might even look a bit paranoid), when we
1774 // encounter such an ill-formed image, we simply display a warning
1775 // message and proceed on parsing (while crossing fingers).
1776 long filePosition = Fp->tellg();
1777 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1778 << std::hex << group << " , " << elem
1779 << ") -before- position x(" << filePosition << ")"
1780 << "lgt : " << length );
1784 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1792 * \brief Discover what the swap code is (among little endian, big endian,
1793 * bad little endian, bad big endian).
1795 * @return false when we are absolutely sure
1796 * it's neither ACR-NEMA nor DICOM
1797 * true when we hope ours assuptions are OK
1799 bool Document::CheckSwap()
1806 // First, compare HostByteOrder and NetworkByteOrder in order to
1807 // determine if we shall need to swap bytes (i.e. the Endian type).
1808 bool net2host = Util::IsCurrentProcessorBigEndian();
1810 // The easiest case is the one of a 'true' DICOM header, we just have
1811 // to look for the string "DICM" inside the file preamble.
1814 char *entCur = deb + 128;
1815 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1817 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1819 // Group 0002 should always be VR, and the first element 0000
1820 // Let's be carefull (so many wrong headers ...)
1821 // and determine the value representation (VR) :
1822 // Let's skip to the first element (0002,0000) and check there if we find
1823 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1824 // in which case we (almost) know it is explicit VR.
1825 // WARNING: if it happens to be implicit VR then what we will read
1826 // is the length of the group. If this ascii representation of this
1827 // length happens to be "UL" then we shall believe it is explicit VR.
1828 // We need to skip :
1829 // * the 128 bytes of File Preamble (often padded with zeroes),
1830 // * the 4 bytes of "DICM" string,
1831 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1832 // i.e. a total of 136 bytes.
1835 // group 0x0002 *is always* Explicit VR Sometimes ,
1836 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1837 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1839 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1840 memcmp(entCur, "OB", (size_t)2) == 0 ||
1841 memcmp(entCur, "UI", (size_t)2) == 0 ||
1842 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1843 // when Write DCM *adds*
1845 // Use Document::dicom_vr to test all the possibilities
1846 // instead of just checking for UL, OB and UI !? group 0000
1848 Filetype = ExplicitVR;
1849 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1853 Filetype = ImplicitVR;
1854 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1855 << "Looks like a bugged Header!");
1861 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1866 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1869 // Position the file position indicator at first tag
1870 // (i.e. after the file preamble and the "DICM" string).
1872 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1874 Fp->seekg ( 132L, std::ios::beg);
1876 } // ------------------------------- End of DicomV3 ----------------
1878 // Alas, this is not a DicomV3 file and whatever happens there is no file
1879 // preamble. We can reset the file position indicator to where the data
1880 // is (i.e. the beginning of the file).
1882 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1884 Fp->seekg(0, std::ios::beg);
1886 // Let's check 'No Preamble Dicom File' :
1887 // Should start with group 0x0002
1888 // and be Explicit Value Representation
1890 s16 = *((uint16_t *)(deb));
1903 if ( SwapCode != 0 )
1905 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1906 memcmp(entCur, "OB", (size_t)2) == 0 ||
1907 memcmp(entCur, "UI", (size_t)2) == 0 ||
1908 memcmp(entCur, "SH", (size_t)2) == 0 ||
1909 memcmp(entCur, "AE", (size_t)2) == 0 ||
1910 memcmp(entCur, "OB", (size_t)2) == 0 )
1912 Filetype = ExplicitVR;
1913 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1917 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1919 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1920 // By clean we mean that the length of the first group is written down.
1921 // If this is the case and since the length of the first group HAS to be
1922 // four (bytes), then determining the proper swap code is straightforward.
1925 // We assume the array of char we are considering contains the binary
1926 // representation of a 32 bits integer. Hence the following dirty
1928 s32 = *((uint32_t *)(entCur));
1948 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1949 // It is time for despaired wild guesses.
1950 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1951 // i.e. the 'group length' element is not present :
1953 // check the supposed-to-be 'group number'
1954 // in ( 0x0001 .. 0x0008 )
1955 // to determine ' SwapCode' value .
1956 // Only 0 or 4321 will be possible
1957 // (no oportunity to check for the formerly well known
1958 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1959 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1960 // the file IS NOT ACR-NEMA nor DICOM V3
1961 // Find a trick to tell it the caller...
1963 s16 = *((uint16_t *)(deb));
1990 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1998 * \brief Change the Byte Swap code.
2000 void Document::SwitchByteSwapCode()
2002 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
2003 << " at :" <<std::hex << Fp->tellg() );
2004 if ( SwapCode == 1234 )
2008 else if ( SwapCode == 4321 )
2012 else if ( SwapCode == 3412 )
2016 else if ( SwapCode == 2143 )
2023 * \brief during parsing, Header Elements too long are not loaded in memory
2024 * @param newSize new size
2026 void Document::SetMaxSizeLoadEntry(long newSize)
2032 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2034 MaxSizeLoadEntry = 0xffffffff;
2037 MaxSizeLoadEntry = newSize;
2041 * \brief Read the next tag WITHOUT loading it's value
2042 * (read the 'Group Number', the 'Element Number',
2043 * gets the Dict Entry
2044 * gets the VR, gets the length, gets the offset value)
2045 * @return On succes : the newly created DocEntry, NULL on failure.
2047 DocEntry *Document::ReadNextDocEntry()
2054 group = ReadInt16();
2057 catch ( FormatError e )
2059 // We reached the EOF (or an error occured) therefore
2060 // header parsing has to be considered as finished.
2064 // Sometimes file contains groups of tags with reversed endianess.
2065 HandleBrokenEndian(group, elem);
2067 // In 'true DICOM' files Group 0002 is always little endian
2068 if ( HasDCMPreamble )
2069 HandleOutOfGroup0002(group, elem);
2071 std::string vr = FindDocEntryVR();
2072 std::string realVR = vr;
2074 if ( vr == GDCM_UNKNOWN )
2076 if ( elem == 0x0000 ) // Group Length
2077 realVR = "UL"; // must be UL
2080 DictEntry *dictEntry = GetDictEntry(group,elem);
2082 realVR = dictEntry->GetVR();
2087 if ( Global::GetVR()->IsVROfSequence(realVR) )
2088 newEntry = NewSeqEntry(group, elem);
2089 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2090 newEntry = NewValEntry(group, elem,vr);
2092 newEntry = NewBinEntry(group, elem,vr);
2094 if ( vr == GDCM_UNKNOWN )
2096 if ( Filetype == ExplicitVR )
2098 // We thought this was explicit VR, but we end up with an
2099 // implicit VR tag. Let's backtrack.
2100 if ( newEntry->GetGroup() != 0xfffe )
2103 int offset = Fp->tellg();
2104 msg = Util::Format("Entry (%04x,%04x) at 0x(%x) should be Explicit VR\n",
2105 newEntry->GetGroup(), newEntry->GetElement(), offset );
2106 gdcmWarningMacro( msg.c_str() );
2109 newEntry->SetImplicitVR();
2114 FindDocEntryLength(newEntry);
2116 catch ( FormatError e )
2123 newEntry->SetOffset(Fp->tellg());
2129 * \brief Handle broken private tag from Philips NTSCAN
2130 * where the endianess is being switched to BigEndian
2131 * for no apparent reason
2134 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2136 // Endian reversion. Some files contain groups of tags with reversed endianess.
2137 static int reversedEndian = 0;
2138 // try to fix endian switching in the middle of headers
2139 if ((group == 0xfeff) && (elem == 0x00e0))
2141 // start endian swap mark for group found
2143 SwitchByteSwapCode();
2148 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2150 // end of reversed endian group
2152 SwitchByteSwapCode();
2157 * \brief Group 0002 is always coded Little Endian
2158 * whatever Transfer Syntax is
2161 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2163 // Endian reversion. Some files contain groups of tags with reversed endianess.
2164 if ( !Group0002Parsed && group != 0x0002)
2166 Group0002Parsed = true;
2167 // we just came out of group 0002
2168 // if Transfer syntax is Big Endian we have to change CheckSwap
2170 std::string ts = GetTransferSyntax();
2171 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2173 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2177 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2179 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2181 Filetype = ImplicitVR;
2184 // FIXME Strangely, this works with
2185 //'Implicit VR Transfer Syntax (GE Private)
2186 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2188 gdcmWarningMacro("Transfer Syntax Name = ["
2189 << GetTransferSyntaxName() << "]" );
2190 SwitchByteSwapCode();
2191 group = SwapShort(group);
2192 elem = SwapShort(elem);
2197 //-----------------------------------------------------------------------------
2200 //-----------------------------------------------------------------------------
2201 } // end namespace gdcm