1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/06/17 12:36:07 $
7 Version: $Revision: 1.246 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
37 //-----------------------------------------------------------------------------
39 // Refer to Document::SetMaxSizeLoadEntry()
40 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
44 // Constructors and destructors are protected to avoid user to invoke directly
47 * \brief This default constructor neither loads nor parses the file.
48 * You should then invoke \ref Document::Load.
56 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
59 Filetype = ExplicitVR;
60 // Load will set it to true if sucessfull
61 Group0002Parsed = false;
62 IsDocumentAlreadyLoaded = false;
63 LoadMode = 0x00000000; // default : load everything, later
67 * \brief Constructor (not to break the API)
68 * @param fileName 'Document' (File or DicomDir) to be open for parsing
70 Document::Document( std::string const &fileName )
75 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
78 Filetype = ExplicitVR;
79 Group0002Parsed = false;
80 LoadMode = 0x00000000; // Load everything
82 // Load will set it to true if sucessfull
83 IsDocumentAlreadyLoaded = false;
88 * \brief Canonical destructor.
90 Document::~Document ()
96 //-----------------------------------------------------------------------------
101 * @param fileName 'Document' (File or DicomDir) to be open for parsing
102 * @return false if file cannot be open or no swap info was found,
103 * or no tag was found.
105 bool Document::Load( std::string const &fileName )
107 // We should clean out anything that already exists.
108 // Check IsDocumentAlreadyLoaded to be sure.
109 if( IsDocumentAlreadyLoaded )
111 gdcmWarningMacro( "A file was already parsed inside this "
112 << "gdcm::Document (previous name was: "
113 << Filename.c_str() << ". New name is :"
115 // todo : clean out the 'Document'
116 // Should we call ClearEntry() on the parent object ?!?
124 // warning already performed in OpenFile()
125 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
126 // << Filename.c_str() );
131 Group0002Parsed = false;
133 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
135 Fp->seekg(0, std::ios::end);
136 long lgt = Fp->tellg(); // total length of the file
138 Fp->seekg(0, std::ios::beg);
140 // CheckSwap returns a boolean
141 // (false if no swap info of any kind was found)
144 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
145 << Filename.c_str());
150 long beg = Fp->tellg(); // just after DICOM preamble (if any)
152 lgt -= beg; // remaining length to parse
154 ParseDES( this, beg, lgt, false); // Loading is done during parsing
158 gdcmWarningMacro( "No tag in internal hash table for: "
159 << Filename.c_str());
163 IsDocumentAlreadyLoaded = true;
165 Fp->seekg( 0, std::ios::beg);
167 // Load 'non string' values
169 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
170 if( PhotometricInterpretation == "PALETTE COLOR " )
172 LoadEntryBinArea(0x0028,0x1200); // gray LUT
173 /// FIXME FIXME FIXME
174 /// The tags refered by the three following lines used to be CORRECTLY
175 /// defined as having an US Value Representation in the public
176 /// dictionary. BUT the semantics implied by the three following
177 /// lines state that the corresponding tag contents are in fact
178 /// the ones of a BinEntry.
179 /// In order to fix things "Quick and Dirty" the dictionary was
180 /// altered on PURPOSE but now contains a WRONG value.
181 /// In order to fix things and restore the dictionary to its
182 /// correct value, one needs to decided of the semantics by deciding
183 /// whether the following tags are either:
184 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
185 /// also used as BinEntry, which requires the proper conversion,
186 /// - OW, and hence loaded as BinEntry, but afterwards also used
187 /// as ValEntry, which requires the proper conversion.
188 LoadEntryBinArea(0x0028,0x1201); // R LUT
189 LoadEntryBinArea(0x0028,0x1202); // G LUT
190 LoadEntryBinArea(0x0028,0x1203); // B LUT
192 // Segmented Red Palette Color LUT Data
193 LoadEntryBinArea(0x0028,0x1221);
194 // Segmented Green Palette Color LUT Data
195 LoadEntryBinArea(0x0028,0x1222);
196 // Segmented Blue Palette Color LUT Data
197 LoadEntryBinArea(0x0028,0x1223);
199 //FIXME later : how to use it?
200 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
204 // ----------------------------
205 // Specific code to allow gdcm to read ACR-LibIDO formated images
206 // Note: ACR-LibIDO is an extension of the ACR standard that was
207 // used at CREATIS. For the time being (say a couple years)
208 // we keep this kludge to allow CREATIS users
209 // reading their old images.
211 // if recognition code tells us we deal with a LibIDO image
212 // we switch lineNumber and columnNumber
215 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
216 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
217 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
218 // with "little-endian strings"
220 Filetype = ACR_LIBIDO;
221 std::string rows = GetEntryValue(0x0028, 0x0010);
222 std::string columns = GetEntryValue(0x0028, 0x0011);
223 SetValEntry(columns, 0x0028, 0x0010);
224 SetValEntry(rows , 0x0028, 0x0011);
226 // --- End of ACR-LibIDO kludge ---
232 * \brief Get the public dictionary used
234 Dict *Document::GetPubDict()
240 * \brief Get the shadow dictionary used
242 Dict *Document::GetShaDict()
248 * \brief Set the shadow dictionary used
249 * @param dict dictionary to use in shadow
251 bool Document::SetShaDict(Dict *dict)
258 * \brief Set the shadow dictionary used
259 * @param dictName name of the dictionary to use in shadow
261 bool Document::SetShaDict(DictKey const &dictName)
263 RefShaDict = Global::GetDicts()->GetDict(dictName);
268 * \brief This predicate tells us whether or not the current Document
269 * was properly parsed and contains at least *one* Dicom Element
270 * (and nothing more, sorry).
271 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
274 bool Document::IsReadable()
276 if( Filetype == Unknown)
278 gdcmWarningMacro( "Wrong filetype");
284 gdcmWarningMacro( "No tag in internal hash table.");
292 * \brief Predicate for dicom version 3 file.
293 * @return True when the file is a dicom version 3.
295 bool Document::IsDicomV3()
297 // Checking if Transfer Syntax exists is enough
298 // Anyway, it's too late check if the 'Preamble' was found ...
299 // And ... would it be a rich idea to check ?
300 // (some 'no Preamble' DICOM images exist !)
301 return GetDocEntry(0x0002, 0x0010) != NULL;
305 * \brief Predicate for Papyrus file
306 * Dedicated to whomsoever it may concern
307 * @return True when the file is a Papyrus file.
309 bool Document::IsPapyrus()
311 // check for Papyrus private Sequence
312 DocEntry *e = GetDocEntry(0x0041, 0x1050);
315 // check if it's actually a Sequence
316 if ( !dynamic_cast<SeqEntry*>(e) )
322 * \brief returns the File Type
323 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
324 * @return the FileType code
326 FileType Document::GetFileType()
332 * \brief Accessor to the Transfer Syntax (when present) of the
333 * current document (it internally handles reading the
334 * value from disk when only parsing occured).
335 * @return The encountered Transfer Syntax of the current document.
337 std::string Document::GetTransferSyntax()
339 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
345 // The entry might be present but not loaded (parsing and loading
346 // happen at different stages): try loading and proceed with check...
347 LoadDocEntrySafe(entry);
348 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
350 std::string transfer = valEntry->GetValue();
351 // The actual transfer (as read from disk) might be padded. We
352 // first need to remove the potential padding. We can make the
353 // weak assumption that padding was not executed with digits...
354 if ( transfer.length() == 0 )
356 // for brain damaged headers
359 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
361 transfer.erase(transfer.length()-1, 1);
369 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
370 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
372 std::string Document::GetTransferSyntaxName()
374 // use the TS (TS : Transfer Syntax)
375 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
377 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
379 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
380 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
381 return "Uncompressed ACR-NEMA";
383 if ( transferSyntax == GDCM_UNFOUND )
385 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
386 return "Uncompressed ACR-NEMA";
389 // we do it only when we need it
390 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
392 // Global::GetTS() is a global static you shall never try to delete it!
396 // --------------- Swap Code ------------------
398 * \brief Swaps the bytes so they agree with the processor order
399 * @return The properly swaped 16 bits integer.
401 uint16_t Document::SwapShort(uint16_t a)
403 if ( SwapCode == 4321 || SwapCode == 2143 )
405 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
407 a = ( a << 8 ) | ( a >> 8 );
413 * \brief Swaps back the bytes of 4-byte long integer accordingly to
415 * @return The properly swaped 32 bits integer.
417 uint32_t Document::SwapLong(uint32_t a)
424 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
425 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
427 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
428 ((a>>8) & 0x0000ff00) | (a>>24) );
431 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
432 a=( (a<<16) | (a>>16) );
435 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
438 gdcmErrorMacro( "Unset swap code:" << SwapCode );
445 // -----------------File I/O ---------------
447 * \brief Tries to open the file \ref Document::Filename and
448 * checks the preamble when existing.
449 * @return The FILE pointer on success.
451 std::ifstream *Document::OpenFile()
453 HasDCMPreamble = false;
454 if (Filename.length() == 0)
461 gdcmWarningMacro( "File already open: " << Filename.c_str());
465 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
468 // Don't user gdcmErrorMacro :
469 // a spurious message will appear when you use, for instance
470 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
471 // to create outputFileName.
472 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
476 //exit(1); // No function is allowed to leave the application instead
477 // of warning the caller
481 Fp->read((char*)&zero, (size_t)2);
488 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
490 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
491 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
492 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
493 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
495 std::string msg = Util::Format(
496 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
497 gdcmWarningMacro( msg.c_str() );
502 Fp->seekg(126L, std::ios::cur);
503 char dicm[4] = {' ',' ',' ',' '};
504 Fp->read(dicm, (size_t)4);
510 if( memcmp(dicm, "DICM", 4) == 0 )
512 HasDCMPreamble = true;
516 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
518 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
519 << Filename.c_str());
524 * \brief closes the file
525 * @return TRUE if the close was successfull
527 bool Document::CloseFile()
539 * \brief Writes in a file all the Header Entries (Dicom Elements)
540 * @param fp file pointer on an already open file (actually: Output File Stream)
541 * @param filetype Type of the File to be written
542 * (ACR-NEMA, ExplicitVR, ImplicitVR)
543 * @return Always true.
545 void Document::WriteContent(std::ofstream *fp, FileType filetype)
547 // \TODO move the following lines (and a lot of others, to be written)
548 // to a future function CheckAndCorrectHeader
550 // (necessary if user wants to write a DICOM V3 file
551 // starting from an ACR-NEMA (V2) Header
553 if ( filetype == ImplicitVR || filetype == ExplicitVR )
555 // writing Dicom File Preamble
556 char filePreamble[128];
557 memset(filePreamble, 0, 128);
558 fp->write(filePreamble, 128);
559 fp->write("DICM", 4);
563 * \todo rewrite later, if really usefull
564 * - 'Group Length' element is optional in DICOM
565 * - but un-updated odd groups lengthes can causes pb
568 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
569 * UpdateGroupLength(false,filetype);
570 * if ( filetype == ACR)
571 * UpdateGroupLength(true,ACR);
574 ElementSet::WriteContent(fp, filetype); // This one is recursive
577 // -----------------------------------------
580 * \brief Loads (from disk) the element content
581 * when a string is not suitable
582 * @param group group number of the Entry
583 * @param elem element number of the Entry
585 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
587 // Search the corresponding DocEntry
588 DocEntry *docElement = GetDocEntry(group, elem);
592 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
596 LoadEntryBinArea(binElement);
600 * \brief Loads (from disk) the element content
601 * when a string is not suitable
602 * @param elem Entry whose binArea is going to be loaded
604 void Document::LoadEntryBinArea(BinEntry *elem)
606 if(elem->GetBinArea())
613 size_t o =(size_t)elem->GetOffset();
614 Fp->seekg(o, std::ios::beg);
616 size_t l = elem->GetLength();
617 uint8_t *a = new uint8_t[l];
620 gdcmWarningMacro( "Cannot allocate BinEntry content");
624 Fp->read((char*)a, l);
625 if( Fp->fail() || Fp->eof())
638 * \brief Loads the element while preserving the current
639 * underlying file position indicator as opposed to
640 * LoadDocEntry that modifies it.
641 * @param entry DocEntry whose value will be loaded.
643 void Document::LoadDocEntrySafe(DocEntry *entry)
647 long PositionOnEntry = Fp->tellg();
649 Fp->seekg(PositionOnEntry, std::ios::beg);
654 * \brief Compares two documents, according to \ref DicomDir rules
655 * \warning Does NOT work with ACR-NEMA files
656 * \todo Find a trick to solve the pb (use RET fields ?)
657 * @param document to compare with current one
658 * @return true if 'smaller'
660 bool Document::operator<(Document &document)
663 std::string s1 = GetEntryValue(0x0010,0x0010);
664 std::string s2 = document.GetEntryValue(0x0010,0x0010);
676 s1 = GetEntryValue(0x0010,0x0020);
677 s2 = document.GetEntryValue(0x0010,0x0020);
688 // Study Instance UID
689 s1 = GetEntryValue(0x0020,0x000d);
690 s2 = document.GetEntryValue(0x0020,0x000d);
701 // Serie Instance UID
702 s1 = GetEntryValue(0x0020,0x000e);
703 s2 = document.GetEntryValue(0x0020,0x000e);
718 //-----------------------------------------------------------------------------
721 * \brief Reads a supposed to be 16 Bits integer
722 * (swaps it depending on processor endianness)
725 uint16_t Document::ReadInt16()
729 Fp->read ((char*)&g, (size_t)2);
732 throw FormatError( "Document::ReadInt16()", " file error." );
736 throw FormatError( "Document::ReadInt16()", "EOF." );
743 * \brief Reads a supposed to be 32 Bits integer
744 * (swaps it depending on processor endianness)
747 uint32_t Document::ReadInt32()
751 Fp->read ((char*)&g, (size_t)4);
754 throw FormatError( "Document::ReadInt32()", " file error." );
758 throw FormatError( "Document::ReadInt32()", "EOF." );
765 * \brief skips bytes inside the source file
766 * \warning NOT end user intended method !
769 void Document::SkipBytes(uint32_t nBytes)
771 //FIXME don't dump the returned value
772 Fp->seekg((long)nBytes, std::ios::cur);
776 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
777 * @param filetype Type of the File to be written
779 int Document::ComputeGroup0002Length( FileType filetype )
785 bool found0002 = false;
787 // for each zero-level Tag in the DCM Header
788 DocEntry *entry = GetFirstEntry();
791 gr = entry->GetGroup();
797 if( entry->GetElement() != 0x0000 )
801 if( filetype == ExplicitVR )
803 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
805 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
809 groupLength += 2 + 2 + 4 + entry->GetLength();
815 entry = GetNextEntry();
820 //-----------------------------------------------------------------------------
823 * \brief Loads all the needed Dictionaries
824 * \warning NOT end user intended method !
826 void Document::Initialize()
828 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
834 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
835 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
836 * @param offset start of parsing
837 * @param l_max length to parse
838 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
840 void Document::ParseDES(DocEntrySet *set, long offset,
841 long l_max, bool delim_mode)
843 DocEntry *newDocEntry;
844 ValEntry *newValEntry;
845 BinEntry *newBinEntry;
846 SeqEntry *newSeqEntry;
852 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
858 newDocEntry = ReadNextDocEntry( );
865 vr = newDocEntry->GetVR();
866 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
867 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
868 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
870 if ( newValEntry || newBinEntry )
874 if ( Filetype == ExplicitVR &&
875 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
877 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
878 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
879 << "|" << newDocEntry->GetElement()
880 << " : Neither Valentry, nor BinEntry."
881 "Probably unknown VR.");
884 //////////////////// BinEntry or UNKOWN VR:
885 // When "this" is a Document the Key is simply of the
886 // form ( group, elem )...
887 if ( dynamic_cast< Document* > ( set ) )
889 newBinEntry->SetKey( newBinEntry->GetKey() );
891 // but when "this" is a SQItem, we are inserting this new
892 // valEntry in a sequence item, and the key has the
893 // generalized form (refer to \ref BaseTagKey):
894 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
896 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
897 + newBinEntry->GetKey() );
900 LoadDocEntry( newBinEntry );
901 if( !set->AddEntry( newBinEntry ) )
903 //Expect big troubles if here
904 //delete newBinEntry;
910 /////////////////////// ValEntry
912 // When "set" is a Document, then we are at the top of the
913 // hierarchy and the Key is simply of the form ( group, elem )...
914 if ( dynamic_cast< Document* > ( set ) )
916 newValEntry->SetKey( newValEntry->GetKey() );
918 // ...but when "set" is a SQItem, we are inserting this new
919 // valEntry in a sequence item. Hence the key has the
920 // generalized form (refer to \ref BaseTagKey):
921 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
923 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
924 + newValEntry->GetKey() );
927 LoadDocEntry( newValEntry );
928 bool delimitor=newValEntry->IsItemDelimitor();
930 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
931 // shadow groups ( if possible :
932 // whether element 0x0000 exits)
934 if ( newValEntry->GetGroup()%2 != 0 )
936 if ( newValEntry->GetElement() == 0x0000 )
938 std::string strLgrGroup = newValEntry->GetValue();
940 if ( strLgrGroup != GDCM_UNFOUND)
942 lgrGroup = atoi(strLgrGroup.c_str());
943 Fp->seekg(lgrGroup, std::ios::cur);
951 if( !set->AddEntry( newValEntry ) )
953 // If here expect big troubles
954 // delete newValEntry; //otherwise mem leak
964 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
972 // Just to make sure we are at the beginning of next entry.
973 SkipToNextDocEntry(newDocEntry);
978 unsigned long l = newDocEntry->GetReadLength();
979 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
981 if ( l == 0xffffffff )
991 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
993 Fp->seekg( l, std::ios::cur);
998 // no other way to create it ...
999 newSeqEntry->SetDelimitorMode( delim_mode );
1001 // At the top of the hierarchy, stands a Document. When "set"
1002 // is a Document, then we are building the first depth level.
1003 // Hence the SeqEntry we are building simply has a depth
1005 if ( dynamic_cast< Document* > ( set ) )
1007 newSeqEntry->SetDepthLevel( 1 );
1008 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1010 // But when "set" is already a SQItem, we are building a nested
1011 // sequence, and hence the depth level of the new SeqEntry
1012 // we are building, is one level deeper:
1013 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1015 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1016 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1017 + newSeqEntry->GetKey() );
1021 { // Don't try to parse zero-length sequences
1022 ParseSQ( newSeqEntry,
1023 newDocEntry->GetOffset(),
1026 if( !set->AddEntry( newSeqEntry ) )
1031 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1045 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1046 * @return parsed length for this level
1048 void Document::ParseSQ( SeqEntry *seqEntry,
1049 long offset, long l_max, bool delim_mode)
1051 int SQItemNumber = 0;
1053 long offsetStartCurrentSQItem = offset;
1057 // the first time, we read the fff0,e000 of the first SQItem
1058 DocEntry *newDocEntry = ReadNextDocEntry();
1062 // FIXME Should warn user
1067 if ( newDocEntry->IsSequenceDelimitor() )
1069 seqEntry->SetDelimitationItem( newDocEntry );
1073 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1078 // create the current SQItem
1079 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1080 std::ostringstream newBase;
1081 newBase << seqEntry->GetKey()
1085 itemSQ->SetBaseTagKey( newBase.str() );
1086 unsigned int l = newDocEntry->GetReadLength();
1088 if ( l == 0xffffffff )
1097 // Let's try :------------
1098 // remove fff0,e000, created out of the SQItem
1100 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1101 // fill up the current SQItem, starting at the beginning of fff0,e000
1102 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1103 offsetStartCurrentSQItem = Fp->tellg();
1104 // end try -----------------
1106 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1108 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1116 * \brief Loads the element content if its length doesn't exceed
1117 * the value specified with Document::SetMaxSizeLoadEntry()
1118 * @param entry Header Entry (Dicom Element) to be dealt with
1120 void Document::LoadDocEntry(DocEntry *entry)
1122 uint16_t group = entry->GetGroup();
1123 std::string vr = entry->GetVR();
1124 uint32_t length = entry->GetLength();
1126 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1128 // A SeQuence "contains" a set of Elements.
1129 // (fffe e000) tells us an Element is beginning
1130 // (fffe e00d) tells us an Element just ended
1131 // (fffe e0dd) tells us the current SeQuence just ended
1132 if( group == 0xfffe )
1134 // NO more value field for SQ !
1138 // When the length is zero things are easy:
1141 ((ValEntry *)entry)->SetValue("");
1145 // The elements whose length is bigger than the specified upper bound
1146 // are not loaded. Instead we leave a short notice of the offset of
1147 // the element content and it's length.
1149 std::ostringstream s;
1150 if (length > MaxSizeLoadEntry)
1152 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1154 s << GDCM_NOTLOADED;
1155 s << " Ad.:" << (long)entry->GetOffset();
1156 s << " x(" << std::hex << entry->GetOffset() << ")";
1158 s << " Lgt:" << entry->GetLength();
1159 s << " x(" << std::hex << entry->GetLength() << ")";
1160 binEntryPtr->SetValue(s.str());
1162 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1164 s << GDCM_NOTLOADED;
1165 s << " Address:" << (long)entry->GetOffset();
1166 s << " Length:" << entry->GetLength();
1167 s << " x(" << std::hex << entry->GetLength() << ")";
1168 valEntryPtr->SetValue(s.str());
1173 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1174 << "nor a ValEntry ?! Should never print that !" );
1177 // to be sure we are at the end of the value ...
1178 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1183 // When we find a BinEntry not very much can be done :
1184 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1186 s << GDCM_BINLOADED;
1187 binEntryPtr->SetValue(s.str());
1188 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1192 if ( IsDocEntryAnInteger(entry) )
1196 // When short integer(s) are expected, read and convert the following
1197 // (n * 2) characters properly i.e. consider them as short integers as
1198 // opposed to strings.
1199 // Elements with Value Multiplicity > 1
1200 // contain a set of integers (not a single one)
1201 if (vr == "US" || vr == "SS")
1204 NewInt = ReadInt16();
1208 for (int i=1; i < nbInt; i++)
1211 NewInt = ReadInt16();
1216 // See above comment on multiple integers (mutatis mutandis).
1217 else if (vr == "UL" || vr == "SL")
1220 NewInt = ReadInt32();
1224 for (int i=1; i < nbInt; i++)
1227 NewInt = ReadInt32();
1232 #ifdef GDCM_NO_ANSI_STRING_STREAM
1233 s << std::ends; // to avoid oddities on Solaris
1234 #endif //GDCM_NO_ANSI_STRING_STREAM
1236 ((ValEntry *)entry)->SetValue(s.str());
1240 // FIXME: We need an additional byte for storing \0 that is not on disk
1241 char *str = new char[length+1];
1242 Fp->read(str, (size_t)length);
1243 str[length] = '\0'; //this is only useful when length is odd
1244 // Special DicomString call to properly handle \0 and even length
1245 std::string newValue;
1248 newValue = Util::DicomString(str, length+1);
1249 gdcmWarningMacro("Warning: bad length: " << length <<
1250 " For string :" << newValue.c_str());
1251 // Since we change the length of string update it length
1252 //entry->SetReadLength(length+1);
1256 newValue = Util::DicomString(str, length);
1260 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1262 if ( Fp->fail() || Fp->eof())
1265 gdcmWarningMacro("--> fail");
1267 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1268 << " lgt : " << valEntry->GetReadLength()
1269 << " at " << std::hex << valEntry->GetOffset());
1270 valEntry->SetValue(GDCM_UNREAD);
1276 // Because of correspondance with the VR dic
1277 valEntry->SetValue(newValue);
1281 valEntry->SetValue(newValue);
1286 gdcmErrorMacro( "Should have a ValEntry, here !");
1291 * \brief Find the value Length of the passed Header Entry
1292 * @param entry Header Entry whose length of the value shall be loaded.
1294 void Document::FindDocEntryLength( DocEntry *entry )
1295 throw ( FormatError )
1297 std::string vr = entry->GetVR();
1300 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1302 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1304 // The following reserved two bytes (see PS 3.5-2003, section
1305 // "7.1.2 Data element structure with explicit vr", p 27) must be
1306 // skipped before proceeding on reading the length on 4 bytes.
1307 Fp->seekg( 2L, std::ios::cur);
1308 uint32_t length32 = ReadInt32();
1310 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1315 lengthOB = FindDocEntryLengthOBOrOW();
1317 catch ( FormatUnexpected )
1319 // Computing the length failed (this happens with broken
1320 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1321 // chance to get the pixels by deciding the element goes
1322 // until the end of the file. Hence we artificially fix the
1323 // the length and proceed.
1324 long currentPosition = Fp->tellg();
1325 Fp->seekg(0L,std::ios::end);
1327 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1328 Fp->seekg(currentPosition, std::ios::beg);
1330 entry->SetReadLength(lengthUntilEOF);
1331 entry->SetLength(lengthUntilEOF);
1334 entry->SetReadLength(lengthOB);
1335 entry->SetLength(lengthOB);
1338 FixDocEntryFoundLength(entry, length32);
1342 // Length is encoded on 2 bytes.
1343 length16 = ReadInt16();
1345 // 0xffff means that we deal with 'No Length' Sequence
1346 // or 'No Length' SQItem
1347 if ( length16 == 0xffff)
1351 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1356 // Either implicit VR or a non DICOM conformal (see note below) explicit
1357 // VR that ommited the VR of (at least) this element. Farts happen.
1358 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1359 // on Data elements "Implicit and Explicit VR Data Elements shall
1360 // not coexist in a Data Set and Data Sets nested within it".]
1361 // Length is on 4 bytes.
1363 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1364 // even if Transfer Syntax is 'Implicit VR ...'
1366 FixDocEntryFoundLength( entry, ReadInt32() );
1372 * \brief Find the Length till the next sequence delimiter
1373 * \warning NOT end user intended method !
1376 uint32_t Document::FindDocEntryLengthOBOrOW()
1377 throw( FormatUnexpected )
1379 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1380 long positionOnEntry = Fp->tellg();
1381 bool foundSequenceDelimiter = false;
1382 uint32_t totalLength = 0;
1384 while ( !foundSequenceDelimiter )
1390 group = ReadInt16();
1393 catch ( FormatError )
1395 throw FormatError("Unexpected end of file encountered during ",
1396 "Document::FindDocEntryLengthOBOrOW()");
1398 // We have to decount the group and element we just read
1400 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1402 long filePosition = Fp->tellg();
1404 "Neither an Item tag nor a Sequence delimiter tag on :"
1405 << std::hex << group << " , " << elem
1406 << ") -before- position x(" << filePosition << ")" );
1408 Fp->seekg(positionOnEntry, std::ios::beg);
1409 throw FormatUnexpected(
1410 "Neither an Item tag nor a Sequence delimiter tag.");
1412 if ( elem == 0xe0dd )
1414 foundSequenceDelimiter = true;
1416 uint32_t itemLength = ReadInt32();
1417 // We add 4 bytes since we just read the ItemLength with ReadInt32
1418 totalLength += itemLength + 4;
1419 SkipBytes(itemLength);
1421 if ( foundSequenceDelimiter )
1426 Fp->seekg( positionOnEntry, std::ios::beg);
1431 * \brief Find the Value Representation of the current Dicom Element.
1432 * @return Value Representation of the current Entry
1434 std::string Document::FindDocEntryVR()
1436 if ( Filetype != ExplicitVR )
1437 return GDCM_UNKNOWN;
1439 long positionOnEntry = Fp->tellg();
1440 // Warning: we believe this is explicit VR (Value Representation) because
1441 // we used a heuristic that found "UL" in the first tag. Alas this
1442 // doesn't guarantee that all the tags will be in explicit VR. In some
1443 // cases (see e-film filtered files) one finds implicit VR tags mixed
1444 // within an explicit VR file. Hence we make sure the present tag
1445 // is in explicit VR and try to fix things if it happens not to be
1449 Fp->read (vr, (size_t)2);
1452 if( !CheckDocEntryVR(vr) )
1454 Fp->seekg(positionOnEntry, std::ios::beg);
1455 return GDCM_UNKNOWN;
1461 * \brief Check the correspondance between the VR of the header entry
1462 * and the taken VR. If they are different, the header entry is
1463 * updated with the new VR.
1464 * @param vr Dicom Value Representation
1465 * @return false if the VR is incorrect of if the VR isn't referenced
1466 * otherwise, it returns true
1468 bool Document::CheckDocEntryVR(VRKey vr)
1470 if ( !Global::GetVR()->IsValidVR(vr) )
1477 * \brief Get the transformed value of the header entry. The VR value
1478 * is used to define the transformation to operate on the value
1479 * \warning NOT end user intended method !
1480 * @param entry entry to tranform
1481 * @return Transformed entry value
1483 std::string Document::GetDocEntryValue(DocEntry *entry)
1485 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1487 std::string val = ((ValEntry *)entry)->GetValue();
1488 std::string vr = entry->GetVR();
1489 uint32_t length = entry->GetLength();
1490 std::ostringstream s;
1493 // When short integer(s) are expected, read and convert the following
1494 // n * 2 bytes properly i.e. as a multivaluated strings
1495 // (each single value is separated fromthe next one by '\'
1496 // as usual for standard multivaluated filels
1497 // Elements with Value Multiplicity > 1
1498 // contain a set of short integers (not a single one)
1500 if( vr == "US" || vr == "SS" )
1505 for (int i=0; i < nbInt; i++)
1511 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1512 newInt16 = SwapShort( newInt16 );
1517 // When integer(s) are expected, read and convert the following
1518 // n * 4 bytes properly i.e. as a multivaluated strings
1519 // (each single value is separated fromthe next one by '\'
1520 // as usual for standard multivaluated filels
1521 // Elements with Value Multiplicity > 1
1522 // contain a set of integers (not a single one)
1523 else if( vr == "UL" || vr == "SL" )
1528 for (int i=0; i < nbInt; i++)
1534 newInt32 = ( val[4*i+0] & 0xFF )
1535 + (( val[4*i+1] & 0xFF ) << 8 )
1536 + (( val[4*i+2] & 0xFF ) << 16 )
1537 + (( val[4*i+3] & 0xFF ) << 24 );
1538 newInt32 = SwapLong( newInt32 );
1542 #ifdef GDCM_NO_ANSI_STRING_STREAM
1543 s << std::ends; // to avoid oddities on Solaris
1544 #endif //GDCM_NO_ANSI_STRING_STREAM
1547 return ((ValEntry *)entry)->GetValue();
1551 * \brief Get the reverse transformed value of the header entry. The VR
1552 * value is used to define the reverse transformation to operate on
1554 * \warning NOT end user intended method !
1555 * @param entry Entry to reverse transform
1556 * @return Reverse transformed entry value
1558 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1560 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1562 std::string vr = entry->GetVR();
1563 std::vector<std::string> tokens;
1564 std::ostringstream s;
1566 if ( vr == "US" || vr == "SS" )
1570 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1571 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1572 for (unsigned int i=0; i<tokens.size(); i++)
1574 newInt16 = atoi(tokens[i].c_str());
1575 s << ( newInt16 & 0xFF )
1576 << (( newInt16 >> 8 ) & 0xFF );
1580 if ( vr == "UL" || vr == "SL")
1584 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1585 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1586 for (unsigned int i=0; i<tokens.size();i++)
1588 newInt32 = atoi(tokens[i].c_str());
1589 s << (char)( newInt32 & 0xFF )
1590 << (char)(( newInt32 >> 8 ) & 0xFF )
1591 << (char)(( newInt32 >> 16 ) & 0xFF )
1592 << (char)(( newInt32 >> 24 ) & 0xFF );
1597 #ifdef GDCM_NO_ANSI_STRING_STREAM
1598 s << std::ends; // to avoid oddities on Solaris
1599 #endif //GDCM_NO_ANSI_STRING_STREAM
1603 return ((ValEntry *)entry)->GetValue();
1607 * \brief Skip a given Header Entry
1608 * \warning NOT end user intended method !
1609 * @param entry entry to skip
1611 void Document::SkipDocEntry(DocEntry *entry)
1613 SkipBytes(entry->GetLength());
1617 * \brief Skips to the beginning of the next Header Entry
1618 * \warning NOT end user intended method !
1619 * @param currentDocEntry entry to skip
1621 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1623 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1624 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1625 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1629 * \brief When the length of an element value is obviously wrong (because
1630 * the parser went Jabberwocky) one can hope improving things by
1631 * applying some heuristics.
1632 * @param entry entry to check
1633 * @param foundLength first assumption about length
1635 void Document::FixDocEntryFoundLength(DocEntry *entry,
1636 uint32_t foundLength)
1638 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1639 if ( foundLength == 0xffffffff)
1644 uint16_t gr = entry->GetGroup();
1645 uint16_t elem = entry->GetElement();
1647 if ( foundLength % 2)
1649 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1650 << " in x(" << std::hex << gr << "," << elem <<")");
1653 //////// Fix for some naughty General Electric images.
1654 // Allthough not recent many such GE corrupted images are still present
1655 // on Creatis hard disks. Hence this fix shall remain when such images
1656 // are no longer in use (we are talking a few years, here)...
1657 // Note: XMedCon probably uses such a trick since it is able to read
1658 // those pesky GE images ...
1659 if ( foundLength == 13)
1661 // Only happens for this length !
1662 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1665 entry->SetReadLength(10); // a bug is to be fixed !?
1669 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1670 // Occurence of such images is quite low (unless one leaves close to a
1671 // 'Leonardo' source. Hence, one might consider commenting out the
1672 // following fix on efficiency reasons.
1673 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1676 entry->SetReadLength(4); // a bug is to be fixed !?
1679 else if ( entry->GetVR() == "SQ" )
1681 foundLength = 0; // ReadLength is unchanged
1684 //////// We encountered a 'delimiter' element i.e. a tag of the form
1685 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1686 // taken into account.
1687 else if( gr == 0xfffe )
1689 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1690 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1691 // causes extra troubles...
1692 if( entry->GetElement() != 0x0000 )
1697 entry->SetLength(foundLength);
1701 * \brief Apply some heuristics to predict whether the considered
1702 * element value contains/represents an integer or not.
1703 * @param entry The element value on which to apply the predicate.
1704 * @return The result of the heuristical predicate.
1706 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1708 uint16_t elem = entry->GetElement();
1709 uint16_t group = entry->GetGroup();
1710 const std::string &vr = entry->GetVR();
1711 uint32_t length = entry->GetLength();
1713 // When we have some semantics on the element we just read, and if we
1714 // a priori know we are dealing with an integer, then we shall be
1715 // able to swap it's element value properly.
1716 if ( elem == 0 ) // This is the group length of the group
1724 // Allthough this should never happen, still some images have a
1725 // corrupted group length [e.g. have a glance at offset x(8336) of
1726 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1727 // Since for dicom compliant and well behaved headers, the present
1728 // test is useless (and might even look a bit paranoid), when we
1729 // encounter such an ill-formed image, we simply display a warning
1730 // message and proceed on parsing (while crossing fingers).
1731 long filePosition = Fp->tellg();
1732 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1733 << std::hex << group << " , " << elem
1734 << ") -before- position x(" << filePosition << ")"
1735 << "lgt : " << length );
1739 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1747 * \brief Discover what the swap code is (among little endian, big endian,
1748 * bad little endian, bad big endian).
1750 * @return false when we are absolutely sure
1751 * it's neither ACR-NEMA nor DICOM
1752 * true when we hope ours assuptions are OK
1754 bool Document::CheckSwap()
1756 // The only guaranted way of finding the swap code is to find a
1757 // group tag since we know it's length has to be of four bytes i.e.
1758 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1759 // occurs when we can't find such group...
1766 // First, compare HostByteOrder and NetworkByteOrder in order to
1767 // determine if we shall need to swap bytes (i.e. the Endian type).
1768 bool net2host = Util::IsCurrentProcessorBigEndian();
1770 // The easiest case is the one of a 'true' DICOM header, we just have
1771 // to look for the string "DICM" inside the file preamble.
1774 char *entCur = deb + 128;
1775 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1777 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1779 // Group 0002 should always be VR, and the first element 0000
1780 // Let's be carefull (so many wrong headers ...)
1781 // and determine the value representation (VR) :
1782 // Let's skip to the first element (0002,0000) and check there if we find
1783 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1784 // in which case we (almost) know it is explicit VR.
1785 // WARNING: if it happens to be implicit VR then what we will read
1786 // is the length of the group. If this ascii representation of this
1787 // length happens to be "UL" then we shall believe it is explicit VR.
1788 // We need to skip :
1789 // * the 128 bytes of File Preamble (often padded with zeroes),
1790 // * the 4 bytes of "DICM" string,
1791 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1792 // i.e. a total of 136 bytes.
1795 // group 0x0002 *is always* Explicit VR Sometimes ,
1796 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1797 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1799 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1800 memcmp(entCur, "OB", (size_t)2) == 0 ||
1801 memcmp(entCur, "UI", (size_t)2) == 0 ||
1802 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1803 // when Write DCM *adds*
1805 // Use Document::dicom_vr to test all the possibilities
1806 // instead of just checking for UL, OB and UI !? group 0000
1808 Filetype = ExplicitVR;
1809 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1813 Filetype = ImplicitVR;
1814 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1815 << "Looks like a bugged Header!");
1821 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1826 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1829 // Position the file position indicator at first tag
1830 // (i.e. after the file preamble and the "DICM" string).
1832 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1834 Fp->seekg ( 132L, std::ios::beg);
1836 } // ------------------------------- End of DicomV3 ----------------
1838 // Alas, this is not a DicomV3 file and whatever happens there is no file
1839 // preamble. We can reset the file position indicator to where the data
1840 // is (i.e. the beginning of the file).
1842 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1844 Fp->seekg(0, std::ios::beg);
1846 // Let's check 'No Preamble Dicom File' :
1847 // Should start with group 0x0002
1848 // and be Explicit Value Representation
1850 s16 = *((uint16_t *)(deb));
1863 if ( SwapCode != 0 )
1865 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1866 memcmp(entCur, "OB", (size_t)2) == 0 ||
1867 memcmp(entCur, "UI", (size_t)2) == 0 ||
1868 memcmp(entCur, "SH", (size_t)2) == 0 ||
1869 memcmp(entCur, "AE", (size_t)2) == 0 ||
1870 memcmp(entCur, "OB", (size_t)2) == 0 )
1872 Filetype = ExplicitVR;
1873 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1877 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1879 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1880 // By clean we mean that the length of the first group is written down.
1881 // If this is the case and since the length of the first group HAS to be
1882 // four (bytes), then determining the proper swap code is straightforward.
1885 // We assume the array of char we are considering contains the binary
1886 // representation of a 32 bits integer. Hence the following dirty
1888 s32 = *((uint32_t *)(entCur));
1908 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1909 // It is time for despaired wild guesses.
1910 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1911 // i.e. the 'group length' element is not present :
1913 // check the supposed-to-be 'group number'
1914 // in ( 0x0001 .. 0x0008 )
1915 // to determine ' SwapCode' value .
1916 // Only 0 or 4321 will be possible
1917 // (no oportunity to check for the formerly well known
1918 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1919 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1920 // the file IS NOT ACR-NEMA nor DICOM V3
1921 // Find a trick to tell it the caller...
1923 s16 = *((uint16_t *)(deb));
1950 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1958 * \brief Change the Byte Swap code.
1960 void Document::SwitchByteSwapCode()
1962 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1963 if ( SwapCode == 1234 )
1967 else if ( SwapCode == 4321 )
1971 else if ( SwapCode == 3412 )
1975 else if ( SwapCode == 2143 )
1982 * \brief during parsing, Header Elements too long are not loaded in memory
1983 * @param newSize new size
1985 void Document::SetMaxSizeLoadEntry(long newSize)
1991 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1993 MaxSizeLoadEntry = 0xffffffff;
1996 MaxSizeLoadEntry = newSize;
2000 * \brief Read the next tag but WITHOUT loading it's value
2001 * (read the 'Group Number', the 'Element Number',
2002 * gets the Dict Entry
2003 * gets the VR, gets the length, gets the offset value)
2004 * @return On succes the newly created DocEntry, NULL on failure.
2006 DocEntry *Document::ReadNextDocEntry()
2013 group = ReadInt16();
2016 catch ( FormatError e )
2018 // We reached the EOF (or an error occured) therefore
2019 // header parsing has to be considered as finished.
2023 // Sometimes file contains groups of tags with reversed endianess.
2024 HandleBrokenEndian(group, elem);
2026 // In 'true DICOM' files Group 0002 is always little endian
2027 if ( HasDCMPreamble )
2028 HandleOutOfGroup0002(group, elem);
2030 std::string vr = FindDocEntryVR();
2031 std::string realVR = vr;
2033 if( vr == GDCM_UNKNOWN)
2035 if ( elem == 0x0000 ) // Group Length
2036 realVR = "UL"; // must be UL
2039 DictEntry *dictEntry = GetDictEntry(group,elem);
2041 realVR = dictEntry->GetVR();
2046 if( Global::GetVR()->IsVROfSequence(realVR) )
2047 newEntry = NewSeqEntry(group, elem);
2048 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2049 newEntry = NewValEntry(group, elem,vr);
2051 newEntry = NewBinEntry(group, elem,vr);
2053 if( vr == GDCM_UNKNOWN )
2055 if( Filetype == ExplicitVR )
2057 // We thought this was explicit VR, but we end up with an
2058 // implicit VR tag. Let's backtrack.
2059 if ( newEntry->GetGroup() != 0xfffe )
2062 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2063 newEntry->GetGroup(), newEntry->GetElement());
2064 gdcmWarningMacro( msg.c_str() );
2067 newEntry->SetImplicitVR();
2072 FindDocEntryLength(newEntry);
2074 catch ( FormatError e )
2081 newEntry->SetOffset(Fp->tellg());
2087 * \brief Handle broken private tag from Philips NTSCAN
2088 * where the endianess is being switch to BigEndian for no
2092 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2094 // Endian reversion. Some files contain groups of tags with reversed endianess.
2095 static int reversedEndian = 0;
2096 // try to fix endian switching in the middle of headers
2097 if ((group == 0xfeff) && (elem == 0x00e0))
2099 // start endian swap mark for group found
2101 SwitchByteSwapCode();
2106 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2108 // end of reversed endian group
2110 SwitchByteSwapCode();
2115 * \brief Group 0002 is always coded Little Endian
2116 * whatever Transfer Syntax is
2119 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2121 // Endian reversion. Some files contain groups of tags with reversed endianess.
2122 if ( !Group0002Parsed && group != 0x0002)
2124 Group0002Parsed = true;
2125 // we just came out of group 0002
2126 // if Transfer syntax is Big Endian we have to change CheckSwap
2128 std::string ts = GetTransferSyntax();
2129 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2131 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2135 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2137 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2139 Filetype = ImplicitVR;
2142 // FIXME Strangely, this works with
2143 //'Implicit VR Transfer Syntax (GE Private)
2144 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2146 gdcmWarningMacro("Transfer Syntax Name = ["
2147 << GetTransferSyntaxName() << "]" );
2148 SwitchByteSwapCode();
2149 group = SwapShort(group);
2150 elem = SwapShort(elem);
2155 //-----------------------------------------------------------------------------
2158 //-----------------------------------------------------------------------------
2159 } // end namespace gdcm