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