1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2007/10/24 10:38:51 $
7 Version: $Revision: 1.374 $
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
36 #if defined(__BORLANDC__)
37 #include <mem.h> // for memset
40 namespace GDCM_NAME_SPACE
42 //-----------------------------------------------------------------------------
44 // Refer to Document::SetMaxSizeLoadEntry()
45 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
49 // Constructors and destructors are protected to avoid user to invoke directly
52 * \brief This default constructor neither loads nor parses the file.
53 * You should then invoke Document::Load.
61 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
64 Filetype = ExplicitVR;
65 CurrentOffsetPosition = 0;
66 // Load will set it to true if sucessfull
67 Group0002Parsed = false;
68 IsDocumentAlreadyLoaded = false;
69 IsDocumentModified = true;
70 LoadMode = LD_ALL; // default : load everything, later
78 * \brief Canonical destructor.
80 Document::~Document ()
85 //-----------------------------------------------------------------------------
88 * \brief Loader. use SetLoadMode(), SetFileName() before !
89 * @return false if file cannot be open or no swap info was found,
90 * or no tag was found.
92 bool Document::Load( )
94 if ( GetFileName() == "" )
96 gdcmWarningMacro( "Use SetFileName, before !" );
99 return DoTheLoadingDocumentJob( );
103 //#ifndef GDCM_LEGACY_REMOVE
105 * \brief Loader. (DEPRECATED : not to break the API)
106 * @param fileName 'Document' (File or DicomDir) to be open for parsing
107 * @return false if file cannot be open or no swap info was found,
108 * or no tag was found.
111 bool Document::Load( std::string const &fileName )
114 return DoTheLoadingDocumentJob( );
120 * \brief Performs the Loading Job (internal use only)
121 * @return false if file cannot be open or no swap info was found,
122 * or no tag was found.
124 bool Document::DoTheLoadingDocumentJob( )
126 if ( ! IsDocumentModified ) // Nothing to do !
134 // warning already performed in OpenFile()
139 Group0002Parsed = false;
141 gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
143 // Computes the total length of the file
144 Fp->seekg(0, std::ios::end); // Once per Document !
145 long lgt = Fp->tellg(); // Once per Document !
146 Fp->seekg(0, std::ios::beg); // Once per Document !
148 // CheckSwap returns a boolean
149 // (false if no swap info of any kind was found)
152 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
153 << Filename.c_str());
158 long beg = Fp->tellg(); // just after DICOM preamble (if any)
160 lgt -= beg; // remaining length to parse
163 // Loading is done during parsing
164 ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
168 gdcmErrorMacro( "No tag in internal hash table for: "
169 << Filename.c_str());
173 IsDocumentAlreadyLoaded = true;
175 //Fp->seekg(0, std::ios::beg); // Once per Document!
177 // Load 'non string' values
179 std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);
180 if ( PhotometricInterpretation == "PALETTE COLOR " )
183 // Probabely this line should be outside the 'if'
184 // Try to find an image sample holding a 'gray LUT'
185 LoadEntryBinArea(0x0028,0x1200); // gray LUT
188 /// --> FIXME : The difference between BinEntry and DataEntry
189 /// --> no longer exists, but the alteration of Dicom Dictionary remains.
190 /// --> Old comment restored on purpose.
191 /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
192 /// --> had absolutely no meaning.
193 /// --> The whole comment will be removed when the stuff is cleaned !
195 /// The tags refered by the three following lines used to be CORRECTLY
196 /// defined as having an US Value Representation in the public
197 /// dictionary. BUT the semantics implied by the three following
198 /// lines state that the corresponding tag contents are in fact
199 /// the ones of a BinEntry.
200 /// In order to fix things "Quick and Dirty" the dictionary was
201 /// altered on PURPOSE but now contains a WRONG value.
202 /// In order to fix things and restore the dictionary to its
203 /// correct value, one needs to decide of the semantics by deciding
204 /// whether the following tags are either :
205 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
206 /// also used as BinEntry, which requires the proper conversion,
207 /// - OW, and hence loaded as BinEntry, but afterwards also used
208 /// as ValEntry, which requires the proper conversion.
210 // --> OB (byte aray) or OW (short int aray)
211 // The actual VR has to be deduced from other entries.
212 // Our way of loading them may fail in some cases :
213 // We must or not SwapByte depending on other field values.
215 LoadEntryBinArea(0x0028,0x1201); // R LUT
216 LoadEntryBinArea(0x0028,0x1202); // G LUT
217 LoadEntryBinArea(0x0028,0x1203); // B LUT
219 // Segmented Red Palette Color LUT Data
220 LoadEntryBinArea(0x0028,0x1221);
221 // Segmented Green Palette Color LUT Data
222 LoadEntryBinArea(0x0028,0x1222);
223 // Segmented Blue Palette Color LUT Data
224 LoadEntryBinArea(0x0028,0x1223);
227 //FIXME later : how to use it?
228 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000); // Modality LUT Sequence
231 SQItem *sqi= modLutSeq->GetFirstSQItem();
234 DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006); // LUT Data
235 if ( dataEntry != 0 )
237 if ( dataEntry->GetLength() != 0 )
239 // FIXME : CTX dependent means : contexted dependant.
240 // see upper comment.
241 LoadEntryBinArea(dataEntry); //LUT Data (CTX dependent)
247 // Force Loading some more elements if user asked to.
249 GDCM_NAME_SPACE::DocEntry *d;
250 for (ListElements::iterator it = UserForceLoadList.begin();
251 it != UserForceLoadList.end();
254 gdcmDebugMacro( "Force Load " << std::hex
255 << (*it).Group << "|" <<(*it).Elem );
257 d = GetDocEntry( (*it).Group, (*it).Elem);
261 gdcmWarningMacro( "You asked to ForceLoad " << std::hex
262 << (*it).Group <<"|"<< (*it).Elem
263 << " that doesn't exist" );
267 LoadDocEntry(d, true);
272 // ----------------------------
273 // Specific code to allow gdcm to read ACR-LibIDO formated images
274 // Note: ACR-LibIDO is an extension of the ACR standard that was
275 // used at CREATIS. For the time being (say a couple of years)
276 // we keep this kludge to allow CREATIS users
277 // reading their old images.
279 // if recognition code tells us we deal with a LibIDO image
280 // we switch lineNumber and columnNumber
283 RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
284 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
285 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
286 // with "little-endian strings"
288 Filetype = ACR_LIBIDO;
289 std::string rows = GetEntryString(0x0028, 0x0010);
290 std::string columns = GetEntryString(0x0028, 0x0011);
291 SetEntryString(columns, 0x0028, 0x0010);
292 SetEntryString(rows , 0x0028, 0x0011);
294 // --- End of ACR-LibIDO kludge ---
300 * \brief Adds a new element we want to load anyway
301 * @param group Group number of the target tag.
302 * @param elem Element number of the target tag.
304 void Document::AddForceLoadElement (uint16_t group, uint16_t elem)
309 UserForceLoadList.push_back(el);
312 * \brief Get the public dictionary used
314 Dict *Document::GetPubDict()
320 * \brief Get the shadow dictionary used
322 Dict *Document::GetShaDict()
328 * \brief Set the shadow dictionary used
329 * @param dict dictionary to use in shadow
331 bool Document::SetShaDict(Dict *dict)
338 * \brief Set the shadow dictionary used
339 * @param dictName name of the dictionary to use in shadow
341 bool Document::SetShaDict(DictKey const &dictName)
343 RefShaDict = Global::GetDicts()->GetDict(dictName);
348 * \brief This predicate tells us whether or not the current Document
349 * was properly parsed and contains at least *one* Dicom Element
350 * (and nothing more, sorry).
351 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
354 bool Document::IsParsable()
356 if ( Filetype == Unknown )
358 gdcmWarningMacro( "Wrong filetype for " << GetFileName());
364 gdcmWarningMacro( "No tag in internal hash table.");
371 * \brief This predicate tells us whether or not the current Document
372 * was properly parsed and contains at least *one* Dicom Element
373 * (and nothing more, sorry).
374 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
377 bool Document::IsReadable()
383 * \brief Predicate for dicom version 3 file.
384 * @return True when the file is a dicom version 3.
386 bool Document::IsDicomV3()
388 // Checking if Transfer Syntax exists is enough
389 // Anyway, it's too late check if the 'Preamble' was found ...
390 // And ... would it be a rich idea to check ?
391 // (some 'no Preamble' DICOM images exist !)
392 return GetDocEntry(0x0002, 0x0010) != NULL;
396 * \brief Predicate for Papyrus file
397 * Dedicated to whomsoever it may concern
398 * @return True when the file is a Papyrus file.
400 bool Document::IsPapyrus()
402 // check for Papyrus private Sequence
403 DocEntry *e = GetDocEntry(0x0041, 0x1050);
406 // check if it's actually a Sequence
407 if ( !dynamic_cast<SeqEntry*>(e) )
413 * \brief returns the File Type
414 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
415 * @return the FileType code
417 FileType Document::GetFileType()
423 * \brief Accessor to the Transfer Syntax (when present) of the
424 * current document (it internally handles reading the
425 * value from disk when only parsing occured).
426 * @return The encountered Transfer Syntax of the current document, if DICOM.
427 * GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
429 std::string Document::GetTransferSyntax()
431 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
437 // The entry might be present but not loaded (parsing and loading
438 // happen at different stages): try loading and proceed with check...
441 // (parsing and loading happen at the very same stage!)
442 //LoadDocEntrySafe(entry); //JPRx
443 if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
445 std::string transfer = dataEntry->GetString();
446 // The actual transfer (as read from disk) might be padded. We
447 // first need to remove the potential padding. We can make the
448 // weak assumption that padding was not executed with digits...
449 if ( transfer.length() == 0 )
451 // for brain damaged headers
452 gdcmWarningMacro( "Transfer Syntax has length = 0.");
455 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
457 transfer.erase(transfer.length()-1, 1);
458 if ( transfer.length() == 0 )
460 // for brain damaged headers
461 gdcmWarningMacro( "Transfer Syntax contains no valid character.");
471 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
472 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
474 std::string Document::GetTransferSyntaxName()
476 // use the TS (TS : Transfer Syntax)
477 std::string transferSyntax = GetEntryString(0x0002,0x0010);
479 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
481 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
482 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
483 return "Uncompressed ACR-NEMA";
485 if ( transferSyntax == GDCM_UNFOUND )
487 gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
488 return "Uncompressed ACR-NEMA";
491 // we do it only when we need it
492 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
494 // Global::GetTS() is a global static you shall never try to delete it!
498 // --------------- Swap Code ------------------
500 * \brief Swaps the bytes so they agree with the processor order
501 * @return The properly swaped 16 bits integer.
503 uint16_t Document::SwapShort(uint16_t a)
505 if ( SwapCode == 4321 || SwapCode == 2143 )
507 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
509 a = ( a << 8 ) | ( a >> 8 );
515 * \brief Swaps back the bytes of 4-byte long integer accordingly to
517 * @return The properly swaped 32 bits integer.
519 uint32_t Document::SwapLong(uint32_t a)
526 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
527 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
529 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
530 ((a>>8) & 0x0000ff00) | (a>>24) );
533 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
534 a=( (a<<16) | (a>>16) );
537 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
540 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
547 * \brief Swaps back the bytes of 8-byte long 'double' accordingly to
549 * @return The properly swaped 64 bits double.
551 double Document::SwapDouble(double a)
555 // There were no 'double' at ACR-NEMA time.
556 // We just have to deal with 'straight Little Endian' and
557 // 'straight Big Endian'
562 char *beg = (char *)&a;
565 for (unsigned int i = 0; i<7; i++)
576 gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
583 // -----------------File I/O ---------------
585 * \brief Tries to open the file Document::Filename and
586 * checks the preamble when existing,
587 * or if the file starts with an ACR-NEMA look-like element.
588 * @return The FILE pointer on success, 0 on failure.
590 std::ifstream *Document::OpenFile()
592 HasDCMPreamble = false;
593 if (Filename.length() == 0)
600 gdcmDebugMacro( "File already open: " << Filename.c_str());
604 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
607 // Don't user gdcmErrorMacro :
608 // a spurious message will appear when you use, for instance
609 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
610 // to create outputFileName.
612 // FIXME : if the upper comment is still usefull
613 // --> the constructor is not so good ...
615 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
619 //exit(1); // No function is allowed to leave the application instead
620 // of warning the caller
624 Fp->read((char*)&zero, (size_t)2);
632 Fp->seekg(126L, std::ios::cur); // Once per Document
633 char dicm[4]; // = {' ',' ',' ',' '};
634 Fp->read(dicm, (size_t)4);
641 if ( memcmp(dicm, "DICM", 4) == 0 )
643 HasDCMPreamble = true;
647 //-- Broken ACR or DICOM (?) with no Preamble; may start with a Shadow Group --
648 // FIXME : We cannot be sure the preable is only zeroes..
649 // (see ACUSON-24-YBR_FULL-RLE.dcm )
651 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
652 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
653 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
654 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 ||
655 zero == 0x0028 || 0x2800 // worse : some ACR-NEMA like files
656 // start 00028 group ?!?
659 std::string msg = Util::Format(
660 "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
661 // FIXME : is it a Warning message, or a Debug message?
662 gdcmWarningMacro( msg.c_str() );
666 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
668 // Don't user Warning nor Error, not to pollute the output
669 // while directory recursive parsing ...
670 gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
671 << Filename.c_str());
676 * \brief closes the file
677 * @return TRUE if the close was successfull
679 bool Document::CloseFile()
691 * \brief Writes in a file all the Entries (Dicom Elements)
692 * @param fp file pointer on an already open file (actually: Output File Stream)
693 * @param filetype Type of the File to be written
694 * (ACR-NEMA, ExplicitVR, ImplicitVR)
696 void Document::WriteContent(std::ofstream *fp, FileType filetype, bool, bool)
698 // Skip if user wants to write an ACR-NEMA file
700 if ( filetype == ImplicitVR || filetype == ExplicitVR ||
701 filetype == JPEG || filetype == JPEG2000 )
703 // writing Dicom File Preamble
704 char filePreamble[128];
705 memset(filePreamble, 0, 128);
706 fp->write(filePreamble, 128);
707 fp->write("DICM", 4);
710 * \todo rewrite later, if really usefull
711 * - 'Group Length' element is optional in DICOM
712 * - but un-updated odd groups lengthes can causes pb
715 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
716 * UpdateGroupLength(false,filetype);
717 * if ( filetype == ACR)
718 * UpdateGroupLength(true,ACR);
720 * --> Computing group length for groups with embeded Sequences
721 * --> was too much tricky / we were [in a hurry / too lazy]
722 * --> We don't write the element 0x0000 (group length)
724 // This one is recursive
725 // false : outside MetaElements
726 // false : outside Sequence
727 ElementSet::WriteContent(fp, filetype, false, false);
730 // -----------------------------------------
733 * \brief Loads (from disk) the element content
734 * when a string is not suitable
735 * @param group group number of the Entry
736 * @param elem element number of the Entry
738 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
740 // Search the corresponding DocEntry
741 DocEntry *docEntry = GetDocEntry(group, elem);
744 gdcmDebugMacro(std::hex << group << "|" << elem
745 << " doesn't exist" );
748 DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
751 gdcmWarningMacro(std::hex << group << "|" << elem
752 << " is NOT a DataEntry");
755 LoadEntryBinArea(dataEntry);
759 * \brief Loads (from disk) the element content
760 * when a string is not suitable
761 * @param entry Entry whose binArea is going to be loaded
763 void Document::LoadEntryBinArea(DataEntry *entry)
765 if( entry->GetBinArea() )
772 //size_t o =(size_t)entry->GetOffset();
773 Fp->seekg((size_t)entry->GetOffset(), std::ios::beg); // FIXME : for each DataEntry !
775 size_t l = entry->GetLength();
776 uint8_t *data = new uint8_t[l];
779 gdcmWarningMacro( "Cannot allocate DataEntry content for : "
780 << std::hex << entry->GetGroup()
781 << "|" << entry->GetElement() );
786 Fp->read((char*)data, l);
787 if ( Fp->fail() || Fp->eof() )
790 entry->SetState(DataEntry::STATE_UNREAD);
794 // Swap the data content if necessary
796 unsigned short vrLgth =
797 Global::GetVR()->GetAtomicElementLength(entry->GetVR());
799 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
800 // if( entry->GetVR() == "OW" )
811 uint16_t *data16 = (uint16_t *)data;
812 for(i=0;i<l/vrLgth;i++)
813 data16[i] = SwapShort(data16[i]);
818 uint32_t *data32 = (uint32_t *)data;
819 for(i=0;i<l/vrLgth;i++)
820 data32[i] = SwapLong(data32[i]);
825 double *data64 = (double *)data;
826 for(i=0;i<l/vrLgth;i++)
827 data64[i] = SwapDouble(data64[i]);
832 entry->SetBinArea(data);
834 if ( openFile ) // The file is left in the state (open/close) it was at entrance
839 * \brief Loads the element while preserving the current
840 * underlying file position indicator as opposed to
841 * LoadDocEntry that modifies it
842 * \note seems to be unused!.
843 * @param entry DocEntry whose value will be loaded.
845 //void Document::LoadDocEntrySafe(DocEntry *entry)
849 // long PositionOnEntry = Fp->tellg(); // LoadDocEntrySafe is not used
850 // LoadDocEntry(entry);
851 // Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
856 * \brief Compares two documents, according to DicomDir rules
857 * \warning Does NOT work with ACR-NEMA files
858 * \todo Find a trick to solve the pb (use RET fields ?)
859 * @param document to compare with current one
860 * @return true if 'smaller'
862 bool Document::operator<(Document &document)
865 std::string s1 = GetEntryString(0x0010,0x0010);
866 std::string s2 = document.GetEntryString(0x0010,0x0010);
878 s1 = GetEntryString(0x0010,0x0020);
879 s2 = document.GetEntryString(0x0010,0x0020);
890 // Study Instance UID
891 s1 = GetEntryString(0x0020,0x000d);
892 s2 = document.GetEntryString(0x0020,0x000d);
903 // Serie Instance UID
904 s1 = GetEntryString(0x0020,0x000e);
905 s2 = document.GetEntryString(0x0020,0x000e);
920 //-----------------------------------------------------------------------------
924 * \brief Reads a given length of bytes
925 * (in order to avoid to many CPU time-consuming fread-s)
926 * @param l length to read
928 void Document::ReadBegBuffer(size_t l)
931 Fp->read (BegBuffer, (size_t)l);
934 throw FormatError( "Document::ReadBegBuffer()", " file error." );
938 throw FormatError( "Document::ReadBegBuffer()", "EOF." );
940 PtrBegBuffer = BegBuffer;
941 CurrentOffsetPosition+=l;
944 * \brief Reads a supposed to be 16 Bits integer
945 * (swaps it depending on processor endianness)
948 uint16_t Document::ReadInt16()
952 Fp->read ((char*)&g, (size_t)2);
955 throw FormatError( "Document::ReadInt16()", " file error." );
959 throw FormatError( "Document::ReadInt16()", "EOF." );
966 * \brief Gets from BegBuffer a supposed to be 16 Bits integer
967 * (swaps it depending on processor endianness)
970 uint16_t Document::GetInt16()
972 uint16_t g = *((uint16_t*)PtrBegBuffer);
978 * \brief Reads a supposed to be 32 Bits integer
979 * (swaps it depending on processor endianness)
982 uint32_t Document::ReadInt32()
986 Fp->read ((char*)&g, (size_t)4);
989 throw FormatError( "Document::ReadInt32()", " file error." );
993 throw FormatError( "Document::ReadInt32()", "EOF." );
1000 * \brief Gets from BegBuffer a supposed to be 32 Bits integer
1001 * (swaps it depending on processor endianness)
1002 * @return read value
1004 uint32_t Document::GetInt32()
1006 uint32_t g = *((uint32_t*)PtrBegBuffer);
1013 * \brief Re-computes the length of the Dicom group 0002.
1015 int Document::ComputeGroup0002Length( )
1020 int groupLength = 0;
1021 bool found0002 = false;
1023 // for each zero-level Tag in the DCM Header
1024 DocEntry *entry = GetFirstEntry();
1027 gr = entry->GetGroup();
1033 if ( entry->GetElement() != 0x0000 )
1035 vr = entry->GetVR();
1037 //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
1038 // (no SQ, OW, OL, UT in group 0x0002;)
1041 // explicit VR AND (OB, OW, OL, SQ, UT) : 4 more bytes
1044 groupLength += 2 + 2 + 4 + entry->GetLength();
1047 else if (found0002 )
1050 entry = GetNextEntry();
1056 * \brief CallStartMethod
1058 void Document::CallStartMethod()
1062 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1066 * \brief CallProgressMethod
1068 void Document::CallProgressMethod()
1070 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1074 * \brief CallEndMethod
1076 void Document::CallEndMethod()
1079 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1082 //-----------------------------------------------------------------------------
1085 * \brief Loads all the needed Dictionaries
1086 * \warning NOT end user intended method !
1088 void Document::Initialize()
1090 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1096 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1097 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1098 * @param offset start of parsing
1099 * @param l_max length to parse (meaningless when we are in 'delimitor mode')
1100 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1102 void Document::ParseDES(DocEntrySet *set, long offset,
1103 long l_max, bool delim_mode)
1105 DocEntry *newDocEntry;
1106 DataEntry *newDataEntry;
1107 SeqEntry *newSeqEntry;
1109 bool used; // will be set to false when something wrong happens to an Entry.
1110 // (Entry will then be deleted)
1111 bool delim_mode_intern = delim_mode;
1113 gdcmDebugMacro( "Enter in ParseDES, delim-mode " << delim_mode
1114 << " at offset " << std::hex << "0x(" << offset << ")" );
1118 ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1119 /// Probabely a bug in gdcm code somwhere (some memory erased ?)
1121 // Uncomment to track the bug
1123 if( Debug::GetDebugFlag() )
1124 std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1125 << std::hex << " 0x(" <<(long)(Fp->tellg()) << ")" << std::endl;
1128 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry
1129 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1130 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1135 newDocEntry = ReadNextDocEntry( );
1142 // Uncoment this cerr line to be able to 'follow' the DocEntries
1143 // when something *very* strange happens
1144 if( Debug::GetDebugFlag() )
1145 std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1147 // an Item Starter found elsewhere but in the first position
1148 // of a SeqEntry means previous entry was a Sequence
1149 // but we didn't get it (private Sequence + Implicit VR)
1150 // we have to backtrack.
1151 if ( !first && newDocEntry->IsItemStarter() )
1153 // Debug message within the method !
1154 newDocEntry = Backtrack(newDocEntry);
1158 PreviousDocEntry = newDocEntry;
1162 newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1166 //////////////////////////// DataEntry
1168 //vr = newDocEntry->GetVR(); // useless ?
1170 if ( !set->AddEntry( newDataEntry ) )
1172 gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1173 << newDataEntry->GetKey()
1174 << " (at offset : 0x("
1175 << newDataEntry->GetOffset() << ") )" );
1180 newDataEntry->Delete();
1181 // Load only if we can add (not a duplicate key)
1182 LoadDocEntry( newDataEntry );
1184 if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1186 if ( newDataEntry->GetGroup()%2 != 0 ) // if Shadow Group
1188 if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1190 std::string strLgrGroup = newDataEntry->GetString();
1193 //if ( newDataEntry->IsUnfound() ) /?!? JPR
1195 lgrGroup = atoi(strLgrGroup.c_str());
1196 Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1197 RemoveEntry( newDocEntry ); // Remove and delete
1204 bool delimitor = newDataEntry->IsItemDelimitor();
1205 bool outOfBounds = false;
1207 if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1210 // 'and then', 'or else' don't exist in C++ :-(
1211 // if ( (delimitor) ||
1212 // (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1214 if ( delimitor || outOfBounds )
1217 newDocEntry->Delete();
1221 // Just to make sure we are at the beginning of next entry.
1222 SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1226 /////////////////////// SeqEntry : VR = "SQ"
1228 unsigned long l = newDocEntry->GetReadLength();
1229 if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1231 if ( l == 0xffffffff )
1233 delim_mode_intern = true;
1237 delim_mode_intern = false;
1241 if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1243 // User asked to skip SeQuences *only* if they belong to Shadow Group
1244 if ( newDocEntry->GetGroup()%2 != 0 )
1246 Fp->seekg( l, std::ios::cur); // once per SQITEM, when NOSHADOWSEQ
1247 newDocEntry->Delete(); // Delete, not in the set
1251 if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern )
1253 // User asked to skip *any* SeQuence
1254 Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1255 newDocEntry->Delete(); // Delete, not in the set
1258 // delay the dynamic cast as late as possible
1259 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1261 // no other way to create the Delimitor ...
1262 newSeqEntry->SetDelimitorMode( delim_mode_intern );
1264 // At the top of the hierarchy, stands a Document. When "set"
1265 // is a Document, then we are building the first depth level.
1266 // Hence the SeqEntry we are building simply has a depth
1268 if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1270 newSeqEntry->SetDepthLevel( 1 );
1272 // But when "set" is already a SQItem, we are building a nested
1273 // sequence, and hence the depth level of the new SeqEntry
1274 // we are building, is one level deeper:
1276 // time waste hunting
1277 else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1279 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1283 { // Don't try to parse zero-length sequences
1285 gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1286 << " at offset 0x(" << std::hex
1287 << newDocEntry->GetOffset() << ")");
1289 bool res = ParseSQ( newSeqEntry,
1290 newDocEntry->GetOffset(),
1291 l, delim_mode_intern);
1293 gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern << " -->return : " << res);
1295 if ( !set->AddEntry( newSeqEntry ) )
1297 gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1298 << newSeqEntry->GetKey()
1299 << " (at offset : 0x("
1300 << newSeqEntry->GetOffset() << ") )" );
1305 newDocEntry->Delete();
1308 // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1310 if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1311 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1315 newDocEntry->Delete();
1318 } // end SeqEntry : VR = "SQ"
1322 newDocEntry->Delete();
1326 if (UnexpectedEOF) // some terminator was missing
1329 gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1333 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1334 * @return false if expected fff0,e000 not found
1336 bool Document::ParseSQ( SeqEntry *seqEntry,
1337 long offset, long l_max, bool delim_mode)
1339 int SQItemNumber = 0;
1341 long offsetStartCurrentSQItem = offset;
1345 // the first time, we read the fff0,e000 of the first SQItem
1346 DocEntry *newDocEntry = ReadNextDocEntry();
1350 // The most frequent is when a SQ terminator is missing (?!?)
1351 gdcmWarningMacro("in ParseSQ : should never get here!");
1352 UnexpectedEOF = true;
1357 if ( newDocEntry->IsSequenceDelimitor() )
1359 seqEntry->SetDelimitationItem( newDocEntry );
1360 newDocEntry->Delete();
1364 else // ! delim_mode
1366 if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1368 newDocEntry->Delete();
1372 // create the current SQItem
1373 SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1374 unsigned int l = newDocEntry->GetReadLength();
1376 if ( l == 0xffffffff )
1385 // fill up the current SQItem, starting at the beginning of fff0,e000
1387 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg); // Once per SQItem
1388 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1389 offsetStartCurrentSQItem = Fp->tellg(); // Once per SQItem
1391 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1393 newDocEntry->Delete();
1395 //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1396 if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1405 * \brief When a private Sequence + Implicit VR is encountered
1406 * we cannot guess it's a Sequence till we find the first
1407 * Item Starter. We then backtrack to do the job.
1408 * @param docEntry Item Starter that warned us
1410 DocEntry *Document::Backtrack(DocEntry *docEntry)
1412 // delete the Item Starter, built erroneously out of any Sequence
1413 // it's not yet in the HTable/chained list
1416 // Get all info we can from PreviousDocEntry
1417 uint16_t group = PreviousDocEntry->GetGroup();
1418 uint16_t elem = PreviousDocEntry->GetElement();
1419 uint32_t lgt = PreviousDocEntry->GetLength();
1420 long offset = PreviousDocEntry->GetOffset();
1422 gdcmDebugMacro( "Backtrack :" << std::hex << group
1424 << " at offset 0x(" <<offset << ")" );
1425 RemoveEntry( PreviousDocEntry );
1427 // forge the Seq Entry
1428 DocEntry *newEntry = NewSeqEntry(group, elem);
1429 newEntry->SetLength(lgt);
1430 newEntry->SetOffset(offset);
1432 // Move back to the beginning of the Sequence
1434 Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1439 * \brief Loads (or not) the element content depending if its length exceeds
1440 * or not the value specified with Document::SetMaxSizeLoadEntry()
1441 * @param entry Header Entry (Dicom Element) to be dealt with
1442 * @param forceLoad whether you want to force loading of 'long' elements
1444 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1446 uint16_t group = entry->GetGroup();
1447 uint16_t elem = entry->GetElement();
1448 const VRKey &vr = entry->GetVR();
1449 uint32_t length = entry->GetLength();
1451 // Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1453 // A SeQuence "contains" a set of Elements.
1454 // (fffe e000) tells us an Element is beginning
1455 // (fffe e00d) tells us an Element just ended
1456 // (fffe e0dd) tells us the current SeQuence just ended
1457 // (fffe 0000) is an 'impossible' tag value,
1458 // found in MR-PHILIPS-16-Multi-Seq.dcm
1460 if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1462 // NO more value field for SQ !
1466 DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1472 // When the length is zero things are easy:
1475 dataEntryPtr->SetBinArea(NULL,true);
1479 // The elements whose length is bigger than the specified upper bound
1484 if (length > MaxSizeLoadEntry)
1486 dataEntryPtr->SetBinArea(NULL,true);
1487 dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1489 // to be sure we are at the end of the value ...
1490 // Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1491 // std::ios::beg); //JPRx
1496 /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1497 /// + a ForceLoad call on the +/- 20 'usefull' fields
1498 /// Allow user to tell the fields he wants to ForceLoad
1499 /// during initial stage.
1500 /// Later, a GetString or GetBinArea will load the value from disk, if not loaded
1501 /// + a method that load *everything* that's not yet loaded
1503 LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1507 * \brief Find the value Length of the passed Doc Entry
1508 * @param entry Header Entry whose length of the value shall be loaded.
1510 void Document::FindDocEntryLength( DocEntry *entry )
1511 throw ( FormatError )
1513 const VRKey &vr = entry->GetVR();
1515 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1520 // For some images, length of UN elements is coded on 2 bytes (instead of 4)
1521 // There are *not* readable !
1522 // You can make a quick and dirty patch, commenting out
1524 // in the following line.
1525 // (the 'straight' images will no longer be readable ...)
1527 if ( vr == "OB" || vr == "OW" || vr == "OL" || vr == "SQ" || vr == "UT"
1528 || vr == "UN" || changeFromUN == true)
1530 changeFromUN = false;
1531 // The following reserved two bytes (see PS 3.5-2003, section
1532 // "7.1.2 Data element structure with explicit vr", p 27) must be
1533 // skipped before proceeding on reading the length on 4 bytes.
1535 //Fp->seekg( 2L, std::ios::cur); // Once per OB,OW,OL,SQ DocEntry
1536 uint32_t length32 = ReadInt32(); // Once per Ob,OW,OL,SQ DocEntry
1537 CurrentOffsetPosition+=4;
1538 if ( (vr == "OB" || vr == "OW" || vr == "OL") && length32 == 0xffffffff )
1543 lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel
1545 catch ( FormatUnexpected )
1547 // Computing the length failed (this happens with broken
1548 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1549 // chance to get the pixels by deciding the element goes
1550 // until the end of the file. Hence we artificially fix the
1551 // the length and proceed.
1552 gdcmWarningMacro( " Computing the length failed for " <<
1553 entry->GetKey() <<" in " <<GetFileName());
1555 long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1556 Fp->seekg(0L,std::ios::end); // Only for gdcm-JPEG-LossLess3a.dcm-like
1558 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1559 Fp->seekg(currentPosition, std::ios::beg); // Only for gdcm-JPEG-LossLess3a.dcm-like
1561 entry->SetReadLength(lengthUntilEOF);
1562 entry->SetLength(lengthUntilEOF);
1565 entry->SetReadLength(lengthOB);
1566 entry->SetLength(lengthOB);
1569 FixDocEntryFoundLength(entry, length32);
1572 // Length is encoded on 2 bytes.
1573 //length16 = ReadInt16();
1574 length16 = GetInt16();
1575 // 0xffff means that we deal with 'No Length' Sequence
1576 // or 'No Length' SQItem
1577 if ( length16 == 0xffff)
1581 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1586 // Either implicit VR or a non DICOM conformal (see note below) explicit
1587 // VR that ommited the VR of (at least) this element. Farts happen.
1588 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1589 // on Data elements "Implicit and Explicit VR Data Elements shall
1590 // not coexist in a Data Set and Data Sets nested within it".]
1591 // Length is on 4 bytes.
1593 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1594 // even if Transfer Syntax is 'Implicit VR ...'
1595 // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private'
1596 // where Group 0x0002 is *also* encoded in Implicit VR !
1598 FixDocEntryFoundLength( entry, GetInt32() /*ReadInt32()*/ );
1604 * \brief Find the Length till the next sequence delimiter
1605 * \warning NOT end user intended method !
1608 uint32_t Document::FindDocEntryLengthOBOrOW()
1609 throw( FormatUnexpected )
1611 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1613 long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1615 bool foundSequenceDelimiter = false;
1616 uint32_t totalLength = 0;
1618 while ( !foundSequenceDelimiter )
1624 { ///\todo make sure there is never OL encoded pixel data!
1626 //group = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1627 //elem = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1628 ReadBegBuffer(4); // Once per fragment (if any) of OB,OW DataElements
1630 catch ( FormatError )
1632 throw FormatError("Unexpected end of file encountered during ",
1633 "Document::FindDocEntryLengthOBOrOW()");
1638 // We have to decount the group and element we just read
1640 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1643 "Neither an Item tag nor a Sequence delimiter tag on :"
1644 << std::hex << group << " , " << elem
1647 Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1648 throw FormatUnexpected(
1649 "Neither an Item tag nor a Sequence delimiter tag.");
1651 if ( elem == 0xe0dd )
1653 foundSequenceDelimiter = true;
1655 uint32_t itemLength = ReadInt32(); // Once per fragment (if any) of OB,OW DataElements
1656 // We add 4 bytes since we just read the ItemLength with ReadInt32
1657 totalLength += itemLength + 4;
1658 SkipBytes(itemLength);
1660 if ( foundSequenceDelimiter )
1665 Fp->seekg( positionOnEntry, std::ios::beg); // Only once for OB,OW DataElements
1670 * \brief Find the Value Representation of the current Dicom Element.
1671 * @return Value Representation of the current Entry
1673 VRKey Document::FindDocEntryVR()
1675 if ( Filetype != ExplicitVR )
1677 return GDCM_VRUNKNOWN;
1680 // Delimiters (0xfffe), are not explicit VR ...
1681 if ( CurrentGroup == 0xfffe )
1682 return GDCM_VRUNKNOWN;
1684 //long positionOnEntry;
1685 //if( Debug::GetWarningFlag() )
1686 // positionOnEntry = Fp->tellg(); // Only in Warning Mode
1688 // Warning: we believe this is explicit VR (Value Representation) because
1689 // we used a heuristic that found "UL" in the first tag and/or
1690 // 'Transfer Syntax' told us it is.
1691 // Alas this doesn't guarantee that all the tags will be in explicit VR.
1692 // In some cases one finds implicit VR tags mixed within an explicit VR file
1694 // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1696 // Hence we make sure the present tag is in explicit VR and try to fix things
1697 // if it happens not to be the case.
1700 //Fp->read(&(vr[0]),(size_t)2);
1701 vr[0] = *PtrBegBuffer++;
1702 vr[1] = *PtrBegBuffer++;
1704 //if ( !CheckDocEntryVR(vr) ) // avoid useless function call
1705 if ( !Global::GetVR()->IsValidVR(vr) )
1708 // std::cout << "================================================================Unknown VR"
1709 << std::hex << "0x("
1710 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1711 << ")" << "for : " << CurrentGroup
1712 << " at offset : 0x(" << positionOnEntry << ")"
1715 gdcmWarningMacro( "Unknown VR " << std::hex << "0x("
1716 << (unsigned int)vr[0] << "|" << (unsigned int)vr[1]
1718 << " at offset : 0x(" << CurrentOffsetPosition-4<< ") for group " << CurrentGroup
1721 //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1722 //Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?)
1723 //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1725 return GDCM_VRUNKNOWN;
1731 * \brief Check the correspondance between the VR of the header entry
1732 * and the taken VR. If they are different, the header entry is
1733 * updated with the new VR.
1734 * @param vr Dicom Value Representation
1735 * @return false if the VR is incorrect or if the VR isn't referenced
1736 * otherwise, it returns true
1738 bool Document::CheckDocEntryVR(const VRKey &vr)
1740 return Global::GetVR()->IsValidVR(vr);
1744 * \brief Skip a given Header Entry
1745 * @param entry entry to skip
1747 void Document::SkipDocEntry(DocEntry *entry)
1749 SkipBytes(entry->GetLength());
1753 * \brief Skips to the beginning of the next Header Entry
1754 * @param currentDocEntry entry to skip
1756 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1758 long l = currentDocEntry->GetReadLength();
1759 if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1760 // ... but PMS imagers happen !
1762 Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1763 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1765 Fp->seekg( l,std::ios::cur); //FIXME :each DocEntry
1770 * \brief When the length of an element value is obviously wrong (because
1771 * the parser went Jabberwocky) one can hope improving things by
1772 * applying some heuristics.
1773 * @param entry entry to check
1774 * @param foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)
1776 void Document::FixDocEntryFoundLength(DocEntry *entry,
1777 uint32_t foundLength)
1779 entry->SetReadLength( foundLength );// will be updated only if a bug is found
1781 if ( foundLength == 0xffffffff)
1784 //entry->SetLength(foundLength);
1785 entry->SetLength(0);
1786 return; // return ASAP; don't waist time on useless tests
1789 uint16_t gr = entry->GetGroup();
1790 uint16_t elem = entry->GetElement();
1792 if ( foundLength % 2)
1794 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1795 << " in x(" << std::hex << gr << "," << elem <<")");
1798 //////// Fix for some naughty General Electric images.
1799 // Allthough not recent many such GE corrupted images are still present
1800 // on Creatis hard disks. Hence this fix shall remain when such images
1801 // are no longer in use (we are talking a few years, here)...
1802 // Note: XMedCon probably uses such a trick since it is able to read
1803 // those pesky GE images ...
1804 if ( foundLength == 13)
1806 // Only happens for this length !
1807 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1810 entry->SetReadLength(10); // a bug is to be fixed !?
1814 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1815 // Occurence of such images is quite low (unless one leaves close to a
1816 // 'Leonardo' source. Hence, one might consider commenting out the
1817 // following fix on efficiency reasons.
1818 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1820 // Ideally we should check we are in Explicit and double check
1821 // that VR=UL... this is done properly in gdcm2
1822 if( foundLength == 6 )
1824 gdcmWarningMacro( "Replacing Length from 6 into 4" );
1826 entry->SetReadLength(4); // a bug is to be fixed !
1828 else if ( foundLength%4 )
1830 gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1831 "The length of this tag seems to be wrong" );
1835 else if ( entry->GetVR() == "SQ" )
1837 foundLength = 0; // ReadLength is unchanged
1840 //////// We encountered a 'delimiter' element i.e. a tag of the form
1841 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1842 // taken into account.
1843 else if ( gr == 0xfffe )
1845 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1846 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1847 // causes extra troubles...
1848 if ( elem != 0x0000 )
1854 foundLength=12; // to skip the mess that follows this bugged Tag !
1857 entry->SetLength(foundLength);
1861 * \brief Apply some heuristics to predict whether the considered
1862 * element value contains/represents an integer or not.
1863 * @param entry The element value on which to apply the predicate.
1864 * @return The result of the heuristical predicate.
1866 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1868 uint16_t elem = entry->GetElement();
1869 uint16_t group = entry->GetGroup();
1870 const VRKey &vr = entry->GetVR();
1871 uint32_t length = entry->GetLength();
1873 // When we have some semantics on the element we just read, and if we
1874 // a priori know we are dealing with an integer, then we shall be
1875 // able to swap its element value properly.
1876 if ( elem == 0 ) // This is the group length of the group
1884 // Although this should never happen, still some images have a
1885 // corrupted group length [e.g. have a glance at offset x(8336) of
1886 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1887 // Since for dicom compliant and well behaved headers, the present
1888 // test is useless (and might even look a bit paranoid), when we
1889 // encounter such an ill-formed image, we simply display a warning
1890 // message and proceed on parsing (while crossing fingers).
1891 long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1893 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1894 << std::hex << group << " , " << elem
1895 << ") -before- position x(" << filePosition << ")"
1896 << "lgt : " << length );
1900 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1908 * \brief Discover what the swap code is (among little endian, big endian,
1909 * bad little endian, bad big endian).
1911 * @return false when we are absolutely sure
1912 * it's neither ACR-NEMA nor DICOM
1913 * true when we hope ours assuptions are OK
1915 bool Document::CheckSwap()
1922 // First, compare HostByteOrder and NetworkByteOrder in order to
1923 // determine if we shall need to swap bytes (i.e. the Endian type).
1924 bool net2host = Util::IsCurrentProcessorBigEndian();
1926 // The easiest case is the one of a 'true' DICOM header, we just have
1927 // to look for the string "DICM" inside the file preamble.
1930 char *entCur = deb + 128;
1931 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1933 gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1935 // Group 0002 should always be VR, and the first element 0000
1936 // Let's be carefull (so many wrong headers ...)
1937 // and determine the value representation (VR) :
1938 // Let's skip to the first element (0002,0000) and check there if we find
1939 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1940 // in which case we (almost) know it is explicit VR.
1941 // WARNING: if it happens to be implicit VR then what we will read
1942 // is the length of the group. If this ascii representation of this
1943 // length happens to be "UL" then we shall believe it is explicit VR.
1944 // We need to skip :
1945 // * the 128 bytes of File Preamble (often padded with zeroes),
1946 // * the 4 bytes of "DICM" string,
1947 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1948 // i.e. a total of 136 bytes.
1951 // group 0x0002 *is always* Explicit VR Sometimes,
1952 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1953 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1955 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1956 memcmp(entCur, "OB", (size_t)2) == 0 ||
1957 memcmp(entCur, "UI", (size_t)2) == 0 ||
1958 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1959 // when Write DCM *adds*
1961 // Use Document::dicom_vr to test all the possibilities
1962 // instead of just checking for UL, OB and UI !? group 0000
1964 Filetype = ExplicitVR;
1965 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1969 Filetype = ImplicitVR;
1970 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1971 << "Looks like a bugged Header!");
1974 // Here, we assume that the file IS kosher Dicom !
1975 // (The meta elements - group 0x0002 - ARE little endian !)
1979 gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1984 gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1987 // Position the file position indicator at first tag
1988 // (i.e. after the file preamble and the "DICM" string).
1990 Fp->seekg ( 132L, std::ios::beg); // Once per Document
1991 CurrentOffsetPosition = 132;
1993 } // ------------------------------- End of DicomV3 ----------------
1995 // Alas, this is not a DicomV3 file and whatever happens there is no file
1996 // preamble. We can reset the file position indicator to where the data
1997 // is (i.e. the beginning of the file).
1999 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
2001 Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
2002 CurrentOffsetPosition = 0;
2003 // Let's check 'No Preamble Dicom File' :
2004 // Should start with group 0x0002
2005 // and be Explicit Value Representation
2007 s16 = *((uint16_t *)(deb));
2020 if ( SwapCode != 0 )
2022 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2023 memcmp(entCur, "OB", (size_t)2) == 0 ||
2024 memcmp(entCur, "UI", (size_t)2) == 0 ||
2025 memcmp(entCur, "SH", (size_t)2) == 0 ||
2026 memcmp(entCur, "AE", (size_t)2) == 0 ||
2027 memcmp(entCur, "OB", (size_t)2) == 0 )
2029 Filetype = ExplicitVR; // FIXME : not enough to say it's Explicit
2030 // Wait untill reading Transfer Syntax
2031 gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
2035 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2037 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2038 // By clean we mean that the length of the first group is written down.
2039 // If this is the case and since the length of the first group HAS to be
2040 // four (bytes), then determining the proper swap code is straightforward.
2043 // We assume the array of char we are considering contains the binary
2044 // representation of a 32 bits integer. Hence the following dirty
2046 s32 = *((uint32_t *)(entCur));
2066 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2067 // It is time for despaired wild guesses.
2068 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2069 // i.e. the 'group length' element is not present :
2071 // check the supposed-to-be 'group number'
2072 // in ( 0x0001 .. 0x0008 )
2073 // to determine ' SwapCode' value .
2074 // Only 0 or 4321 will be possible
2075 // (no oportunity to check for the formerly well known
2076 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2077 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
2078 // the file IS NOT ACR-NEMA nor DICOM V3
2079 // Find a trick to tell it the caller...
2081 s16 = *((uint16_t *)(deb));
2083 gdcmDebugMacro("not a DicomV3 nor a 'clean' ACR/NEMA;"
2084 << " (->despaired wild guesses !)");
2113 s16 = *((uint16_t *)(deb));
2116 s16 = *((uint16_t *)(deb+2));
2118 Fp->seekg ( 0L, std::ios::beg); // Once per Document
2119 CurrentOffsetPosition = 0;
2120 switch(s16) // try an other trick!
2121 // -> to be able to decode 0029|1010 DataElement
2122 // -> and be not less cleaver than dcmdump ;-)
2131 gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2135 // Check if next 2 bytes are a VR
2136 // Probabely something more time-consuming exists with std::string
2137 const char VRvalues[] = "AEASATCSDADTFLFDISLOLTPNSHSLSSSTTMUIULUSUTOBOWOLOFATUNSQRT";
2139 const char *pt = VRvalues;
2140 for (int i=0;i<nbVal;i++)
2142 if(*(deb+4) == *pt++) {
2143 if(*(deb+5) == *pt++) {
2144 Filetype = ExplicitVR;
2152 Filetype = ImplicitVR;
2159 * \brief Change the Byte Swap code.
2161 void Document::SwitchByteSwapCode()
2163 gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2164 << " at: 0x" << std::hex << Fp->tellg() ); // Only when DEBUG
2165 if ( SwapCode == 1234 )
2169 else if ( SwapCode == 4321 )
2173 else if ( SwapCode == 3412 )
2177 else if ( SwapCode == 2143 )
2181 gdcmDebugMacro( " Into: "<< SwapCode );
2185 * \brief during parsing, Header Elements too long are not loaded in memory
2186 * @param newSize new size
2188 void Document::SetMaxSizeLoadEntry(long newSize)
2194 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2196 MaxSizeLoadEntry = 0xffffffff;
2199 MaxSizeLoadEntry = newSize;
2203 * \brief Read the next tag WITHOUT loading it's value
2204 * (read the 'Group Number', the 'Element Number',
2205 * gets the Dict Entry
2206 * gets the VR, gets the length, gets the offset value)
2207 * @return On succes : the newly created DocEntry, NULL on failure.
2209 DocEntry *Document::ReadNextDocEntry()
2213 ReadBegBuffer(8); // Avoid to many time consuming freads
2214 //CurrentGroup = ReadInt16();
2215 //CurrentElem = ReadInt16();
2217 catch ( FormatError )
2219 // We reached the EOF (or an error occured) therefore
2220 // header parsing has to be considered as finished.
2224 changeFromUN = false;
2225 CurrentGroup = GetInt16();
2226 CurrentElem = GetInt16();
2228 // In 'true DICOM' files Group 0002 is always little endian
2229 if ( HasDCMPreamble )
2231 if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2232 HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2234 // Sometimes file contains groups of tags with reversed endianess.
2235 HandleBrokenEndian(CurrentGroup, CurrentElem);
2238 VRKey vr = FindDocEntryVR();
2241 if ( vr == GDCM_VRUNKNOWN )
2243 if ( CurrentElem == 0x0000 ) // Group Length
2245 realVR = "UL"; // must be UL
2247 else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2252 // Was commented out in order not to generate 'Shadow Groups' where some
2253 // Data Elements are Explicit VR and some other ones Implicit VR
2254 // -> Better we fix the problem at Write time
2256 else if (CurrentGroup%2 == 1 )
2258 if (CurrentElem >= 0x0010 && CurrentElem <=0x00ff )
2260 // DICOM PS 3-5 7.8.1 a) states that :
2261 // Private Creator Data Elements numbered (gggg,0010-00FF) (gggg is odd)
2262 // attributes have to be LO (Long String) and the VM shall be equal to 1
2265 // Seems not to be true
2266 // Still in gdcmtk, David Clunnie disagrees, Marco Eichelberg says it's OK ...
2267 // We let it for a while?
2268 //(We should check length==4, for more security, but we don't have it yet !)
2270 else if ( CurrentElem == 0x0001)
2272 realVR = "UL"; // Private Group Length To Eng
2274 else // check the private dictionary for shadow elements when Implicit VR!
2276 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2279 realVR = dictEntry->GetVR();
2280 dictEntry->Unregister(); // GetDictEntry registered it
2287 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2290 realVR = dictEntry->GetVR();
2291 dictEntry->Unregister(); // GetDictEntry registered it
2296 // if UN found, let's check the dictionary, and trust it!
2297 // (maybe a private dictionary exists?)
2298 else if (vr == "UN")
2300 DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);
2303 realVR = dictEntry->GetVR();
2304 dictEntry->Unregister(); // GetDictEntry registered it
2306 // for VR = "UN", length is always stored on 4 bytes.
2308 /// \todo : fixme If inside a supposed to be UN DataElement (but SQ according to a private dictionnary)
2309 /// there is some more supposed to be UN DataElements, it will probabely fail.
2310 /// --> find a -non time consuming- trick to store changeFromUN info at DataElement level,
2311 /// not at the Document level.
2316 //if ( Global::GetVR()->IsVROfSequence(realVR) )
2319 newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2323 newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2324 static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2327 if ( vr == GDCM_VRUNKNOWN )
2329 if ( Filetype == ExplicitVR )
2331 // We thought this was explicit VR, but we end up with an
2332 // implicit VR tag. Let's backtrack.
2334 //if ( newEntry->GetGroup() != 0xfffe )
2335 if (CurrentGroup != 0xfffe)
2337 int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2339 gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2340 << offset << ") should be Explicit VR");
2343 newEntry->SetImplicitVR();
2348 FindDocEntryLength(newEntry);
2350 catch ( FormatError )
2357 newEntry->SetOffset(Fp->tellg()); // for each DocEntry
2362 * \brief Handle broken private tag from Philips NTSCAN
2363 * where the endianess is being switched to BigEndian
2364 * for no apparent reason
2367 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2369 // for strange PMS Gyroscan Intera images
2370 // Item 'starter' has a tag : 0x3f3f,0x3f00, for no apparent reason
2372 // --- Feel free to remove this test *on your own coy of gdcm*
2373 // if you are sure you'll never face this problem.
2375 if ((group == 0x3f3f) && (elem == 0x3f00))
2377 // start endian swap mark for group found
2378 gdcmDebugMacro( " delimiter 0x3f3f found." );
2384 // --- End of removable code
2386 // Endian reversion.
2387 // Some files contain groups of tags with reversed endianess.
2388 static int reversedEndian = 0;
2389 // try to fix endian switching in the middle of headers
2390 if ((group == 0xfeff) && (elem == 0x00e0))
2392 // start endian swap mark for group found
2393 gdcmDebugMacro( "Start endian swap mark found." );
2395 SwitchByteSwapCode();
2400 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2402 // end of reversed endian group
2403 gdcmDebugMacro( "End of reversed endian." );
2405 SwitchByteSwapCode();
2407 else if (group == 0xfeff && elem == 0xdde0)
2409 // reversed Sequence Terminator found
2410 // probabely a bug in the header !
2411 // Do what you want, it breaks !
2413 //SwitchByteSwapCode();
2414 gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2419 else if (group == 0xfffe && elem == 0xe0dd)
2421 gdcmDebugMacro( "Straight Sequence Terminator." );
2426 * \brief Group 0002 is always coded Little Endian
2427 * whatever Transfer Syntax is
2430 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2432 // Endian reversion.
2433 // Some files contain groups of tags with reversed endianess.
2435 Group0002Parsed = true;
2436 // we just came out of group 0002
2437 // if Transfer Syntax is Big Endian we have to change CheckSwap
2439 std::string ts = GetTransferSyntax();
2440 TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2442 // Group 0002 is always 'Explicit ...'
2443 // even when Transfer Syntax says 'Implicit ..."
2445 if ( s == TS::ImplicitVRLittleEndian
2447 s == TS::ImplicitVRBigEndianPrivateGE
2450 Filetype = ImplicitVR;
2453 // FIXME Strangely, this works with
2454 //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2456 // --> Probabely normal, since we considered we never have
2457 // to trust manufacturers.
2458 // (we often find 'Implicit VR' tag,
2459 // even when Transfer Syntax tells us it's Explicit ...
2461 // NEVER trust the meta elements!
2462 // (see what ezDICOM does ...)
2465 if ( s == TS::ExplicitVRBigEndian )
2467 gdcmDebugMacro("Transfer Syntax Name = ["
2468 << GetTransferSyntaxName() << "]" );
2469 SwitchByteSwapCode();
2470 group = SwapShort(group);
2471 elem = SwapShort(elem);
2474 //-- Broken ACR may start with a Shadow Group --
2475 // worse : some ACR-NEMA like files start 00028 group ?!?
2476 if ( !( (group >= 0x0001 && group <= 0x0008) || group == 0x0028 ) )
2478 // We trust what we see.
2479 SwitchByteSwapCode();
2480 group = SwapShort(group);
2481 elem = SwapShort(elem);
2482 // not what we where told (by meta elements) !
2483 gdcmDebugMacro("Transfer Syntax Name = ["
2484 << GetTransferSyntaxName() << "]" );
2487 /// \todo find a trick to warn user and stop processing
2489 if ( s == TS::DeflatedExplicitVRLittleEndian)
2491 gdcmWarningMacro("Transfer Syntax ["
2492 << GetTransferSyntaxName() << "] :"
2493 << " not yet dealt with ");
2497 // The following shouldn't occur very often
2498 // Let's check at the very end.
2500 if ( ts == GDCM_UNKNOWN )
2502 gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2506 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2508 gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: ["
2514 //-----------------------------------------------------------------------------
2517 //-----------------------------------------------------------------------------
2518 } // end namespace gdcm