1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/05/25 12:54:17 $
7 Version: $Revision: 1.241 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
37 //-----------------------------------------------------------------------------
38 // Refer to Document::CheckSwap()
39 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
41 // Refer to Document::SetMaxSizeLoadEntry()
42 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
46 // Constructors and destructors are protected to avoid user to invoke directly
49 * \brief This default constructor neither loads nor parses the file.
50 * You should then invoke \ref Document::Load.
58 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
61 Filetype = ExplicitVR;
62 // Load will set it to true if sucessfull
63 Group0002Parsed = false;
64 IsDocumentAlreadyLoaded = false;
65 LoadMode = 0x00000000; // default : load everything, later
69 * \brief Constructor (not to break the API)
70 * @param filename 'Document' (File or DicomDir) to be opened for parsing
72 Document::Document( std::string const &fileName )
77 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
80 Filetype = ExplicitVR;
81 Group0002Parsed = false;
82 LoadMode = 0x00000000; // Load everything
84 // Load will set it to true if sucessfull
85 IsDocumentAlreadyLoaded = false;
89 // Normaly (?) Fp should be already deleted by CloseFile()
95 * \brief Canonical destructor.
97 Document::~Document ()
103 //-----------------------------------------------------------------------------
108 * @param filename 'Document' (File or DicomDir) to be opened for parsing
109 * @return false if file cannot be open or no swap info was found,
110 * or no tag was found.
112 bool Document::Load( std::string const &fileName )
114 // We should clean out anything that already exists.
115 // Check IsDocumentAlreadyLoaded to be sure.
116 if( IsDocumentAlreadyLoaded )
118 gdcmWarningMacro( "A file was already parsed inside this "
119 << "gdcm::Document (previous name was: "
120 << Filename.c_str() << ". New name is :"
122 // todo : clean out the 'Document'
123 // We should call ClearEntry() on the parent object ?!?
131 // warning already performed in OpenFile()
132 //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
133 // << Filename.c_str() );
138 Group0002Parsed = false;
140 gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
142 Fp->seekg(0, std::ios::end);
143 long lgt = Fp->tellg(); // total length of the file
145 Fp->seekg(0, std::ios::beg);
147 // CheckSwap returns a boolean
148 // (false if no swap info of any kind was found)
151 gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: "
152 << Filename.c_str());
157 long beg = Fp->tellg(); // just after DICOM preamble (if any)
159 lgt -= beg; // remaining length to parse
161 ParseDES( this, beg, lgt, false); // Loading is done during parsing
165 gdcmWarningMacro( "No tag in internal hash table for: "
166 << Filename.c_str());
170 IsDocumentAlreadyLoaded = true;
172 Fp->seekg( 0, std::ios::beg);
174 // Load 'non string' values
176 std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);
177 if( PhotometricInterpretation == "PALETTE COLOR " )
179 LoadEntryBinArea(0x0028,0x1200); // gray LUT
180 /// FIXME FIXME FIXME
181 /// The tags refered by the three following lines used to be CORRECTLY
182 /// defined as having an US Value Representation in the public
183 /// dictionary. BUT the semantics implied by the three following
184 /// lines state that the corresponding tag contents are in fact
185 /// the ones of a BinEntry.
186 /// In order to fix things "Quick and Dirty" the dictionary was
187 /// altered on PURPOSE but now contains a WRONG value.
188 /// In order to fix things and restore the dictionary to its
189 /// correct value, one needs to decided of the semantics by deciding
190 /// whether the following tags are either:
191 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
192 /// also used as BinEntry, which requires the proper conversion,
193 /// - OW, and hence loaded as BinEntry, but afterwards also used
194 /// as ValEntry, which requires the proper conversion.
195 LoadEntryBinArea(0x0028,0x1201); // R LUT
196 LoadEntryBinArea(0x0028,0x1202); // G LUT
197 LoadEntryBinArea(0x0028,0x1203); // B LUT
199 // Segmented Red Palette Color LUT Data
200 LoadEntryBinArea(0x0028,0x1221);
201 // Segmented Green Palette Color LUT Data
202 LoadEntryBinArea(0x0028,0x1222);
203 // Segmented Blue Palette Color LUT Data
204 LoadEntryBinArea(0x0028,0x1223);
206 //FIXME later : how to use it?
207 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
211 // ----------------------------
212 // Specific code to allow gdcm to read ACR-LibIDO formated images
213 // Note: ACR-LibIDO is an extension of the ACR standard that was
214 // used at CREATIS. For the time being (say a couple years)
215 // we keep this kludge to allow CREATIS users
216 // reading their old images.
218 // if recognition code tells us we deal with a LibIDO image
219 // we switch lineNumber and columnNumber
222 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
223 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
224 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
225 // with "little-endian strings"
227 Filetype = ACR_LIBIDO;
228 std::string rows = GetEntryValue(0x0028, 0x0010);
229 std::string columns = GetEntryValue(0x0028, 0x0011);
230 SetValEntry(columns, 0x0028, 0x0010);
231 SetValEntry(rows , 0x0028, 0x0011);
233 // --- End of ACR-LibIDO kludge ---
239 * \brief Get the public dictionary used
241 Dict *Document::GetPubDict()
247 * \brief Get the shadow dictionary used
249 Dict *Document::GetShaDict()
255 * \brief Set the shadow dictionary used
256 * @param dict dictionary to use in shadow
258 bool Document::SetShaDict(Dict *dict)
265 * \brief Set the shadow dictionary used
266 * @param dictName name of the dictionary to use in shadow
268 bool Document::SetShaDict(DictKey const &dictName)
270 RefShaDict = Global::GetDicts()->GetDict(dictName);
275 * \brief This predicate tells us whether or not the current Document
276 * was properly parsed and contains at least *one* Dicom Element
277 * (and nothing more, sorry).
278 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
281 bool Document::IsReadable()
283 if( Filetype == Unknown)
285 gdcmWarningMacro( "Wrong filetype");
291 gdcmWarningMacro( "No tag in internal hash table.");
299 * \brief Predicate for dicom version 3 file.
300 * @return True when the file is a dicom version 3.
302 bool Document::IsDicomV3()
304 // Checking if Transfer Syntax exists is enough
305 // Anyway, it's too late check if the 'Preamble' was found ...
306 // And ... would it be a rich idea to check ?
307 // (some 'no Preamble' DICOM images exist !)
308 return GetDocEntry(0x0002, 0x0010) != NULL;
312 * \brief Predicate for Papyrus file
313 * Dedicated to whomsoever it may concern
314 * @return True when the file is a Papyrus file.
316 bool Document::IsPapyrus()
318 // check for Papyrus private Sequence
319 DocEntry *e = GetDocEntry(0x0041, 0x1050);
322 // check if it's actually a Sequence
323 if ( !dynamic_cast<SeqEntry*>(e) )
329 * \brief returns the File Type
330 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
331 * @return the FileType code
333 FileType Document::GetFileType()
339 * \brief Accessor to the Transfer Syntax (when present) of the
340 * current document (it internally handles reading the
341 * value from disk when only parsing occured).
342 * @return The encountered Transfer Syntax of the current document.
344 std::string Document::GetTransferSyntax()
346 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
352 // The entry might be present but not loaded (parsing and loading
353 // happen at different stages): try loading and proceed with check...
354 LoadDocEntrySafe(entry);
355 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
357 std::string transfer = valEntry->GetValue();
358 // The actual transfer (as read from disk) might be padded. We
359 // first need to remove the potential padding. We can make the
360 // weak assumption that padding was not executed with digits...
361 if ( transfer.length() == 0 )
363 // for brain damaged headers
366 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
368 transfer.erase(transfer.length()-1, 1);
376 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
377 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
379 std::string Document::GetTransferSyntaxName()
381 // use the TS (TS : Transfer Syntax)
382 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
384 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
386 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
387 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
388 return "Uncompressed ACR-NEMA";
390 if ( transferSyntax == GDCM_UNFOUND )
392 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
393 return "Uncompressed ACR-NEMA";
396 // we do it only when we need it
397 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
399 // Global::GetTS() is a global static you shall never try to delete it!
403 // --------------- Swap Code ------------------
405 * \brief Swaps the bytes so they agree with the processor order
406 * @return The properly swaped 16 bits integer.
408 uint16_t Document::SwapShort(uint16_t a)
410 if ( SwapCode == 4321 || SwapCode == 2143 )
412 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
414 a = ( a << 8 ) | ( a >> 8 );
420 * \brief Swaps back the bytes of 4-byte long integer accordingly to
422 * @return The properly swaped 32 bits integer.
424 uint32_t Document::SwapLong(uint32_t a)
431 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
432 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
434 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
435 ((a>>8) & 0x0000ff00) | (a>>24) );
438 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
439 a=( (a<<16) | (a>>16) );
442 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
445 gdcmErrorMacro( "Unset swap code:" << SwapCode );
452 // -----------------File I/O ---------------
454 * \brief Tries to open the file \ref Document::Filename and
455 * checks the preamble when existing.
456 * @return The FILE pointer on success.
458 std::ifstream *Document::OpenFile()
460 HasDCMPreamble = false;
461 if (Filename.length() == 0)
468 gdcmWarningMacro( "File already open: " << Filename.c_str());
472 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
475 // Don't user gdcmErrorMacro :
476 // a spurious message will appear when you use, for instance
477 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
478 // to create outputFileName.
479 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
483 //exit(1); // No function is allowed to leave the application instead
484 // of warning the caller
488 Fp->read((char*)&zero, (size_t)2);
495 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
497 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
498 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
499 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
500 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
502 std::string msg = Util::Format(
503 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
504 gdcmWarningMacro( msg.c_str() );
509 Fp->seekg(126L, std::ios::cur);
510 char dicm[4] = {' ',' ',' ',' '};
511 Fp->read(dicm, (size_t)4);
517 if( memcmp(dicm, "DICM", 4) == 0 )
519 HasDCMPreamble = true;
523 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
525 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
526 << Filename.c_str());
531 * \brief closes the file
532 * @return TRUE if the close was successfull
534 bool Document::CloseFile()
546 * \brief Writes in a file all the Header Entries (Dicom Elements)
547 * @param fp file pointer on an already open file (actually: Output File Stream)
548 * @param filetype Type of the File to be written
549 * (ACR-NEMA, ExplicitVR, ImplicitVR)
550 * @return Always true.
552 void Document::WriteContent(std::ofstream *fp, FileType filetype)
554 // \TODO move the following lines (and a lot of others, to be written)
555 // to a future function CheckAndCorrectHeader
557 // (necessary if user wants to write a DICOM V3 file
558 // starting from an ACR-NEMA (V2) Header
560 if ( filetype == ImplicitVR || filetype == ExplicitVR )
562 // writing Dicom File Preamble
563 char filePreamble[128];
564 memset(filePreamble, 0, 128);
565 fp->write(filePreamble, 128);
566 fp->write("DICM", 4);
570 * \todo rewrite later, if really usefull
571 * - 'Group Length' element is optional in DICOM
572 * - but un-updated odd groups lengthes can causes pb
575 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
576 * UpdateGroupLength(false,filetype);
577 * if ( filetype == ACR)
578 * UpdateGroupLength(true,ACR);
581 ElementSet::WriteContent(fp, filetype); // This one is recursive
584 // -----------------------------------------
587 * \brief Loads (from disk) the element content
588 * when a string is not suitable
589 * @param group group number of the Entry
590 * @param elem element number of the Entry
592 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
594 // Search the corresponding DocEntry
595 DocEntry *docElement = GetDocEntry(group, elem);
599 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
603 LoadEntryBinArea(binElement);
607 * \brief Loads (from disk) the element content
608 * when a string is not suitable
609 * @param elem Entry whose binArea is going to be loaded
611 void Document::LoadEntryBinArea(BinEntry *elem)
613 if(elem->GetBinArea())
620 size_t o =(size_t)elem->GetOffset();
621 Fp->seekg(o, std::ios::beg);
623 size_t l = elem->GetLength();
624 uint8_t *a = new uint8_t[l];
627 gdcmWarningMacro( "Cannot allocate BinEntry content");
631 Fp->read((char*)a, l);
632 if( Fp->fail() || Fp->eof())
645 * \brief Loads the element while preserving the current
646 * underlying file position indicator as opposed to
647 * LoadDocEntry that modifies it.
648 * @param entry DocEntry whose value will be loaded.
650 void Document::LoadDocEntrySafe(DocEntry *entry)
654 long PositionOnEntry = Fp->tellg();
656 Fp->seekg(PositionOnEntry, std::ios::beg);
661 * \brief Compares two documents, according to \ref DicomDir rules
662 * \warning Does NOT work with ACR-NEMA files
663 * \todo Find a trick to solve the pb (use RET fields ?)
664 * @param document to compare with current one
665 * @return true if 'smaller'
667 bool Document::operator<(Document &document)
670 std::string s1 = GetEntryValue(0x0010,0x0010);
671 std::string s2 = document.GetEntryValue(0x0010,0x0010);
683 s1 = GetEntryValue(0x0010,0x0020);
684 s2 = document.GetEntryValue(0x0010,0x0020);
695 // Study Instance UID
696 s1 = GetEntryValue(0x0020,0x000d);
697 s2 = document.GetEntryValue(0x0020,0x000d);
708 // Serie Instance UID
709 s1 = GetEntryValue(0x0020,0x000e);
710 s2 = document.GetEntryValue(0x0020,0x000e);
725 //-----------------------------------------------------------------------------
728 * \brief Reads a supposed to be 16 Bits integer
729 * (swaps it depending on processor endianness)
732 uint16_t Document::ReadInt16()
736 Fp->read ((char*)&g, (size_t)2);
739 throw FormatError( "Document::ReadInt16()", " file error." );
743 throw FormatError( "Document::ReadInt16()", "EOF." );
750 * \brief Reads a supposed to be 32 Bits integer
751 * (swaps it depending on processor endianness)
754 uint32_t Document::ReadInt32()
758 Fp->read ((char*)&g, (size_t)4);
761 throw FormatError( "Document::ReadInt32()", " file error." );
765 throw FormatError( "Document::ReadInt32()", "EOF." );
772 * \brief skips bytes inside the source file
773 * \warning NOT end user intended method !
776 void Document::SkipBytes(uint32_t nBytes)
778 //FIXME don't dump the returned value
779 Fp->seekg((long)nBytes, std::ios::cur);
783 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
784 * @param filetype Type of the File to be written
786 int Document::ComputeGroup0002Length( FileType filetype )
792 bool found0002 = false;
794 // for each zero-level Tag in the DCM Header
795 DocEntry *entry = GetFirstEntry();
798 gr = entry->GetGroup();
804 if( entry->GetElement() != 0x0000 )
808 if( filetype == ExplicitVR )
810 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
812 // explicit VR AND OB, OW, SQ : 4 more bytes
816 groupLength += 2 + 2 + 4 + entry->GetLength();
822 entry = GetNextEntry();
827 //-----------------------------------------------------------------------------
830 * \brief Loads all the needed Dictionaries
831 * \warning NOT end user intended method !
833 void Document::Initialize()
835 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
841 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
842 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
843 * @param offset start of parsing
844 * @param l_max length to parse
845 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
847 void Document::ParseDES(DocEntrySet *set, long offset,
848 long l_max, bool delim_mode)
850 DocEntry *newDocEntry;
851 ValEntry *newValEntry;
852 BinEntry *newBinEntry;
853 SeqEntry *newSeqEntry;
859 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
865 newDocEntry = ReadNextDocEntry( );
872 vr = newDocEntry->GetVR();
873 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
874 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
875 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
877 if ( newValEntry || newBinEntry )
881 if ( Filetype == ExplicitVR &&
882 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
884 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
885 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
886 << "|" << newDocEntry->GetElement()
887 << " : Neither Valentry, nor BinEntry."
888 "Probably unknown VR.");
891 //////////////////// BinEntry or UNKOWN VR:
892 // When "this" is a Document the Key is simply of the
893 // form ( group, elem )...
894 if ( dynamic_cast< Document* > ( set ) )
896 newBinEntry->SetKey( newBinEntry->GetKey() );
898 // but when "this" is a SQItem, we are inserting this new
899 // valEntry in a sequence item, and the key has the
900 // generalized form (refer to \ref BaseTagKey):
901 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
903 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
904 + newBinEntry->GetKey() );
907 LoadDocEntry( newBinEntry );
908 if( !set->AddEntry( newBinEntry ) )
910 //Expect big troubles if here
911 //delete newBinEntry;
917 /////////////////////// ValEntry
919 // When "set" is a Document, then we are at the top of the
920 // hierarchy and the Key is simply of the form ( group, elem )...
921 if ( dynamic_cast< Document* > ( set ) )
923 newValEntry->SetKey( newValEntry->GetKey() );
925 // ...but when "set" is a SQItem, we are inserting this new
926 // valEntry in a sequence item. Hence the key has the
927 // generalized form (refer to \ref BaseTagKey):
928 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
930 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
931 + newValEntry->GetKey() );
934 LoadDocEntry( newValEntry );
935 bool delimitor=newValEntry->IsItemDelimitor();
937 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
938 // shadow groups ( if possible :
939 // whether element 0x0000 exits)
941 if ( newValEntry->GetGroup()%2 != 0 )
943 if ( newValEntry->GetElement() == 0x0000 )
945 std::string strLgrGroup = newValEntry->GetValue();
947 if ( strLgrGroup != GDCM_UNFOUND)
949 lgrGroup = atoi(strLgrGroup.c_str());
950 Fp->seekg(lgrGroup , std::ios::cur);
958 if( !set->AddEntry( newValEntry ) )
960 // If here expect big troubles
961 // delete newValEntry; //otherwise mem leak
971 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
979 // Just to make sure we are at the beginning of next entry.
980 SkipToNextDocEntry(newDocEntry);
985 unsigned long l = newDocEntry->GetReadLength();
986 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
988 if ( l == 0xffffffff )
998 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
1000 Fp->seekg( l, std::ios::cur);
1005 // no other way to create it ...
1006 newSeqEntry->SetDelimitorMode( delim_mode );
1008 // At the top of the hierarchy, stands a Document. When "set"
1009 // is a Document, then we are building the first depth level.
1010 // Hence the SeqEntry we are building simply has a depth
1012 if ( dynamic_cast< Document* > ( set ) )
1014 newSeqEntry->SetDepthLevel( 1 );
1015 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1017 // But when "set" is already a SQItem, we are building a nested
1018 // sequence, and hence the depth level of the new SeqEntry
1019 // we are building, is one level deeper:
1020 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1022 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1023 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1024 + newSeqEntry->GetKey() );
1028 { // Don't try to parse zero-length sequences
1029 ParseSQ( newSeqEntry,
1030 newDocEntry->GetOffset(),
1033 if( !set->AddEntry( newSeqEntry ) )
1038 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1052 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1053 * @return parsed length for this level
1055 void Document::ParseSQ( SeqEntry *seqEntry,
1056 long offset, long l_max, bool delim_mode)
1058 int SQItemNumber = 0;
1060 long offsetStartCurrentSQItem = offset;
1064 // the first time, we read the fff0,e000 of the first SQItem
1065 DocEntry *newDocEntry = ReadNextDocEntry();
1069 // FIXME Should warn user
1074 if ( newDocEntry->IsSequenceDelimitor() )
1076 seqEntry->SetDelimitationItem( newDocEntry );
1080 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1085 // create the current SQItem
1086 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1087 std::ostringstream newBase;
1088 newBase << seqEntry->GetKey()
1092 itemSQ->SetBaseTagKey( newBase.str() );
1093 unsigned int l = newDocEntry->GetReadLength();
1095 if ( l == 0xffffffff )
1104 // Let's try :------------
1105 // remove fff0,e000, created out of the SQItem
1107 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1108 // fill up the current SQItem, starting at the beginning of fff0,e000
1109 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1110 offsetStartCurrentSQItem = Fp->tellg();
1111 // end try -----------------
1113 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1115 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1123 * \brief Loads the element content if its length doesn't exceed
1124 * the value specified with Document::SetMaxSizeLoadEntry()
1125 * @param entry Header Entry (Dicom Element) to be dealt with
1127 void Document::LoadDocEntry(DocEntry *entry)
1129 uint16_t group = entry->GetGroup();
1130 std::string vr = entry->GetVR();
1131 uint32_t length = entry->GetLength();
1133 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1135 // A SeQuence "contains" a set of Elements.
1136 // (fffe e000) tells us an Element is beginning
1137 // (fffe e00d) tells us an Element just ended
1138 // (fffe e0dd) tells us the current SeQuence just ended
1139 if( group == 0xfffe )
1141 // NO more value field for SQ !
1145 // When the length is zero things are easy:
1148 ((ValEntry *)entry)->SetValue("");
1152 // The elements whose length is bigger than the specified upper bound
1153 // are not loaded. Instead we leave a short notice of the offset of
1154 // the element content and it's length.
1156 std::ostringstream s;
1157 if (length > MaxSizeLoadEntry)
1159 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1161 //s << "gdcm::NotLoaded (BinEntry)";
1162 s << GDCM_NOTLOADED;
1163 s << " Ad.:" << (long)entry->GetOffset();
1164 s << " x(" << std::hex << entry->GetOffset() << ")";
1166 s << " Lgt:" << entry->GetLength();
1167 s << " x(" << std::hex << entry->GetLength() << ")";
1168 binEntryPtr->SetValue(s.str());
1170 // Be carefull : a BinEntry IS_A ValEntry ...
1171 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1173 // s << "gdcm::NotLoaded. (ValEntry)";
1174 s << GDCM_NOTLOADED;
1175 s << " Address:" << (long)entry->GetOffset();
1176 s << " Length:" << entry->GetLength();
1177 s << " x(" << std::hex << entry->GetLength() << ")";
1178 valEntryPtr->SetValue(s.str());
1183 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1184 << "nor a ValEntry ?! Should never print that !" );
1187 // to be sure we are at the end of the value ...
1188 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1193 // When we find a BinEntry not very much can be done :
1194 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1196 s << GDCM_BINLOADED;
1197 binEntryPtr->SetValue(s.str());
1198 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1202 if ( IsDocEntryAnInteger(entry) )
1206 // When short integer(s) are expected, read and convert the following
1207 // n *two characters properly i.e. consider them as short integers as
1208 // opposed to strings.
1209 // Elements with Value Multiplicity > 1
1210 // contain a set of integers (not a single one)
1211 if (vr == "US" || vr == "SS")
1214 NewInt = ReadInt16();
1218 for (int i=1; i < nbInt; i++)
1221 NewInt = ReadInt16();
1226 // See above comment on multiple integers (mutatis mutandis).
1227 else if (vr == "UL" || vr == "SL")
1230 NewInt = ReadInt32();
1234 for (int i=1; i < nbInt; i++)
1237 NewInt = ReadInt32();
1242 #ifdef GDCM_NO_ANSI_STRING_STREAM
1243 s << std::ends; // to avoid oddities on Solaris
1244 #endif //GDCM_NO_ANSI_STRING_STREAM
1246 ((ValEntry *)entry)->SetValue(s.str());
1250 // FIXME: We need an additional byte for storing \0 that is not on disk
1251 char *str = new char[length+1];
1252 Fp->read(str, (size_t)length);
1253 str[length] = '\0'; //this is only useful when length is odd
1254 // Special DicomString call to properly handle \0 and even length
1255 std::string newValue;
1258 newValue = Util::DicomString(str, length+1);
1259 gdcmWarningMacro("Warning: bad length: " << length <<
1260 ",For string :" << newValue.c_str());
1261 // Since we change the length of string update it length
1262 //entry->SetReadLength(length+1);
1266 newValue = Util::DicomString(str, length);
1270 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1272 if ( Fp->fail() || Fp->eof())
1274 gdcmWarningMacro("Unread element value");
1275 valEntry->SetValue(GDCM_UNREAD);
1281 // Because of correspondance with the VR dic
1282 valEntry->SetValue(newValue);
1286 valEntry->SetValue(newValue);
1291 gdcmErrorMacro( "Should have a ValEntry, here !");
1296 * \brief Find the value Length of the passed Header Entry
1297 * @param entry Header Entry whose length of the value shall be loaded.
1299 void Document::FindDocEntryLength( DocEntry *entry )
1300 throw ( FormatError )
1302 std::string vr = entry->GetVR();
1305 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1307 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1309 // The following reserved two bytes (see PS 3.5-2003, section
1310 // "7.1.2 Data element structure with explicit vr", p 27) must be
1311 // skipped before proceeding on reading the length on 4 bytes.
1312 Fp->seekg( 2L, std::ios::cur);
1313 uint32_t length32 = ReadInt32();
1315 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1320 lengthOB = FindDocEntryLengthOBOrOW();
1322 catch ( FormatUnexpected )
1324 // Computing the length failed (this happens with broken
1325 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1326 // chance to get the pixels by deciding the element goes
1327 // until the end of the file. Hence we artificially fix the
1328 // the length and proceed.
1329 long currentPosition = Fp->tellg();
1330 Fp->seekg(0L,std::ios::end);
1332 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1333 Fp->seekg(currentPosition, std::ios::beg);
1335 entry->SetReadLength(lengthUntilEOF);
1336 entry->SetLength(lengthUntilEOF);
1339 entry->SetReadLength(lengthOB);
1340 entry->SetLength(lengthOB);
1343 FixDocEntryFoundLength(entry, length32);
1347 // Length is encoded on 2 bytes.
1348 length16 = ReadInt16();
1350 // 0xffff means that we deal with 'No Length' Sequence
1351 // or 'No Length' SQItem
1352 if ( length16 == 0xffff)
1356 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1361 // Either implicit VR or a non DICOM conformal (see note below) explicit
1362 // VR that ommited the VR of (at least) this element. Farts happen.
1363 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1364 // on Data elements "Implicit and Explicit VR Data Elements shall
1365 // not coexist in a Data Set and Data Sets nested within it".]
1366 // Length is on 4 bytes.
1368 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1369 // even if Transfer Syntax is 'Implicit VR ...'
1371 FixDocEntryFoundLength( entry, ReadInt32() );
1377 * \brief Find the Length till the next sequence delimiter
1378 * \warning NOT end user intended method !
1381 uint32_t Document::FindDocEntryLengthOBOrOW()
1382 throw( FormatUnexpected )
1384 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1385 long positionOnEntry = Fp->tellg();
1386 bool foundSequenceDelimiter = false;
1387 uint32_t totalLength = 0;
1389 while ( !foundSequenceDelimiter )
1395 group = ReadInt16();
1398 catch ( FormatError )
1400 throw FormatError("Unexpected end of file encountered during ",
1401 "Document::FindDocEntryLengthOBOrOW()");
1403 // We have to decount the group and element we just read
1405 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1407 long filePosition = Fp->tellg();
1409 "Neither an Item tag nor a Sequence delimiter tag on :"
1410 << std::hex << group << " , " << elem
1411 << ") -before- position x(" << filePosition << ")" );
1413 Fp->seekg(positionOnEntry, std::ios::beg);
1414 throw FormatUnexpected(
1415 "Neither an Item tag nor a Sequence delimiter tag.");
1417 if ( elem == 0xe0dd )
1419 foundSequenceDelimiter = true;
1421 uint32_t itemLength = ReadInt32();
1422 // We add 4 bytes since we just read the ItemLength with ReadInt32
1423 totalLength += itemLength + 4;
1424 SkipBytes(itemLength);
1426 if ( foundSequenceDelimiter )
1431 Fp->seekg( positionOnEntry, std::ios::beg);
1436 * \brief Find the Value Representation of the current Dicom Element.
1437 * @return Value Representation of the current Entry
1439 std::string Document::FindDocEntryVR()
1441 if ( Filetype != ExplicitVR )
1442 return GDCM_UNKNOWN;
1444 long positionOnEntry = Fp->tellg();
1445 // Warning: we believe this is explicit VR (Value Representation) because
1446 // we used a heuristic that found "UL" in the first tag. Alas this
1447 // doesn't guarantee that all the tags will be in explicit VR. In some
1448 // cases (see e-film filtered files) one finds implicit VR tags mixed
1449 // within an explicit VR file. Hence we make sure the present tag
1450 // is in explicit VR and try to fix things if it happens not to be
1454 Fp->read (vr, (size_t)2);
1457 if( !CheckDocEntryVR(vr) )
1459 Fp->seekg(positionOnEntry, std::ios::beg);
1460 return GDCM_UNKNOWN;
1466 * \brief Check the correspondance between the VR of the header entry
1467 * and the taken VR. If they are different, the header entry is
1468 * updated with the new VR.
1469 * @param vr Dicom Value Representation
1470 * @return false if the VR is incorrect of if the VR isn't referenced
1471 * otherwise, it returns true
1473 bool Document::CheckDocEntryVR(VRKey vr)
1475 if ( !Global::GetVR()->IsValidVR(vr) )
1482 * \brief Get the transformed value of the header entry. The VR value
1483 * is used to define the transformation to operate on the value
1484 * \warning NOT end user intended method !
1485 * @param entry entry to tranform
1486 * @return Transformed entry value
1488 std::string Document::GetDocEntryValue(DocEntry *entry)
1490 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1492 std::string val = ((ValEntry *)entry)->GetValue();
1493 std::string vr = entry->GetVR();
1494 uint32_t length = entry->GetLength();
1495 std::ostringstream s;
1498 // When short integer(s) are expected, read and convert the following
1499 // n * 2 bytes properly i.e. as a multivaluated strings
1500 // (each single value is separated fromthe next one by '\'
1501 // as usual for standard multivaluated filels
1502 // Elements with Value Multiplicity > 1
1503 // contain a set of short integers (not a single one)
1505 if( vr == "US" || vr == "SS" )
1510 for (int i=0; i < nbInt; i++)
1516 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1517 newInt16 = SwapShort( newInt16 );
1522 // When integer(s) are expected, read and convert the following
1523 // n * 4 bytes properly i.e. as a multivaluated strings
1524 // (each single value is separated fromthe next one by '\'
1525 // as usual for standard multivaluated filels
1526 // Elements with Value Multiplicity > 1
1527 // contain a set of integers (not a single one)
1528 else if( vr == "UL" || vr == "SL" )
1533 for (int i=0; i < nbInt; i++)
1539 newInt32 = ( val[4*i+0] & 0xFF )
1540 + (( val[4*i+1] & 0xFF ) << 8 )
1541 + (( val[4*i+2] & 0xFF ) << 16 )
1542 + (( val[4*i+3] & 0xFF ) << 24 );
1543 newInt32 = SwapLong( newInt32 );
1547 #ifdef GDCM_NO_ANSI_STRING_STREAM
1548 s << std::ends; // to avoid oddities on Solaris
1549 #endif //GDCM_NO_ANSI_STRING_STREAM
1552 return ((ValEntry *)entry)->GetValue();
1556 * \brief Get the reverse transformed value of the header entry. The VR
1557 * value is used to define the reverse transformation to operate on
1559 * \warning NOT end user intended method !
1560 * @param entry Entry to reverse transform
1561 * @return Reverse transformed entry value
1563 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1565 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1567 std::string vr = entry->GetVR();
1568 std::vector<std::string> tokens;
1569 std::ostringstream s;
1571 if ( vr == "US" || vr == "SS" )
1575 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1576 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1577 for (unsigned int i=0; i<tokens.size(); i++)
1579 newInt16 = atoi(tokens[i].c_str());
1580 s << ( newInt16 & 0xFF )
1581 << (( newInt16 >> 8 ) & 0xFF );
1585 if ( vr == "UL" || vr == "SL")
1589 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1590 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1591 for (unsigned int i=0; i<tokens.size();i++)
1593 newInt32 = atoi(tokens[i].c_str());
1594 s << (char)( newInt32 & 0xFF )
1595 << (char)(( newInt32 >> 8 ) & 0xFF )
1596 << (char)(( newInt32 >> 16 ) & 0xFF )
1597 << (char)(( newInt32 >> 24 ) & 0xFF );
1602 #ifdef GDCM_NO_ANSI_STRING_STREAM
1603 s << std::ends; // to avoid oddities on Solaris
1604 #endif //GDCM_NO_ANSI_STRING_STREAM
1608 return ((ValEntry *)entry)->GetValue();
1612 * \brief Skip a given Header Entry
1613 * \warning NOT end user intended method !
1614 * @param entry entry to skip
1616 void Document::SkipDocEntry(DocEntry *entry)
1618 SkipBytes(entry->GetLength());
1622 * \brief Skips to the beginning of the next Header Entry
1623 * \warning NOT end user intended method !
1624 * @param currentDocEntry entry to skip
1626 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1628 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1629 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1630 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1634 * \brief When the length of an element value is obviously wrong (because
1635 * the parser went Jabberwocky) one can hope improving things by
1636 * applying some heuristics.
1637 * @param entry entry to check
1638 * @param foundLength first assumption about length
1640 void Document::FixDocEntryFoundLength(DocEntry *entry,
1641 uint32_t foundLength)
1643 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1644 if ( foundLength == 0xffffffff)
1649 uint16_t gr = entry->GetGroup();
1650 uint16_t elem = entry->GetElement();
1652 if ( foundLength % 2)
1654 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1655 << " in x(" << std::hex << gr << "," << elem <<")");
1658 //////// Fix for some naughty General Electric images.
1659 // Allthough not recent many such GE corrupted images are still present
1660 // on Creatis hard disks. Hence this fix shall remain when such images
1661 // are no longer in use (we are talking a few years, here)...
1662 // Note: XMedCom probably uses such a trick since it is able to read
1663 // those pesky GE images ...
1664 if ( foundLength == 13)
1666 // Only happens for this length !
1667 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1670 entry->SetReadLength(10); // a bug is to be fixed !?
1674 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1675 // Occurence of such images is quite low (unless one leaves close to a
1676 // 'Leonardo' source. Hence, one might consider commenting out the
1677 // following fix on efficiency reasons.
1678 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1681 entry->SetReadLength(4); // a bug is to be fixed !?
1684 else if ( entry->GetVR() == "SQ" )
1686 foundLength = 0; // ReadLength is unchanged
1689 //////// We encountered a 'delimiter' element i.e. a tag of the form
1690 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1691 // taken into account.
1692 else if( gr == 0xfffe )
1694 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1695 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1696 // causes extra troubles...
1697 if( entry->GetElement() != 0x0000 )
1702 entry->SetLength(foundLength);
1706 * \brief Apply some heuristics to predict whether the considered
1707 * element value contains/represents an integer or not.
1708 * @param entry The element value on which to apply the predicate.
1709 * @return The result of the heuristical predicate.
1711 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1713 uint16_t elem = entry->GetElement();
1714 uint16_t group = entry->GetGroup();
1715 const std::string &vr = entry->GetVR();
1716 uint32_t length = entry->GetLength();
1718 // When we have some semantics on the element we just read, and if we
1719 // a priori know we are dealing with an integer, then we shall be
1720 // able to swap it's element value properly.
1721 if ( elem == 0 ) // This is the group length of the group
1729 // Allthough this should never happen, still some images have a
1730 // corrupted group length [e.g. have a glance at offset x(8336) of
1731 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1732 // Since for dicom compliant and well behaved headers, the present
1733 // test is useless (and might even look a bit paranoid), when we
1734 // encounter such an ill-formed image, we simply display a warning
1735 // message and proceed on parsing (while crossing fingers).
1736 long filePosition = Fp->tellg();
1737 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1738 << std::hex << group << " , " << elem
1739 << ") -before- position x(" << filePosition << ")"
1740 << "lgt : " << length );
1744 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1752 * \brief Discover what the swap code is (among little endian, big endian,
1753 * bad little endian, bad big endian).
1755 * @return false when we are absolutely sure
1756 * it's neither ACR-NEMA nor DICOM
1757 * true when we hope ours assuptions are OK
1759 bool Document::CheckSwap()
1761 // The only guaranted way of finding the swap code is to find a
1762 // group tag since we know it's length has to be of four bytes i.e.
1763 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1764 // occurs when we can't find such group...
1771 // First, compare HostByteOrder and NetworkByteOrder in order to
1772 // determine if we shall need to swap bytes (i.e. the Endian type).
1773 bool net2host = Util::IsCurrentProcessorBigEndian();
1775 // The easiest case is the one of a 'true' DICOM header, we just have
1776 // to look for the string "DICM" inside the file preamble.
1779 char *entCur = deb + 128;
1780 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1782 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1784 // Group 0002 should always be VR, and the first element 0000
1785 // Let's be carefull (so many wrong headers ...)
1786 // and determine the value representation (VR) :
1787 // Let's skip to the first element (0002,0000) and check there if we find
1788 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1789 // in which case we (almost) know it is explicit VR.
1790 // WARNING: if it happens to be implicit VR then what we will read
1791 // is the length of the group. If this ascii representation of this
1792 // length happens to be "UL" then we shall believe it is explicit VR.
1793 // We need to skip :
1794 // * the 128 bytes of File Preamble (often padded with zeroes),
1795 // * the 4 bytes of "DICM" string,
1796 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1797 // i.e. a total of 136 bytes.
1800 // group 0x0002 *is always* Explicit VR Sometimes ,
1801 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1802 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1804 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1805 memcmp(entCur, "OB", (size_t)2) == 0 ||
1806 memcmp(entCur, "UI", (size_t)2) == 0 ||
1807 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1808 // when Write DCM *adds*
1810 // Use Document::dicom_vr to test all the possibilities
1811 // instead of just checking for UL, OB and UI !? group 0000
1813 Filetype = ExplicitVR;
1814 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1818 Filetype = ImplicitVR;
1819 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1820 << "Looks like a bugged Header!");
1826 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1831 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1834 // Position the file position indicator at first tag
1835 // (i.e. after the file preamble and the "DICM" string).
1837 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1839 Fp->seekg ( 132L, std::ios::beg);
1841 } // ------------------------------- End of DicomV3 ----------------
1843 // Alas, this is not a DicomV3 file and whatever happens there is no file
1844 // preamble. We can reset the file position indicator to where the data
1845 // is (i.e. the beginning of the file).
1847 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1849 Fp->seekg(0, std::ios::beg);
1851 // Let's check 'No Preamble Dicom File' :
1852 // Should start with group 0x0002
1853 // and be Explicit Value Representation
1855 s16 = *((uint16_t *)(deb));
1868 if ( SwapCode != 0 )
1870 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1871 memcmp(entCur, "OB", (size_t)2) == 0 ||
1872 memcmp(entCur, "UI", (size_t)2) == 0 ||
1873 memcmp(entCur, "SH", (size_t)2) == 0 ||
1874 memcmp(entCur, "AE", (size_t)2) == 0 ||
1875 memcmp(entCur, "OB", (size_t)2) == 0 )
1877 Filetype = ExplicitVR;
1878 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1882 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1884 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1885 // By clean we mean that the length of the first group is written down.
1886 // If this is the case and since the length of the first group HAS to be
1887 // four (bytes), then determining the proper swap code is straightforward.
1890 // We assume the array of char we are considering contains the binary
1891 // representation of a 32 bits integer. Hence the following dirty
1893 s32 = *((uint32_t *)(entCur));
1913 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1914 // It is time for despaired wild guesses.
1915 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1916 // i.e. the 'group length' element is not present :
1918 // check the supposed-to-be 'group number'
1919 // in ( 0x0001 .. 0x0008 )
1920 // to determine ' SwapCode' value .
1921 // Only 0 or 4321 will be possible
1922 // (no oportunity to check for the formerly well known
1923 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1924 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1925 // the file IS NOT ACR-NEMA nor DICOM V3
1926 // Find a trick to tell it the caller...
1928 s16 = *((uint16_t *)(deb));
1955 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1963 * \brief Change the Byte Swap code.
1965 void Document::SwitchByteSwapCode()
1967 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1968 if ( SwapCode == 1234 )
1972 else if ( SwapCode == 4321 )
1976 else if ( SwapCode == 3412 )
1980 else if ( SwapCode == 2143 )
1987 * \brief during parsing, Header Elements too long are not loaded in memory
1988 * @param newSize new size
1990 void Document::SetMaxSizeLoadEntry(long newSize)
1996 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1998 MaxSizeLoadEntry = 0xffffffff;
2001 MaxSizeLoadEntry = newSize;
2005 * \brief Read the next tag but WITHOUT loading it's value
2006 * (read the 'Group Number', the 'Element Number',
2007 * gets the Dict Entry
2008 * gets the VR, gets the length, gets the offset value)
2009 * @return On succes the newly created DocEntry, NULL on failure.
2011 DocEntry *Document::ReadNextDocEntry()
2018 group = ReadInt16();
2021 catch ( FormatError e )
2023 // We reached the EOF (or an error occured) therefore
2024 // header parsing has to be considered as finished.
2028 // Sometimes file contains groups of tags with reversed endianess.
2029 HandleBrokenEndian(group, elem);
2031 // In 'true DICOM' files Group 0002 is always little endian
2032 if ( HasDCMPreamble )
2033 HandleOutOfGroup0002(group, elem);
2035 std::string vr = FindDocEntryVR();
2036 std::string realVR = vr;
2038 if( vr == GDCM_UNKNOWN)
2040 if ( elem == 0x0000 ) // Group Length
2041 realVR = "UL"; // must be UL
2044 DictEntry *dictEntry = GetDictEntry(group,elem);
2046 realVR = dictEntry->GetVR();
2051 if( Global::GetVR()->IsVROfSequence(realVR) )
2052 newEntry = NewSeqEntry(group, elem);
2053 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2054 newEntry = NewValEntry(group, elem,vr);
2056 newEntry = NewBinEntry(group, elem,vr);
2058 if( vr == GDCM_UNKNOWN )
2060 if( Filetype == ExplicitVR )
2062 // We thought this was explicit VR, but we end up with an
2063 // implicit VR tag. Let's backtrack.
2064 if ( newEntry->GetGroup() != 0xfffe )
2067 msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n",
2068 newEntry->GetGroup(), newEntry->GetElement());
2069 gdcmWarningMacro( msg.c_str() );
2072 newEntry->SetImplicitVR();
2077 FindDocEntryLength(newEntry);
2079 catch ( FormatError e )
2086 newEntry->SetOffset(Fp->tellg());
2092 * \brief Handle broken private tag from Philips NTSCAN
2093 * where the endianess is being switch to BigEndian for no
2097 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2099 // Endian reversion. Some files contain groups of tags with reversed endianess.
2100 static int reversedEndian = 0;
2101 // try to fix endian switching in the middle of headers
2102 if ((group == 0xfeff) && (elem == 0x00e0))
2104 // start endian swap mark for group found
2106 SwitchByteSwapCode();
2111 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2113 // end of reversed endian group
2115 SwitchByteSwapCode();
2120 * \brief Group 0002 is always coded Little Endian
2121 * whatever Transfer Syntax is
2124 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2126 // Endian reversion. Some files contain groups of tags with reversed endianess.
2127 if ( !Group0002Parsed && group != 0x0002)
2129 Group0002Parsed = true;
2130 // we just came out of group 0002
2131 // if Transfer syntax is Big Endian we have to change CheckSwap
2133 std::string ts = GetTransferSyntax();
2134 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2136 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2140 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2142 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2144 Filetype = ImplicitVR;
2147 // FIXME Strangely, this works with
2148 //'Implicit VR Transfer Syntax (GE Private)
2149 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2151 gdcmWarningMacro("Transfer Syntax Name = ["
2152 << GetTransferSyntaxName() << "]" );
2153 SwitchByteSwapCode();
2154 group = SwapShort(group);
2155 elem = SwapShort(elem);
2160 //-----------------------------------------------------------------------------
2163 //-----------------------------------------------------------------------------
2164 } // end namespace gdcm