1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/06/24 10:53:46 $
7 Version: $Revision: 1.251 $
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);
998 unsigned long l = newDocEntry->GetReadLength();
999 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1001 if ( l == 0xffffffff )
1011 if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
1013 Fp->seekg( l, std::ios::cur);
1018 // no other way to create it ...
1019 newSeqEntry->SetDelimitorMode( delim_mode );
1021 // At the top of the hierarchy, stands a Document. When "set"
1022 // is a Document, then we are building the first depth level.
1023 // Hence the SeqEntry we are building simply has a depth
1025 if ( dynamic_cast< Document* > ( set ) )
1027 newSeqEntry->SetDepthLevel( 1 );
1028 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1030 // But when "set" is already a SQItem, we are building a nested
1031 // sequence, and hence the depth level of the new SeqEntry
1032 // we are building, is one level deeper:
1033 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1035 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1036 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1037 + newSeqEntry->GetKey() );
1041 { // Don't try to parse zero-length sequences
1042 ParseSQ( newSeqEntry,
1043 newDocEntry->GetOffset(),
1046 if ( !set->AddEntry( newSeqEntry ) )
1051 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1065 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1066 * @return parsed length for this level
1068 void Document::ParseSQ( SeqEntry *seqEntry,
1069 long offset, long l_max, bool delim_mode)
1071 int SQItemNumber = 0;
1073 long offsetStartCurrentSQItem = offset;
1077 // the first time, we read the fff0,e000 of the first SQItem
1078 DocEntry *newDocEntry = ReadNextDocEntry();
1082 // FIXME Should warn user
1087 if ( newDocEntry->IsSequenceDelimitor() )
1089 seqEntry->SetDelimitationItem( newDocEntry );
1093 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1098 // create the current SQItem
1099 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1100 std::ostringstream newBase;
1101 newBase << seqEntry->GetKey()
1105 itemSQ->SetBaseTagKey( newBase.str() );
1106 unsigned int l = newDocEntry->GetReadLength();
1108 if ( l == 0xffffffff )
1117 // Let's try :------------
1118 // remove fff0,e000, created out of the SQItem
1120 Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1121 // fill up the current SQItem, starting at the beginning of fff0,e000
1122 ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1123 offsetStartCurrentSQItem = Fp->tellg();
1124 // end try -----------------
1126 seqEntry->AddSQItem( itemSQ, SQItemNumber );
1128 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1136 * \brief Loads the element content if its length doesn't exceed
1137 * the value specified with Document::SetMaxSizeLoadEntry()
1138 * @param entry Header Entry (Dicom Element) to be dealt with
1140 void Document::LoadDocEntry(DocEntry *entry)
1142 uint16_t group = entry->GetGroup();
1143 std::string vr = entry->GetVR();
1144 uint32_t length = entry->GetLength();
1146 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1148 // A SeQuence "contains" a set of Elements.
1149 // (fffe e000) tells us an Element is beginning
1150 // (fffe e00d) tells us an Element just ended
1151 // (fffe e0dd) tells us the current SeQuence just ended
1152 if ( group == 0xfffe )
1154 // NO more value field for SQ !
1158 // When the length is zero things are easy:
1161 ((ValEntry *)entry)->SetValue("");
1165 // The elements whose length is bigger than the specified upper bound
1166 // are not loaded. Instead we leave a short notice of the offset of
1167 // the element content and it's length.
1169 std::ostringstream s;
1170 if (length > MaxSizeLoadEntry)
1172 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1174 s << GDCM_NOTLOADED;
1175 s << " Ad.:" << (long)entry->GetOffset();
1176 s << " x(" << std::hex << entry->GetOffset() << ")";
1178 s << " Lgt:" << entry->GetLength();
1179 s << " x(" << std::hex << entry->GetLength() << ")";
1180 binEntryPtr->SetValue(s.str());
1182 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1184 s << GDCM_NOTLOADED;
1185 s << " Address:" << (long)entry->GetOffset();
1186 s << " Length:" << entry->GetLength();
1187 s << " x(" << std::hex << entry->GetLength() << ")";
1188 valEntryPtr->SetValue(s.str());
1193 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1194 << "nor a ValEntry ?! Should never print that !" );
1197 // to be sure we are at the end of the value ...
1198 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1203 // When we find a BinEntry not very much can be done :
1204 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1206 s << GDCM_BINLOADED;
1207 binEntryPtr->SetValue(s.str());
1208 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1212 if ( IsDocEntryAnInteger(entry) )
1216 // When short integer(s) are expected, read and convert the following
1217 // (n * 2) characters properly i.e. consider them as short integers as
1218 // opposed to strings.
1219 // Elements with Value Multiplicity > 1
1220 // contain a set of integers (not a single one)
1221 if (vr == "US" || vr == "SS")
1224 NewInt = ReadInt16();
1228 for (int i=1; i < nbInt; i++)
1231 NewInt = ReadInt16();
1236 // See above comment on multiple integers (mutatis mutandis).
1237 else if (vr == "UL" || vr == "SL")
1240 NewInt = ReadInt32();
1244 for (int i=1; i < nbInt; i++)
1247 NewInt = ReadInt32();
1252 #ifdef GDCM_NO_ANSI_STRING_STREAM
1253 s << std::ends; // to avoid oddities on Solaris
1254 #endif //GDCM_NO_ANSI_STRING_STREAM
1256 ((ValEntry *)entry)->SetValue(s.str());
1260 // FIXME: We need an additional byte for storing \0 that is not on disk
1261 char *str = new char[length+1];
1262 Fp->read(str, (size_t)length);
1263 str[length] = '\0'; //this is only useful when length is odd
1264 // Special DicomString call to properly handle \0 and even length
1265 std::string newValue;
1268 newValue = Util::DicomString(str, length+1);
1269 gdcmWarningMacro("Warning: bad length: " << length <<
1270 " For string :" << newValue.c_str());
1271 // Since we change the length of string update it length
1272 //entry->SetReadLength(length+1);
1276 newValue = Util::DicomString(str, length);
1280 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1282 if ( Fp->fail() || Fp->eof())
1285 gdcmWarningMacro("--> fail");
1287 gdcmWarningMacro("Unread element value " << valEntry->GetKey()
1288 << " lgt : " << valEntry->GetReadLength()
1289 << " at " << std::hex << valEntry->GetOffset());
1290 valEntry->SetValue(GDCM_UNREAD);
1296 // Because of correspondance with the VR dic
1297 valEntry->SetValue(newValue);
1301 valEntry->SetValue(newValue);
1306 gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey()
1307 << " lgt : " << valEntry->GetReadLength()
1308 << " at " << std::hex << valEntry->GetOffset());
1313 * \brief Find the value Length of the passed Header Entry
1314 * @param entry Header Entry whose length of the value shall be loaded.
1316 void Document::FindDocEntryLength( DocEntry *entry )
1317 throw ( FormatError )
1319 std::string vr = entry->GetVR();
1322 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1324 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" )
1326 // The following reserved two bytes (see PS 3.5-2003, section
1327 // "7.1.2 Data element structure with explicit vr", p 27) must be
1328 // skipped before proceeding on reading the length on 4 bytes.
1329 Fp->seekg( 2L, std::ios::cur);
1330 uint32_t length32 = ReadInt32();
1332 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1337 lengthOB = FindDocEntryLengthOBOrOW();
1339 catch ( FormatUnexpected )
1341 // Computing the length failed (this happens with broken
1342 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1343 // chance to get the pixels by deciding the element goes
1344 // until the end of the file. Hence we artificially fix the
1345 // the length and proceed.
1346 long currentPosition = Fp->tellg();
1347 Fp->seekg(0L,std::ios::end);
1349 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1350 Fp->seekg(currentPosition, std::ios::beg);
1352 entry->SetReadLength(lengthUntilEOF);
1353 entry->SetLength(lengthUntilEOF);
1356 entry->SetReadLength(lengthOB);
1357 entry->SetLength(lengthOB);
1360 FixDocEntryFoundLength(entry, length32);
1364 // Length is encoded on 2 bytes.
1365 length16 = ReadInt16();
1367 // 0xffff means that we deal with 'No Length' Sequence
1368 // or 'No Length' SQItem
1369 if ( length16 == 0xffff)
1373 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1378 // Either implicit VR or a non DICOM conformal (see note below) explicit
1379 // VR that ommited the VR of (at least) this element. Farts happen.
1380 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1381 // on Data elements "Implicit and Explicit VR Data Elements shall
1382 // not coexist in a Data Set and Data Sets nested within it".]
1383 // Length is on 4 bytes.
1385 // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1386 // even if Transfer Syntax is 'Implicit VR ...'
1388 FixDocEntryFoundLength( entry, ReadInt32() );
1394 * \brief Find the Length till the next sequence delimiter
1395 * \warning NOT end user intended method !
1398 uint32_t Document::FindDocEntryLengthOBOrOW()
1399 throw( FormatUnexpected )
1401 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1402 long positionOnEntry = Fp->tellg();
1403 bool foundSequenceDelimiter = false;
1404 uint32_t totalLength = 0;
1406 while ( !foundSequenceDelimiter )
1412 group = ReadInt16();
1415 catch ( FormatError )
1417 throw FormatError("Unexpected end of file encountered during ",
1418 "Document::FindDocEntryLengthOBOrOW()");
1420 // We have to decount the group and element we just read
1422 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1424 long filePosition = Fp->tellg();
1426 "Neither an Item tag nor a Sequence delimiter tag on :"
1427 << std::hex << group << " , " << elem
1428 << ") -before- position x(" << filePosition << ")" );
1430 Fp->seekg(positionOnEntry, std::ios::beg);
1431 throw FormatUnexpected(
1432 "Neither an Item tag nor a Sequence delimiter tag.");
1434 if ( elem == 0xe0dd )
1436 foundSequenceDelimiter = true;
1438 uint32_t itemLength = ReadInt32();
1439 // We add 4 bytes since we just read the ItemLength with ReadInt32
1440 totalLength += itemLength + 4;
1441 SkipBytes(itemLength);
1443 if ( foundSequenceDelimiter )
1448 Fp->seekg( positionOnEntry, std::ios::beg);
1453 * \brief Find the Value Representation of the current Dicom Element.
1454 * @return Value Representation of the current Entry
1456 std::string Document::FindDocEntryVR()
1458 if ( Filetype != ExplicitVR )
1459 return GDCM_UNKNOWN;
1461 long positionOnEntry = Fp->tellg();
1462 // Warning: we believe this is explicit VR (Value Representation) because
1463 // we used a heuristic that found "UL" in the first tag. Alas this
1464 // doesn't guarantee that all the tags will be in explicit VR. In some
1465 // cases (see e-film filtered files) one finds implicit VR tags mixed
1466 // within an explicit VR file. Hence we make sure the present tag
1467 // is in explicit VR and try to fix things if it happens not to be
1471 Fp->read (vr, (size_t)2);
1474 if ( !CheckDocEntryVR(vr) )
1476 Fp->seekg(positionOnEntry, std::ios::beg);
1477 return GDCM_UNKNOWN;
1483 * \brief Check the correspondance between the VR of the header entry
1484 * and the taken VR. If they are different, the header entry is
1485 * updated with the new VR.
1486 * @param vr Dicom Value Representation
1487 * @return false if the VR is incorrect of if the VR isn't referenced
1488 * otherwise, it returns true
1490 bool Document::CheckDocEntryVR(VRKey vr)
1492 if ( !Global::GetVR()->IsValidVR(vr) )
1499 * \brief Get the transformed value of the header entry. The VR value
1500 * is used to define the transformation to operate on the value
1501 * \warning NOT end user intended method !
1502 * @param entry entry to tranform
1503 * @return Transformed entry value
1505 std::string Document::GetDocEntryValue(DocEntry *entry)
1507 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1509 std::string val = ((ValEntry *)entry)->GetValue();
1510 std::string vr = entry->GetVR();
1511 uint32_t length = entry->GetLength();
1512 std::ostringstream s;
1515 // When short integer(s) are expected, read and convert the following
1516 // n * 2 bytes properly i.e. as a multivaluated strings
1517 // (each single value is separated fromthe next one by '\'
1518 // as usual for standard multivaluated filels
1519 // Elements with Value Multiplicity > 1
1520 // contain a set of short integers (not a single one)
1522 if ( vr == "US" || vr == "SS" )
1527 for (int i=0; i < nbInt; i++)
1533 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1534 newInt16 = SwapShort( newInt16 );
1539 // When integer(s) are expected, read and convert the following
1540 // n * 4 bytes properly i.e. as a multivaluated strings
1541 // (each single value is separated fromthe next one by '\'
1542 // as usual for standard multivaluated filels
1543 // Elements with Value Multiplicity > 1
1544 // contain a set of integers (not a single one)
1545 else if ( vr == "UL" || vr == "SL" )
1550 for (int i=0; i < nbInt; i++)
1556 newInt32 = ( val[4*i+0] & 0xFF )
1557 + (( val[4*i+1] & 0xFF ) << 8 )
1558 + (( val[4*i+2] & 0xFF ) << 16 )
1559 + (( val[4*i+3] & 0xFF ) << 24 );
1560 newInt32 = SwapLong( newInt32 );
1564 #ifdef GDCM_NO_ANSI_STRING_STREAM
1565 s << std::ends; // to avoid oddities on Solaris
1566 #endif //GDCM_NO_ANSI_STRING_STREAM
1569 return ((ValEntry *)entry)->GetValue();
1573 * \brief Get the reverse transformed value of the header entry. The VR
1574 * value is used to define the reverse transformation to operate on
1576 * \warning NOT end user intended method !
1577 * @param entry Entry to reverse transform
1578 * @return Reverse transformed entry value
1580 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1582 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1584 std::string vr = entry->GetVR();
1585 std::vector<std::string> tokens;
1586 std::ostringstream s;
1588 if ( vr == "US" || vr == "SS" )
1592 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1593 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1594 for (unsigned int i=0; i<tokens.size(); i++)
1596 newInt16 = atoi(tokens[i].c_str());
1597 s << ( newInt16 & 0xFF )
1598 << (( newInt16 >> 8 ) & 0xFF );
1602 if ( vr == "UL" || vr == "SL")
1606 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1607 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1608 for (unsigned int i=0; i<tokens.size();i++)
1610 newInt32 = atoi(tokens[i].c_str());
1611 s << (char)( newInt32 & 0xFF )
1612 << (char)(( newInt32 >> 8 ) & 0xFF )
1613 << (char)(( newInt32 >> 16 ) & 0xFF )
1614 << (char)(( newInt32 >> 24 ) & 0xFF );
1619 #ifdef GDCM_NO_ANSI_STRING_STREAM
1620 s << std::ends; // to avoid oddities on Solaris
1621 #endif //GDCM_NO_ANSI_STRING_STREAM
1625 return ((ValEntry *)entry)->GetValue();
1629 * \brief Skip a given Header Entry
1630 * \warning NOT end user intended method !
1631 * @param entry entry to skip
1633 void Document::SkipDocEntry(DocEntry *entry)
1635 SkipBytes(entry->GetLength());
1639 * \brief Skips to the beginning of the next Header Entry
1640 * \warning NOT end user intended method !
1641 * @param currentDocEntry entry to skip
1643 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1645 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1646 if (currentDocEntry->GetGroup() != 0xfffe) // for fffe pb
1647 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1651 * \brief When the length of an element value is obviously wrong (because
1652 * the parser went Jabberwocky) one can hope improving things by
1653 * applying some heuristics.
1654 * @param entry entry to check
1655 * @param foundLength first assumption about length
1657 void Document::FixDocEntryFoundLength(DocEntry *entry,
1658 uint32_t foundLength)
1660 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1661 if ( foundLength == 0xffffffff)
1666 uint16_t gr = entry->GetGroup();
1667 uint16_t elem = entry->GetElement();
1669 if ( foundLength % 2)
1671 gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1672 << " in x(" << std::hex << gr << "," << elem <<")");
1675 //////// Fix for some naughty General Electric images.
1676 // Allthough not recent many such GE corrupted images are still present
1677 // on Creatis hard disks. Hence this fix shall remain when such images
1678 // are no longer in use (we are talking a few years, here)...
1679 // Note: XMedCon probably uses such a trick since it is able to read
1680 // those pesky GE images ...
1681 if ( foundLength == 13)
1683 // Only happens for this length !
1684 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1687 entry->SetReadLength(10); // a bug is to be fixed !?
1691 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1692 // Occurence of such images is quite low (unless one leaves close to a
1693 // 'Leonardo' source. Hence, one might consider commenting out the
1694 // following fix on efficiency reasons.
1695 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1698 entry->SetReadLength(4); // a bug is to be fixed !?
1701 else if ( entry->GetVR() == "SQ" )
1703 foundLength = 0; // ReadLength is unchanged
1706 //////// We encountered a 'delimiter' element i.e. a tag of the form
1707 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1708 // taken into account.
1709 else if ( gr == 0xfffe )
1711 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1712 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1713 // causes extra troubles...
1714 if ( entry->GetElement() != 0x0000 )
1719 entry->SetLength(foundLength);
1723 * \brief Apply some heuristics to predict whether the considered
1724 * element value contains/represents an integer or not.
1725 * @param entry The element value on which to apply the predicate.
1726 * @return The result of the heuristical predicate.
1728 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1730 uint16_t elem = entry->GetElement();
1731 uint16_t group = entry->GetGroup();
1732 const std::string &vr = entry->GetVR();
1733 uint32_t length = entry->GetLength();
1735 // When we have some semantics on the element we just read, and if we
1736 // a priori know we are dealing with an integer, then we shall be
1737 // able to swap it's element value properly.
1738 if ( elem == 0 ) // This is the group length of the group
1746 // Allthough this should never happen, still some images have a
1747 // corrupted group length [e.g. have a glance at offset x(8336) of
1748 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1749 // Since for dicom compliant and well behaved headers, the present
1750 // test is useless (and might even look a bit paranoid), when we
1751 // encounter such an ill-formed image, we simply display a warning
1752 // message and proceed on parsing (while crossing fingers).
1753 long filePosition = Fp->tellg();
1754 gdcmWarningMacro( "Erroneous Group Length element length on : ("
1755 << std::hex << group << " , " << elem
1756 << ") -before- position x(" << filePosition << ")"
1757 << "lgt : " << length );
1761 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1769 * \brief Discover what the swap code is (among little endian, big endian,
1770 * bad little endian, bad big endian).
1772 * @return false when we are absolutely sure
1773 * it's neither ACR-NEMA nor DICOM
1774 * true when we hope ours assuptions are OK
1776 bool Document::CheckSwap()
1783 // First, compare HostByteOrder and NetworkByteOrder in order to
1784 // determine if we shall need to swap bytes (i.e. the Endian type).
1785 bool net2host = Util::IsCurrentProcessorBigEndian();
1787 // The easiest case is the one of a 'true' DICOM header, we just have
1788 // to look for the string "DICM" inside the file preamble.
1791 char *entCur = deb + 128;
1792 if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1794 gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1796 // Group 0002 should always be VR, and the first element 0000
1797 // Let's be carefull (so many wrong headers ...)
1798 // and determine the value representation (VR) :
1799 // Let's skip to the first element (0002,0000) and check there if we find
1800 // "UL" - or "OB" if the 1st one is (0002,0001) -,
1801 // in which case we (almost) know it is explicit VR.
1802 // WARNING: if it happens to be implicit VR then what we will read
1803 // is the length of the group. If this ascii representation of this
1804 // length happens to be "UL" then we shall believe it is explicit VR.
1805 // We need to skip :
1806 // * the 128 bytes of File Preamble (often padded with zeroes),
1807 // * the 4 bytes of "DICM" string,
1808 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1809 // i.e. a total of 136 bytes.
1812 // group 0x0002 *is always* Explicit VR Sometimes ,
1813 // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1814 // *Implicit* VR (see former 'gdcmData/icone.dcm')
1816 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1817 memcmp(entCur, "OB", (size_t)2) == 0 ||
1818 memcmp(entCur, "UI", (size_t)2) == 0 ||
1819 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
1820 // when Write DCM *adds*
1822 // Use Document::dicom_vr to test all the possibilities
1823 // instead of just checking for UL, OB and UI !? group 0000
1825 Filetype = ExplicitVR;
1826 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1830 Filetype = ImplicitVR;
1831 gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1832 << "Looks like a bugged Header!");
1838 gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1843 gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1846 // Position the file position indicator at first tag
1847 // (i.e. after the file preamble and the "DICM" string).
1849 Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1851 Fp->seekg ( 132L, std::ios::beg);
1853 } // ------------------------------- End of DicomV3 ----------------
1855 // Alas, this is not a DicomV3 file and whatever happens there is no file
1856 // preamble. We can reset the file position indicator to where the data
1857 // is (i.e. the beginning of the file).
1859 gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1861 Fp->seekg(0, std::ios::beg);
1863 // Let's check 'No Preamble Dicom File' :
1864 // Should start with group 0x0002
1865 // and be Explicit Value Representation
1867 s16 = *((uint16_t *)(deb));
1880 if ( SwapCode != 0 )
1882 if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1883 memcmp(entCur, "OB", (size_t)2) == 0 ||
1884 memcmp(entCur, "UI", (size_t)2) == 0 ||
1885 memcmp(entCur, "SH", (size_t)2) == 0 ||
1886 memcmp(entCur, "AE", (size_t)2) == 0 ||
1887 memcmp(entCur, "OB", (size_t)2) == 0 )
1889 Filetype = ExplicitVR;
1890 gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1894 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1896 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1897 // By clean we mean that the length of the first group is written down.
1898 // If this is the case and since the length of the first group HAS to be
1899 // four (bytes), then determining the proper swap code is straightforward.
1902 // We assume the array of char we are considering contains the binary
1903 // representation of a 32 bits integer. Hence the following dirty
1905 s32 = *((uint32_t *)(entCur));
1925 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1926 // It is time for despaired wild guesses.
1927 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1928 // i.e. the 'group length' element is not present :
1930 // check the supposed-to-be 'group number'
1931 // in ( 0x0001 .. 0x0008 )
1932 // to determine ' SwapCode' value .
1933 // Only 0 or 4321 will be possible
1934 // (no oportunity to check for the formerly well known
1935 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
1936 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
1937 // the file IS NOT ACR-NEMA nor DICOM V3
1938 // Find a trick to tell it the caller...
1940 s16 = *((uint16_t *)(deb));
1967 gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1975 * \brief Change the Byte Swap code.
1977 void Document::SwitchByteSwapCode()
1979 gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
1980 << " at :" <<std::hex << Fp->tellg() );
1981 if ( SwapCode == 1234 )
1985 else if ( SwapCode == 4321 )
1989 else if ( SwapCode == 3412 )
1993 else if ( SwapCode == 2143 )
2000 * \brief during parsing, Header Elements too long are not loaded in memory
2001 * @param newSize new size
2003 void Document::SetMaxSizeLoadEntry(long newSize)
2009 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2011 MaxSizeLoadEntry = 0xffffffff;
2014 MaxSizeLoadEntry = newSize;
2018 * \brief Read the next tag but WITHOUT loading it's value
2019 * (read the 'Group Number', the 'Element Number',
2020 * gets the Dict Entry
2021 * gets the VR, gets the length, gets the offset value)
2022 * @return On succes the newly created DocEntry, NULL on failure.
2024 DocEntry *Document::ReadNextDocEntry()
2031 group = ReadInt16();
2034 catch ( FormatError e )
2036 // We reached the EOF (or an error occured) therefore
2037 // header parsing has to be considered as finished.
2041 // Sometimes file contains groups of tags with reversed endianess.
2042 HandleBrokenEndian(group, elem);
2044 // In 'true DICOM' files Group 0002 is always little endian
2045 if ( HasDCMPreamble )
2046 HandleOutOfGroup0002(group, elem);
2048 std::string vr = FindDocEntryVR();
2049 std::string realVR = vr;
2051 if ( vr == GDCM_UNKNOWN )
2053 if ( elem == 0x0000 ) // Group Length
2054 realVR = "UL"; // must be UL
2057 DictEntry *dictEntry = GetDictEntry(group,elem);
2059 realVR = dictEntry->GetVR();
2064 if ( Global::GetVR()->IsVROfSequence(realVR) )
2065 newEntry = NewSeqEntry(group, elem);
2066 else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2067 newEntry = NewValEntry(group, elem,vr);
2069 newEntry = NewBinEntry(group, elem,vr);
2071 if ( vr == GDCM_UNKNOWN )
2073 if ( Filetype == ExplicitVR )
2075 // We thought this was explicit VR, but we end up with an
2076 // implicit VR tag. Let's backtrack.
2077 if ( newEntry->GetGroup() != 0xfffe )
2080 int offset = Fp->tellg();
2081 msg = Util::Format("Entry (%04x,%04x) at %x should be Explicit VR\n",
2082 newEntry->GetGroup(), newEntry->GetElement(), offset );
2083 gdcmWarningMacro( msg.c_str() );
2086 newEntry->SetImplicitVR();
2091 FindDocEntryLength(newEntry);
2093 catch ( FormatError e )
2100 newEntry->SetOffset(Fp->tellg());
2106 * \brief Handle broken private tag from Philips NTSCAN
2107 * where the endianess is being switch to BigEndian for no
2111 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2113 // Endian reversion. Some files contain groups of tags with reversed endianess.
2114 static int reversedEndian = 0;
2115 // try to fix endian switching in the middle of headers
2116 if ((group == 0xfeff) && (elem == 0x00e0))
2118 // start endian swap mark for group found
2120 SwitchByteSwapCode();
2125 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2127 // end of reversed endian group
2129 SwitchByteSwapCode();
2134 * \brief Group 0002 is always coded Little Endian
2135 * whatever Transfer Syntax is
2138 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2140 // Endian reversion. Some files contain groups of tags with reversed endianess.
2141 if ( !Group0002Parsed && group != 0x0002)
2143 Group0002Parsed = true;
2144 // we just came out of group 0002
2145 // if Transfer syntax is Big Endian we have to change CheckSwap
2147 std::string ts = GetTransferSyntax();
2148 if ( !Global::GetTS()->IsTransferSyntax(ts) )
2150 gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2154 // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..."
2156 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2158 Filetype = ImplicitVR;
2161 // FIXME Strangely, this works with
2162 //'Implicit VR Transfer Syntax (GE Private)
2163 if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2165 gdcmWarningMacro("Transfer Syntax Name = ["
2166 << GetTransferSyntaxName() << "]" );
2167 SwitchByteSwapCode();
2168 group = SwapShort(group);
2169 elem = SwapShort(elem);
2174 //-----------------------------------------------------------------------------
2177 //-----------------------------------------------------------------------------
2178 } // end namespace gdcm