1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/06/29 15:58:33 $
7 Version: $Revision: 1.252 $
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 " )
173 // Probabely this line should be outside the 'if'
174 // Try to find an image sample holding a 'gray LUT'
175 LoadEntryBinArea(0x0028,0x1200); // gray LUT
178 /// The tags refered by the three following lines used to be CORRECTLY
179 /// defined as having an US Value Representation in the public
180 /// dictionary. BUT the semantics implied by the three following
181 /// lines state that the corresponding tag contents are in fact
182 /// the ones of a BinEntry.
183 /// In order to fix things "Quick and Dirty" the dictionary was
184 /// altered on PURPOSE but now contains a WRONG value.
185 /// In order to fix things and restore the dictionary to its
186 /// correct value, one needs to decided of the semantics by deciding
187 /// whether the following tags are either:
188 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
189 /// also used as BinEntry, which requires the proper conversion,
190 /// - OW, and hence loaded as BinEntry, but afterwards also used
191 /// as ValEntry, which requires the proper conversion.
192 LoadEntryBinArea(0x0028,0x1201); // R LUT
193 LoadEntryBinArea(0x0028,0x1202); // G LUT
194 LoadEntryBinArea(0x0028,0x1203); // B LUT
196 // Segmented Red Palette Color LUT Data
197 LoadEntryBinArea(0x0028,0x1221);
198 // Segmented Green Palette Color LUT Data
199 LoadEntryBinArea(0x0028,0x1222);
200 // Segmented Blue Palette Color LUT Data
201 LoadEntryBinArea(0x0028,0x1223);
204 //FIXME later : how to use it?
205 SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
208 SQItem *sqi= modLutSeq->GetFirstSQItem();
211 BinEntry *b = sqi->GetBinEntry(0x0028,0x3006);
214 if ( b->GetLength() != 0 )
216 LoadEntryBinArea(b); //LUT Data (CTX dependent)
224 // ----------------------------
225 // Specific code to allow gdcm to read ACR-LibIDO formated images
226 // Note: ACR-LibIDO is an extension of the ACR standard that was
227 // used at CREATIS. For the time being (say a couple years)
228 // we keep this kludge to allow CREATIS users
229 // reading their old images.
231 // if recognition code tells us we deal with a LibIDO image
232 // we switch lineNumber and columnNumber
235 RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
236 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
237 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
238 // with "little-endian strings"
240 Filetype = ACR_LIBIDO;
241 std::string rows = GetEntryValue(0x0028, 0x0010);
242 std::string columns = GetEntryValue(0x0028, 0x0011);
243 SetValEntry(columns, 0x0028, 0x0010);
244 SetValEntry(rows , 0x0028, 0x0011);
246 // --- End of ACR-LibIDO kludge ---
252 * \brief Get the public dictionary used
254 Dict *Document::GetPubDict()
260 * \brief Get the shadow dictionary used
262 Dict *Document::GetShaDict()
268 * \brief Set the shadow dictionary used
269 * @param dict dictionary to use in shadow
271 bool Document::SetShaDict(Dict *dict)
278 * \brief Set the shadow dictionary used
279 * @param dictName name of the dictionary to use in shadow
281 bool Document::SetShaDict(DictKey const &dictName)
283 RefShaDict = Global::GetDicts()->GetDict(dictName);
288 * \brief This predicate tells us whether or not the current Document
289 * was properly parsed and contains at least *one* Dicom Element
290 * (and nothing more, sorry).
291 * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
294 bool Document::IsReadable()
296 if ( Filetype == Unknown )
298 gdcmWarningMacro( "Wrong filetype");
304 gdcmWarningMacro( "No tag in internal hash table.");
312 * \brief Predicate for dicom version 3 file.
313 * @return True when the file is a dicom version 3.
315 bool Document::IsDicomV3()
317 // Checking if Transfer Syntax exists is enough
318 // Anyway, it's too late check if the 'Preamble' was found ...
319 // And ... would it be a rich idea to check ?
320 // (some 'no Preamble' DICOM images exist !)
321 return GetDocEntry(0x0002, 0x0010) != NULL;
325 * \brief Predicate for Papyrus file
326 * Dedicated to whomsoever it may concern
327 * @return True when the file is a Papyrus file.
329 bool Document::IsPapyrus()
331 // check for Papyrus private Sequence
332 DocEntry *e = GetDocEntry(0x0041, 0x1050);
335 // check if it's actually a Sequence
336 if ( !dynamic_cast<SeqEntry*>(e) )
342 * \brief returns the File Type
343 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
344 * @return the FileType code
346 FileType Document::GetFileType()
352 * \brief Accessor to the Transfer Syntax (when present) of the
353 * current document (it internally handles reading the
354 * value from disk when only parsing occured).
355 * @return The encountered Transfer Syntax of the current document.
357 std::string Document::GetTransferSyntax()
359 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
365 // The entry might be present but not loaded (parsing and loading
366 // happen at different stages): try loading and proceed with check...
367 LoadDocEntrySafe(entry);
368 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
370 std::string transfer = valEntry->GetValue();
371 // The actual transfer (as read from disk) might be padded. We
372 // first need to remove the potential padding. We can make the
373 // weak assumption that padding was not executed with digits...
374 if ( transfer.length() == 0 )
376 // for brain damaged headers
379 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
381 transfer.erase(transfer.length()-1, 1);
389 * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
390 * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
392 std::string Document::GetTransferSyntaxName()
394 // use the TS (TS : Transfer Syntax)
395 std::string transferSyntax = GetEntryValue(0x0002,0x0010);
397 if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
399 gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
400 << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
401 return "Uncompressed ACR-NEMA";
403 if ( transferSyntax == GDCM_UNFOUND )
405 gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
406 return "Uncompressed ACR-NEMA";
409 // we do it only when we need it
410 const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
412 // Global::GetTS() is a global static you shall never try to delete it!
416 // --------------- Swap Code ------------------
418 * \brief Swaps the bytes so they agree with the processor order
419 * @return The properly swaped 16 bits integer.
421 uint16_t Document::SwapShort(uint16_t a)
423 if ( SwapCode == 4321 || SwapCode == 2143 )
425 //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
427 a = ( a << 8 ) | ( a >> 8 );
433 * \brief Swaps back the bytes of 4-byte long integer accordingly to
435 * @return The properly swaped 32 bits integer.
437 uint32_t Document::SwapLong(uint32_t a)
444 // a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
445 // ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
447 a=( ( a<<24) | ((a<<8) & 0x00ff0000) |
448 ((a>>8) & 0x0000ff00) | (a>>24) );
451 // a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
452 a=( (a<<16) | (a>>16) );
455 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
458 gdcmErrorMacro( "Unset swap code:" << SwapCode );
465 // -----------------File I/O ---------------
467 * \brief Tries to open the file \ref Document::Filename and
468 * checks the preamble when existing.
469 * @return The FILE pointer on success.
471 std::ifstream *Document::OpenFile()
473 HasDCMPreamble = false;
474 if (Filename.length() == 0)
481 gdcmWarningMacro( "File already open: " << Filename.c_str());
485 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
488 // Don't user gdcmErrorMacro :
489 // a spurious message will appear when you use, for instance
490 // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
491 // to create outputFileName.
492 gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
496 //exit(1); // No function is allowed to leave the application instead
497 // of warning the caller
501 Fp->read((char*)&zero, (size_t)2);
508 //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
510 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
511 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
512 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
513 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
515 std::string msg = Util::Format(
516 "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
517 gdcmWarningMacro( msg.c_str() );
522 Fp->seekg(126L, std::ios::cur);
523 char dicm[4] = {' ',' ',' ',' '};
524 Fp->read(dicm, (size_t)4);
530 if ( memcmp(dicm, "DICM", 4) == 0 )
532 HasDCMPreamble = true;
536 // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
538 gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
539 << Filename.c_str());
544 * \brief closes the file
545 * @return TRUE if the close was successfull
547 bool Document::CloseFile()
559 * \brief Writes in a file all the Header Entries (Dicom Elements)
560 * @param fp file pointer on an already open file (actually: Output File Stream)
561 * @param filetype Type of the File to be written
562 * (ACR-NEMA, ExplicitVR, ImplicitVR)
563 * @return Always true.
565 void Document::WriteContent(std::ofstream *fp, FileType filetype)
567 // \TODO move the following lines (and a lot of others, to be written)
568 // to a future function CheckAndCorrectHeader
570 // (necessary if user wants to write a DICOM V3 file
571 // starting from an ACR-NEMA (V2) Header
573 if ( filetype == ImplicitVR || filetype == ExplicitVR )
575 // writing Dicom File Preamble
576 char filePreamble[128];
577 memset(filePreamble, 0, 128);
578 fp->write(filePreamble, 128);
579 fp->write("DICM", 4);
583 * \todo rewrite later, if really usefull
584 * - 'Group Length' element is optional in DICOM
585 * - but un-updated odd groups lengthes can causes pb
588 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
589 * UpdateGroupLength(false,filetype);
590 * if ( filetype == ACR)
591 * UpdateGroupLength(true,ACR);
594 ElementSet::WriteContent(fp, filetype); // This one is recursive
597 // -----------------------------------------
600 * \brief Loads (from disk) the element content
601 * when a string is not suitable
602 * @param group group number of the Entry
603 * @param elem element number of the Entry
605 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
607 // Search the corresponding DocEntry
608 DocEntry *docElement = GetDocEntry(group, elem);
612 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
616 LoadEntryBinArea(binElement);
620 * \brief Loads (from disk) the element content
621 * when a string is not suitable
622 * @param elem Entry whose binArea is going to be loaded
624 void Document::LoadEntryBinArea(BinEntry *elem)
626 if (elem->GetBinArea() )
633 size_t o =(size_t)elem->GetOffset();
634 Fp->seekg(o, std::ios::beg);
636 size_t l = elem->GetLength();
637 uint8_t *a = new uint8_t[l];
640 gdcmWarningMacro( "Cannot allocate BinEntry content");
644 Fp->read((char*)a, l);
645 if ( Fp->fail() || Fp->eof() )
658 * \brief Loads the element while preserving the current
659 * underlying file position indicator as opposed to
660 * LoadDocEntry that modifies it.
661 * @param entry DocEntry whose value will be loaded.
663 void Document::LoadDocEntrySafe(DocEntry *entry)
667 long PositionOnEntry = Fp->tellg();
669 Fp->seekg(PositionOnEntry, std::ios::beg);
674 * \brief Compares two documents, according to \ref DicomDir rules
675 * \warning Does NOT work with ACR-NEMA files
676 * \todo Find a trick to solve the pb (use RET fields ?)
677 * @param document to compare with current one
678 * @return true if 'smaller'
680 bool Document::operator<(Document &document)
683 std::string s1 = GetEntryValue(0x0010,0x0010);
684 std::string s2 = document.GetEntryValue(0x0010,0x0010);
696 s1 = GetEntryValue(0x0010,0x0020);
697 s2 = document.GetEntryValue(0x0010,0x0020);
708 // Study Instance UID
709 s1 = GetEntryValue(0x0020,0x000d);
710 s2 = document.GetEntryValue(0x0020,0x000d);
721 // Serie Instance UID
722 s1 = GetEntryValue(0x0020,0x000e);
723 s2 = document.GetEntryValue(0x0020,0x000e);
738 //-----------------------------------------------------------------------------
741 * \brief Reads a supposed to be 16 Bits integer
742 * (swaps it depending on processor endianness)
745 uint16_t Document::ReadInt16()
749 Fp->read ((char*)&g, (size_t)2);
752 throw FormatError( "Document::ReadInt16()", " file error." );
756 throw FormatError( "Document::ReadInt16()", "EOF." );
763 * \brief Reads a supposed to be 32 Bits integer
764 * (swaps it depending on processor endianness)
767 uint32_t Document::ReadInt32()
771 Fp->read ((char*)&g, (size_t)4);
774 throw FormatError( "Document::ReadInt32()", " file error." );
778 throw FormatError( "Document::ReadInt32()", "EOF." );
785 * \brief skips bytes inside the source file
786 * \warning NOT end user intended method !
789 void Document::SkipBytes(uint32_t nBytes)
791 //FIXME don't dump the returned value
792 Fp->seekg((long)nBytes, std::ios::cur);
796 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
797 * @param filetype Type of the File to be written
799 int Document::ComputeGroup0002Length( FileType filetype )
805 bool found0002 = false;
807 // for each zero-level Tag in the DCM Header
808 DocEntry *entry = GetFirstEntry();
811 gr = entry->GetGroup();
817 if ( entry->GetElement() != 0x0000 )
821 if ( filetype == ExplicitVR )
823 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || (vr == "UT") )
825 // explicit VR AND OB, OW, SQ, UT : 4 more bytes
829 groupLength += 2 + 2 + 4 + entry->GetLength();
835 entry = GetNextEntry();
840 //-----------------------------------------------------------------------------
843 * \brief Loads all the needed Dictionaries
844 * \warning NOT end user intended method !
846 void Document::Initialize()
848 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
854 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
855 * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
856 * @param offset start of parsing
857 * @param l_max length to parse
858 * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
860 void Document::ParseDES(DocEntrySet *set, long offset,
861 long l_max, bool delim_mode)
863 DocEntry *newDocEntry;
864 ValEntry *newValEntry;
865 BinEntry *newBinEntry;
866 SeqEntry *newSeqEntry;
872 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
878 newDocEntry = ReadNextDocEntry( );
885 vr = newDocEntry->GetVR();
886 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
887 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
888 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
890 if ( newValEntry || newBinEntry )
894 if ( Filetype == ExplicitVR &&
895 !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
897 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
898 gdcmWarningMacro( std::hex << newDocEntry->GetGroup()
899 << "|" << newDocEntry->GetElement()
900 << " : Neither Valentry, nor BinEntry."
901 "Probably unknown VR.");
904 //////////////////// BinEntry or UNKOWN VR:
905 // When "this" is a Document the Key is simply of the
906 // form ( group, elem )...
907 if ( dynamic_cast< Document* > ( set ) )
909 newBinEntry->SetKey( newBinEntry->GetKey() );
911 // but when "this" is a SQItem, we are inserting this new
912 // valEntry in a sequence item, and the key has the
913 // generalized form (refer to \ref BaseTagKey):
914 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
916 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
917 + newBinEntry->GetKey() );
920 LoadDocEntry( newBinEntry );
921 if ( !set->AddEntry( newBinEntry ) )
923 //Expect big troubles if here
924 //delete newBinEntry;
930 /////////////////////// ValEntry
932 // When "set" is a Document, then we are at the top of the
933 // hierarchy and the Key is simply of the form ( group, elem )...
934 if ( dynamic_cast< Document* > ( set ) )
936 newValEntry->SetKey( newValEntry->GetKey() );
938 // ...but when "set" is a SQItem, we are inserting this new
939 // valEntry in a sequence item. Hence the key has the
940 // generalized form (refer to \ref BaseTagKey):
941 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
943 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
944 + newValEntry->GetKey() );
947 LoadDocEntry( newValEntry );
948 bool delimitor=newValEntry->IsItemDelimitor();
950 if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible,
951 // shadow groups ( if possible :
952 // whether element 0x0000 exits)
954 if ( newValEntry->GetGroup()%2 != 0 )
956 if ( newValEntry->GetElement() == 0x0000 )
958 std::string strLgrGroup = newValEntry->GetValue();
960 if ( strLgrGroup != GDCM_UNFOUND)
962 lgrGroup = atoi(strLgrGroup.c_str());
963 Fp->seekg(lgrGroup, std::ios::cur);
971 if ( !set->AddEntry( newValEntry ) )
973 // If here expect big troubles
974 // delete newValEntry; //otherwise mem leak
984 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max )
992 // Just to make sure we are at the beginning of next entry.
993 SkipToNextDocEntry(newDocEntry);
997 /////////////////////// SeqEntry : VR = "SQ"
999 unsigned long l = newDocEntry->GetReadLength();
1000 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1002 if ( l == 0xffffffff )
1012 if ( (LoadMode & NO_SHADOWSEQ) && ! delim_mode )
1014 // User asked to skip SQ only if they belong to Shadow group
1015 if ( newDocEntry->GetGroup()%2 != 0 )
1017 Fp->seekg( l, std::ios::cur);
1023 if ( (LoadMode & NO_SEQ) && ! delim_mode )
1025 // User asked to skip *any* SeQuence
1026 Fp->seekg( l, std::ios::cur);
1031 // no other way to create it ...
1032 newSeqEntry->SetDelimitorMode( delim_mode );
1034 // At the top of the hierarchy, stands a Document. When "set"
1035 // is a Document, then we are building the first depth level.
1036 // Hence the SeqEntry we are building simply has a depth
1038 if ( dynamic_cast< Document* > ( set ) )
1040 newSeqEntry->SetDepthLevel( 1 );
1041 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1043 // But when "set" is already a SQItem, we are building a nested
1044 // sequence, and hence the depth level of the new SeqEntry
1045 // we are building, is one level deeper:
1046 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1048 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1049 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1050 + newSeqEntry->GetKey() );
1054 { // Don't try to parse zero-length sequences
1055 ParseSQ( newSeqEntry,
1056 newDocEntry->GetOffset(),
1059 if ( !set->AddEntry( newSeqEntry ) )
1064 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1078 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1079 * @return parsed length for this level
1081 void Document::ParseSQ( SeqEntry *seqEntry,
1082 long offset, long l_max, bool delim_mode)
1084 int SQItemNumber = 0;
1086 long offsetStartCurrentSQItem = offset;
1090 // the first time, we read the fff0,e000 of the first SQItem
1091 DocEntry *newDocEntry = ReadNextDocEntry();
1095 // FIXME Should warn user
1100 if ( newDocEntry->IsSequenceDelimitor() )
1102 seqEntry->SetDelimitationItem( newDocEntry );
1106 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1111 // create the current SQItem
1112 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1113 std::ostringstream newBase;
1114 newBase << seqEntry->GetKey()
1118 itemSQ->SetBaseTagKey( newBase.str() );
1119 unsigned int l = newDocEntry->GetReadLength();
1121 if ( l == 0xffffffff )
1130 // Let's try :------------
1131 // remove fff0,e000, created out of the SQItem
1133 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1134 // fill up the current SQItem, starting at the beginning of fff0,e000
1135 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1136 offsetStartCurrentSQItem = Fp->tellg();
1137 // end try -----------------
1139 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1141 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1149 * \brief Loads the element content if its length doesn't exceed
1150 * the value specified with Document::SetMaxSizeLoadEntry()
1151 * @param entry Header Entry (Dicom Element) to be dealt with
1153 void Document::LoadDocEntry(DocEntry *entry)
1155 uint16_t group = entry->GetGroup();
1156 std::string vr = entry->GetVR();
1157 uint32_t length = entry->GetLength();
1159 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1161 // A SeQuence "contains" a set of Elements.
1162 // (fffe e000) tells us an Element is beginning
1163 // (fffe e00d) tells us an Element just ended
1164 // (fffe e0dd) tells us the current SeQuence just ended
1165 if ( group == 0xfffe )
1167 // NO more value field for SQ !
1171 // When the length is zero things are easy:
1174 ((ValEntry *)entry)->SetValue("");
1178 // The elements whose length is bigger than the specified upper bound
1179 // are not loaded. Instead we leave a short notice of the offset of
1180 // the element content and it's length.
1182 std::ostringstream s;
1183 if (length > MaxSizeLoadEntry)
1185 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1187 s << GDCM_NOTLOADED;
1188 s << " Ad.:" << (long)entry->GetOffset();
1189 s << " x(" << std::hex << entry->GetOffset() << ")";
1191 s << " Lgt:" << entry->GetLength();
1192 s << " x(" << std::hex << entry->GetLength() << ")";
1193 binEntryPtr->SetValue(s.str());
1195 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1197 s << GDCM_NOTLOADED;
1198 s << " Address:" << (long)entry->GetOffset();
1199 s << " Length:" << entry->GetLength();
1200 s << " x(" << std::hex << entry->GetLength() << ")";
1201 valEntryPtr->SetValue(s.str());
1206 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1207 << "nor a ValEntry ?! Should never print that !" );
1210 // to be sure we are at the end of the value ...
1211 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1216 // When we find a BinEntry not very much can be done :
1217 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1219 s << GDCM_BINLOADED;
1220 binEntryPtr->SetValue(s.str());
1221 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1225 if ( IsDocEntryAnInteger(entry) )
1229 // When short integer(s) are expected, read and convert the following
1230 // (n * 2) characters properly i.e. consider them as short integers as
1231 // opposed to strings.
1232 // Elements with Value Multiplicity > 1
1233 // contain a set of integers (not a single one)
1234 if (vr == "US" || vr == "SS")
1237 NewInt = ReadInt16();
1241 for (int i=1; i < nbInt; i++)
1244 NewInt = ReadInt16();
1249 // See above comment on multiple integers (mutatis mutandis).
1250 else if (vr == "UL" || vr == "SL")
1253 NewInt = ReadInt32();
1257 for (int i=1; i < nbInt; i++)
1260 NewInt = ReadInt32();
1265 #ifdef GDCM_NO_ANSI_STRING_STREAM
1266 s << std::ends; // to avoid oddities on Solaris
1267 #endif //GDCM_NO_ANSI_STRING_STREAM
1269 ((ValEntry *)entry)->SetValue(s.str());
1273 // FIXME: We need an additional byte for storing \0 that is not on disk
1274 char *str = new char[length+1];
1275 Fp->read(str, (size_t)length);
1276 str[length] = '\0'; //this is only useful when length is odd
1277 // Special DicomString call to properly handle \0 and even length
1278 std::string newValue;
1281 newValue = Util::DicomString(str, length+1);
1282 gdcmWarningMacro("Warning: bad length: " << length <<
1283 " For string :" << newValue.c_str());
1284 // Since we change the length of string update it length
1285 //entry->SetReadLength(length+1);
1289 newValue = Util::DicomString(str, length);
1293 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1295 if ( Fp->fail() || Fp->eof())
1298 gdcmWarningMacro("--> fail");
1300 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1301 << " lgt : " << valEntry->GetReadLength()
1302 << " at " << std::hex << valEntry->GetOffset());
1303 valEntry->SetValue(GDCM_UNREAD);
1309 // Because of correspondance with the VR dic
1310 valEntry->SetValue(newValue);
1314 valEntry->SetValue(newValue);
1319 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1320 << " lgt : " << valEntry->GetReadLength()
1321 << " at " << std::hex << valEntry->GetOffset());
1326 * \brief Find the value Length of the passed Header Entry
1327 * @param entry Header Entry whose length of the value shall be loaded.
1329 void Document::FindDocEntryLength( DocEntry *entry )
1330 throw ( FormatError )
1332 std::string vr = entry->GetVR();
1335 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1337 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1339 // The following reserved two bytes (see PS 3.5-2003, section
1340 // "7.1.2 Data element structure with explicit vr", p 27) must be
1341 // skipped before proceeding on reading the length on 4 bytes.
1342 Fp->seekg( 2L, std::ios::cur);
1343 uint32_t length32 = ReadInt32();
1345 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1350 lengthOB = FindDocEntryLengthOBOrOW();
1352 catch ( FormatUnexpected )
1354 // Computing the length failed (this happens with broken
1355 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1356 // chance to get the pixels by deciding the element goes
1357 // until the end of the file. Hence we artificially fix the
1358 // the length and proceed.
1359 long currentPosition = Fp->tellg();
1360 Fp->seekg(0L,std::ios::end);
1362 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1363 Fp->seekg(currentPosition, std::ios::beg);
1365 entry->SetReadLength(lengthUntilEOF);
1366 entry->SetLength(lengthUntilEOF);
1369 entry->SetReadLength(lengthOB);
1370 entry->SetLength(lengthOB);
1373 FixDocEntryFoundLength(entry, length32);
1377 // Length is encoded on 2 bytes.
1378 length16 = ReadInt16();
1380 // 0xffff means that we deal with 'No Length' Sequence
1381 // or 'No Length' SQItem
1382 if ( length16 == 0xffff)
1386 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1391 // Either implicit VR or a non DICOM conformal (see note below) explicit
1392 // VR that ommited the VR of (at least) this element. Farts happen.
1393 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1394 // on Data elements "Implicit and Explicit VR Data Elements shall
1395 // not coexist in a Data Set and Data Sets nested within it".]
1396 // Length is on 4 bytes.
1398 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1399 // even if Transfer Syntax is 'Implicit VR ...'
1401 FixDocEntryFoundLength( entry, ReadInt32() );
1407 * \brief Find the Length till the next sequence delimiter
1408 * \warning NOT end user intended method !
1411 uint32_t Document::FindDocEntryLengthOBOrOW()
1412 throw( FormatUnexpected )
1414 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1415 long positionOnEntry = Fp->tellg();
1416 bool foundSequenceDelimiter = false;
1417 uint32_t totalLength = 0;
1419 while ( !foundSequenceDelimiter )
1425 group = ReadInt16();
1428 catch ( FormatError )
1430 throw FormatError("Unexpected end of file encountered during ",
1431 "Document::FindDocEntryLengthOBOrOW()");
1433 // We have to decount the group and element we just read
1435 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1437 long filePosition = Fp->tellg();
1439 "Neither an Item tag nor a Sequence delimiter tag on :"
1440 << std::hex << group << " , " << elem
1441 << ") -before- position x(" << filePosition << ")" );
1443 Fp->seekg(positionOnEntry, std::ios::beg);
1444 throw FormatUnexpected(
1445 "Neither an Item tag nor a Sequence delimiter tag.");
1447 if ( elem == 0xe0dd )
1449 foundSequenceDelimiter = true;
1451 uint32_t itemLength = ReadInt32();
1452 // We add 4 bytes since we just read the ItemLength with ReadInt32
1453 totalLength += itemLength + 4;
1454 SkipBytes(itemLength);
1456 if ( foundSequenceDelimiter )
1461 Fp->seekg( positionOnEntry, std::ios::beg);
1466 * \brief Find the Value Representation of the current Dicom Element.
1467 * @return Value Representation of the current Entry
1469 std::string Document::FindDocEntryVR()
1471 if ( Filetype != ExplicitVR )
1472 return GDCM_UNKNOWN;
1474 long positionOnEntry = Fp->tellg();
1475 // Warning: we believe this is explicit VR (Value Representation) because
1476 // we used a heuristic that found "UL" in the first tag. Alas this
1477 // doesn't guarantee that all the tags will be in explicit VR. In some
1478 // cases (see e-film filtered files) one finds implicit VR tags mixed
1479 // within an explicit VR file. Hence we make sure the present tag
1480 // is in explicit VR and try to fix things if it happens not to be
1484 Fp->read (vr, (size_t)2);
1487 if ( !CheckDocEntryVR(vr) )
1489 Fp->seekg(positionOnEntry, std::ios::beg);
1490 return GDCM_UNKNOWN;
1496 * \brief Check the correspondance between the VR of the header entry
1497 * and the taken VR. If they are different, the header entry is
1498 * updated with the new VR.
1499 * @param vr Dicom Value Representation
1500 * @return false if the VR is incorrect of if the VR isn't referenced
1501 * otherwise, it returns true
1503 bool Document::CheckDocEntryVR(VRKey vr)
1505 if ( !Global::GetVR()->IsValidVR(vr) )
1512 * \brief Get the transformed value of the header entry. The VR value
1513 * is used to define the transformation to operate on the value
1514 * \warning NOT end user intended method !
1515 * @param entry entry to tranform
1516 * @return Transformed entry value
1518 std::string Document::GetDocEntryValue(DocEntry *entry)
1520 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1522 std::string val = ((ValEntry *)entry)->GetValue();
1523 std::string vr = entry->GetVR();
1524 uint32_t length = entry->GetLength();
1525 std::ostringstream s;
1528 // When short integer(s) are expected, read and convert the following
1529 // n * 2 bytes properly i.e. as a multivaluated strings
1530 // (each single value is separated fromthe next one by '\'
1531 // as usual for standard multivaluated filels
1532 // Elements with Value Multiplicity > 1
1533 // contain a set of short integers (not a single one)
1535 if ( vr == "US" || vr == "SS" )
1540 for (int i=0; i < nbInt; i++)
1546 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1547 newInt16 = SwapShort( newInt16 );
1552 // When integer(s) are expected, read and convert the following
1553 // n * 4 bytes properly i.e. as a multivaluated strings
1554 // (each single value is separated fromthe next one by '\'
1555 // as usual for standard multivaluated filels
1556 // Elements with Value Multiplicity > 1
1557 // contain a set of integers (not a single one)
1558 else if ( vr == "UL" || vr == "SL" )
1563 for (int i=0; i < nbInt; i++)
1569 newInt32 = ( val[4*i+0] & 0xFF )
1570 + (( val[4*i+1] & 0xFF ) << 8 )
1571 + (( val[4*i+2] & 0xFF ) << 16 )
1572 + (( val[4*i+3] & 0xFF ) << 24 );
1573 newInt32 = SwapLong( newInt32 );
1577 #ifdef GDCM_NO_ANSI_STRING_STREAM
1578 s << std::ends; // to avoid oddities on Solaris
1579 #endif //GDCM_NO_ANSI_STRING_STREAM
1582 return ((ValEntry *)entry)->GetValue();
1586 * \brief Get the reverse transformed value of the header entry. The VR
1587 * value is used to define the reverse transformation to operate on
1589 * \warning NOT end user intended method !
1590 * @param entry Entry to reverse transform
1591 * @return Reverse transformed entry value
1593 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1595 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1597 std::string vr = entry->GetVR();
1598 std::vector<std::string> tokens;
1599 std::ostringstream s;
1601 if ( vr == "US" || vr == "SS" )
1605 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1606 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1607 for (unsigned int i=0; i<tokens.size(); i++)
1609 newInt16 = atoi(tokens[i].c_str());
1610 s << ( newInt16 & 0xFF )
1611 << (( newInt16 >> 8 ) & 0xFF );
1615 if ( vr == "UL" || vr == "SL")
1619 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1620 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1621 for (unsigned int i=0; i<tokens.size();i++)
1623 newInt32 = atoi(tokens[i].c_str());
1624 s << (char)( newInt32 & 0xFF )
1625 << (char)(( newInt32 >> 8 ) & 0xFF )
1626 << (char)(( newInt32 >> 16 ) & 0xFF )
1627 << (char)(( newInt32 >> 24 ) & 0xFF );
1632 #ifdef GDCM_NO_ANSI_STRING_STREAM
1633 s << std::ends; // to avoid oddities on Solaris
1634 #endif //GDCM_NO_ANSI_STRING_STREAM
1638 return ((ValEntry *)entry)->GetValue();
1642 * \brief Skip a given Header Entry
1643 * \warning NOT end user intended method !
1644 * @param entry entry to skip
1646 void Document::SkipDocEntry(DocEntry *entry)
1648 SkipBytes(entry->GetLength());
1652 * \brief Skips to the beginning of the next Header Entry
1653 * \warning NOT end user intended method !
1654 * @param currentDocEntry entry to skip
1656 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1658 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1659 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1660 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1664 * \brief When the length of an element value is obviously wrong (because
1665 * the parser went Jabberwocky) one can hope improving things by
1666 * applying some heuristics.
1667 * @param entry entry to check
1668 * @param foundLength first assumption about length
1670 void Document::FixDocEntryFoundLength(DocEntry *entry,
1671 uint32_t foundLength)
1673 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1674 if ( foundLength == 0xffffffff)
1679 uint16_t gr = entry->GetGroup();
1680 uint16_t elem = entry->GetElement();
1682 if ( foundLength % 2)
1684 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1685 << " in x(" << std::hex << gr << "," << elem <<")");
1688 //////// Fix for some naughty General Electric images.
1689 // Allthough not recent many such GE corrupted images are still present
1690 // on Creatis hard disks. Hence this fix shall remain when such images
1691 // are no longer in use (we are talking a few years, here)...
1692 // Note: XMedCon probably uses such a trick since it is able to read
1693 // those pesky GE images ...
1694 if ( foundLength == 13)
1696 // Only happens for this length !
1697 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1700 entry->SetReadLength(10); // a bug is to be fixed !?
1704 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1705 // Occurence of such images is quite low (unless one leaves close to a
1706 // 'Leonardo' source. Hence, one might consider commenting out the
1707 // following fix on efficiency reasons.
1708 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1711 entry->SetReadLength(4); // a bug is to be fixed !?
1714 else if ( entry->GetVR() == "SQ" )
1716 foundLength = 0; // ReadLength is unchanged
1719 //////// We encountered a 'delimiter' element i.e. a tag of the form
1720 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1721 // taken into account.
1722 else if ( gr == 0xfffe )
1724 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1725 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1726 // causes extra troubles...
1727 if ( entry->GetElement() != 0x0000 )
1732 entry->SetLength(foundLength);
1736 * \brief Apply some heuristics to predict whether the considered
1737 * element value contains/represents an integer or not.
1738 * @param entry The element value on which to apply the predicate.
1739 * @return The result of the heuristical predicate.
1741 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1743 uint16_t elem = entry->GetElement();
1744 uint16_t group = entry->GetGroup();
1745 const std::string &vr = entry->GetVR();
1746 uint32_t length = entry->GetLength();
1748 // When we have some semantics on the element we just read, and if we
1749 // a priori know we are dealing with an integer, then we shall be
1750 // able to swap it's element value properly.
1751 if ( elem == 0 ) // This is the group length of the group
1759 // Allthough this should never happen, still some images have a
1760 // corrupted group length [e.g. have a glance at offset x(8336) of
1761 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1762 // Since for dicom compliant and well behaved headers, the present
1763 // test is useless (and might even look a bit paranoid), when we
1764 // encounter such an ill-formed image, we simply display a warning
1765 // message and proceed on parsing (while crossing fingers).
1766 long filePosition = Fp->tellg();
1767 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1768 << std::hex << group << " , " << elem
1769 << ") -before- position x(" << filePosition << ")"
1770 << "lgt : " << length );
1774 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1782 * \brief Discover what the swap code is (among little endian, big endian,
1783 * bad little endian, bad big endian).
1785 * @return false when we are absolutely sure
1786 * it's neither ACR-NEMA nor DICOM
1787 * true when we hope ours assuptions are OK
1789 bool Document::CheckSwap()
1796 // First, compare HostByteOrder and NetworkByteOrder in order to
1797 // determine if we shall need to swap bytes (i.e. the Endian type).
1798 bool net2host = Util::IsCurrentProcessorBigEndian();
1800 // The easiest case is the one of a 'true' DICOM header, we just have
1801 // to look for the string "DICM" inside the file preamble.
1804 char *entCur = deb + 128;
1805 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1807 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1809 // Group 0002 should always be VR, and the first element 0000
1810 // Let's be carefull (so many wrong headers ...)
1811 // and determine the value representation (VR) :
1812 // Let's skip to the first element (0002,0000) and check there if we find
1813 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1814 // in which case we (almost) know it is explicit VR.
1815 // WARNING: if it happens to be implicit VR then what we will read
1816 // is the length of the group. If this ascii representation of this
1817 // length happens to be "UL" then we shall believe it is explicit VR.
1818 // We need to skip :
1819 // * the 128 bytes of File Preamble (often padded with zeroes),
1820 // * the 4 bytes of "DICM" string,
1821 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1822 // i.e. a total of 136 bytes.
1825 // group 0x0002 *is always* Explicit VR Sometimes ,
1826 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1827 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1829 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1830 memcmp(entCur, "OB", (size_t)2) == 0 ||
1831 memcmp(entCur, "UI", (size_t)2) == 0 ||
1832 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1833 // when Write DCM *adds*
1835 // Use Document::dicom_vr to test all the possibilities
1836 // instead of just checking for UL, OB and UI !? group 0000
1838 Filetype = ExplicitVR;
1839 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1843 Filetype = ImplicitVR;
1844 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1845 << "Looks like a bugged Header!");
1851 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1856 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1859 // Position the file position indicator at first tag
1860 // (i.e. after the file preamble and the "DICM" string).
1862 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1864 Fp->seekg ( 132L, std::ios::beg);
1866 } // ------------------------------- End of DicomV3 ----------------
1868 // Alas, this is not a DicomV3 file and whatever happens there is no file
1869 // preamble. We can reset the file position indicator to where the data
1870 // is (i.e. the beginning of the file).
1872 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1874 Fp->seekg(0, std::ios::beg);
1876 // Let's check 'No Preamble Dicom File' :
1877 // Should start with group 0x0002
1878 // and be Explicit Value Representation
1880 s16 = *((uint16_t *)(deb));
1893 if ( SwapCode != 0 )
1895 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1896 memcmp(entCur, "OB", (size_t)2) == 0 ||
1897 memcmp(entCur, "UI", (size_t)2) == 0 ||
1898 memcmp(entCur, "SH", (size_t)2) == 0 ||
1899 memcmp(entCur, "AE", (size_t)2) == 0 ||
1900 memcmp(entCur, "OB", (size_t)2) == 0 )
1902 Filetype = ExplicitVR;
1903 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1907 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1909 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1910 // By clean we mean that the length of the first group is written down.
1911 // If this is the case and since the length of the first group HAS to be
1912 // four (bytes), then determining the proper swap code is straightforward.
1915 // We assume the array of char we are considering contains the binary
1916 // representation of a 32 bits integer. Hence the following dirty
1918 s32 = *((uint32_t *)(entCur));
1938 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1939 // It is time for despaired wild guesses.
1940 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1941 // i.e. the 'group length' element is not present :
1943 // check the supposed-to-be 'group number'
1944 // in ( 0x0001 .. 0x0008 )
1945 // to determine ' SwapCode' value .
1946 // Only 0 or 4321 will be possible
1947 // (no oportunity to check for the formerly well known
1948 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1949 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1950 // the file IS NOT ACR-NEMA nor DICOM V3
1951 // Find a trick to tell it the caller...
1953 s16 = *((uint16_t *)(deb));
1980 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1988 * \brief Change the Byte Swap code.
1990 void Document::SwitchByteSwapCode()
1992 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
1993 << " at :" <<std::hex << Fp->tellg() );
1994 if ( SwapCode == 1234 )
1998 else if ( SwapCode == 4321 )
2002 else if ( SwapCode == 3412 )
2006 else if ( SwapCode == 2143 )
2013 * \brief during parsing, Header Elements too long are not loaded in memory
2014 * @param newSize new size
2016 void Document::SetMaxSizeLoadEntry(long newSize)
2022 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2024 MaxSizeLoadEntry = 0xffffffff;
2027 MaxSizeLoadEntry = newSize;
2031 * \brief Read the next tag but WITHOUT loading it's value
2032 * (read the 'Group Number', the 'Element Number',
2033 * gets the Dict Entry
2034 * gets the VR, gets the length, gets the offset value)
2035 * @return On succes the newly created DocEntry, NULL on failure.
2037 DocEntry *Document::ReadNextDocEntry()
2044 group = ReadInt16();
2047 catch ( FormatError e )
2049 // We reached the EOF (or an error occured) therefore
2050 // header parsing has to be considered as finished.
2054 // Sometimes file contains groups of tags with reversed endianess.
2055 HandleBrokenEndian(group, elem);
2057 // In 'true DICOM' files Group 0002 is always little endian
2058 if ( HasDCMPreamble )
2059 HandleOutOfGroup0002(group, elem);
2061 std::string vr = FindDocEntryVR();
2062 std::string realVR = vr;
2064 if ( vr == GDCM_UNKNOWN )
2066 if ( elem == 0x0000 ) // Group Length
2067 realVR = "UL"; // must be UL
2070 DictEntry *dictEntry = GetDictEntry(group,elem);
2072 realVR = dictEntry->GetVR();
2077 if ( Global::GetVR()->IsVROfSequence(realVR) )
2078 newEntry = NewSeqEntry(group, elem);
2079 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2080 newEntry = NewValEntry(group, elem,vr);
2082 newEntry = NewBinEntry(group, elem,vr);
2084 if ( vr == GDCM_UNKNOWN )
2086 if ( Filetype == ExplicitVR )
2088 // We thought this was explicit VR, but we end up with an
2089 // implicit VR tag. Let's backtrack.
2090 if ( newEntry->GetGroup() != 0xfffe )
2093 int offset = Fp->tellg();
2094 msg = Util::Format("Entry (%04x,%04x) at %x should be Explicit VR\n",
2095 newEntry->GetGroup(), newEntry->GetElement(), offset );
2096 gdcmWarningMacro( msg.c_str() );
2099 newEntry->SetImplicitVR();
2104 FindDocEntryLength(newEntry);
2106 catch ( FormatError e )
2113 newEntry->SetOffset(Fp->tellg());
2119 * \brief Handle broken private tag from Philips NTSCAN
2120 * where the endianess is being switched to BigEndian for no
2124 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2126 // Endian reversion. Some files contain groups of tags with reversed endianess.
2127 static int reversedEndian = 0;
2128 // try to fix endian switching in the middle of headers
2129 if ((group == 0xfeff) && (elem == 0x00e0))
2131 // start endian swap mark for group found
2133 SwitchByteSwapCode();
2138 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2140 // end of reversed endian group
2142 SwitchByteSwapCode();
2147 * \brief Group 0002 is always coded Little Endian
2148 * whatever Transfer Syntax is
2151 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2153 // Endian reversion. Some files contain groups of tags with reversed endianess.
2154 if ( !Group0002Parsed && group != 0x0002)
2156 Group0002Parsed = true;
2157 // we just came out of group 0002
2158 // if Transfer syntax is Big Endian we have to change CheckSwap
2160 std::string ts = GetTransferSyntax();
2161 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2163 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2167 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2169 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2171 Filetype = ImplicitVR;
2174 // FIXME Strangely, this works with
2175 //'Implicit VR Transfer Syntax (GE Private)
2176 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2178 gdcmWarningMacro("Transfer Syntax Name = ["
2179 << GetTransferSyntaxName() << "]" );
2180 SwitchByteSwapCode();
2181 group = SwapShort(group);
2182 elem = SwapShort(elem);
2187 //-----------------------------------------------------------------------------
2190 //-----------------------------------------------------------------------------
2191 } // end namespace gdcm