1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/10/27 18:12:40 $
7 Version: $Revision: 1.318 $
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 "gdcmSeqEntry.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmDebug.h"
25 #include "gdcmDictSet.h"
26 #include "gdcmDocEntrySet.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
33 #include <ctype.h> // for isdigit
34 #include <stdlib.h> // for atoi
38 //-----------------------------------------------------------------------------
40 // Refer to Document::SetMaxSizeLoadEntry()
41 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
43 //-----------------------------------------------------------------------------
44 // Constructor / Destructor
45 // Constructors and destructors are protected to avoid user to invoke directly
48 * \brief This default constructor neither loads nor parses the file.
49 * You should then invoke \ref Document::Load.
57 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
60 Filetype = ExplicitVR;
61 // Load will set it to true if sucessfull
62 Group0002Parsed = false;
63 IsDocumentAlreadyLoaded = false;
64 IsDocumentModified = true;
65 LoadMode = LD_ALL; // default : load everything, later
70 * \brief Canonical destructor.
72 Document::~Document ()
77 //-----------------------------------------------------------------------------
81 * \brief Loader. use SetLoadMode(), SetFileName() before !
82 * @return false if file cannot be open or no swap info was found,
83 * or no tag was found.
85 bool Document::Load( )
87 if ( GetFileName() == "" )
89 gdcmWarningMacro( "Use SetFileName, before !" );
92 return DoTheLoadingDocumentJob( );
95 * \brief Loader. (DEPRECATED : not to break the API)
96 * @param fileName 'Document' (File or DicomDir) to be open for parsing
97 * @return false if file cannot be open or no swap info was found,
98 * or no tag was found.
100 bool Document::Load( std::string const &fileName )
103 return DoTheLoadingDocumentJob( );
107 * \brief Performs the Loading Job (internal use only)
108 * @return false if file cannot be open or no swap info was found,
109 * or no tag was found.
111 bool Document::DoTheLoadingDocumentJob( )
113 if ( ! IsDocumentModified ) // Nothing to do !
121 // warning already performed in OpenFile()
126 Group0002Parsed = false;
128 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
130 Fp->seekg(0, std::ios::end);
131 long lgt = Fp->tellg(); // total length of the file
133 Fp->seekg(0, std::ios::beg);
135 // CheckSwap returns a boolean
136 // (false if no swap info of any kind was found)
139 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
140 << Filename.c_str());
145 long beg = Fp->tellg(); // just after DICOM preamble (if any)
147 lgt -= beg; // remaining length to parse
150 // Loading is done during parsing
151 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
155 gdcmErrorMacro( "No tag in internal hash table for: "
156 << Filename.c_str());
160 IsDocumentAlreadyLoaded = true;
162 Fp->seekg( 0, std::ios::beg);
164 // Load 'non string' values
166 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
167 if ( PhotometricInterpretation == "PALETTE COLOR " )
170 // Probabely this line should be outside the 'if'
171 // Try to find an image sample holding a 'gray LUT'
172 LoadEntryBinArea(0x0028,0x1200); // gray LUT
175 /// --> FIXME : The difference between BinEntry and DataEntry
176 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
177 /// --> Old comment restored on purpose.
178 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
179 /// --> had absolutely no meaning.
180 /// --> The whole comment will be removed when the stuff is cleaned !
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.
197 // --> OB (byte aray) or OW (short int aray)
198 // The actual VR has to be deduced from other entries.
199 // Our way of loading them may fail in some cases :
200 // We must or not SwapByte depending on other field values.
202 LoadEntryBinArea(0x0028,0x1201); // R LUT
203 LoadEntryBinArea(0x0028,0x1202); // G LUT
204 LoadEntryBinArea(0x0028,0x1203); // B LUT
206 // Segmented Red Palette Color LUT Data
207 LoadEntryBinArea(0x0028,0x1221);
208 // Segmented Green Palette Color LUT Data
209 LoadEntryBinArea(0x0028,0x1222);
210 // Segmented Blue Palette Color LUT Data
211 LoadEntryBinArea(0x0028,0x1223);
214 //FIXME later : how to use it?
215 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
218 SQItem *sqi= modLutSeq->GetFirstSQItem();
221 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
222 if ( dataEntry != 0 )
224 if ( dataEntry->GetLength() != 0 )
226 // FIXME : CTX dependent means : contexted dependant.
227 // see upper comment.
228 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
234 // Force Loading some more elements if user asked to.
237 for (ListElements::iterator it = UserForceLoadList.begin();
238 it != UserForceLoadList.end();
241 gdcmDebugMacro( "Force Load " << std::hex
242 << (*it).Group << "|" <<(*it).Elem );
244 d = GetDocEntry( (*it).Group, (*it).Elem);
248 gdcmWarningMacro( "You asked toForce Load " << std::hex
249 << (*it).Group <<"|"<< (*it).Elem
250 << " that doesn't exist" );
254 LoadDocEntry(d, true);
259 // ----------------------------
260 // Specific code to allow gdcm to read ACR-LibIDO formated images
261 // Note: ACR-LibIDO is an extension of the ACR standard that was
262 // used at CREATIS. For the time being (say a couple of years)
263 // we keep this kludge to allow CREATIS users
264 // reading their old images.
266 // if recognition code tells us we deal with a LibIDO image
267 // we switch lineNumber and columnNumber
270 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
271 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
272 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
273 // with "little-endian strings"
275 Filetype = ACR_LIBIDO;
276 std::string rows = GetEntryString(0x0028, 0x0010);
277 std::string columns = GetEntryString(0x0028, 0x0011);
278 SetEntryString(columns, 0x0028, 0x0010);
279 SetEntryString(rows , 0x0028, 0x0011);
281 // --- End of ACR-LibIDO kludge ---
287 * \brief Adds a new element we want to load anyway
288 * @param group Group number of the target tag.
289 * @param elem Element number of the target tag.
291 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
296 UserForceLoadList.push_back(el);
299 * \brief Get the public dictionary used
301 Dict *Document::GetPubDict()
307 * \brief Get the shadow dictionary used
309 Dict *Document::GetShaDict()
315 * \brief Set the shadow dictionary used
316 * @param dict dictionary to use in shadow
318 bool Document::SetShaDict(Dict *dict)
325 * \brief Set the shadow dictionary used
326 * @param dictName name of the dictionary to use in shadow
328 bool Document::SetShaDict(DictKey const &dictName)
330 RefShaDict = Global::GetDicts()->GetDict(dictName);
335 * \brief This predicate tells us whether or not the current Document
336 * was properly parsed and contains at least *one* Dicom Element
337 * (and nothing more, sorry).
338 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
341 bool Document::IsReadable()
343 if ( Filetype == Unknown )
345 gdcmErrorMacro( "Wrong filetype");
351 gdcmErrorMacro( "No tag in internal hash table.");
359 * \brief Predicate for dicom version 3 file.
360 * @return True when the file is a dicom version 3.
362 bool Document::IsDicomV3()
364 // Checking if Transfer Syntax exists is enough
365 // Anyway, it's too late check if the 'Preamble' was found ...
366 // And ... would it be a rich idea to check ?
367 // (some 'no Preamble' DICOM images exist !)
368 return GetDocEntry(0x0002, 0x0010) != NULL;
372 * \brief Predicate for Papyrus file
373 * Dedicated to whomsoever it may concern
374 * @return True when the file is a Papyrus file.
376 bool Document::IsPapyrus()
378 // check for Papyrus private Sequence
379 DocEntry *e = GetDocEntry(0x0041, 0x1050);
382 // check if it's actually a Sequence
383 if ( !dynamic_cast<SeqEntry*>(e) )
389 * \brief returns the File Type
390 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
391 * @return the FileType code
393 FileType Document::GetFileType()
399 * \brief Accessor to the Transfer Syntax (when present) of the
400 * current document (it internally handles reading the
401 * value from disk when only parsing occured).
402 * @return The encountered Transfer Syntax of the current document, if DICOM.
403 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
405 std::string Document::GetTransferSyntax()
407 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
413 // The entry might be present but not loaded (parsing and loading
414 // happen at different stages): try loading and proceed with check...
415 LoadDocEntrySafe(entry);
416 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
418 std::string transfer = dataEntry->GetString();
419 // The actual transfer (as read from disk) might be padded. We
420 // first need to remove the potential padding. We can make the
421 // weak assumption that padding was not executed with digits...
422 if ( transfer.length() == 0 )
424 // for brain damaged headers
425 gdcmWarningMacro( "Transfer Syntax has length = 0.");
428 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
430 transfer.erase(transfer.length()-1, 1);
431 if ( transfer.length() == 0 )
433 // for brain damaged headers
434 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
444 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
445 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
447 std::string Document::GetTransferSyntaxName()
449 // use the TS (TS : Transfer Syntax)
450 std::string transferSyntax = GetEntryString(0x0002,0x0010);
452 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
454 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
455 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
456 return "Uncompressed ACR-NEMA";
458 if ( transferSyntax == GDCM_UNFOUND )
460 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
461 return "Uncompressed ACR-NEMA";
464 // we do it only when we need it
465 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
467 // Global::GetTS() is a global static you shall never try to delete it!
471 // --------------- Swap Code ------------------
473 * \brief Swaps the bytes so they agree with the processor order
474 * @return The properly swaped 16 bits integer.
476 uint16_t Document::SwapShort(uint16_t a)
478 if ( SwapCode == 4321 || SwapCode == 2143 )
480 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
482 a = ( a << 8 ) | ( a >> 8 );
488 * \brief Swaps back the bytes of 4-byte long integer accordingly to
490 * @return The properly swaped 32 bits integer.
492 uint32_t Document::SwapLong(uint32_t a)
499 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
500 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
502 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
503 ((a>>8) & 0x0000ff00) | (a>>24) );
506 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
507 a=( (a<<16) | (a>>16) );
510 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
513 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
520 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
522 * @return The properly swaped 64 bits double.
524 double Document::SwapDouble(double a)
528 // There were no 'double' at ACR-NEMA time.
529 // We just have to deal with 'straight Little Endian' and
530 // 'straight Big Endian'
535 char *beg = (char *)&a;
538 for (unsigned int i = 0; i<7; i++)
549 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
556 // -----------------File I/O ---------------
558 * \brief Tries to open the file \ref Document::Filename and
559 * checks the preamble when existing.
560 * @return The FILE pointer on success.
562 std::ifstream *Document::OpenFile()
564 HasDCMPreamble = false;
565 if (Filename.length() == 0)
572 gdcmDebugMacro( "File already open: " << Filename.c_str());
576 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
579 // Don't user gdcmErrorMacro :
580 // a spurious message will appear when you use, for instance
581 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
582 // to create outputFileName.
584 // FIXME : if the upper comment is still usefull
585 // --> the constructor is not so good ...
587 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
591 //exit(1); // No function is allowed to leave the application instead
592 // of warning the caller
596 Fp->read((char*)&zero, (size_t)2);
603 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
605 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
606 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
607 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
608 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
610 std::string msg = Util::Format(
611 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
612 // FIXME : is it a Warning message, or a Debug message?
613 gdcmWarningMacro( msg.c_str() );
618 Fp->seekg(126L, std::ios::cur);
619 char dicm[4]; // = {' ',' ',' ',' '};
620 Fp->read(dicm, (size_t)4);
626 if ( memcmp(dicm, "DICM", 4) == 0 )
628 HasDCMPreamble = true;
632 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
634 // Don't user Warning nor Error, not to polute the output
635 // while directory recursive parsing ...
636 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
637 << Filename.c_str());
642 * \brief closes the file
643 * @return TRUE if the close was successfull
645 bool Document::CloseFile()
657 * \brief Writes in a file all the Entries (Dicom Elements)
658 * @param fp file pointer on an already open file (actually: Output File Stream)
659 * @param filetype Type of the File to be written
660 * (ACR-NEMA, ExplicitVR, ImplicitVR)
662 void Document::WriteContent(std::ofstream *fp, FileType filetype)
664 // Skip if user wants to write an ACR-NEMA file
666 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
669 // writing Dicom File Preamble
670 char filePreamble[128];
671 memset(filePreamble, 0, 128);
672 fp->write(filePreamble, 128);
673 fp->write("DICM", 4);
677 * \todo rewrite later, if really usefull
678 * - 'Group Length' element is optional in DICOM
679 * - but un-updated odd groups lengthes can causes pb
682 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
683 * UpdateGroupLength(false,filetype);
684 * if ( filetype == ACR)
685 * UpdateGroupLength(true,ACR);
687 * --> Computing group length for groups with embeded Sequences
688 * --> was too much tricky / we were [in a hurry / too lazy]
689 * --> We don't write the element 0x0000 (group length)
692 ElementSet::WriteContent(fp, filetype); // This one is recursive
695 // -----------------------------------------
698 * \brief Loads (from disk) the element content
699 * when a string is not suitable
700 * @param group group number of the Entry
701 * @param elem element number of the Entry
703 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
705 // Search the corresponding DocEntry
706 DocEntry *docEntry = GetDocEntry(group, elem);
709 gdcmWarningMacro(std::hex << group << "|" << elem
710 << "doesn't exist" );
713 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
716 gdcmWarningMacro(std::hex << group << "|" << elem
717 << "is NOT a DataEntry");
720 LoadEntryBinArea(dataEntry);
724 * \brief Loads (from disk) the element content
725 * when a string is not suitable
726 * @param entry Entry whose binArea is going to be loaded
728 void Document::LoadEntryBinArea(DataEntry *entry)
730 if( entry->GetBinArea() )
737 size_t o =(size_t)entry->GetOffset();
738 Fp->seekg(o, std::ios::beg);
740 size_t l = entry->GetLength();
741 uint8_t *data = new uint8_t[l];
744 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
745 << std::hex << entry->GetGroup()
746 << "|" << entry->GetElement() );
751 Fp->read((char*)data, l);
752 if ( Fp->fail() || Fp->eof() )
755 entry->SetState(DataEntry::STATE_UNREAD);
759 // Swap the data content if necessary
761 unsigned short vrLgth =
762 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
764 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
765 if( entry->GetVR() == "OW" )
772 gdcmDebugMacro( "Atomic lgt = 1 ; NO swap at reading");
777 uint16_t *data16 = (uint16_t *)data;
778 for(i=0;i<l/vrLgth;i++)
779 data16[i] = SwapShort(data16[i]);
784 uint32_t *data32 = (uint32_t *)data;
785 for(i=0;i<l/vrLgth;i++)
786 data32[i] = SwapLong(data32[i]);
791 double *data64 = (double *)data;
792 for(i=0;i<l/vrLgth;i++)
793 data64[i] = SwapDouble(data64[i]);
798 entry->SetBinArea(data);
805 * \brief Loads the element while preserving the current
806 * underlying file position indicator as opposed to
807 * LoadDocEntry that modifies it.
808 * @param entry DocEntry whose value will be loaded.
810 void Document::LoadDocEntrySafe(DocEntry *entry)
814 long PositionOnEntry = Fp->tellg();
816 Fp->seekg(PositionOnEntry, std::ios::beg);
821 * \brief Compares two documents, according to \ref DicomDir rules
822 * \warning Does NOT work with ACR-NEMA files
823 * \todo Find a trick to solve the pb (use RET fields ?)
824 * @param document to compare with current one
825 * @return true if 'smaller'
827 bool Document::operator<(Document &document)
830 std::string s1 = GetEntryString(0x0010,0x0010);
831 std::string s2 = document.GetEntryString(0x0010,0x0010);
843 s1 = GetEntryString(0x0010,0x0020);
844 s2 = document.GetEntryString(0x0010,0x0020);
855 // Study Instance UID
856 s1 = GetEntryString(0x0020,0x000d);
857 s2 = document.GetEntryString(0x0020,0x000d);
868 // Serie Instance UID
869 s1 = GetEntryString(0x0020,0x000e);
870 s2 = document.GetEntryString(0x0020,0x000e);
885 //-----------------------------------------------------------------------------
888 * \brief Reads a supposed to be 16 Bits integer
889 * (swaps it depending on processor endianness)
892 uint16_t Document::ReadInt16()
896 Fp->read ((char*)&g, (size_t)2);
899 throw FormatError( "Document::ReadInt16()", " file error." );
903 throw FormatError( "Document::ReadInt16()", "EOF." );
910 * \brief Reads a supposed to be 32 Bits integer
911 * (swaps it depending on processor endianness)
914 uint32_t Document::ReadInt32()
918 Fp->read ((char*)&g, (size_t)4);
921 throw FormatError( "Document::ReadInt32()", " file error." );
925 throw FormatError( "Document::ReadInt32()", "EOF." );
932 * \brief skips bytes inside the source file
933 * \warning NOT end user intended method !
936 void Document::SkipBytes(uint32_t nBytes)
938 //FIXME don't dump the returned value
939 Fp->seekg((long)nBytes, std::ios::cur);
943 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
945 int Document::ComputeGroup0002Length( )
951 bool found0002 = false;
953 // for each zero-level Tag in the DCM Header
954 DocEntry *entry = GetFirstEntry();
957 gr = entry->GetGroup();
963 if ( entry->GetElement() != 0x0000 )
967 // FIXME : group 0x0002 is *always* Explicit VR!
968 // --> Except for Implicit VR Transfer Syntax (GE Private) !!
970 //if ( filetype == ExplicitVR )
972 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
973 // (no SQ, OW, UT in group 0x0002;)
976 // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
980 groupLength += 2 + 2 + 4 + entry->GetLength();
986 entry = GetNextEntry();
991 //-----------------------------------------------------------------------------
994 * \brief Loads all the needed Dictionaries
995 * \warning NOT end user intended method !
997 void Document::Initialize()
999 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1005 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1006 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1007 * @param offset start of parsing
1008 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1009 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1011 void Document::ParseDES(DocEntrySet *set, long offset,
1012 long l_max, bool delim_mode)
1014 DocEntry *newDocEntry;
1015 DataEntry *newDataEntry;
1016 SeqEntry *newSeqEntry;
1018 bool used; // will be set to false when something wrong happens to an Entry.
1019 // (Entry will then be deleted)
1020 bool delim_mode_intern = delim_mode;
1022 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1023 << " at offset " << std::hex << offset );
1026 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1031 newDocEntry = ReadNextDocEntry( );
1033 // Uncoment this cerr line to be able to 'follow' the DocEntries
1034 // when something *very* strange happens
1035 if( Debug::GetDebugFlag() )
1036 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1043 // an Item Starter found elsewhere but the first position
1044 // of a SeqEntry means previous entry was a Sequence
1045 // but we didn't get it (private Sequence + Implicit VR)
1046 // we have to backtrack.
1047 if ( !first && newDocEntry->IsItemStarter() )
1049 // Debug message within the method !
1050 newDocEntry = Backtrack(newDocEntry);
1054 PreviousDocEntry = newDocEntry;
1058 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1062 //////////////////////////// DataEntry
1064 vr = newDocEntry->GetVR();
1066 if ( !set->AddEntry( newDataEntry ) )
1068 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1069 << newDataEntry->GetKey()
1071 << newDataEntry->GetOffset() << " )" );
1076 newDataEntry->Delete();
1077 // Load only if we can add (not a duplicate key)
1078 LoadDocEntry( newDataEntry );
1081 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1083 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1085 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1087 std::string strLgrGroup = newDataEntry->GetString();
1089 if ( newDataEntry->IsUnfound() )
1091 lgrGroup = atoi(strLgrGroup.c_str());
1092 Fp->seekg(lgrGroup, std::ios::cur);
1093 //used = false; // never used
1094 RemoveEntry( newDocEntry ); // Remove and delete
1095 // bcc 5.5 is right "assigned a value that's never used"
1103 bool delimitor = newDataEntry->IsItemDelimitor();
1106 (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1109 newDocEntry->Delete();
1113 // Just to make sure we are at the beginning of next entry.
1114 SkipToNextDocEntry(newDocEntry);
1118 /////////////////////// SeqEntry : VR = "SQ"
1120 unsigned long l = newDocEntry->GetReadLength();
1121 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1123 if ( l == 0xffffffff )
1125 delim_mode_intern = true;
1129 delim_mode_intern = false;
1133 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1135 // User asked to skip SeQuences *only* if they belong to Shadow Group
1136 if ( newDocEntry->GetGroup()%2 != 0 )
1138 Fp->seekg( l, std::ios::cur);
1139 newDocEntry->Delete(); // Delete, not in the set
1143 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1145 // User asked to skip *any* SeQuence
1146 Fp->seekg( l, std::ios::cur);
1147 newDocEntry->Delete(); // Delete, not in the set
1150 // delay the dynamic cast as late as possible
1151 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1153 // no other way to create the Delimitor ...
1154 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1156 // At the top of the hierarchy, stands a Document. When "set"
1157 // is a Document, then we are building the first depth level.
1158 // Hence the SeqEntry we are building simply has a depth
1160 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1162 newSeqEntry->SetDepthLevel( 1 );
1164 // But when "set" is already a SQItem, we are building a nested
1165 // sequence, and hence the depth level of the new SeqEntry
1166 // we are building, is one level deeper:
1168 // time waste hunting
1169 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1171 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1175 { // Don't try to parse zero-length sequences
1177 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1178 << " at offset " << std::hex
1179 << newDocEntry->GetOffset() );
1181 ParseSQ( newSeqEntry,
1182 newDocEntry->GetOffset(),
1183 l, delim_mode_intern);
1185 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1188 if ( !set->AddEntry( newSeqEntry ) )
1190 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1191 << newSeqEntry->GetKey()
1193 << newSeqEntry->GetOffset() << " )" );
1198 newDocEntry->Delete();
1201 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1204 newDocEntry->Delete();
1207 } // end SeqEntry : VR = "SQ"
1211 newDocEntry->Delete();
1215 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1219 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1220 * @return parsed length for this level
1222 void Document::ParseSQ( SeqEntry *seqEntry,
1223 long offset, long l_max, bool delim_mode)
1225 int SQItemNumber = 0;
1227 long offsetStartCurrentSQItem = offset;
1231 // the first time, we read the fff0,e000 of the first SQItem
1232 DocEntry *newDocEntry = ReadNextDocEntry();
1236 gdcmWarningMacro("in ParseSQ : should never get here!");
1241 if ( newDocEntry->IsSequenceDelimitor() )
1243 seqEntry->SetDelimitationItem( newDocEntry );
1244 newDocEntry->Delete();
1248 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1250 newDocEntry->Delete();
1253 // create the current SQItem
1254 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1255 unsigned int l = newDocEntry->GetReadLength();
1257 if ( l == 0xffffffff )
1266 // remove fff0,e000, created out of the SQItem
1267 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1268 // fill up the current SQItem, starting at the beginning of fff0,e000
1270 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1272 offsetStartCurrentSQItem = Fp->tellg();
1274 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1276 newDocEntry->Delete();
1278 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1286 * \brief When a private Sequence + Implicit VR is encountered
1287 * we cannot guess it's a Sequence till we find the first
1288 * Item Starter. We then backtrack to do the job.
1289 * @param docEntry Item Starter that warned us
1291 DocEntry *Document::Backtrack(DocEntry *docEntry)
1293 // delete the Item Starter, built erroneously out of any Sequence
1294 // it's not yet in the HTable/chained list
1297 // Get all info we can from PreviousDocEntry
1298 uint16_t group = PreviousDocEntry->GetGroup();
1299 uint16_t elem = PreviousDocEntry->GetElement();
1300 uint32_t lgt = PreviousDocEntry->GetLength();
1301 long offset = PreviousDocEntry->GetOffset();
1303 gdcmDebugMacro( "Backtrack :" << std::hex << group
1305 << " at offset " << offset );
1306 RemoveEntry( PreviousDocEntry );
1308 // forge the Seq Entry
1309 DocEntry *newEntry = NewSeqEntry(group, elem);
1310 newEntry->SetLength(lgt);
1311 newEntry->SetOffset(offset);
1313 // Move back to the beginning of the Sequence
1314 Fp->seekg( 0, std::ios::beg);
1315 Fp->seekg(offset, std::ios::cur);
1321 * \brief Loads (or not) the element content depending if its length exceeds
1322 * or not the value specified with Document::SetMaxSizeLoadEntry()
1323 * @param entry Header Entry (Dicom Element) to be dealt with
1324 * @param forceLoad whether you want to force loading of 'long' elements
1326 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1328 uint16_t group = entry->GetGroup();
1329 uint16_t elem = entry->GetElement();
1330 const VRKey &vr = entry->GetVR();
1331 uint32_t length = entry->GetLength();
1333 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1335 // A SeQuence "contains" a set of Elements.
1336 // (fffe e000) tells us an Element is beginning
1337 // (fffe e00d) tells us an Element just ended
1338 // (fffe e0dd) tells us the current SeQuence just ended
1340 // (fffe 0000) is an 'impossible' tag value,
1341 // found in MR-PHILIPS-16-Multi-Seq.dcm
1343 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1345 // NO more value field for SQ !
1349 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1355 // When the length is zero things are easy:
1358 dataEntryPtr->SetBinArea(NULL,true);
1362 // The elements whose length is bigger than the specified upper bound
1365 std::ostringstream s;
1369 if (length > MaxSizeLoadEntry)
1371 dataEntryPtr->SetBinArea(NULL,true);
1372 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1374 // to be sure we are at the end of the value ...
1375 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1381 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1385 * \brief Find the value Length of the passed Doc Entry
1386 * @param entry Header Entry whose length of the value shall be loaded.
1388 void Document::FindDocEntryLength( DocEntry *entry )
1389 throw ( FormatError )
1391 const VRKey &vr = entry->GetVR();
1394 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1396 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT"
1399 // The following reserved two bytes (see PS 3.5-2003, section
1400 // "7.1.2 Data element structure with explicit vr", p 27) must be
1401 // skipped before proceeding on reading the length on 4 bytes.
1402 Fp->seekg( 2L, std::ios::cur);
1403 uint32_t length32 = ReadInt32();
1405 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1410 lengthOB = FindDocEntryLengthOBOrOW();
1412 catch ( FormatUnexpected )
1414 // Computing the length failed (this happens with broken
1415 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1416 // chance to get the pixels by deciding the element goes
1417 // until the end of the file. Hence we artificially fix the
1418 // the length and proceed.
1419 gdcmWarningMacro( " Computing the length failed for " <<
1420 entry->GetKey() <<" in " <<GetFileName());
1422 long currentPosition = Fp->tellg();
1423 Fp->seekg(0L,std::ios::end);
1425 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1426 Fp->seekg(currentPosition, std::ios::beg);
1428 entry->SetReadLength(lengthUntilEOF);
1429 entry->SetLength(lengthUntilEOF);
1432 entry->SetReadLength(lengthOB);
1433 entry->SetLength(lengthOB);
1436 FixDocEntryFoundLength(entry, length32);
1440 // Length is encoded on 2 bytes.
1441 length16 = ReadInt16();
1443 // 0xffff means that we deal with 'No Length' Sequence
1444 // or 'No Length' SQItem
1445 if ( length16 == 0xffff)
1449 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1454 // Either implicit VR or a non DICOM conformal (see note below) explicit
1455 // VR that ommited the VR of (at least) this element. Farts happen.
1456 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1457 // on Data elements "Implicit and Explicit VR Data Elements shall
1458 // not coexist in a Data Set and Data Sets nested within it".]
1459 // Length is on 4 bytes.
1461 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1462 // even if Transfer Syntax is 'Implicit VR ...'
1463 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1465 FixDocEntryFoundLength( entry, ReadInt32() );
1471 * \brief Find the Length till the next sequence delimiter
1472 * \warning NOT end user intended method !
1475 uint32_t Document::FindDocEntryLengthOBOrOW()
1476 throw( FormatUnexpected )
1478 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1479 long positionOnEntry = Fp->tellg();
1480 bool foundSequenceDelimiter = false;
1481 uint32_t totalLength = 0;
1483 while ( !foundSequenceDelimiter )
1489 group = ReadInt16();
1492 catch ( FormatError )
1494 throw FormatError("Unexpected end of file encountered during ",
1495 "Document::FindDocEntryLengthOBOrOW()");
1497 // We have to decount the group and element we just read
1499 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1501 long filePosition = Fp->tellg();
1503 "Neither an Item tag nor a Sequence delimiter tag on :"
1504 << std::hex << group << " , " << elem
1505 << ") -before- position x(" << filePosition << ")" );
1507 Fp->seekg(positionOnEntry, std::ios::beg);
1508 throw FormatUnexpected(
1509 "Neither an Item tag nor a Sequence delimiter tag.");
1511 if ( elem == 0xe0dd )
1513 foundSequenceDelimiter = true;
1515 uint32_t itemLength = ReadInt32();
1516 // We add 4 bytes since we just read the ItemLength with ReadInt32
1517 totalLength += itemLength + 4;
1518 SkipBytes(itemLength);
1520 if ( foundSequenceDelimiter )
1525 Fp->seekg( positionOnEntry, std::ios::beg);
1530 * \brief Find the Value Representation of the current Dicom Element.
1531 * @return Value Representation of the current Entry
1533 VRKey Document::FindDocEntryVR()
1535 if ( Filetype != ExplicitVR )
1536 return GDCM_VRUNKNOWN;
1538 long positionOnEntry = Fp->tellg();
1539 // Warning: we believe this is explicit VR (Value Representation) because
1540 // we used a heuristic that found "UL" in the first tag and/or
1541 // 'Transfer Syntax' told us it is.
1542 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1543 // In some cases one finds implicit VR tags mixed within an explicit VR file.
1544 // Hence we make sure the present tag is in explicit VR and try to fix things
1545 // if it happens not to be the case.
1548 Fp->read(&(vr[0]),(size_t)2);
1550 if ( !CheckDocEntryVR(vr) )
1552 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1553 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1554 << ") at offset :" << positionOnEntry );
1555 Fp->seekg(positionOnEntry, std::ios::beg);
1556 return GDCM_VRUNKNOWN;
1562 * \brief Check the correspondance between the VR of the header entry
1563 * and the taken VR. If they are different, the header entry is
1564 * updated with the new VR.
1565 * @param vr Dicom Value Representation
1566 * @return false if the VR is incorrect or if the VR isn't referenced
1567 * otherwise, it returns true
1569 bool Document::CheckDocEntryVR(const VRKey &vr)
1571 return Global::GetVR()->IsValidVR(vr);
1575 * \brief Skip a given Header Entry
1576 * \warning NOT end user intended method !
1577 * @param entry entry to skip
1579 void Document::SkipDocEntry(DocEntry *entry)
1581 SkipBytes(entry->GetLength());
1585 * \brief Skips to the beginning of the next Header Entry
1586 * \warning NOT end user intended method !
1587 * @param currentDocEntry entry to skip
1589 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1591 int l = currentDocEntry->GetReadLength();
1592 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1593 // ... but PMS imagers happen !
1595 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1596 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1598 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1603 * \brief When the length of an element value is obviously wrong (because
1604 * the parser went Jabberwocky) one can hope improving things by
1605 * applying some heuristics.
1606 * @param entry entry to check
1607 * @param foundLength first assumption about length
1609 void Document::FixDocEntryFoundLength(DocEntry *entry,
1610 uint32_t foundLength)
1612 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1613 if ( foundLength == 0xffffffff)
1618 uint16_t gr = entry->GetGroup();
1619 uint16_t elem = entry->GetElement();
1621 if ( foundLength % 2)
1623 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1624 << " in x(" << std::hex << gr << "," << elem <<")");
1627 //////// Fix for some naughty General Electric images.
1628 // Allthough not recent many such GE corrupted images are still present
1629 // on Creatis hard disks. Hence this fix shall remain when such images
1630 // are no longer in use (we are talking a few years, here)...
1631 // Note: XMedCon probably uses such a trick since it is able to read
1632 // those pesky GE images ...
1633 if ( foundLength == 13)
1635 // Only happens for this length !
1636 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1639 entry->SetReadLength(10); // a bug is to be fixed !?
1643 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1644 // Occurence of such images is quite low (unless one leaves close to a
1645 // 'Leonardo' source. Hence, one might consider commenting out the
1646 // following fix on efficiency reasons.
1647 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1650 entry->SetReadLength(4); // a bug is to be fixed !
1653 else if ( entry->GetVR() == "SQ" )
1655 foundLength = 0; // ReadLength is unchanged
1658 //////// We encountered a 'delimiter' element i.e. a tag of the form
1659 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1660 // taken into account.
1661 else if ( gr == 0xfffe )
1663 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1664 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1665 // causes extra troubles...
1666 if ( entry->GetElement() != 0x0000 )
1672 foundLength=12; // to skip the mess that follows this bugged Tag !
1675 entry->SetLength(foundLength);
1679 * \brief Apply some heuristics to predict whether the considered
1680 * element value contains/represents an integer or not.
1681 * @param entry The element value on which to apply the predicate.
1682 * @return The result of the heuristical predicate.
1684 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1686 uint16_t elem = entry->GetElement();
1687 uint16_t group = entry->GetGroup();
1688 const VRKey &vr = entry->GetVR();
1689 uint32_t length = entry->GetLength();
1691 // When we have some semantics on the element we just read, and if we
1692 // a priori know we are dealing with an integer, then we shall be
1693 // able to swap it's element value properly.
1694 if ( elem == 0 ) // This is the group length of the group
1702 // Although this should never happen, still some images have a
1703 // corrupted group length [e.g. have a glance at offset x(8336) of
1704 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1705 // Since for dicom compliant and well behaved headers, the present
1706 // test is useless (and might even look a bit paranoid), when we
1707 // encounter such an ill-formed image, we simply display a warning
1708 // message and proceed on parsing (while crossing fingers).
1709 long filePosition = Fp->tellg();
1710 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1711 << std::hex << group << " , " << elem
1712 << ") -before- position x(" << filePosition << ")"
1713 << "lgt : " << length );
1717 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1725 * \brief Discover what the swap code is (among little endian, big endian,
1726 * bad little endian, bad big endian).
1728 * @return false when we are absolutely sure
1729 * it's neither ACR-NEMA nor DICOM
1730 * true when we hope ours assuptions are OK
1732 bool Document::CheckSwap()
1739 // First, compare HostByteOrder and NetworkByteOrder in order to
1740 // determine if we shall need to swap bytes (i.e. the Endian type).
1741 bool net2host = Util::IsCurrentProcessorBigEndian();
1743 // The easiest case is the one of a 'true' DICOM header, we just have
1744 // to look for the string "DICM" inside the file preamble.
1747 char *entCur = deb + 128;
1748 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1750 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1752 // Group 0002 should always be VR, and the first element 0000
1753 // Let's be carefull (so many wrong headers ...)
1754 // and determine the value representation (VR) :
1755 // Let's skip to the first element (0002,0000) and check there if we find
1756 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1757 // in which case we (almost) know it is explicit VR.
1758 // WARNING: if it happens to be implicit VR then what we will read
1759 // is the length of the group. If this ascii representation of this
1760 // length happens to be "UL" then we shall believe it is explicit VR.
1761 // We need to skip :
1762 // * the 128 bytes of File Preamble (often padded with zeroes),
1763 // * the 4 bytes of "DICM" string,
1764 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1765 // i.e. a total of 136 bytes.
1768 // group 0x0002 *is always* Explicit VR Sometimes ,
1769 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1770 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1772 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1773 memcmp(entCur, "OB", (size_t)2) == 0 ||
1774 memcmp(entCur, "UI", (size_t)2) == 0 ||
1775 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1776 // when Write DCM *adds*
1778 // Use Document::dicom_vr to test all the possibilities
1779 // instead of just checking for UL, OB and UI !? group 0000
1781 Filetype = ExplicitVR;
1782 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1786 Filetype = ImplicitVR;
1787 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1788 << "Looks like a bugged Header!");
1794 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1799 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1802 // Position the file position indicator at first tag
1803 // (i.e. after the file preamble and the "DICM" string).
1805 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1807 Fp->seekg ( 132L, std::ios::beg);
1809 } // ------------------------------- End of DicomV3 ----------------
1811 // Alas, this is not a DicomV3 file and whatever happens there is no file
1812 // preamble. We can reset the file position indicator to where the data
1813 // is (i.e. the beginning of the file).
1815 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1817 Fp->seekg(0, std::ios::beg);
1819 // Let's check 'No Preamble Dicom File' :
1820 // Should start with group 0x0002
1821 // and be Explicit Value Representation
1823 s16 = *((uint16_t *)(deb));
1836 if ( SwapCode != 0 )
1838 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1839 memcmp(entCur, "OB", (size_t)2) == 0 ||
1840 memcmp(entCur, "UI", (size_t)2) == 0 ||
1841 memcmp(entCur, "SH", (size_t)2) == 0 ||
1842 memcmp(entCur, "AE", (size_t)2) == 0 ||
1843 memcmp(entCur, "OB", (size_t)2) == 0 )
1845 Filetype = ExplicitVR;
1846 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1850 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1852 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1853 // By clean we mean that the length of the first group is written down.
1854 // If this is the case and since the length of the first group HAS to be
1855 // four (bytes), then determining the proper swap code is straightforward.
1858 // We assume the array of char we are considering contains the binary
1859 // representation of a 32 bits integer. Hence the following dirty
1861 s32 = *((uint32_t *)(entCur));
1881 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1882 // It is time for despaired wild guesses.
1883 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1884 // i.e. the 'group length' element is not present :
1886 // check the supposed-to-be 'group number'
1887 // in ( 0x0001 .. 0x0008 )
1888 // to determine ' SwapCode' value .
1889 // Only 0 or 4321 will be possible
1890 // (no oportunity to check for the formerly well known
1891 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1892 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1893 // the file IS NOT ACR-NEMA nor DICOM V3
1894 // Find a trick to tell it the caller...
1896 s16 = *((uint16_t *)(deb));
1923 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1931 * \brief Change the Byte Swap code.
1933 void Document::SwitchByteSwapCode()
1935 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1936 << " at: 0x" << std::hex << Fp->tellg() );
1937 if ( SwapCode == 1234 )
1941 else if ( SwapCode == 4321 )
1945 else if ( SwapCode == 3412 )
1949 else if ( SwapCode == 2143 )
1953 gdcmDebugMacro( " Into: "<< SwapCode );
1957 * \brief during parsing, Header Elements too long are not loaded in memory
1958 * @param newSize new size
1960 void Document::SetMaxSizeLoadEntry(long newSize)
1966 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1968 MaxSizeLoadEntry = 0xffffffff;
1971 MaxSizeLoadEntry = newSize;
1975 * \brief Read the next tag WITHOUT loading it's value
1976 * (read the 'Group Number', the 'Element Number',
1977 * gets the Dict Entry
1978 * gets the VR, gets the length, gets the offset value)
1979 * @return On succes : the newly created DocEntry, NULL on failure.
1981 DocEntry *Document::ReadNextDocEntry()
1988 group = ReadInt16();
1991 catch ( FormatError )
1993 // We reached the EOF (or an error occured) therefore
1994 // header parsing has to be considered as finished.
1998 // Sometimes file contains groups of tags with reversed endianess.
1999 HandleBrokenEndian(group, elem);
2001 // In 'true DICOM' files Group 0002 is always little endian
2002 if ( HasDCMPreamble )
2003 HandleOutOfGroup0002(group, elem);
2005 VRKey vr = FindDocEntryVR();
2009 if ( vr == GDCM_VRUNKNOWN )
2011 if ( elem == 0x0000 ) // Group Length
2013 realVR = "UL"; // must be UL
2015 else if (group%2 == 1 && (elem >= 0x0010 && elem <=0x00ff ))
2017 // DICOM PS 3-5 7.8.1 a) states that those
2018 // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2023 DictEntry *dictEntry = GetDictEntry(group,elem);
2026 realVR = dictEntry->GetVR();
2027 dictEntry->Unregister();
2031 // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2034 if ( Global::GetVR()->IsVROfSequence(realVR) )
2035 newEntry = NewSeqEntry(group, elem);
2038 newEntry = NewDataEntry(group, elem, realVR);
2039 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2042 if ( vr == GDCM_VRUNKNOWN )
2044 if ( Filetype == ExplicitVR )
2046 // We thought this was explicit VR, but we end up with an
2047 // implicit VR tag. Let's backtrack.
2048 if ( newEntry->GetGroup() != 0xfffe )
2051 int offset = Fp->tellg();
2053 "Entry (%04x,%04x) at x(%x) should be Explicit VR\n",
2054 newEntry->GetGroup(), newEntry->GetElement(), offset );
2055 gdcmWarningMacro( msg.c_str() );
2058 newEntry->SetImplicitVR();
2063 FindDocEntryLength(newEntry);
2065 catch ( FormatError )
2072 newEntry->SetOffset(Fp->tellg());
2078 * \brief Handle broken private tag from Philips NTSCAN
2079 * where the endianess is being switched to BigEndian
2080 * for no apparent reason
2083 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2085 // Endian reversion.
2086 // Some files contain groups of tags with reversed endianess.
2087 static int reversedEndian = 0;
2088 // try to fix endian switching in the middle of headers
2089 if ((group == 0xfeff) && (elem == 0x00e0))
2091 // start endian swap mark for group found
2093 SwitchByteSwapCode();
2098 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2100 // end of reversed endian group
2102 SwitchByteSwapCode();
2104 else if (group == 0xfeff && elem == 0xdde0)
2106 // reversed Sequence Terminator found
2107 // probabely a bug in the header !
2108 // Do what you want, it breaks !
2110 //SwitchByteSwapCode();
2111 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2116 else if (group == 0xfffe && elem == 0xe0dd)
2118 gdcmDebugMacro( "Straight Sequence Terminator." );
2123 * \brief Group 0002 is always coded Little Endian
2124 * whatever Transfer Syntax is
2127 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2129 // Endian reversion.
2130 // Some files contain groups of tags with reversed endianess.
2131 if ( !Group0002Parsed && group != 0x0002)
2133 Group0002Parsed = true;
2134 // we just came out of group 0002
2135 // if Transfer Syntax is Big Endian we have to change CheckSwap
2137 std::string ts = GetTransferSyntax();
2138 if ( ts == GDCM_UNKNOWN )
2140 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2143 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2145 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2150 // Group 0002 is always 'Explicit ...'
2151 // even when Transfer Syntax says 'Implicit ..."
2153 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2154 TS::ImplicitVRLittleEndian )
2156 Filetype = ImplicitVR;
2159 // FIXME Strangely, this works with
2160 //'Implicit VR BigEndian Transfer Syntax (GE Private)
2162 // --> Probabely normal, since we considered we never have
2163 // to trust manufacturers.
2164 // (we find very often 'Implicit VR' tag,
2165 // even when Transfer Syntax tells us it's Explicit ...
2166 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) ==
2167 TS::ExplicitVRBigEndian )
2169 gdcmDebugMacro("Transfer Syntax Name = ["
2170 << GetTransferSyntaxName() << "]" );
2171 SwitchByteSwapCode();
2172 group = SwapShort(group);
2173 elem = SwapShort(elem);
2178 //-----------------------------------------------------------------------------
2181 //-----------------------------------------------------------------------------
2182 } // end namespace gdcm