1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/26 11:42:02 $
7 Version: $Revision: 1.212 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmRLEFramesInfo.h"
29 #include "gdcmJPEGFragmentsInfo.h"
30 #include "gdcmDocEntrySet.h"
31 #include "gdcmSQItem.h"
37 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
41 #ifdef CMAKE_HAVE_NETINET_IN_H
42 #include <netinet/in.h>
48 //-----------------------------------------------------------------------------
49 // Refer to Document::CheckSwap()
50 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
52 // Refer to Document::SetMaxSizeLoadEntry()
53 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
54 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
56 //-----------------------------------------------------------------------------
57 // Constructor / Destructor
61 * @param filename 'Document' (File or DicomDir) to be opened for parsing
63 Document::Document( std::string const &filename ) : ElementSet(-1)
68 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
78 Group0002Parsed = false;
80 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
81 // Fp->seekg( 0, std::ios::beg);
83 Fp->seekg(0, std::ios::end);
84 long lgt = Fp->tellg();
86 Fp->seekg( 0, std::ios::beg);
89 long beg = Fp->tellg();
92 ParseDES( this, beg, lgt, false); // Loading is done during parsing
94 Fp->seekg( 0, std::ios::beg);
96 // Load 'non string' values
98 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
99 if( PhotometricInterpretation == "PALETTE COLOR " )
101 LoadEntryBinArea(0x0028,0x1200); // gray LUT
102 /// FIXME FIXME FIXME
103 /// The tags refered by the three following lines used to be CORRECTLY
104 /// defined as having an US Value Representation in the public
105 /// dictionary. BUT the semantics implied by the three following
106 /// lines state that the corresponding tag contents are in fact
107 /// the ones of a BinEntry.
108 /// In order to fix things "Quick and Dirty" the dictionary was
109 /// altered on PURPOSE but now contains a WRONG value.
110 /// In order to fix things and restore the dictionary to its
111 /// correct value, one needs to decided of the semantics by deciding
112 /// whether the following tags are either:
113 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
114 /// also used as BinEntry, which requires the proper conversion,
115 /// - OW, and hence loaded as BinEntry, but afterwards also used
116 /// as ValEntry, which requires the proper conversion.
117 LoadEntryBinArea(0x0028,0x1201); // R LUT
118 LoadEntryBinArea(0x0028,0x1202); // G LUT
119 LoadEntryBinArea(0x0028,0x1203); // B LUT
121 // Segmented Red Palette Color LUT Data
122 LoadEntryBinArea(0x0028,0x1221);
123 // Segmented Green Palette Color LUT Data
124 LoadEntryBinArea(0x0028,0x1222);
125 // Segmented Blue Palette Color LUT Data
126 LoadEntryBinArea(0x0028,0x1223);
128 //FIXME later : how to use it?
129 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
133 // --------------------------------------------------------------
134 // Specific code to allow gdcm to read ACR-LibIDO formated images
135 // Note: ACR-LibIDO is an extension of the ACR standard that was
136 // used at CREATIS. For the time being (say a couple years)
137 // we keep this kludge to allow a smooth move to gdcm for
138 // CREATIS developpers (sorry folks).
140 // if recognition code tells us we deal with a LibIDO image
141 // we switch lineNumber and columnNumber
144 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
145 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
146 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
147 // with "little-endian strings"
149 Filetype = ACR_LIBIDO;
150 std::string rows = GetEntryValue(0x0028, 0x0010);
151 std::string columns = GetEntryValue(0x0028, 0x0011);
152 SetValEntry(columns, 0x0028, 0x0010);
153 SetValEntry(rows , 0x0028, 0x0011);
155 // ----------------- End of ACR-LibIDO kludge ------------------
159 * \brief This default constructor doesn't parse the file. You should
160 * then invoke \ref Document::SetFileName and then the parsing.
162 Document::Document() : ElementSet(-1)
169 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
172 Filetype = ExplicitVR;
173 Group0002Parsed = false;
177 * \brief Canonical destructor.
179 Document::~Document ()
190 //-----------------------------------------------------------------------------
194 * \brief Prints The Dict Entries of THE public Dicom Dictionary
195 * @param os ostream to print to
198 void Document::PrintPubDict(std::ostream &os)
200 RefPubDict->SetPrintLevel(PrintLevel);
201 RefPubDict->Print(os);
205 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
206 * @param os ostream to print to
209 void Document::PrintShaDict(std::ostream &os)
211 RefShaDict->SetPrintLevel(PrintLevel);
212 RefShaDict->Print(os);
215 //-----------------------------------------------------------------------------
218 * \brief Get the public dictionary used
220 Dict *Document::GetPubDict()
226 * \brief Get the shadow dictionary used
228 Dict *Document::GetShaDict()
234 * \brief Set the shadow dictionary used
235 * @param dict dictionary to use in shadow
237 bool Document::SetShaDict(Dict *dict)
244 * \brief Set the shadow dictionary used
245 * @param dictName name of the dictionary to use in shadow
247 bool Document::SetShaDict(DictKey const &dictName)
249 RefShaDict = Global::GetDicts()->GetDict(dictName);
254 * \brief This predicate, based on hopefully reasonable heuristics,
255 * decides whether or not the current Document was properly parsed
256 * and contains the mandatory information for being considered as
257 * a well formed and usable Dicom/Acr File.
258 * @return true when Document is the one of a reasonable Dicom/Acr file,
261 bool Document::IsReadable()
263 if( Filetype == Unknown)
265 gdcmVerboseMacro( "Wrong filetype");
271 gdcmVerboseMacro( "No tag in internal hash table.");
279 * \brief Accessor to the Transfer Syntax (when present) of the
280 * current document (it internally handles reading the
281 * value from disk when only parsing occured).
282 * @return The encountered Transfer Syntax of the current document.
284 std::string Document::GetTransferSyntax()
286 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
292 // The entry might be present but not loaded (parsing and loading
293 // happen at different stages): try loading and proceed with check...
294 LoadDocEntrySafe(entry);
295 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
297 std::string transfer = valEntry->GetValue();
298 // The actual transfer (as read from disk) might be padded. We
299 // first need to remove the potential padding. We can make the
300 // weak assumption that padding was not executed with digits...
301 if ( transfer.length() == 0 )
303 // for brain damaged headers
306 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
308 transfer.erase(transfer.length()-1, 1);
316 * \brief Predicate for dicom version 3 file.
317 * @return True when the file is a dicom version 3.
319 bool Document::IsDicomV3()
321 // Checking if Transfer Syntax exists is enough
322 // Anyway, it's to late check if the 'Preamble' was found ...
323 // And ... would it be a rich idea to check ?
324 // (some 'no Preamble' DICOM images exist !)
325 return GetDocEntry(0x0002, 0x0010) != NULL;
329 * \brief Predicate for Papyrus file
330 * Dedicated to whomsoever it may concern
331 * @return True when the file is a Papyrus file.
333 bool Document::IsPapyrus()
335 // check for Papyrus private Sequence
336 DocEntry *e = GetDocEntry(0x0041, 0x1050);
339 // check if it's actually a Sequence
340 if ( !dynamic_cast<SeqEntry*>(e) )
346 * \brief returns the File Type
347 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
348 * @return the FileType code
350 FileType Document::GetFileType()
356 * \brief Tries to open the file \ref Document::Filename and
357 * checks the preamble when existing.
358 * @return The FILE pointer on success.
360 std::ifstream *Document::OpenFile()
363 HasDCMPreamble = false;
364 if (Filename.length() == 0)
371 gdcmVerboseMacro( "File already open: " << Filename.c_str());
374 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
377 gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
384 Fp->read((char*)&zero, (size_t)2);
391 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
393 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
394 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
395 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
396 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
399 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
400 gdcmVerboseMacro( msg.c_str() );
405 Fp->seekg(126L, std::ios::cur);
407 Fp->read(dicm, (size_t)4);
413 if( memcmp(dicm, "DICM", 4) == 0 )
415 HasDCMPreamble = true;
420 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
426 * \brief closes the file
427 * @return TRUE if the close was successfull
429 bool Document::CloseFile()
437 return true; //FIXME how do we detect a non-closed ifstream ?
441 * \brief Writes in a file all the Header Entries (Dicom Elements)
442 * @param fp file pointer on an already open file (actually: Output File Stream)
443 * @param filetype Type of the File to be written
444 * (ACR-NEMA, ExplicitVR, ImplicitVR)
445 * @return Always true.
447 void Document::WriteContent(std::ofstream *fp, FileType filetype)
449 // \TODO move the following lines (and a lot of others, to be written)
450 // to a future function CheckAndCorrectHeader
452 // (necessary if user wants to write a DICOM V3 file
453 // starting from an ACR-NEMA (V2) Header
455 if ( filetype == ImplicitVR || filetype == ExplicitVR )
457 // writing Dicom File Preamble
458 char filePreamble[128];
459 memset(filePreamble, 0, 128);
460 fp->write(filePreamble, 128);
461 fp->write("DICM", 4);
465 * \todo rewrite later, if really usefull
466 * - 'Group Length' element is optional in DICOM
467 * - but un-updated odd groups lengthes can causes pb
470 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
471 * UpdateGroupLength(false,filetype);
472 * if ( filetype == ACR)
473 * UpdateGroupLength(true,ACR);
476 ElementSet::WriteContent(fp, filetype); // This one is recursive
479 //-----------------------------------------------------------------------------
482 * \brief Loads (from disk) the element content
483 * when a string is not suitable
484 * @param group group number of the Entry
485 * @param elem element number of the Entry
487 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
489 // Search the corresponding DocEntry
490 DocEntry *docElement = GetDocEntry(group, elem);
494 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
498 LoadEntryBinArea(binElement);
502 * \brief Loads (from disk) the element content
503 * when a string is not suitable
504 * @param elem Entry whose binArea is going to be loaded
506 void Document::LoadEntryBinArea(BinEntry *elem)
508 if(elem->GetBinArea())
515 size_t o =(size_t)elem->GetOffset();
516 Fp->seekg(o, std::ios::beg);
518 size_t l = elem->GetLength();
519 uint8_t *a = new uint8_t[l];
522 gdcmVerboseMacro( "Cannot allocate BinEntry content");
526 /// \todo check the result
527 Fp->read((char*)a, l);
528 if( Fp->fail() || Fp->eof())
541 * \brief Sets a 'non string' value to a given Dicom Element
542 * @param area area containing the 'non string' value
543 * @param group Group number of the searched Dicom Element
544 * @param elem Element number of the searched Dicom Element
547 /*bool Document::SetEntryBinArea(uint8_t *area,
548 uint16_t group, uint16_t elem)
550 DocEntry *currentEntry = GetDocEntry(group, elem);
556 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
558 binEntry->SetBinArea( area );
567 * \brief Loads the element while preserving the current
568 * underlying file position indicator as opposed to
569 * LoadDocEntry that modifies it.
570 * @param entry Header Entry whose value will be loaded.
573 void Document::LoadDocEntrySafe(DocEntry *entry)
577 long PositionOnEntry = Fp->tellg();
579 Fp->seekg(PositionOnEntry, std::ios::beg);
584 * \brief Swaps back the bytes of 4-byte long integer accordingly to
586 * @return The properly swaped 32 bits integer.
588 uint32_t Document::SwapLong(uint32_t a)
595 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
596 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
599 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
602 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
605 gdcmErrorMacro( "Unset swap code:" << SwapCode );
612 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
614 * @return The properly unswaped 32 bits integer.
616 uint32_t Document::UnswapLong(uint32_t a)
622 * \brief Swaps the bytes so they agree with the processor order
623 * @return The properly swaped 16 bits integer.
625 uint16_t Document::SwapShort(uint16_t a)
627 if ( SwapCode == 4321 || SwapCode == 2143 )
629 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
635 * \brief Unswaps the bytes so they agree with the processor order
636 * @return The properly unswaped 16 bits integer.
638 uint16_t Document::UnswapShort(uint16_t a)
643 //-----------------------------------------------------------------------------
647 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
648 * @return length of the parsed set.
650 void Document::ParseDES(DocEntrySet *set, long offset,
651 long l_max, bool delim_mode)
653 DocEntry *newDocEntry = 0;
654 ValEntry *newValEntry;
655 BinEntry *newBinEntry;
656 SeqEntry *newSeqEntry;
662 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
668 newDocEntry = ReadNextDocEntry( );
675 vr = newDocEntry->GetVR();
676 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
677 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
678 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
680 if ( newValEntry || newBinEntry )
684 if ( Filetype == ExplicitVR &&
685 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
687 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
688 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup()
689 << "|" << newDocEntry->GetElement()
690 << " : Neither Valentry, nor BinEntry."
691 "Probably unknown VR.");
694 //////////////////// BinEntry or UNKOWN VR:
695 // When "this" is a Document the Key is simply of the
696 // form ( group, elem )...
697 if ( dynamic_cast< Document* > ( set ) )
699 newBinEntry->SetKey( newBinEntry->GetKey() );
701 // but when "this" is a SQItem, we are inserting this new
702 // valEntry in a sequence item, and the key has the
703 // generalized form (refer to \ref BaseTagKey):
704 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
706 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
707 + newBinEntry->GetKey() );
710 LoadDocEntry( newBinEntry );
711 if( !set->AddEntry( newBinEntry ) )
713 //Expect big troubles if here
714 //delete newBinEntry;
720 /////////////////////// ValEntry
721 // When "set" is a Document, then we are at the top of the
722 // hierarchy and the Key is simply of the form ( group, elem )...
723 if ( dynamic_cast< Document* > ( set ) )
725 newValEntry->SetKey( newValEntry->GetKey() );
727 // ...but when "set" is a SQItem, we are inserting this new
728 // valEntry in a sequence item. Hence the key has the
729 // generalized form (refer to \ref BaseTagKey):
730 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
732 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
733 + newValEntry->GetKey() );
736 LoadDocEntry( newValEntry );
737 bool delimitor=newValEntry->IsItemDelimitor();
738 if( !set->AddEntry( newValEntry ) )
740 // If here expect big troubles
741 //delete newValEntry; //otherwise mem leak
751 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
759 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
760 && ( newDocEntry->GetElement() == 0x0010 ) )
762 std::string ts = GetTransferSyntax();
763 if ( Global::GetTS()->IsRLELossless(ts) )
765 long positionOnEntry = Fp->tellg();
766 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
768 Fp->seekg( positionOnEntry, std::ios::beg );
770 else if ( Global::GetTS()->IsJPEG(ts) )
772 long positionOnEntry = Fp->tellg();
773 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
774 ComputeJPEGFragmentInfo();
775 Fp->seekg( positionOnEntry, std::ios::beg );
779 // Just to make sure we are at the beginning of next entry.
780 SkipToNextDocEntry(newDocEntry);
785 unsigned long l = newDocEntry->GetReadLength();
786 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
788 if ( l == 0xffffffff )
797 // no other way to create it ...
798 newSeqEntry->SetDelimitorMode( delim_mode );
800 // At the top of the hierarchy, stands a Document. When "set"
801 // is a Document, then we are building the first depth level.
802 // Hence the SeqEntry we are building simply has a depth
804 if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
807 newSeqEntry->SetDepthLevel( 1 );
808 newSeqEntry->SetKey( newSeqEntry->GetKey() );
810 // But when "set" is already a SQItem, we are building a nested
811 // sequence, and hence the depth level of the new SeqEntry
812 // we are building, is one level deeper:
813 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
815 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
816 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
817 + newSeqEntry->GetKey() );
821 { // Don't try to parse zero-length sequences
822 ParseSQ( newSeqEntry,
823 newDocEntry->GetOffset(),
826 if( !set->AddEntry( newSeqEntry ) )
830 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
844 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
845 * @return parsed length for this level
847 void Document::ParseSQ( SeqEntry *seqEntry,
848 long offset, long l_max, bool delim_mode)
850 int SQItemNumber = 0;
852 long offsetStartCurrentSQItem = offset;
856 // the first time, we read the fff0,e000 of the first SQItem
857 DocEntry *newDocEntry = ReadNextDocEntry();
861 // FIXME Should warn user
866 if ( newDocEntry->IsSequenceDelimitor() )
868 seqEntry->SetDelimitationItem( newDocEntry );
872 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
877 // create the current SQItem
878 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
879 std::ostringstream newBase;
880 newBase << seqEntry->GetKey()
884 itemSQ->SetBaseTagKey( newBase.str() );
885 unsigned int l = newDocEntry->GetReadLength();
887 if ( l == 0xffffffff )
896 // when we're here, element fffe,e000 is already passed.
897 // it's lost for the SQItem we're going to process !!
899 //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
900 //delete newDocEntry; // FIXME well ... it's too late to use it !
902 // Let's try :------------
903 // remove fff0,e000, created out of the SQItem
905 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
906 // fill up the current SQItem, starting at the beginning of fff0,e000
907 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
908 offsetStartCurrentSQItem = Fp->tellg();
909 // end try -----------------
911 seqEntry->AddSQItem( itemSQ, SQItemNumber );
913 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
921 * \brief Loads the element content if its length doesn't exceed
922 * the value specified with Document::SetMaxSizeLoadEntry()
923 * @param entry Header Entry (Dicom Element) to be dealt with
925 void Document::LoadDocEntry(DocEntry *entry)
927 uint16_t group = entry->GetGroup();
928 std::string vr = entry->GetVR();
929 uint32_t length = entry->GetLength();
931 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
933 // A SeQuence "contains" a set of Elements.
934 // (fffe e000) tells us an Element is beginning
935 // (fffe e00d) tells us an Element just ended
936 // (fffe e0dd) tells us the current SeQuence just ended
937 if( group == 0xfffe )
939 // NO more value field for SQ !
943 // When the length is zero things are easy:
946 ((ValEntry *)entry)->SetValue("");
950 // The elements whose length is bigger than the specified upper bound
951 // are not loaded. Instead we leave a short notice of the offset of
952 // the element content and it's length.
954 std::ostringstream s;
955 if (length > MaxSizeLoadEntry)
957 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
959 //s << "gdcm::NotLoaded (BinEntry)";
961 s << " Address:" << (long)entry->GetOffset();
962 s << " Length:" << entry->GetLength();
963 s << " x(" << std::hex << entry->GetLength() << ")";
964 binEntryPtr->SetValue(s.str());
966 // Be carefull : a BinEntry IS_A ValEntry ...
967 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
969 // s << "gdcm::NotLoaded. (ValEntry)";
971 s << " Address:" << (long)entry->GetOffset();
972 s << " Length:" << entry->GetLength();
973 s << " x(" << std::hex << entry->GetLength() << ")";
974 valEntryPtr->SetValue(s.str());
979 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
980 << "nor a ValEntry ?! Should never print that !" );
983 // to be sure we are at the end of the value ...
984 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
989 // When we find a BinEntry not very much can be done :
990 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
993 binEntryPtr->SetValue(s.str());
994 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
998 /// \todo Any compacter code suggested (?)
999 if ( IsDocEntryAnInteger(entry) )
1003 // When short integer(s) are expected, read and convert the following
1004 // n *two characters properly i.e. consider them as short integers as
1005 // opposed to strings.
1006 // Elements with Value Multiplicity > 1
1007 // contain a set of integers (not a single one)
1008 if (vr == "US" || vr == "SS")
1011 NewInt = ReadInt16();
1015 for (int i=1; i < nbInt; i++)
1018 NewInt = ReadInt16();
1023 // See above comment on multiple integers (mutatis mutandis).
1024 else if (vr == "UL" || vr == "SL")
1027 NewInt = ReadInt32();
1031 for (int i=1; i < nbInt; i++)
1034 NewInt = ReadInt32();
1039 #ifdef GDCM_NO_ANSI_STRING_STREAM
1040 s << std::ends; // to avoid oddities on Solaris
1041 #endif //GDCM_NO_ANSI_STRING_STREAM
1043 ((ValEntry *)entry)->SetValue(s.str());
1047 // FIXME: We need an additional byte for storing \0 that is not on disk
1048 char *str = new char[length+1];
1049 Fp->read(str, (size_t)length);
1050 str[length] = '\0'; //this is only useful when length is odd
1051 // Special DicomString call to properly handle \0 and even length
1052 std::string newValue;
1055 newValue = Util::DicomString(str, length+1);
1056 gdcmVerboseMacro("Warning: bad length: " << length <<
1057 ",For string :" << newValue.c_str());
1058 // Since we change the length of string update it length
1059 //entry->SetReadLength(length+1);
1063 newValue = Util::DicomString(str, length);
1067 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1069 if ( Fp->fail() || Fp->eof())
1071 gdcmVerboseMacro("Unread element value");
1072 valEntry->SetValue(GDCM_UNREAD);
1078 // Because of correspondance with the VR dic
1079 valEntry->SetValue(newValue);
1083 valEntry->SetValue(newValue);
1088 gdcmErrorMacro( "Should have a ValEntry, here !");
1094 * \brief Find the value Length of the passed Header Entry
1095 * @param entry Header Entry whose length of the value shall be loaded.
1097 void Document::FindDocEntryLength( DocEntry *entry )
1098 throw ( FormatError )
1100 std::string vr = entry->GetVR();
1103 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1105 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1107 // The following reserved two bytes (see PS 3.5-2003, section
1108 // "7.1.2 Data element structure with explicit vr", p 27) must be
1109 // skipped before proceeding on reading the length on 4 bytes.
1110 Fp->seekg( 2L, std::ios::cur);
1111 uint32_t length32 = ReadInt32();
1113 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1118 lengthOB = FindDocEntryLengthOBOrOW();
1120 catch ( FormatUnexpected )
1122 // Computing the length failed (this happens with broken
1123 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1124 // chance to get the pixels by deciding the element goes
1125 // until the end of the file. Hence we artificially fix the
1126 // the length and proceed.
1127 long currentPosition = Fp->tellg();
1128 Fp->seekg(0L,std::ios::end);
1130 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1131 Fp->seekg(currentPosition, std::ios::beg);
1133 entry->SetReadLength(lengthUntilEOF);
1134 entry->SetLength(lengthUntilEOF);
1137 entry->SetReadLength(lengthOB);
1138 entry->SetLength(lengthOB);
1141 FixDocEntryFoundLength(entry, length32);
1145 // Length is encoded on 2 bytes.
1146 length16 = ReadInt16();
1148 // FIXME : This heuristic supposes that the first group following
1149 // group 0002 *has* and element 0000.
1150 // BUT ... Element 0000 is optionnal :-(
1153 // Fixed using : HandleOutOfGroup0002()
1154 // (first hereafter strategy ...)
1156 // We can tell the current file is encoded in big endian (like
1157 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1158 // and it's value is the one of the encoding of a big endian file.
1159 // In order to deal with such big endian encoded files, we have
1160 // (at least) two strategies:
1161 // * when we load the "Transfer Syntax" tag with value of big endian
1162 // encoding, we raise the proper flags. Then we wait for the end
1163 // of the META group (0x0002) among which is "Transfer Syntax",
1164 // before switching the swap code to big endian. We have to postpone
1165 // the switching of the swap code since the META group is fully encoded
1166 // in little endian, and big endian coding only starts at the next
1167 // group. The corresponding code can be hard to analyse and adds
1168 // many additional unnecessary tests for regular tags.
1169 // * the second strategy consists in waiting for trouble, that shall
1170 // appear when we find the first group with big endian encoding. This
1171 // is easy to detect since the length of a "Group Length" tag (the
1172 // ones with zero as element number) has to be of 4 (0x0004). When we
1173 // encounter 1024 (0x0400) chances are the encoding changed and we
1174 // found a group with big endian encoding.
1175 //---> Unfortunately, element 0000 is optional.
1176 //---> This will not work when missing!
1177 // We shall use this second strategy. In order to make sure that we
1178 // can interpret the presence of an apparently big endian encoded
1179 // length of a "Group Length" without committing a big mistake, we
1180 // add an additional check: we look in the already parsed elements
1181 // for the presence of a "Transfer Syntax" whose value has to be "big
1182 // endian encoding". When this is the case, chances are we have got our
1183 // hands on a big endian encoded file: we switch the swap code to
1184 // big endian and proceed...
1186 // if ( element == 0x0000 && length16 == 0x0400 )
1188 // std::string ts = GetTransferSyntax();
1189 // if ( Global::GetTS()->GetSpecialTransferSyntax(ts)
1190 // != TS::ExplicitVRBigEndian )
1192 // throw FormatError( "Document::FindDocEntryLength()",
1193 // " not explicit VR." );
1197 // SwitchByteSwapCode();
1199 // // Restore the unproperly loaded values i.e. the group, the element
1200 // // and the dictionary entry depending on them.
1201 // uint16_t correctGroup = SwapShort( entry->GetGroup() );
1202 // uint16_t correctElem = SwapShort( entry->GetElement() );
1203 // DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1206 // // This correct tag is not in the dictionary. Create a new one.
1207 // newTag = NewVirtualDictEntry(correctGroup, correctElem);
1209 // // FIXME this can create a memory leaks on the old entry that be
1210 // // left unreferenced.
1211 // entry->SetDictEntry( newTag );
1214 // 0xffff means that we deal with 'No Length' Sequence
1215 // or 'No Length' SQItem
1216 if ( length16 == 0xffff)
1220 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1225 // Either implicit VR or a non DICOM conformal (see note below) explicit
1226 // VR that ommited the VR of (at least) this element. Farts happen.
1227 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1228 // on Data elements "Implicit and Explicit VR Data Elements shall
1229 // not coexist in a Data Set and Data Sets nested within it".]
1230 // Length is on 4 bytes.
1232 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1233 // even if Transfer Syntax is 'Implicit VR ...'
1235 FixDocEntryFoundLength( entry, ReadInt32() );
1241 * \brief Find the Value Representation of the current Dicom Element.
1242 * @return Value Representation of the current Entry
1244 std::string Document::FindDocEntryVR()
1246 if ( Filetype != ExplicitVR )
1247 return GDCM_UNKNOWN;
1249 long positionOnEntry = Fp->tellg();
1250 // Warning: we believe this is explicit VR (Value Representation) because
1251 // we used a heuristic that found "UL" in the first tag. Alas this
1252 // doesn't guarantee that all the tags will be in explicit VR. In some
1253 // cases (see e-film filtered files) one finds implicit VR tags mixed
1254 // within an explicit VR file. Hence we make sure the present tag
1255 // is in explicit VR and try to fix things if it happens not to be
1259 Fp->read (vr, (size_t)2);
1262 if( !CheckDocEntryVR(vr) )
1264 Fp->seekg(positionOnEntry, std::ios::beg);
1265 return GDCM_UNKNOWN;
1271 * \brief Check the correspondance between the VR of the header entry
1272 * and the taken VR. If they are different, the header entry is
1273 * updated with the new VR.
1274 * @param vr Dicom Value Representation
1275 * @return false if the VR is incorrect of if the VR isn't referenced
1276 * otherwise, it returns true
1278 bool Document::CheckDocEntryVR(VRKey vr)
1280 // CLEANME searching the dicom_vr at each occurence is expensive.
1281 // PostPone this test in an optional integrity check at the end
1282 // of parsing or only in debug mode.
1283 if ( !Global::GetVR()->IsValidVR(vr) )
1290 * \brief Get the transformed value of the header entry. The VR value
1291 * is used to define the transformation to operate on the value
1292 * \warning NOT end user intended method !
1293 * @param entry entry to tranform
1294 * @return Transformed entry value
1296 std::string Document::GetDocEntryValue(DocEntry *entry)
1298 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1300 std::string val = ((ValEntry *)entry)->GetValue();
1301 std::string vr = entry->GetVR();
1302 uint32_t length = entry->GetLength();
1303 std::ostringstream s;
1306 // When short integer(s) are expected, read and convert the following
1307 // n * 2 bytes properly i.e. as a multivaluated strings
1308 // (each single value is separated fromthe next one by '\'
1309 // as usual for standard multivaluated filels
1310 // Elements with Value Multiplicity > 1
1311 // contain a set of short integers (not a single one)
1313 if( vr == "US" || vr == "SS" )
1318 for (int i=0; i < nbInt; i++)
1324 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1325 newInt16 = SwapShort( newInt16 );
1330 // When integer(s) are expected, read and convert the following
1331 // n * 4 bytes properly i.e. as a multivaluated strings
1332 // (each single value is separated fromthe next one by '\'
1333 // as usual for standard multivaluated filels
1334 // Elements with Value Multiplicity > 1
1335 // contain a set of integers (not a single one)
1336 else if( vr == "UL" || vr == "SL" )
1341 for (int i=0; i < nbInt; i++)
1347 newInt32 = ( val[4*i+0] & 0xFF )
1348 + (( val[4*i+1] & 0xFF ) << 8 )
1349 + (( val[4*i+2] & 0xFF ) << 16 )
1350 + (( val[4*i+3] & 0xFF ) << 24 );
1351 newInt32 = SwapLong( newInt32 );
1355 #ifdef GDCM_NO_ANSI_STRING_STREAM
1356 s << std::ends; // to avoid oddities on Solaris
1357 #endif //GDCM_NO_ANSI_STRING_STREAM
1361 return ((ValEntry *)entry)->GetValue();
1365 * \brief Get the reverse transformed value of the header entry. The VR
1366 * value is used to define the reverse transformation to operate on
1368 * \warning NOT end user intended method !
1369 * @param entry Entry to reverse transform
1370 * @return Reverse transformed entry value
1372 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1374 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1376 std::string vr = entry->GetVR();
1377 std::vector<std::string> tokens;
1378 std::ostringstream s;
1380 if ( vr == "US" || vr == "SS" )
1384 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1385 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1386 for (unsigned int i=0; i<tokens.size(); i++)
1388 newInt16 = atoi(tokens[i].c_str());
1389 s << ( newInt16 & 0xFF )
1390 << (( newInt16 >> 8 ) & 0xFF );
1394 if ( vr == "UL" || vr == "SL")
1398 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1399 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1400 for (unsigned int i=0; i<tokens.size();i++)
1402 newInt32 = atoi(tokens[i].c_str());
1403 s << (char)( newInt32 & 0xFF )
1404 << (char)(( newInt32 >> 8 ) & 0xFF )
1405 << (char)(( newInt32 >> 16 ) & 0xFF )
1406 << (char)(( newInt32 >> 24 ) & 0xFF );
1411 #ifdef GDCM_NO_ANSI_STRING_STREAM
1412 s << std::ends; // to avoid oddities on Solaris
1413 #endif //GDCM_NO_ANSI_STRING_STREAM
1417 return ((ValEntry *)entry)->GetValue();
1421 * \brief Skip a given Header Entry
1422 * \warning NOT end user intended method !
1423 * @param entry entry to skip
1425 void Document::SkipDocEntry(DocEntry *entry)
1427 SkipBytes(entry->GetLength());
1431 * \brief Skips to the begining of the next Header Entry
1432 * \warning NOT end user intended method !
1433 * @param currentDocEntry entry to skip
1435 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1437 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1438 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1439 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1443 * \brief When the length of an element value is obviously wrong (because
1444 * the parser went Jabberwocky) one can hope improving things by
1445 * applying some heuristics.
1446 * @param entry entry to check
1447 * @param foundLength first assumption about length
1449 void Document::FixDocEntryFoundLength(DocEntry *entry,
1450 uint32_t foundLength)
1452 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1453 if ( foundLength == 0xffffffff)
1458 uint16_t gr = entry->GetGroup();
1459 uint16_t elem = entry->GetElement();
1461 if ( foundLength % 2)
1463 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1464 << " in x(" << std::hex << gr << "," << elem <<")");
1467 //////// Fix for some naughty General Electric images.
1468 // Allthough not recent many such GE corrupted images are still present
1469 // on Creatis hard disks. Hence this fix shall remain when such images
1470 // are no longer in use (we are talking a few years, here)...
1471 // Note: XMedCom probably uses such a trick since it is able to read
1472 // those pesky GE images ...
1473 if ( foundLength == 13)
1475 // Only happens for this length !
1476 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1479 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1483 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1484 // Occurence of such images is quite low (unless one leaves close to a
1485 // 'Leonardo' source. Hence, one might consider commenting out the
1486 // following fix on efficiency reasons.
1487 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1490 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1493 else if ( entry->GetVR() == "SQ" )
1495 foundLength = 0; // ReadLength is unchanged
1498 //////// We encountered a 'delimiter' element i.e. a tag of the form
1499 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1500 // taken into account.
1501 else if( gr == 0xfffe )
1503 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1504 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1505 // causes extra troubles...
1506 if( entry->GetElement() != 0x0000 )
1512 entry->SetLength(foundLength);
1516 * \brief Apply some heuristics to predict whether the considered
1517 * element value contains/represents an integer or not.
1518 * @param entry The element value on which to apply the predicate.
1519 * @return The result of the heuristical predicate.
1521 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1523 uint16_t elem = entry->GetElement();
1524 uint16_t group = entry->GetGroup();
1525 const std::string &vr = entry->GetVR();
1526 uint32_t length = entry->GetLength();
1528 // When we have some semantics on the element we just read, and if we
1529 // a priori know we are dealing with an integer, then we shall be
1530 // able to swap it's element value properly.
1531 if ( elem == 0 ) // This is the group length of the group
1539 // Allthough this should never happen, still some images have a
1540 // corrupted group length [e.g. have a glance at offset x(8336) of
1541 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1542 // Since for dicom compliant and well behaved headers, the present
1543 // test is useless (and might even look a bit paranoid), when we
1544 // encounter such an ill-formed image, we simply display a warning
1545 // message and proceed on parsing (while crossing fingers).
1546 long filePosition = Fp->tellg();
1547 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
1548 << std::hex << group << " , " << elem
1549 << ") -before- position x(" << filePosition << ")"
1550 << "lgt : " << length );
1554 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1562 * \brief Find the Length till the next sequence delimiter
1563 * \warning NOT end user intended method !
1567 uint32_t Document::FindDocEntryLengthOBOrOW()
1568 throw( FormatUnexpected )
1570 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1571 long positionOnEntry = Fp->tellg();
1572 bool foundSequenceDelimiter = false;
1573 uint32_t totalLength = 0;
1575 while ( !foundSequenceDelimiter )
1581 group = ReadInt16();
1584 catch ( FormatError )
1586 throw FormatError("Unexpected end of file encountered during ",
1587 "Document::FindDocEntryLengthOBOrOW()");
1590 // We have to decount the group and element we just read
1593 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1595 long filePosition = Fp->tellg();
1596 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
1597 << std::hex << group << " , " << elem
1598 << ") -before- position x(" << filePosition << ")" );
1600 Fp->seekg(positionOnEntry, std::ios::beg);
1601 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1604 if ( elem == 0xe0dd )
1606 foundSequenceDelimiter = true;
1609 uint32_t itemLength = ReadInt32();
1610 // We add 4 bytes since we just read the ItemLength with ReadInt32
1611 totalLength += itemLength + 4;
1612 SkipBytes(itemLength);
1614 if ( foundSequenceDelimiter )
1619 Fp->seekg( positionOnEntry, std::ios::beg);
1624 * \brief Reads a supposed to be 16 Bits integer
1625 * (swaps it depending on processor endianity)
1626 * @return read value
1628 uint16_t Document::ReadInt16()
1629 throw( FormatError )
1632 Fp->read ((char*)&g, (size_t)2);
1635 throw FormatError( "Document::ReadInt16()", " file error." );
1639 throw FormatError( "Document::ReadInt16()", "EOF." );
1646 * \brief Reads a supposed to be 32 Bits integer
1647 * (swaps it depending on processor endianity)
1648 * @return read value
1650 uint32_t Document::ReadInt32()
1651 throw( FormatError )
1654 Fp->read ((char*)&g, (size_t)4);
1657 throw FormatError( "Document::ReadInt32()", " file error." );
1661 throw FormatError( "Document::ReadInt32()", "EOF." );
1668 * \brief skips bytes inside the source file
1669 * \warning NOT end user intended method !
1672 void Document::SkipBytes(uint32_t nBytes)
1674 //FIXME don't dump the returned value
1675 Fp->seekg((long)nBytes, std::ios::cur);
1679 * \brief Loads all the needed Dictionaries
1680 * \warning NOT end user intended method !
1682 void Document::Initialize()
1684 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1686 RLEInfo = new RLEFramesInfo;
1687 JPEGInfo = new JPEGFragmentsInfo;
1692 * \brief Discover what the swap code is (among little endian, big endian,
1693 * bad little endian, bad big endian).
1695 * @return false when we are absolutely sure
1696 * it's neither ACR-NEMA nor DICOM
1697 * true when we hope ours assuptions are OK
1699 bool Document::CheckSwap()
1701 // The only guaranted way of finding the swap code is to find a
1702 // group tag since we know it's length has to be of four bytes i.e.
1703 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1704 // occurs when we can't find such group...
1706 uint32_t x = 4; // x : for ntohs
1707 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1713 // First, compare HostByteOrder and NetworkByteOrder in order to
1714 // determine if we shall need to swap bytes (i.e. the Endian type).
1715 if ( x == ntohs(x) )
1724 // The easiest case is the one of a 'true' DICOM header, we just have
1725 // to look for the string "DICM" inside the file preamble.
1728 char *entCur = deb + 128;
1729 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1731 gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1733 // Group 0002 should always be VR, and the first element 0000
1734 // Let's be carefull (so many wrong headers ...)
1735 // and determine the value representation (VR) :
1736 // Let's skip to the first element (0002,0000) and check there if we find
1737 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1738 // in which case we (almost) know it is explicit VR.
1739 // WARNING: if it happens to be implicit VR then what we will read
1740 // is the length of the group. If this ascii representation of this
1741 // length happens to be "UL" then we shall believe it is explicit VR.
1742 // We need to skip :
1743 // * the 128 bytes of File Preamble (often padded with zeroes),
1744 // * the 4 bytes of "DICM" string,
1745 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1746 // i.e. a total of 136 bytes.
1749 // group 0x0002 *is always* Explicit VR Sometimes ,
1750 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1751 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1753 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1754 memcmp(entCur, "OB", (size_t)2) == 0 ||
1755 memcmp(entCur, "UI", (size_t)2) == 0 ||
1756 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1757 // when Write DCM *adds*
1759 // Use Document::dicom_vr to test all the possibilities
1760 // instead of just checking for UL, OB and UI !? group 0000
1762 Filetype = ExplicitVR;
1763 gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
1767 Filetype = ImplicitVR;
1768 gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
1769 << "Looks like a bugged Header!");
1775 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
1780 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
1783 // Position the file position indicator at first tag
1784 // (i.e. after the file preamble and the "DICM" string).
1785 Fp->seekg(0, std::ios::beg);
1786 Fp->seekg ( 132L, std::ios::beg);
1790 // Alas, this is not a DicomV3 file and whatever happens there is no file
1791 // preamble. We can reset the file position indicator to where the data
1792 // is (i.e. the beginning of the file).
1793 gdcmVerboseMacro( "Not a DICOM Version3 file");
1794 Fp->seekg(0, std::ios::beg);
1796 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1797 // By clean we mean that the length of the first tag is written down.
1798 // If this is the case and since the length of the first group HAS to be
1799 // four (bytes), then determining the proper swap code is straightforward.
1802 // We assume the array of char we are considering contains the binary
1803 // representation of a 32 bits integer. Hence the following dirty
1805 s32 = *((uint32_t *)(entCur));
1826 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1827 // It is time for despaired wild guesses.
1828 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1829 // i.e. the 'group length' element is not present :
1831 // check the supposed-to-be 'group number'
1832 // in ( 0x0001 .. 0x0008 )
1833 // to determine ' SwapCode' value .
1834 // Only 0 or 4321 will be possible
1835 // (no oportunity to check for the formerly well known
1836 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1837 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1838 // the file IS NOT ACR-NEMA nor DICOM V3
1839 // Find a trick to tell it the caller...
1841 s16 = *((uint16_t *)(deb));
1868 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1876 * \brief Change the Byte Swap code.
1878 void Document::SwitchByteSwapCode()
1880 gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
1881 if ( SwapCode == 1234 )
1885 else if ( SwapCode == 4321 )
1889 else if ( SwapCode == 3412 )
1893 else if ( SwapCode == 2143 )
1900 * \brief during parsing, Header Elements too long are not loaded in memory
1903 void Document::SetMaxSizeLoadEntry(long newSize)
1909 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1911 MaxSizeLoadEntry = 0xffffffff;
1914 MaxSizeLoadEntry = newSize;
1919 * \brief Header Elements too long will not be printed
1920 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
1923 void Document::SetMaxSizePrintEntry(long newSize)
1929 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1931 MaxSizePrintEntry = 0xffffffff;
1934 MaxSizePrintEntry = newSize;
1940 * \brief Handle broken private tag from Philips NTSCAN
1941 * where the endianess is being switch to BigEndian for no
1945 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
1947 // Endian reversion. Some files contain groups of tags with reversed endianess.
1948 static int reversedEndian = 0;
1949 // try to fix endian switching in the middle of headers
1950 if ((group == 0xfeff) && (elem == 0x00e0))
1952 // start endian swap mark for group found
1954 SwitchByteSwapCode();
1959 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
1961 // end of reversed endian group
1963 SwitchByteSwapCode();
1968 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
1969 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
1971 std::string Document::GetTransferSyntaxName()
1973 // use the TS (TS : Transfer Syntax)
1974 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
1976 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
1978 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
1979 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
1980 return "Uncompressed ACR-NEMA";
1982 if ( transferSyntax == GDCM_UNFOUND )
1984 gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
1985 return "Uncompressed ACR-NEMA";
1988 // we do it only when we need it
1989 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
1991 // Global::GetTS() is a global static you shall never try to delete it!
1996 * \brief Group 0002 is always coded Little Endian
1997 * whatever Transfer Syntax is
2000 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2002 // Endian reversion. Some files contain groups of tags with reversed endianess.
2003 if ( !Group0002Parsed && group != 0x0002)
2005 Group0002Parsed = true;
2006 // we just came out of group 0002
2007 // if Transfer syntax is Big Endian we have to change CheckSwap
2009 std::string ts = GetTransferSyntax();
2010 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2012 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2016 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2018 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2020 Filetype = ImplicitVR;
2023 // FIXME Strangely, this works with
2024 //'Implicit VR Transfer Syntax (GE Private)
2025 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2027 gdcmVerboseMacro("Transfer Syntax Name = ["
2028 << GetTransferSyntaxName() << "]" );
2029 SwitchByteSwapCode();
2030 group = SwapShort(group);
2031 elem = SwapShort(elem);
2037 * \brief Read the next tag but WITHOUT loading it's value
2038 * (read the 'Group Number', the 'Element Number',
2039 * gets the Dict Entry
2040 * gets the VR, gets the length, gets the offset value)
2041 * @return On succes the newly created DocEntry, NULL on failure.
2043 DocEntry *Document::ReadNextDocEntry()
2050 group = ReadInt16();
2053 catch ( FormatError e )
2055 // We reached the EOF (or an error occured) therefore
2056 // header parsing has to be considered as finished.
2061 // Sometimes file contains groups of tags with reversed endianess.
2062 HandleBrokenEndian(group, elem);
2064 // In 'true DICOM' files Group 0002 is always little endian
2065 if ( HasDCMPreamble )
2066 HandleOutOfGroup0002(group, elem);
2068 std::string vr = FindDocEntryVR();
2069 std::string realVR = vr;
2071 if( vr == GDCM_UNKNOWN)
2073 DictEntry *dictEntry = GetDictEntry(group,elem);
2075 realVR = dictEntry->GetVR();
2079 if( Global::GetVR()->IsVROfSequence(realVR) )
2080 newEntry = NewSeqEntry(group, elem);
2081 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2082 newEntry = NewValEntry(group, elem,vr);
2084 newEntry = NewBinEntry(group, elem,vr);
2086 if( vr == GDCM_UNKNOWN )
2088 if( Filetype == ExplicitVR )
2090 // We thought this was explicit VR, but we end up with an
2091 // implicit VR tag. Let's backtrack.
2092 if ( newEntry->GetGroup() != 0xfffe )
2095 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2096 newEntry->GetGroup(), newEntry->GetElement());
2097 gdcmVerboseMacro( msg.c_str() );
2100 newEntry->SetImplicitVR();
2105 FindDocEntryLength(newEntry);
2107 catch ( FormatError e )
2115 newEntry->SetOffset(Fp->tellg());
2120 //GenerateFreeTagKeyInGroup? What was it designed for ?!?
2122 * \brief Generate a free TagKey i.e. a TagKey that is not present
2123 * in the TagHt dictionary.
2124 * @param group The generated tag must belong to this group.
2125 * @return The element of tag with given group which is fee.
2127 //uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2129 // for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2131 // TagKey key = DictEntry::TranslateToKey(group, elem);
2132 // if (TagHT.count(key) == 0)
2137 // return UINT32_MAX;
2141 * \brief Assuming the internal file pointer \ref Document::Fp
2142 * is placed at the beginning of a tag check whether this
2143 * tag is (TestGroup, TestElement).
2144 * \warning On success the internal file pointer \ref Document::Fp
2145 * is modified to point after the tag.
2146 * On failure (i.e. when the tag wasn't the expected tag
2147 * (TestGroup, TestElement) the internal file pointer
2148 * \ref Document::Fp is restored to it's original position.
2149 * @param testGroup The expected group of the tag.
2150 * @param testElement The expected Element of the tag.
2151 * @return True on success, false otherwise.
2153 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2155 long positionOnEntry = Fp->tellg();
2156 long currentPosition = Fp->tellg(); // On debugging purposes
2158 //// Read the Item Tag group and element, and make
2159 // sure they are what we expected:
2160 uint16_t itemTagGroup;
2161 uint16_t itemTagElement;
2164 itemTagGroup = ReadInt16();
2165 itemTagElement = ReadInt16();
2167 catch ( FormatError e )
2169 //std::cerr << e << std::endl;
2172 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2174 gdcmVerboseMacro( "Wrong Item Tag found:"
2175 << " We should have found tag ("
2176 << std::hex << testGroup << "," << testElement << ")" << std::endl
2177 << " but instead we encountered tag ("
2178 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2179 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2181 Fp->seekg(positionOnEntry, std::ios::beg);
2189 * \brief Assuming the internal file pointer \ref Document::Fp
2190 * is placed at the beginning of a tag (TestGroup, TestElement),
2191 * read the length associated to the Tag.
2192 * \warning On success the internal file pointer \ref Document::Fp
2193 * is modified to point after the tag and it's length.
2194 * On failure (i.e. when the tag wasn't the expected tag
2195 * (TestGroup, TestElement) the internal file pointer
2196 * \ref Document::Fp is restored to it's original position.
2197 * @param testGroup The expected group of the tag.
2198 * @param testElement The expected Element of the tag.
2199 * @return On success returns the length associated to the tag. On failure
2202 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2205 if ( !ReadTag(testGroup, testElement) )
2210 //// Then read the associated Item Length
2211 long currentPosition = Fp->tellg();
2212 uint32_t itemLength = ReadInt32();
2214 gdcmVerboseMacro( "Basic Item Length is: "
2215 << itemLength << std::endl
2216 << " at address: " << std::hex << (unsigned int)currentPosition);
2222 * \brief When parsing the Pixel Data of an encapsulated file, read
2223 * the basic offset table (when present, and BTW dump it).
2225 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2227 //// Read the Basic Offset Table Item Tag length...
2228 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2230 // When present, read the basic offset table itself.
2231 // Notes: - since the presence of this basic offset table is optional
2232 // we can't rely on it for the implementation, and we will simply
2233 // trash it's content (when present).
2234 // - still, when present, we could add some further checks on the
2235 // lengths, but we won't bother with such fuses for the time being.
2236 if ( itemLength != 0 )
2238 char *basicOffsetTableItemValue = new char[itemLength + 1];
2239 Fp->read(basicOffsetTableItemValue, itemLength);
2242 for (unsigned int i=0; i < itemLength; i += 4 )
2244 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2246 gdcmVerboseMacro( "Read one length: " <<
2247 std::hex << individualLength );
2251 delete[] basicOffsetTableItemValue;
2256 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2257 * Compute the RLE extra information and store it in \ref RLEInfo
2258 * for later pixel retrieval usage.
2260 void Document::ComputeRLEInfo()
2262 std::string ts = GetTransferSyntax();
2263 if ( !Global::GetTS()->IsRLELossless(ts) )
2268 // Encoded pixel data: for the time being we are only concerned with
2269 // Jpeg or RLE Pixel data encodings.
2270 // As stated in PS 3.5-2003, section 8.2 p44:
2271 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2272 // value representation OB is used".
2273 // Hence we expect an OB value representation. Concerning OB VR,
2274 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2275 // "For the Value Representations OB and OW, the encoding shall meet the
2276 // following specifications depending on the Data element tag:"
2278 // - the first item in the sequence of items before the encoded pixel
2279 // data stream shall be basic offset table item. The basic offset table
2280 // item value, however, is not required to be present"
2282 ReadAndSkipEncapsulatedBasicOffsetTable();
2284 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2285 // Loop on the individual frame[s] and store the information
2286 // on the RLE fragments in a RLEFramesInfo.
2287 // Note: - when only a single frame is present, this is a
2289 // - when more than one frame are present, then we are in
2290 // the case of a multi-frame image.
2292 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2294 // Parse the RLE Header and store the corresponding RLE Segment
2295 // Offset Table information on fragments of this current Frame.
2296 // Note that the fragment pixels themselves are not loaded
2297 // (but just skipped).
2298 long frameOffset = Fp->tellg();
2300 uint32_t nbRleSegments = ReadInt32();
2301 if ( nbRleSegments > 16 )
2303 // There should be at most 15 segments (refer to RLEFrame class)
2304 gdcmVerboseMacro( "Too many segments.");
2307 uint32_t rleSegmentOffsetTable[16];
2308 for( int k = 1; k <= 15; k++ )
2310 rleSegmentOffsetTable[k] = ReadInt32();
2313 // Deduce from both the RLE Header and the frameLength the
2314 // fragment length, and again store this info in a
2316 long rleSegmentLength[15];
2317 // skipping (not reading) RLE Segments
2318 if ( nbRleSegments > 1)
2320 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2322 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2323 - rleSegmentOffsetTable[k];
2324 SkipBytes(rleSegmentLength[k]);
2328 rleSegmentLength[nbRleSegments] = frameLength
2329 - rleSegmentOffsetTable[nbRleSegments];
2330 SkipBytes(rleSegmentLength[nbRleSegments]);
2332 // Store the collected info
2333 RLEFrame *newFrameInfo = new RLEFrame;
2334 newFrameInfo->SetNumberOfFragments(nbRleSegments);
2335 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2337 newFrameInfo->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
2338 newFrameInfo->SetLength(uk,rleSegmentLength[uk]);
2340 RLEInfo->Frames.push_back( newFrameInfo );
2343 // Make sure that at the end of the item we encounter a 'Sequence
2345 if ( !ReadTag(0xfffe, 0xe0dd) )
2347 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2352 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2353 * Compute the jpeg extra information (fragment[s] offset[s] and
2354 * length) and store it[them] in \ref JPEGInfo for later pixel
2357 void Document::ComputeJPEGFragmentInfo()
2359 // If you need to, look for comments of ComputeRLEInfo().
2360 std::string ts = GetTransferSyntax();
2361 if ( ! Global::GetTS()->IsJPEG(ts) )
2366 ReadAndSkipEncapsulatedBasicOffsetTable();
2368 // Loop on the fragments[s] and store the parsed information in a
2370 long fragmentLength;
2371 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2373 long fragmentOffset = Fp->tellg();
2375 // Store the collected info
2376 JPEGFragment *newFragment = new JPEGFragment;
2377 newFragment->SetOffset(fragmentOffset);
2378 newFragment->SetLength(fragmentLength);
2379 JPEGInfo->Fragments.push_back( newFragment );
2381 SkipBytes( fragmentLength );
2384 // Make sure that at the end of the item we encounter a 'Sequence
2386 if ( !ReadTag(0xfffe, 0xe0dd) )
2388 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2393 * \brief Walk recursively the given \ref DocEntrySet, and feed
2394 * the given hash table (\ref TagDocEntryHT) with all the
2395 * \ref DocEntry (Dicom entries) encountered.
2396 * This method does the job for \ref BuildFlatHashTable.
2397 * @param builtHT Where to collect all the \ref DocEntry encountered
2398 * when recursively walking the given set.
2399 * @param set The structure to be traversed (recursively).
2401 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2404 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2406 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2407 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2408 i != currentHT.end();
2411 DocEntry *entry = i->second;
2412 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2414 const ListSQItem& items = seqEntry->GetSQItems();
2415 for( ListSQItem::const_iterator item = items.begin();
2416 item != items.end();
2419 BuildFlatHashTableRecurse( builtHT, *item );
2423 builtHT[entry->GetKey()] = entry;
2428 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2430 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2431 for (ListDocEntry::const_iterator i = currentList.begin();
2432 i != currentList.end();
2435 DocEntry *entry = *i;
2436 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2438 const ListSQItem& items = seqEntry->GetSQItems();
2439 for( ListSQItem::const_iterator item = items.begin();
2440 item != items.end();
2443 BuildFlatHashTableRecurse( builtHT, *item );
2447 builtHT[entry->GetKey()] = entry;
2454 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2457 * The structure used by a Document (through \ref ElementSet),
2458 * in order to hold the parsed entries of a Dicom header, is a recursive
2459 * one. This is due to the fact that the sequences (when present)
2460 * can be nested. Additionaly, the sequence items (represented in
2461 * gdcm as \ref SQItem) add an extra complexity to the data
2462 * structure. Hence, a gdcm user whishing to visit all the entries of
2463 * a Dicom header will need to dig in the gdcm internals (which
2464 * implies exposing all the internal data structures to the API).
2465 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2466 * recursively builds a temporary hash table, which holds all the
2467 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2469 * \warning Of course there is NO integrity constrain between the
2470 * returned \ref TagDocEntryHT and the \ref ElementSet used
2471 * to build it. Hence if the underlying \ref ElementSet is
2472 * altered, then it is the caller responsability to invoke
2473 * \ref BuildFlatHashTable again...
2474 * @return The flat std::map<> we juste build.
2476 /*TagDocEntryHT *Document::BuildFlatHashTable()
2478 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2479 BuildFlatHashTableRecurse( *FlatHT, this );
2486 * \brief Compares two documents, according to \ref DicomDir rules
2487 * \warning Does NOT work with ACR-NEMA files
2488 * \todo Find a trick to solve the pb (use RET fields ?)
2490 * @return true if 'smaller'
2492 bool Document::operator<(Document &document)
2495 std::string s1 = GetEntryValue(0x0010,0x0010);
2496 std::string s2 = document.GetEntryValue(0x0010,0x0010);
2508 s1 = GetEntryValue(0x0010,0x0020);
2509 s2 = document.GetEntryValue(0x0010,0x0020);
2520 // Study Instance UID
2521 s1 = GetEntryValue(0x0020,0x000d);
2522 s2 = document.GetEntryValue(0x0020,0x000d);
2533 // Serie Instance UID
2534 s1 = GetEntryValue(0x0020,0x000e);
2535 s2 = document.GetEntryValue(0x0020,0x000e);
2551 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2552 * @param filetype Type of the File to be written
2554 int Document::ComputeGroup0002Length( FileType filetype )
2559 int groupLength = 0;
2560 bool found0002 = false;
2562 // for each zero-level Tag in the DCM Header
2563 DocEntry *entry = GetFirstEntry();
2566 gr = entry->GetGroup();
2571 vr = entry->GetVR();
2573 if (filetype == ExplicitVR)
2575 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
2577 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
2580 groupLength += 2 + 2 + 4 + entry->GetLength();
2582 else if (found0002 )
2585 entry = GetNextEntry();
2590 } // end namespace gdcm
2592 //-----------------------------------------------------------------------------