1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/11 11:37:13 $
7 Version: $Revision: 1.173 $
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 "gdcmException.h"
28 #include "gdcmDictSet.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
31 #include "gdcmDocEntrySet.h"
32 #include "gdcmSQItem.h"
38 #if defined(_MSC_VER) || defined(__BORLANDC__)
41 #include <netinet/in.h>
46 //-----------------------------------------------------------------------------
47 static const char *TransferSyntaxStrings[] = {
48 // Implicit VR Little Endian
50 // Implicit VR Big Endian DLX (G.E Private)
52 // Explicit VR Little Endian
53 "1.2.840.10008.1.2.1",
54 // Deflated Explicit VR Little Endian
55 "1.2.840.10008.1.2.1.99",
56 // Explicit VR Big Endian
57 "1.2.840.10008.1.2.2",
58 // JPEG Baseline (Process 1)
59 "1.2.840.10008.1.2.4.50",
60 // JPEG Extended (Process 2 & 4)
61 "1.2.840.10008.1.2.4.51",
62 // JPEG Extended (Process 3 & 5)
63 "1.2.840.10008.1.2.4.52",
64 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
65 "1.2.840.10008.1.2.4.53",
66 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
67 "1.2.840.10008.1.2.4.55",
68 // JPEG Lossless, Non-Hierarchical (Process 14)
69 "1.2.840.10008.1.2.4.57",
70 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
71 "1.2.840.10008.1.2.4.70",
73 "1.2.840.10008.1.2.4.90",
75 "1.2.840.10008.1.2.4.91",
77 "1.2.840.10008.1.2.5",
79 "Unknown Transfer Syntax"
82 //-----------------------------------------------------------------------------
83 // Refer to Document::CheckSwap()
84 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
86 // Refer to Document::SetMaxSizeLoadEntry()
87 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
88 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
90 //-----------------------------------------------------------------------------
91 // Constructor / Destructor
95 * @param filename file to be opened for parsing
97 Document::Document( std::string const &filename ) : ElementSet(-1)
99 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
109 Group0002Parsed = false;
111 gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
112 // Fp->seekg( 0, std::ios::beg);
114 Fp->seekg(0, std::ios::end);
115 long lgt = Fp->tellg();
117 Fp->seekg( 0, std::ios::beg);
119 long beg = Fp->tellg();
122 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
124 Fp->seekg( 0, std::ios::beg);
126 // Load 'non string' values
128 std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);
129 if( PhotometricInterpretation == "PALETTE COLOR " )
131 LoadEntryBinArea(0x0028,0x1200); // gray LUT
132 /// FIXME FIXME FIXME
133 /// The tags refered by the three following lines used to be CORRECTLY
134 /// defined as having an US Value Representation in the public
135 /// dictionnary. BUT the semantics implied by the three following
136 /// lines state that the corresponding tag contents are in fact
137 /// the ones of a BinEntry.
138 /// In order to fix things "Quick and Dirty" the dictionnary was
139 /// altered on PURPOUS but now contains a WRONG value.
140 /// In order to fix things and restore the dictionary to its
141 /// correct value, one needs to decided of the semantics by deciding
142 /// wether the following tags are either:
143 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
144 /// also used as BinEntry, which requires the proper conversion,
145 /// - OW, and hence loaded as BinEntry, but afterwards also used
146 /// as ValEntry, which requires the proper conversion.
147 LoadEntryBinArea(0x0028,0x1201); // R LUT
148 LoadEntryBinArea(0x0028,0x1202); // G LUT
149 LoadEntryBinArea(0x0028,0x1203); // B LUT
151 // Segmented Red Palette Color LUT Data
152 LoadEntryBinArea(0x0028,0x1221);
153 // Segmented Green Palette Color LUT Data
154 LoadEntryBinArea(0x0028,0x1222);
155 // Segmented Blue Palette Color LUT Data
156 LoadEntryBinArea(0x0028,0x1223);
158 //FIXME later : how to use it?
159 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
163 // --------------------------------------------------------------
164 // Specific code to allow gdcm to read ACR-LibIDO formated images
165 // Note: ACR-LibIDO is an extension of the ACR standard that was
166 // used at CREATIS. For the time being (say a couple years)
167 // we keep this kludge to allow a smooth move to gdcm for
168 // CREATIS developpers (sorry folks).
170 // if recognition code tells us we deal with a LibIDO image
171 // we switch lineNumber and columnNumber
174 RecCode = GetEntry(0x0008, 0x0010); // recognition code
175 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
176 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
177 // with "little-endian strings"
179 Filetype = ACR_LIBIDO;
180 std::string rows = GetEntry(0x0028, 0x0010);
181 std::string columns = GetEntry(0x0028, 0x0011);
182 SetEntry(columns, 0x0028, 0x0010);
183 SetEntry(rows , 0x0028, 0x0011);
185 // ----------------- End of ACR-LibIDO kludge ------------------
189 * \brief This default constructor doesn't parse the file. You should
190 * then invoke \ref Document::SetFileName and then the parsing.
192 Document::Document() : ElementSet(-1)
196 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
199 Filetype = ExplicitVR;
200 Group0002Parsed = false;
204 * \brief Canonical destructor.
206 Document::~Document ()
215 //-----------------------------------------------------------------------------
219 * \brief Prints The Dict Entries of THE public Dicom Dictionary
222 void Document::PrintPubDict(std::ostream &os)
224 RefPubDict->SetPrintLevel(PrintLevel);
225 RefPubDict->Print(os);
229 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
232 void Document::PrintShaDict(std::ostream &os)
234 RefShaDict->SetPrintLevel(PrintLevel);
235 RefShaDict->Print(os);
238 //-----------------------------------------------------------------------------
241 * \brief Get the public dictionary used
243 Dict *Document::GetPubDict()
249 * \brief Get the shadow dictionary used
251 Dict *Document::GetShaDict()
257 * \brief Set the shadow dictionary used
258 * @param dict dictionary to use in shadow
260 bool Document::SetShaDict(Dict *dict)
267 * \brief Set the shadow dictionary used
268 * @param dictName name of the dictionary to use in shadow
270 bool Document::SetShaDict(DictKey const &dictName)
272 RefShaDict = Global::GetDicts()->GetDict(dictName);
277 * \brief This predicate, based on hopefully reasonable heuristics,
278 * decides whether or not the current Document was properly parsed
279 * and contains the mandatory information for being considered as
280 * a well formed and usable Dicom/Acr File.
281 * @return true when Document is the one of a reasonable Dicom/Acr file,
284 bool Document::IsReadable()
286 if( Filetype == Unknown)
288 gdcmVerboseMacro( "Wrong filetype");
294 gdcmVerboseMacro( "No tags in internal hash table.");
302 * \brief Accessor to the Transfer Syntax (when present) of the
303 * current document (it internally handles reading the
304 * value from disk when only parsing occured).
305 * @return The encountered Transfer Syntax of the current document.
307 TransferSyntaxType Document::GetTransferSyntax()
309 DocEntry *entry = GetDocEntry(0x0002, 0x0010);
315 // The entry might be present but not loaded (parsing and loading
316 // happen at different stages): try loading and proceed with check...
317 LoadDocEntrySafe(entry);
318 if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
320 std::string transfer = valEntry->GetValue();
321 // The actual transfer (as read from disk) might be padded. We
322 // first need to remove the potential padding. We can make the
323 // weak assumption that padding was not executed with digits...
324 if ( transfer.length() == 0 )
326 // for brain damaged headers
329 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
331 transfer.erase(transfer.length()-1, 1);
333 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
335 if ( TransferSyntaxStrings[i] == transfer )
337 return TransferSyntaxType(i);
344 bool Document::IsJPEGLossless()
346 TransferSyntaxType r = GetTransferSyntax();
347 return r == JPEGFullProgressionProcess10_12
348 || r == JPEGLosslessProcess14
349 || r == JPEGLosslessProcess14_1;
353 * \brief Determines if the Transfer Syntax was already encountered
354 * and if it corresponds to a JPEG2000 one
355 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
358 bool Document::IsJPEG2000()
360 TransferSyntaxType r = GetTransferSyntax();
361 return r == JPEG2000Lossless || r == JPEG2000;
365 * \brief Determines if the Transfer Syntax corresponds to any form
366 * of Jpeg encoded Pixel data.
367 * @return True when any form of JPEG found. False otherwise.
369 bool Document::IsJPEG()
371 TransferSyntaxType r = GetTransferSyntax();
372 return r == JPEGBaselineProcess1
373 || r == JPEGExtendedProcess2_4
374 || r == JPEGExtendedProcess3_5
375 || r == JPEGSpectralSelectionProcess6_8
381 * \brief Determines if the Transfer Syntax corresponds to encapsulated
382 * of encoded Pixel Data (as opposed to native).
383 * @return True when encapsulated. False when native.
385 bool Document::IsEncapsulate()
387 TransferSyntaxType r = GetTransferSyntax();
388 return IsJPEG() || r == RLELossless;
392 * \brief Predicate for dicom version 3 file.
393 * @return True when the file is a dicom version 3.
395 bool Document::IsDicomV3()
397 // Checking if Transfer Syntax exists is enough
398 // Anyway, it's to late check if the 'Preamble' was found ...
399 // And ... would it be a rich idea to check ?
400 // (some 'no Preamble' DICOM images exist !)
401 return GetDocEntry(0x0002, 0x0010) != NULL;
405 * \brief returns the File Type
406 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
407 * @return the FileType code
409 FileType Document::GetFileType()
415 * \brief Tries to open the file \ref Document::Filename and
416 * checks the preamble when existing.
417 * @return The FILE pointer on success.
419 std::ifstream *Document::OpenFile()
422 HasDCMPreamble = false;
423 if (Filename.length() == 0)
430 gdcmVerboseMacro( "File already open: " << Filename.c_str());
433 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
436 gdcmVerboseMacro( "Cannot open file: " << Filename.c_str());
443 Fp->read((char*)&zero, (size_t)2);
450 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
452 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
453 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
454 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
455 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
458 = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
459 gdcmVerboseMacro( msg.c_str() );
464 Fp->seekg(126L, std::ios::cur);
466 Fp->read(dicm, (size_t)4);
472 if( memcmp(dicm, "DICM", 4) == 0 )
474 HasDCMPreamble = true;
479 gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
485 * \brief closes the file
486 * @return TRUE if the close was successfull
488 bool Document::CloseFile()
497 return true; //FIXME how do we detect a non-close ifstream ?
501 * \brief Writes in a file all the Header Entries (Dicom Elements)
502 * @param fp file pointer on an already open file
503 * @param filetype Type of the File to be written
504 * (ACR-NEMA, ExplicitVR, ImplicitVR)
505 * \return Always true.
507 void Document::WriteContent(std::ofstream *fp, FileType filetype)
509 /// \todo move the following lines (and a lot of others, to be written)
510 /// to a future function CheckAndCorrectHeader
511 /// (necessary if user wants to write a DICOM V3 file
512 /// starting from an ACR-NEMA (V2) Header
514 if ( filetype == ImplicitVR || filetype == ExplicitVR )
516 // writing Dicom File Preamble
517 char filePreamble[128];
518 memset(filePreamble, 0, 128);
519 fp->write(filePreamble, 128);
520 fp->write("DICM", 4);
524 * \todo rewrite later, if really usefull
525 * - 'Group Length' element is optional in DICOM
526 * - but un-updated odd groups lengthes can causes pb
529 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
530 * UpdateGroupLength(false,filetype);
531 * if ( filetype == ACR)
532 * UpdateGroupLength(true,ACR);
535 ElementSet::WriteContent(fp, filetype); // This one is recursive
539 * \brief Modifies the value of a given Doc Entry (Dicom Element)
540 * when it exists. Create it with the given value when unexistant.
541 * @param value (string) Value to be set
542 * @param group Group number of the Entry
543 * @param elem Element number of the Entry
544 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
545 * \return pointer to the modified/created Header Entry (NULL when creation
548 ValEntry *Document::ReplaceOrCreate(std::string const &value,
553 ValEntry *valEntry = 0;
554 DocEntry *currentEntry = GetDocEntry( group, elem);
558 valEntry = dynamic_cast< ValEntry* >(currentEntry);
562 if( valEntry->GetVR()!=vr )
565 // if currentEntry doesn't correspond to the requested valEntry
568 if (!RemoveEntry(currentEntry))
570 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
577 // Create a new valEntry if necessary
580 valEntry = NewValEntry(group, elem, vr);
582 if ( !AddEntry(valEntry))
584 gdcmVerboseMacro("AddEntry failed although this is a creation.");
591 // Set the binEntry value
592 SetEntry(value, valEntry);
597 * \brief Modifies the value of a given Header Entry (Dicom Element)
598 * when it exists. Create it with the given value when unexistant.
599 * A copy of the binArea is made to be kept in the Document.
600 * @param binArea (binary) value to be set
601 * @param Group Group number of the Entry
602 * @param Elem Element number of the Entry
603 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
604 * \return pointer to the modified/created Header Entry (NULL when creation
607 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
613 BinEntry *binEntry = 0;
614 DocEntry *currentEntry = GetDocEntry( group, elem);
616 // Verify the currentEntry
619 binEntry = dynamic_cast< BinEntry* >(currentEntry);
623 if( binEntry->GetVR()!=vr )
626 // if currentEntry doesn't correspond to the requested valEntry
629 if (!RemoveEntry(currentEntry))
631 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
638 // Create a new binEntry if necessary
641 binEntry = NewBinEntry(group, elem, vr);
643 if ( !AddEntry(binEntry))
645 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
652 // Set the binEntry value
654 if (lgth>0 && binArea)
656 tmpArea = new uint8_t[lgth];
657 memcpy(tmpArea,binArea,lgth);
663 if (!SetEntry(tmpArea,lgth,binEntry))
675 * \brief Modifies the value of a given Header Entry (Dicom Element)
676 * when it exists. Create it when unexistant.
677 * @param Group Group number of the Entry
678 * @param Elem Element number of the Entry
679 * \return pointer to the modified/created SeqEntry (NULL when creation
682 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
684 SeqEntry *seqEntry = 0;
685 DocEntry *currentEntry = GetDocEntry( group, elem);
687 // Verify the currentEntry
690 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
694 if( seqEntry->GetVR()!="SQ" )
697 // if currentEntry doesn't correspond to the requested valEntry
700 if (!RemoveEntry(currentEntry))
702 gdcmVerboseMacro( "Removal of previous DocEntry failed.");
709 // Create a new seqEntry if necessary
712 seqEntry = NewSeqEntry(group, elem);
714 if ( !AddEntry(seqEntry))
716 gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
727 * \brief Set a new value if the invoked element exists
728 * Seems to be useless !!!
729 * @param value new element value
730 * @param group group number of the Entry
731 * @param elem element number of the Entry
734 bool Document::ReplaceIfExist(std::string const &value,
735 uint16_t group, uint16_t elem )
737 SetEntry(value, group, elem);
742 std::string Document::GetTransferSyntaxValue(TransferSyntaxType type)
744 return TransferSyntaxStrings[type];
747 //-----------------------------------------------------------------------------
751 * \brief Checks if a given Dicom Element exists within the H table
752 * @param group Group number of the searched Dicom Element
753 * @param element Element number of the searched Dicom Element
754 * @return true is found
756 bool Document::CheckIfEntryExist(uint16_t group, uint16_t element )
758 const std::string &key = DictEntry::TranslateToKey(group, element );
759 return TagHT.count(key) != 0;
764 * \brief Searches within Header Entries (Dicom Elements) parsed with
765 * the public and private dictionaries
766 * for the element value representation of a given tag.
767 * @param group Group number of the searched tag.
768 * @param element Element number of the searched tag.
769 * @return Corresponding element value representation when it exists,
770 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
772 std::string Document::GetEntry(uint16_t group, uint16_t element)
774 TagKey key = DictEntry::TranslateToKey(group, element);
775 if ( !TagHT.count(key))
780 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
784 * \brief Searches within Header Entries (Dicom Elements) parsed with
785 * the public and private dictionaries
786 * for the element value representation of a given tag..
788 * Obtaining the VR (Value Representation) might be needed by caller
789 * to convert the string typed content to caller's native type
790 * (think of C++ vs Python). The VR is actually of a higher level
791 * of semantics than just the native C++ type.
792 * @param group Group number of the searched tag.
793 * @param element Element number of the searched tag.
794 * @return Corresponding element value representation when it exists,
795 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
797 std::string Document::GetEntryVR(uint16_t group, uint16_t element)
799 DocEntry *elem = GetDocEntry(group, element);
804 return elem->GetVR();
808 * \brief Searches within Header Entries (Dicom Elements) parsed with
809 * the public and private dictionaries
810 * for the value length of a given tag..
811 * @param group Group number of the searched tag.
812 * @param element Element number of the searched tag.
813 * @return Corresponding element length; -2 if not found
815 int Document::GetEntryLength(uint16_t group, uint16_t element)
817 DocEntry *elem = GetDocEntry(group, element);
820 return -2; //magic number
822 return elem->GetLength();
826 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
827 * through it's (group, element) and modifies it's content with
829 * @param content new value (string) to substitute with
830 * @param group group number of the Dicom Element to modify
831 * @param element element number of the Dicom Element to modify
833 bool Document::SetEntry(std::string const& content,
834 uint16_t group, uint16_t element)
836 ValEntry *entry = GetValEntry(group, element);
839 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
842 return SetEntry(content,entry);
846 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
847 * through it's (group, element) and modifies it's content with
849 * @param content new value (void* -> uint8_t*) to substitute with
850 * @param lgth new value length
851 * @param group group number of the Dicom Element to modify
852 * @param element element number of the Dicom Element to modify
854 bool Document::SetEntry(uint8_t*content, int lgth,
855 uint16_t group, uint16_t element)
857 BinEntry *entry = GetBinEntry(group, element);
860 gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
864 return SetEntry(content,lgth,entry);
868 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
869 * and modifies it's content with the given value.
870 * @param content new value (string) to substitute with
871 * @param entry Entry to be modified
873 bool Document::SetEntry(std::string const &content,ValEntry *entry)
877 entry->SetValue(content);
884 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
885 * and modifies it's content with the given value.
886 * @param content new value (void* -> uint8_t*) to substitute with
887 * @param entry Entry to be modified
888 * @param lgth new value length
890 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
894 // Hope Binary field length is *never* wrong
895 /*if(lgth%2) // Non even length are padded with a space (020H).
898 //content = content + '\0'; // fing a trick to enlarge a binary field?
901 entry->SetBinArea(content);
902 entry->SetLength(lgth);
903 entry->SetValue(GDCM_BINLOADED);
910 * \brief Gets (from Header) a 'non string' element value
911 * (LoadElementValues has already be executed)
912 * @param group group number of the Entry
913 * @param elem element number of the Entry
914 * @return Pointer to the 'non string' area
916 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem)
918 DocEntry *entry = GetDocEntry(group, elem);
921 gdcmVerboseMacro( "No entry");
924 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
926 return binEntry->GetBinArea();
933 * \brief Loads (from disk) the element content
934 * when a string is not suitable
935 * @param group group number of the Entry
936 * @param elem element number of the Entry
938 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
940 // Search the corresponding DocEntry
941 DocEntry *docElement = GetDocEntry(group, elem);
945 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
949 LoadEntryBinArea(binElement);
953 * \brief Loads (from disk) the element content
954 * when a string is not suitable
955 * @param element Entry whose binArea is going to be loaded
957 void Document::LoadEntryBinArea(BinEntry *element)
959 if(element->GetBinArea())
966 size_t o =(size_t)element->GetOffset();
967 Fp->seekg(o, std::ios::beg);
969 size_t l = element->GetLength();
970 uint8_t *a = new uint8_t[l];
973 gdcmVerboseMacro( "Cannot allocate a");
977 /// \todo check the result
978 Fp->read((char*)a, l);
979 if( Fp->fail() || Fp->eof())
985 element->SetBinArea(a);
992 * \brief Sets a 'non string' value to a given Dicom Element
993 * @param area area containing the 'non string' value
994 * @param group Group number of the searched Dicom Element
995 * @param element Element number of the searched Dicom Element
998 /*bool Document::SetEntryBinArea(uint8_t *area,
999 uint16_t group, uint16_t element)
1001 DocEntry *currentEntry = GetDocEntry(group, element);
1002 if ( !currentEntry )
1007 if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1009 binEntry->SetBinArea( area );
1017 * \brief retrieves a Dicom Element (the first one) using (group, element)
1018 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1019 * if you think it's NOT UNIQUE, check the count number
1020 * and use iterators to retrieve ALL the Dicoms Elements within
1021 * a given couple (group, element)
1022 * @param group Group number of the searched Dicom Element
1023 * @param element Element number of the searched Dicom Element
1026 DocEntry *Document::GetDocEntry(uint16_t group, uint16_t element)
1028 TagKey key = DictEntry::TranslateToKey(group, element);
1029 if ( !TagHT.count(key))
1033 return TagHT.find(key)->second;
1037 * \brief Same as \ref Document::GetDocEntry except it only
1038 * returns a result when the corresponding entry is of type
1040 * @return When present, the corresponding ValEntry.
1042 ValEntry *Document::GetValEntry(uint16_t group, uint16_t element)
1044 DocEntry *currentEntry = GetDocEntry(group, element);
1045 if ( !currentEntry )
1049 if ( ValEntry *entry = dynamic_cast<ValEntry*>(currentEntry) )
1053 gdcmVerboseMacro( "Unfound ValEntry.");
1059 * \brief Same as \ref Document::GetDocEntry except it only
1060 * returns a result when the corresponding entry is of type
1062 * @return When present, the corresponding BinEntry.
1064 BinEntry *Document::GetBinEntry(uint16_t group, uint16_t element)
1066 DocEntry *currentEntry = GetDocEntry(group, element);
1067 if ( !currentEntry )
1071 if ( BinEntry *entry = dynamic_cast<BinEntry*>(currentEntry) )
1075 gdcmVerboseMacro( "Unfound BinEntry.");
1081 * \brief Loads the element while preserving the current
1082 * underlying file position indicator as opposed to
1083 * to LoadDocEntry that modifies it.
1084 * @param entry Header Entry whose value shall be loaded.
1087 void Document::LoadDocEntrySafe(DocEntry *entry)
1091 long PositionOnEntry = Fp->tellg();
1092 LoadDocEntry(entry);
1093 Fp->seekg(PositionOnEntry, std::ios::beg);
1098 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1100 * @return The properly swaped 32 bits integer.
1102 uint32_t Document::SwapLong(uint32_t a)
1109 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1110 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1114 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1118 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1121 gdcmErrorMacro( "Unset swap code:" << SwapCode );
1128 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1130 * @return The properly unswaped 32 bits integer.
1132 uint32_t Document::UnswapLong(uint32_t a)
1138 * \brief Swaps the bytes so they agree with the processor order
1139 * @return The properly swaped 16 bits integer.
1141 uint16_t Document::SwapShort(uint16_t a)
1143 if ( SwapCode == 4321 || SwapCode == 2143 )
1145 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1151 * \brief Unswaps the bytes so they agree with the processor order
1152 * @return The properly unswaped 16 bits integer.
1154 uint16_t Document::UnswapShort(uint16_t a)
1156 return SwapShort(a);
1159 //-----------------------------------------------------------------------------
1163 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1164 * @return length of the parsed set.
1166 void Document::ParseDES(DocEntrySet *set, long offset,
1167 long l_max, bool delim_mode)
1169 DocEntry *newDocEntry = 0;
1170 ValEntry *newValEntry;
1171 BinEntry *newBinEntry;
1172 SeqEntry *newSeqEntry;
1178 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1184 newDocEntry = ReadNextDocEntry( );
1190 vr = newDocEntry->GetVR();
1191 newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1192 newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1193 newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1195 if ( newValEntry || newBinEntry )
1199 if ( ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1201 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1202 gdcmVerboseMacro( "Neither Valentry, nor BinEntry."
1203 "Probably unknown VR.");
1206 //////////////////// BinEntry or UNKOWN VR:
1207 // When "this" is a Document the Key is simply of the
1208 // form ( group, elem )...
1209 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1212 newBinEntry->SetKey( newBinEntry->GetKey() );
1214 // but when "this" is a SQItem, we are inserting this new
1215 // valEntry in a sequence item, and the kay has the
1216 // generalized form (refer to \ref BaseTagKey):
1217 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1219 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1220 + newBinEntry->GetKey() );
1223 LoadDocEntry( newBinEntry );
1224 if( !set->AddEntry( newBinEntry ) )
1226 //Expect big troubles if here
1227 //delete newBinEntry;
1233 /////////////////////// ValEntry
1234 // When "set" is a Document, then we are at the top of the
1235 // hierarchy and the Key is simply of the form ( group, elem )...
1236 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1239 newValEntry->SetKey( newValEntry->GetKey() );
1241 // ...but when "set" is a SQItem, we are inserting this new
1242 // valEntry in a sequence item. Hence the key has the
1243 // generalized form (refer to \ref BaseTagKey):
1244 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1246 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1247 + newValEntry->GetKey() );
1250 LoadDocEntry( newValEntry );
1251 bool delimitor=newValEntry->IsItemDelimitor();
1252 if( !set->AddEntry( newValEntry ) )
1254 // If here expect big troubles
1255 //delete newValEntry; //otherwise mem leak
1265 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1273 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1274 && ( newDocEntry->GetElement() == 0x0010 ) )
1276 TransferSyntaxType ts = GetTransferSyntax();
1277 if ( ts == RLELossless )
1279 long positionOnEntry = Fp->tellg();
1280 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1282 Fp->seekg( positionOnEntry, std::ios::beg );
1284 else if ( IsJPEG() )
1286 long positionOnEntry = Fp->tellg();
1287 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1288 ComputeJPEGFragmentInfo();
1289 Fp->seekg( positionOnEntry, std::ios::beg );
1293 // Just to make sure we are at the beginning of next entry.
1294 SkipToNextDocEntry(newDocEntry);
1299 unsigned long l = newDocEntry->GetReadLength();
1300 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1302 if ( l == 0xffffffff )
1311 // no other way to create it ...
1312 newSeqEntry->SetDelimitorMode( delim_mode );
1314 // At the top of the hierarchy, stands a Document. When "set"
1315 // is a Document, then we are building the first depth level.
1316 // Hence the SeqEntry we are building simply has a depth
1318 if (Document *dummy = dynamic_cast< Document* > ( set ) )
1321 newSeqEntry->SetDepthLevel( 1 );
1322 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1324 // But when "set" is allready a SQItem, we are building a nested
1325 // sequence, and hence the depth level of the new SeqEntry
1326 // we are building, is one level deeper:
1327 if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1329 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1330 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1331 + newSeqEntry->GetKey() );
1335 { // Don't try to parse zero-length sequences
1336 ParseSQ( newSeqEntry,
1337 newDocEntry->GetOffset(),
1340 set->AddEntry( newSeqEntry );
1341 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1353 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1354 * @return parsed length for this level
1356 void Document::ParseSQ( SeqEntry *seqEntry,
1357 long offset, long l_max, bool delim_mode)
1359 int SQItemNumber = 0;
1364 DocEntry *newDocEntry = ReadNextDocEntry();
1367 // FIXME Should warn user
1372 if ( newDocEntry->IsSequenceDelimitor() )
1374 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1378 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1384 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1385 std::ostringstream newBase;
1386 newBase << seqEntry->GetKey()
1390 itemSQ->SetBaseTagKey( newBase.str() );
1391 unsigned int l = newDocEntry->GetReadLength();
1393 if ( l == 0xffffffff )
1402 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1405 seqEntry->AddEntry( itemSQ, SQItemNumber );
1407 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1415 * \brief Loads the element content if its length doesn't exceed
1416 * the value specified with Document::SetMaxSizeLoadEntry()
1417 * @param entry Header Entry (Dicom Element) to be dealt with
1419 void Document::LoadDocEntry(DocEntry *entry)
1421 uint16_t group = entry->GetGroup();
1422 std::string vr = entry->GetVR();
1423 uint32_t length = entry->GetLength();
1425 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1427 // A SeQuence "contains" a set of Elements.
1428 // (fffe e000) tells us an Element is beginning
1429 // (fffe e00d) tells us an Element just ended
1430 // (fffe e0dd) tells us the current SeQuence just ended
1431 if( group == 0xfffe )
1433 // NO more value field for SQ !
1437 // When the length is zero things are easy:
1440 ((ValEntry *)entry)->SetValue("");
1444 // The elements whose length is bigger than the specified upper bound
1445 // are not loaded. Instead we leave a short notice of the offset of
1446 // the element content and it's length.
1448 std::ostringstream s;
1449 if (length > MaxSizeLoadEntry)
1451 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1453 //s << "gdcm::NotLoaded (BinEntry)";
1454 s << GDCM_NOTLOADED;
1455 s << " Address:" << (long)entry->GetOffset();
1456 s << " Length:" << entry->GetLength();
1457 s << " x(" << std::hex << entry->GetLength() << ")";
1458 binEntryPtr->SetValue(s.str());
1460 // Be carefull : a BinEntry IS_A ValEntry ...
1461 else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1463 // s << "gdcm::NotLoaded. (ValEntry)";
1464 s << GDCM_NOTLOADED;
1465 s << " Address:" << (long)entry->GetOffset();
1466 s << " Length:" << entry->GetLength();
1467 s << " x(" << std::hex << entry->GetLength() << ")";
1468 valEntryPtr->SetValue(s.str());
1473 gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1474 << "nor a ValEntry ?! Should never print that !" );
1477 // to be sure we are at the end of the value ...
1478 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1483 // When we find a BinEntry not very much can be done :
1484 if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1486 s << GDCM_BINLOADED;
1487 binEntryPtr->SetValue(s.str());
1488 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1492 /// \todo Any compacter code suggested (?)
1493 if ( IsDocEntryAnInteger(entry) )
1497 // When short integer(s) are expected, read and convert the following
1498 // n *two characters properly i.e. consider them as short integers as
1499 // opposed to strings.
1500 // Elements with Value Multiplicity > 1
1501 // contain a set of integers (not a single one)
1502 if (vr == "US" || vr == "SS")
1505 NewInt = ReadInt16();
1509 for (int i=1; i < nbInt; i++)
1512 NewInt = ReadInt16();
1517 // See above comment on multiple integers (mutatis mutandis).
1518 else if (vr == "UL" || vr == "SL")
1521 NewInt = ReadInt32();
1525 for (int i=1; i < nbInt; i++)
1528 NewInt = ReadInt32();
1533 #ifdef GDCM_NO_ANSI_STRING_STREAM
1534 s << std::ends; // to avoid oddities on Solaris
1535 #endif //GDCM_NO_ANSI_STRING_STREAM
1537 ((ValEntry *)entry)->SetValue(s.str());
1541 // FIXME: We need an additional byte for storing \0 that is not on disk
1542 char *str = new char[length+1];
1543 Fp->read(str, (size_t)length);
1544 str[length] = '\0'; //this is only useful when length is odd
1545 // Special DicomString call to properly handle \0 and even length
1546 std::string newValue;
1549 newValue = Util::DicomString(str, length+1);
1550 gdcmVerboseMacro("Warning: bad length: " << length <<
1551 ",For string :" << newValue.c_str());
1552 // Since we change the length of string update it length
1553 //entry->SetReadLength(length+1);
1557 newValue = Util::DicomString(str, length);
1561 if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1563 if ( Fp->fail() || Fp->eof())
1565 gdcmVerboseMacro("Unread element value");
1566 valEntry->SetValue(GDCM_UNREAD);
1572 // Because of correspondance with the VR dic
1573 valEntry->SetValue(newValue);
1577 valEntry->SetValue(newValue);
1582 gdcmErrorMacro( "Should have a ValEntry, here !");
1588 * \brief Find the value Length of the passed Header Entry
1589 * @param entry Header Entry whose length of the value shall be loaded.
1591 void Document::FindDocEntryLength( DocEntry *entry )
1592 throw ( FormatError )
1594 uint16_t element = entry->GetElement();
1595 std::string vr = entry->GetVR();
1598 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1600 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1602 // The following reserved two bytes (see PS 3.5-2003, section
1603 // "7.1.2 Data element structure with explicit vr", p 27) must be
1604 // skipped before proceeding on reading the length on 4 bytes.
1605 Fp->seekg( 2L, std::ios::cur);
1606 uint32_t length32 = ReadInt32();
1608 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1613 lengthOB = FindDocEntryLengthOBOrOW();
1615 catch ( FormatUnexpected )
1617 // Computing the length failed (this happens with broken
1618 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1619 // chance to get the pixels by deciding the element goes
1620 // until the end of the file. Hence we artificially fix the
1621 // the length and proceed.
1622 long currentPosition = Fp->tellg();
1623 Fp->seekg(0L,std::ios::end);
1625 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1626 Fp->seekg(currentPosition, std::ios::beg);
1628 entry->SetReadLength(lengthUntilEOF);
1629 entry->SetLength(lengthUntilEOF);
1632 entry->SetReadLength(lengthOB);
1633 entry->SetLength(lengthOB);
1636 FixDocEntryFoundLength(entry, length32);
1640 // Length is encoded on 2 bytes.
1641 length16 = ReadInt16();
1643 // We can tell the current file is encoded in big endian (like
1644 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1645 // and it's value is the one of the encoding of a big endian file.
1646 // In order to deal with such big endian encoded files, we have
1647 // (at least) two strategies:
1648 // * when we load the "Transfer Syntax" tag with value of big endian
1649 // encoding, we raise the proper flags. Then we wait for the end
1650 // of the META group (0x0002) among which is "Transfer Syntax",
1651 // before switching the swap code to big endian. We have to postpone
1652 // the switching of the swap code since the META group is fully encoded
1653 // in little endian, and big endian coding only starts at the next
1654 // group. The corresponding code can be hard to analyse and adds
1655 // many additional unnecessary tests for regular tags.
1656 // * the second strategy consists in waiting for trouble, that shall
1657 // appear when we find the first group with big endian encoding. This
1658 // is easy to detect since the length of a "Group Length" tag (the
1659 // ones with zero as element number) has to be of 4 (0x0004). When we
1660 // encounter 1024 (0x0400) chances are the encoding changed and we
1661 // found a group with big endian encoding.
1662 // We shall use this second strategy. In order to make sure that we
1663 // can interpret the presence of an apparently big endian encoded
1664 // length of a "Group Length" without committing a big mistake, we
1665 // add an additional check: we look in the already parsed elements
1666 // for the presence of a "Transfer Syntax" whose value has to be "big
1667 // endian encoding". When this is the case, chances are we have got our
1668 // hands on a big endian encoded file: we switch the swap code to
1669 // big endian and proceed...
1670 if ( element == 0x0000 && length16 == 0x0400 )
1672 TransferSyntaxType ts = GetTransferSyntax();
1673 if ( ts != ExplicitVRBigEndian )
1675 throw FormatError( "Document::FindDocEntryLength()",
1676 " not explicit VR." );
1680 SwitchByteSwapCode();
1682 // Restore the unproperly loaded values i.e. the group, the element
1683 // and the dictionary entry depending on them.
1684 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1685 uint16_t correctElem = SwapShort( entry->GetElement() );
1686 DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1689 // This correct tag is not in the dictionary. Create a new one.
1690 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1692 // FIXME this can create a memory leaks on the old entry that be
1693 // left unreferenced.
1694 entry->SetDictEntry( newTag );
1697 // Heuristic: well, some files are really ill-formed.
1698 if ( length16 == 0xffff)
1700 // 0xffff means that we deal with 'Unknown Length' Sequence
1703 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1708 // Either implicit VR or a non DICOM conformal (see note below) explicit
1709 // VR that ommited the VR of (at least) this element. Farts happen.
1710 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1711 // on Data elements "Implicit and Explicit VR Data Elements shall
1712 // not coexist in a Data Set and Data Sets nested within it".]
1713 // Length is on 4 bytes.
1715 FixDocEntryFoundLength( entry, ReadInt32() );
1721 * \brief Find the Value Representation of the current Dicom Element.
1722 * @return Value Representation of the current Entry
1724 std::string Document::FindDocEntryVR()
1726 if ( Filetype != ExplicitVR )
1727 return GDCM_UNKNOWN;
1729 long positionOnEntry = Fp->tellg();
1730 // Warning: we believe this is explicit VR (Value Representation) because
1731 // we used a heuristic that found "UL" in the first tag. Alas this
1732 // doesn't guarantee that all the tags will be in explicit VR. In some
1733 // cases (see e-film filtered files) one finds implicit VR tags mixed
1734 // within an explicit VR file. Hence we make sure the present tag
1735 // is in explicit VR and try to fix things if it happens not to be
1739 Fp->read (vr, (size_t)2);
1742 if( !CheckDocEntryVR(vr) )
1744 Fp->seekg(positionOnEntry, std::ios::beg);
1745 return GDCM_UNKNOWN;
1751 * \brief Check the correspondance between the VR of the header entry
1752 * and the taken VR. If they are different, the header entry is
1753 * updated with the new VR.
1754 * @param vr Dicom Value Representation
1755 * @return false if the VR is incorrect of if the VR isn't referenced
1756 * otherwise, it returns true
1758 bool Document::CheckDocEntryVR(VRKey vr)
1760 // CLEANME searching the dicom_vr at each occurence is expensive.
1761 // PostPone this test in an optional integrity check at the end
1762 // of parsing or only in debug mode.
1763 if ( !Global::GetVR()->IsValidVR(vr) )
1770 * \brief Get the transformed value of the header entry. The VR value
1771 * is used to define the transformation to operate on the value
1772 * \warning NOT end user intended method !
1773 * @param entry entry to tranform
1774 * @return Transformed entry value
1776 std::string Document::GetDocEntryValue(DocEntry *entry)
1778 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1780 std::string val = ((ValEntry *)entry)->GetValue();
1781 std::string vr = entry->GetVR();
1782 uint32_t length = entry->GetLength();
1783 std::ostringstream s;
1786 // When short integer(s) are expected, read and convert the following
1787 // n * 2 bytes properly i.e. as a multivaluated strings
1788 // (each single value is separated fromthe next one by '\'
1789 // as usual for standard multivaluated filels
1790 // Elements with Value Multiplicity > 1
1791 // contain a set of short integers (not a single one)
1793 if( vr == "US" || vr == "SS" )
1798 for (int i=0; i < nbInt; i++)
1804 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1805 newInt16 = SwapShort( newInt16 );
1810 // When integer(s) are expected, read and convert the following
1811 // n * 4 bytes properly i.e. as a multivaluated strings
1812 // (each single value is separated fromthe next one by '\'
1813 // as usual for standard multivaluated filels
1814 // Elements with Value Multiplicity > 1
1815 // contain a set of integers (not a single one)
1816 else if( vr == "UL" || vr == "SL" )
1821 for (int i=0; i < nbInt; i++)
1827 newInt32 = ( val[4*i+0] & 0xFF )
1828 + (( val[4*i+1] & 0xFF ) << 8 )
1829 + (( val[4*i+2] & 0xFF ) << 16 )
1830 + (( val[4*i+3] & 0xFF ) << 24 );
1831 newInt32 = SwapLong( newInt32 );
1835 #ifdef GDCM_NO_ANSI_STRING_STREAM
1836 s << std::ends; // to avoid oddities on Solaris
1837 #endif //GDCM_NO_ANSI_STRING_STREAM
1841 return ((ValEntry *)entry)->GetValue();
1845 * \brief Get the reverse transformed value of the header entry. The VR
1846 * value is used to define the reverse transformation to operate on
1848 * \warning NOT end user intended method !
1849 * @param entry Entry to reverse transform
1850 * @return Reverse transformed entry value
1852 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1854 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1856 std::string vr = entry->GetVR();
1857 std::vector<std::string> tokens;
1858 std::ostringstream s;
1860 if ( vr == "US" || vr == "SS" )
1864 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1865 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1866 for (unsigned int i=0; i<tokens.size(); i++)
1868 newInt16 = atoi(tokens[i].c_str());
1869 s << ( newInt16 & 0xFF )
1870 << (( newInt16 >> 8 ) & 0xFF );
1874 if ( vr == "UL" || vr == "SL")
1878 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1879 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1880 for (unsigned int i=0; i<tokens.size();i++)
1882 newInt32 = atoi(tokens[i].c_str());
1883 s << (char)( newInt32 & 0xFF )
1884 << (char)(( newInt32 >> 8 ) & 0xFF )
1885 << (char)(( newInt32 >> 16 ) & 0xFF )
1886 << (char)(( newInt32 >> 24 ) & 0xFF );
1891 #ifdef GDCM_NO_ANSI_STRING_STREAM
1892 s << std::ends; // to avoid oddities on Solaris
1893 #endif //GDCM_NO_ANSI_STRING_STREAM
1897 return ((ValEntry *)entry)->GetValue();
1901 * \brief Skip a given Header Entry
1902 * \warning NOT end user intended method !
1903 * @param entry entry to skip
1905 void Document::SkipDocEntry(DocEntry *entry)
1907 SkipBytes(entry->GetLength());
1911 * \brief Skips to the begining of the next Header Entry
1912 * \warning NOT end user intended method !
1913 * @param currentDocEntry entry to skip
1915 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry)
1917 Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1918 Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1922 * \brief When the length of an element value is obviously wrong (because
1923 * the parser went Jabberwocky) one can hope improving things by
1924 * applying some heuristics.
1925 * @param entry entry to check
1926 * @param foundLength first assumption about length
1928 void Document::FixDocEntryFoundLength(DocEntry *entry,
1929 uint32_t foundLength)
1931 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
1932 if ( foundLength == 0xffffffff)
1937 uint16_t gr = entry->GetGroup();
1938 uint16_t elem = entry->GetElement();
1940 if ( foundLength % 2)
1942 gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength
1943 << " in x(" << std::hex << gr << "," << elem <<")");
1946 //////// Fix for some naughty General Electric images.
1947 // Allthough not recent many such GE corrupted images are still present
1948 // on Creatis hard disks. Hence this fix shall remain when such images
1949 // are no longer in use (we are talking a few years, here)...
1950 // Note: XMedCom probably uses such a trick since it is able to read
1951 // those pesky GE images ...
1952 if ( foundLength == 13)
1954 // Only happens for this length !
1955 if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1958 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1962 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1963 // Occurence of such images is quite low (unless one leaves close to a
1964 // 'Leonardo' source. Hence, one might consider commenting out the
1965 // following fix on efficiency reasons.
1966 else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1969 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1972 else if ( entry->GetVR() == "SQ" )
1974 foundLength = 0; // ReadLength is unchanged
1977 //////// We encountered a 'delimiter' element i.e. a tag of the form
1978 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1979 // taken into account.
1980 else if( gr == 0xfffe )
1982 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1983 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1984 // causes extra troubles...
1985 if( entry->GetElement() != 0x0000 )
1991 entry->SetLength(foundLength);
1995 * \brief Apply some heuristics to predict whether the considered
1996 * element value contains/represents an integer or not.
1997 * @param entry The element value on which to apply the predicate.
1998 * @return The result of the heuristical predicate.
2000 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2002 uint16_t elem = entry->GetElement();
2003 uint16_t group = entry->GetGroup();
2004 const std::string &vr = entry->GetVR();
2005 uint32_t length = entry->GetLength();
2007 // When we have some semantics on the element we just read, and if we
2008 // a priori know we are dealing with an integer, then we shall be
2009 // able to swap it's element value properly.
2010 if ( elem == 0 ) // This is the group length of the group
2018 // Allthough this should never happen, still some images have a
2019 // corrupted group length [e.g. have a glance at offset x(8336) of
2020 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2021 // Since for dicom compliant and well behaved headers, the present
2022 // test is useless (and might even look a bit paranoid), when we
2023 // encounter such an ill-formed image, we simply display a warning
2024 // message and proceed on parsing (while crossing fingers).
2025 long filePosition = Fp->tellg();
2026 gdcmVerboseMacro( "Erroneous Group Length element length on : ("
2027 << std::hex << group << " , " << elem
2028 << ") -before- position x(" << filePosition << ")"
2029 << "lgt : " << length );
2033 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2041 * \brief Find the Length till the next sequence delimiter
2042 * \warning NOT end user intended method !
2046 uint32_t Document::FindDocEntryLengthOBOrOW()
2047 throw( FormatUnexpected )
2049 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2050 long positionOnEntry = Fp->tellg();
2051 bool foundSequenceDelimiter = false;
2052 uint32_t totalLength = 0;
2054 while ( !foundSequenceDelimiter )
2060 group = ReadInt16();
2063 catch ( FormatError )
2065 throw FormatError("Unexpected end of file encountered during ",
2066 "Document::FindDocEntryLengthOBOrOW()");
2069 // We have to decount the group and element we just read
2072 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2074 long filePosition = Fp->tellg();
2075 gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :"
2076 << std::hex << group << " , " << elem
2077 << ") -before- position x(" << filePosition << ")" );
2079 Fp->seekg(positionOnEntry, std::ios::beg);
2080 throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
2083 if ( elem == 0xe0dd )
2085 foundSequenceDelimiter = true;
2088 uint32_t itemLength = ReadInt32();
2089 // We add 4 bytes since we just read the ItemLength with ReadInt32
2090 totalLength += itemLength + 4;
2091 SkipBytes(itemLength);
2093 if ( foundSequenceDelimiter )
2098 Fp->seekg( positionOnEntry, std::ios::beg);
2103 * \brief Reads a supposed to be 16 Bits integer
2104 * (swaps it depending on processor endianity)
2105 * @return read value
2107 uint16_t Document::ReadInt16()
2108 throw( FormatError )
2111 Fp->read ((char*)&g, (size_t)2);
2114 throw FormatError( "Document::ReadInt16()", " file error." );
2118 throw FormatError( "Document::ReadInt16()", "EOF." );
2125 * \brief Reads a supposed to be 32 Bits integer
2126 * (swaps it depending on processor endianity)
2127 * @return read value
2129 uint32_t Document::ReadInt32()
2130 throw( FormatError )
2133 Fp->read ((char*)&g, (size_t)4);
2136 throw FormatError( "Document::ReadInt32()", " file error." );
2140 throw FormatError( "Document::ReadInt32()", "EOF." );
2147 * \brief skips bytes inside the source file
2148 * \warning NOT end user intended method !
2151 void Document::SkipBytes(uint32_t nBytes)
2153 //FIXME don't dump the returned value
2154 Fp->seekg((long)nBytes, std::ios::cur);
2158 * \brief Loads all the needed Dictionaries
2159 * \warning NOT end user intended method !
2161 void Document::Initialise()
2163 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2165 RLEInfo = new RLEFramesInfo;
2166 JPEGInfo = new JPEGFragmentsInfo;
2171 * \brief Discover what the swap code is (among little endian, big endian,
2172 * bad little endian, bad big endian).
2174 * @return false when we are absolutely sure
2175 * it's neither ACR-NEMA nor DICOM
2176 * true when we hope ours assuptions are OK
2178 bool Document::CheckSwap()
2180 // The only guaranted way of finding the swap code is to find a
2181 // group tag since we know it's length has to be of four bytes i.e.
2182 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2183 // occurs when we can't find such group...
2185 uint32_t x = 4; // x : for ntohs
2186 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2192 // First, compare HostByteOrder and NetworkByteOrder in order to
2193 // determine if we shall need to swap bytes (i.e. the Endian type).
2194 if ( x == ntohs(x) )
2203 // The easiest case is the one of a DICOM header, since it possesses a
2204 // file preamble where it suffice to look for the string "DICM".
2207 char *entCur = deb + 128;
2208 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2210 gdcmVerboseMacro( "Looks like DICOM Version3" );
2212 // Next, determine the value representation (VR). Let's skip to the
2213 // first element (0002, 0000) and check there if we find "UL"
2214 // - or "OB" if the 1st one is (0002,0001) -,
2215 // in which case we (almost) know it is explicit VR.
2216 // WARNING: if it happens to be implicit VR then what we will read
2217 // is the length of the group. If this ascii representation of this
2218 // length happens to be "UL" then we shall believe it is explicit VR.
2219 // FIXME: in order to fix the above warning, we could read the next
2220 // element value (or a couple of elements values) in order to make
2221 // sure we are not commiting a big mistake.
2222 // We need to skip :
2223 // * the 128 bytes of File Preamble (often padded with zeroes),
2224 // * the 4 bytes of "DICM" string,
2225 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2226 // i.e. a total of 136 bytes.
2230 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2231 // but elem 0002,0010 (Transfer Syntax) tells us the file is
2232 // *Implicit* VR. -and it is !-
2234 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2235 memcmp(entCur, "OB", (size_t)2) == 0 ||
2236 memcmp(entCur, "UI", (size_t)2) == 0 ||
2237 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2238 // when Write DCM *adds*
2240 // Use Document::dicom_vr to test all the possibilities
2241 // instead of just checking for UL, OB and UI !? group 0000
2243 Filetype = ExplicitVR;
2244 gdcmVerboseMacro( "Explicit Value Representation");
2248 Filetype = ImplicitVR;
2249 gdcmVerboseMacro( "Not an explicit Value Representation");
2255 gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2260 gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2263 // Position the file position indicator at first tag (i.e.
2264 // after the file preamble and the "DICM" string).
2265 Fp->seekg(0, std::ios::beg);
2266 Fp->seekg ( 132L, std::ios::beg);
2270 // Alas, this is not a DicomV3 file and whatever happens there is no file
2271 // preamble. We can reset the file position indicator to where the data
2272 // is (i.e. the beginning of the file).
2273 gdcmVerboseMacro( "Not a DICOM Version3 file");
2274 Fp->seekg(0, std::ios::beg);
2276 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2277 // By clean we mean that the length of the first tag is written down.
2278 // If this is the case and since the length of the first group HAS to be
2279 // four (bytes), then determining the proper swap code is straightforward.
2282 // We assume the array of char we are considering contains the binary
2283 // representation of a 32 bits integer. Hence the following dirty
2285 s32 = *((uint32_t *)(entCur));
2306 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2307 // It is time for despaired wild guesses.
2308 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2309 // i.e. the 'group length' element is not present :
2311 // check the supposed-to-be 'group number'
2312 // in ( 0x0001 .. 0x0008 )
2313 // to determine ' SwapCode' value .
2314 // Only 0 or 4321 will be possible
2315 // (no oportunity to check for the formerly well known
2316 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2317 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2318 // the file IS NOT ACR-NEMA nor DICOM V3
2319 // Find a trick to tell it the caller...
2321 s16 = *((uint16_t *)(deb));
2348 gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2352 // Then the only info we have is the net2host one.
2364 * \brief Change the Byte Swap code.
2366 void Document::SwitchByteSwapCode()
2368 gdcmVerboseMacro( "Switching Byte Swap code.");
2369 if ( SwapCode == 0 )
2373 else if ( SwapCode == 4321 )
2377 else if ( SwapCode == 3412 )
2381 else if ( SwapCode == 2143 )
2388 * \brief during parsing, Header Elements too long are not loaded in memory
2391 void Document::SetMaxSizeLoadEntry(long newSize)
2397 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2399 MaxSizeLoadEntry = 0xffffffff;
2402 MaxSizeLoadEntry = newSize;
2407 * \brief Header Elements too long will not be printed
2408 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2411 void Document::SetMaxSizePrintEntry(long newSize)
2413 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2418 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2420 MaxSizePrintEntry = 0xffffffff;
2423 MaxSizePrintEntry = newSize;
2429 * \brief Handle broken private tag from Philips NTSCAN
2430 * where the endianess is being switch to BigEndian for no
2434 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2436 // Endian reversion. Some files contain groups of tags with reversed endianess.
2437 static int reversedEndian = 0;
2438 // try to fix endian switching in the middle of headers
2439 if ((group == 0xfeff) && (elem == 0x00e0))
2441 // start endian swap mark for group found
2443 SwitchByteSwapCode();
2448 else if (group == 0xfffe && elem == 0xe00d && reversedEndian)
2450 // end of reversed endian group
2452 SwitchByteSwapCode();
2457 * \brief Group 0002 is always coded Little Endian
2458 * whatever Transfer Syntax is
2461 void Document::HandleOutOfGroup0002(uint16_t group)
2463 // Endian reversion. Some files contain groups of tags with reversed endianess.
2464 if ( !Group0002Parsed && group != 0x0002)
2466 Group0002Parsed = true;
2467 // we just came out of group 0002
2468 // if Transfer syntax is Big Endian we have to change CheckSwap
2470 TagKey key = DictEntry::TranslateToKey(0x0002, 0x0010);
2471 if ( !TagHT.count(key))
2473 gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax ?!?");
2477 // FIXME Strangely, this works with
2478 //'Implicit VR Transfer Syntax (GE Private)
2480 if ( ((ValEntry *)TagHT.find(key)->second)->GetValue()
2481 == "Explicit VR - Big Endian" )
2483 gdcmVerboseMacro("Tansfer Syntax = Explicit VR - Big Endian");
2484 SwitchByteSwapCode();
2490 * \brief Read the next tag but WITHOUT loading it's value
2491 * (read the 'Group Number', the 'Element Number',
2492 * gets the Dict Entry
2493 * gets the VR, gets the length, gets the offset value)
2494 * @return On succes the newly created DocEntry, NULL on failure.
2496 DocEntry *Document::ReadNextDocEntry()
2503 group = ReadInt16();
2506 catch ( FormatError e )
2508 // We reached the EOF (or an error occured) therefore
2509 // header parsing has to be considered as finished.
2514 // Sometimes file contains groups of tags with reversed endianess.
2515 HandleBrokenEndian(group, elem);
2517 // In 'true DICOM' files Group 0002 is allways little endian
2518 if ( HasDCMPreamble )
2519 HandleOutOfGroup0002(group);
2521 std::string vr = FindDocEntryVR();
2522 std::string realVR = vr;
2524 if( vr == GDCM_UNKNOWN)
2526 DictEntry *dictEntry = GetDictEntry(group,elem);
2528 realVR = dictEntry->GetVR();
2532 if( Global::GetVR()->IsVROfSequence(realVR) )
2533 newEntry = NewSeqEntry(group, elem);
2534 else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2535 newEntry = NewValEntry(group, elem,vr);
2537 newEntry = NewBinEntry(group, elem,vr);
2539 if( vr == GDCM_UNKNOWN )
2541 if( Filetype == ExplicitVR )
2543 // We thought this was explicit VR, but we end up with an
2544 // implicit VR tag. Let's backtrack.
2546 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
2547 newEntry->GetGroup(), newEntry->GetElement());
2548 gdcmVerboseMacro( msg.c_str() );
2550 newEntry->SetImplicitVR();
2555 FindDocEntryLength(newEntry);
2557 catch ( FormatError e )
2565 newEntry->SetOffset(Fp->tellg());
2572 * \brief Generate a free TagKey i.e. a TagKey that is not present
2573 * in the TagHt dictionary.
2574 * @param group The generated tag must belong to this group.
2575 * @return The element of tag with given group which is fee.
2577 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2579 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2581 TagKey key = DictEntry::TranslateToKey(group, elem);
2582 if (TagHT.count(key) == 0)
2591 * \brief Assuming the internal file pointer \ref Document::Fp
2592 * is placed at the beginning of a tag check whether this
2593 * tag is (TestGroup, TestElement).
2594 * \warning On success the internal file pointer \ref Document::Fp
2595 * is modified to point after the tag.
2596 * On failure (i.e. when the tag wasn't the expected tag
2597 * (TestGroup, TestElement) the internal file pointer
2598 * \ref Document::Fp is restored to it's original position.
2599 * @param testGroup The expected group of the tag.
2600 * @param testElement The expected Element of the tag.
2601 * @return True on success, false otherwise.
2603 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2605 long positionOnEntry = Fp->tellg();
2606 long currentPosition = Fp->tellg(); // On debugging purposes
2608 //// Read the Item Tag group and element, and make
2609 // sure they are what we expected:
2610 uint16_t itemTagGroup;
2611 uint16_t itemTagElement;
2614 itemTagGroup = ReadInt16();
2615 itemTagElement = ReadInt16();
2617 catch ( FormatError e )
2619 //std::cerr << e << std::endl;
2622 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2624 gdcmVerboseMacro( "Wrong Item Tag found:"
2625 << " We should have found tag ("
2626 << std::hex << testGroup << "," << testElement << ")" << std::endl
2627 << " but instead we encountered tag ("
2628 << std::hex << itemTagGroup << "," << itemTagElement << ")"
2630 << " at address: " << (unsigned int)currentPosition
2632 << " 0x(" << (unsigned int)currentPosition << ")"
2634 Fp->seekg(positionOnEntry, std::ios::beg);
2642 * \brief Assuming the internal file pointer \ref Document::Fp
2643 * is placed at the beginning of a tag (TestGroup, TestElement),
2644 * read the length associated to the Tag.
2645 * \warning On success the internal file pointer \ref Document::Fp
2646 * is modified to point after the tag and it's length.
2647 * On failure (i.e. when the tag wasn't the expected tag
2648 * (TestGroup, TestElement) the internal file pointer
2649 * \ref Document::Fp is restored to it's original position.
2650 * @param testGroup The expected group of the tag.
2651 * @param testElement The expected Element of the tag.
2652 * @return On success returns the length associated to the tag. On failure
2655 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2657 long positionOnEntry = Fp->tellg();
2658 (void)positionOnEntry;
2660 if ( !ReadTag(testGroup, testElement) )
2665 //// Then read the associated Item Length
2666 long currentPosition = Fp->tellg();
2667 uint32_t itemLength = ReadInt32();
2669 gdcmVerboseMacro( "Basic Item Length is: "
2670 << itemLength << std::endl
2671 << " at address: " << (unsigned int)currentPosition);
2677 * \brief When parsing the Pixel Data of an encapsulated file, read
2678 * the basic offset table (when present, and BTW dump it).
2680 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2682 //// Read the Basic Offset Table Item Tag length...
2683 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2685 // When present, read the basic offset table itself.
2686 // Notes: - since the presence of this basic offset table is optional
2687 // we can't rely on it for the implementation, and we will simply
2688 // trash it's content (when present).
2689 // - still, when present, we could add some further checks on the
2690 // lengths, but we won't bother with such fuses for the time being.
2691 if ( itemLength != 0 )
2693 char *basicOffsetTableItemValue = new char[itemLength + 1];
2694 Fp->read(basicOffsetTableItemValue, itemLength);
2697 for (unsigned int i=0; i < itemLength; i += 4 )
2699 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2701 gdcmVerboseMacro( "Read one length: " <<
2702 std::hex << individualLength );
2706 delete[] basicOffsetTableItemValue;
2711 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2712 * Compute the RLE extra information and store it in \ref RLEInfo
2713 * for later pixel retrieval usage.
2715 void Document::ComputeRLEInfo()
2717 TransferSyntaxType ts = GetTransferSyntax();
2718 if ( ts != RLELossless )
2723 // Encoded pixel data: for the time being we are only concerned with
2724 // Jpeg or RLE Pixel data encodings.
2725 // As stated in PS 3.5-2003, section 8.2 p44:
2726 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2727 // value representation OB is used".
2728 // Hence we expect an OB value representation. Concerning OB VR,
2729 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2730 // "For the Value Representations OB and OW, the encoding shall meet the
2731 // following specifications depending on the Data element tag:"
2733 // - the first item in the sequence of items before the encoded pixel
2734 // data stream shall be basic offset table item. The basic offset table
2735 // item value, however, is not required to be present"
2737 ReadAndSkipEncapsulatedBasicOffsetTable();
2739 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2740 // Loop on the individual frame[s] and store the information
2741 // on the RLE fragments in a RLEFramesInfo.
2742 // Note: - when only a single frame is present, this is a
2744 // - when more than one frame are present, then we are in
2745 // the case of a multi-frame image.
2747 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2749 // Parse the RLE Header and store the corresponding RLE Segment
2750 // Offset Table information on fragments of this current Frame.
2751 // Note that the fragment pixels themselves are not loaded
2752 // (but just skipped).
2753 long frameOffset = Fp->tellg();
2755 uint32_t nbRleSegments = ReadInt32();
2756 if ( nbRleSegments > 16 )
2758 // There should be at most 15 segments (refer to RLEFrame class)
2759 gdcmVerboseMacro( "Too many segments.");
2762 uint32_t rleSegmentOffsetTable[16];
2763 for( int k = 1; k <= 15; k++ )
2765 rleSegmentOffsetTable[k] = ReadInt32();
2768 // Deduce from both the RLE Header and the frameLength the
2769 // fragment length, and again store this info in a
2771 long rleSegmentLength[15];
2772 // skipping (not reading) RLE Segments
2773 if ( nbRleSegments > 1)
2775 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2777 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2778 - rleSegmentOffsetTable[k];
2779 SkipBytes(rleSegmentLength[k]);
2783 rleSegmentLength[nbRleSegments] = frameLength
2784 - rleSegmentOffsetTable[nbRleSegments];
2785 SkipBytes(rleSegmentLength[nbRleSegments]);
2787 // Store the collected info
2788 RLEFrame *newFrameInfo = new RLEFrame;
2789 newFrameInfo->NumberFragments = nbRleSegments;
2790 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2792 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2793 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2795 RLEInfo->Frames.push_back( newFrameInfo );
2798 // Make sure that at the end of the item we encounter a 'Sequence
2800 if ( !ReadTag(0xfffe, 0xe0dd) )
2802 gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2807 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2808 * Compute the jpeg extra information (fragment[s] offset[s] and
2809 * length) and store it[them] in \ref JPEGInfo for later pixel
2812 void Document::ComputeJPEGFragmentInfo()
2814 // If you need to, look for comments of ComputeRLEInfo().
2820 ReadAndSkipEncapsulatedBasicOffsetTable();
2822 // Loop on the fragments[s] and store the parsed information in a
2824 long fragmentLength;
2825 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2827 long fragmentOffset = Fp->tellg();
2829 // Store the collected info
2830 JPEGFragment *newFragment = new JPEGFragment;
2831 newFragment->Offset = fragmentOffset;
2832 newFragment->Length = fragmentLength;
2833 JPEGInfo->Fragments.push_back( newFragment );
2835 SkipBytes( fragmentLength );
2838 // Make sure that at the end of the item we encounter a 'Sequence
2840 if ( !ReadTag(0xfffe, 0xe0dd) )
2842 gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2847 * \brief Walk recursively the given \ref DocEntrySet, and feed
2848 * the given hash table (\ref TagDocEntryHT) with all the
2849 * \ref DocEntry (Dicom entries) encountered.
2850 * This method does the job for \ref BuildFlatHashTable.
2851 * @param builtHT Where to collect all the \ref DocEntry encountered
2852 * when recursively walking the given set.
2853 * @param set The structure to be traversed (recursively).
2855 void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2858 if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2860 TagDocEntryHT const ¤tHT = elementSet->GetTagHT();
2861 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2862 i != currentHT.end();
2865 DocEntry *entry = i->second;
2866 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2868 const ListSQItem& items = seqEntry->GetSQItems();
2869 for( ListSQItem::const_iterator item = items.begin();
2870 item != items.end();
2873 BuildFlatHashTableRecurse( builtHT, *item );
2877 builtHT[entry->GetKey()] = entry;
2882 if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2884 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2885 for (ListDocEntry::const_iterator i = currentList.begin();
2886 i != currentList.end();
2889 DocEntry *entry = *i;
2890 if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2892 const ListSQItem& items = seqEntry->GetSQItems();
2893 for( ListSQItem::const_iterator item = items.begin();
2894 item != items.end();
2897 BuildFlatHashTableRecurse( builtHT, *item );
2901 builtHT[entry->GetKey()] = entry;
2908 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2911 * The structure used by a Document (through \ref ElementSet),
2912 * in order to hold the parsed entries of a Dicom header, is a recursive
2913 * one. This is due to the fact that the sequences (when present)
2914 * can be nested. Additionaly, the sequence items (represented in
2915 * gdcm as \ref SQItem) add an extra complexity to the data
2916 * structure. Hence, a gdcm user whishing to visit all the entries of
2917 * a Dicom header will need to dig in the gdcm internals (which
2918 * implies exposing all the internal data structures to the API).
2919 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2920 * recursively builds a temporary hash table, which holds all the
2921 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2923 * \warning Of course there is NO integrity constrain between the
2924 * returned \ref TagDocEntryHT and the \ref ElementSet used
2925 * to build it. Hence if the underlying \ref ElementSet is
2926 * altered, then it is the caller responsability to invoke
2927 * \ref BuildFlatHashTable again...
2928 * @return The flat std::map<> we juste build.
2930 TagDocEntryHT *Document::BuildFlatHashTable()
2932 TagDocEntryHT *FlatHT = new TagDocEntryHT;
2933 BuildFlatHashTableRecurse( *FlatHT, this );
2940 * \brief Compares two documents, according to \ref DicomDir rules
2941 * \warning Does NOT work with ACR-NEMA files
2942 * \todo Find a trick to solve the pb (use RET fields ?)
2944 * @return true if 'smaller'
2946 bool Document::operator<(Document &document)
2949 std::string s1 = GetEntry(0x0010,0x0010);
2950 std::string s2 = document.GetEntry(0x0010,0x0010);
2962 s1 = GetEntry(0x0010,0x0020);
2963 s2 = document.GetEntry(0x0010,0x0020);
2974 // Study Instance UID
2975 s1 = GetEntry(0x0020,0x000d);
2976 s2 = document.GetEntry(0x0020,0x000d);
2987 // Serie Instance UID
2988 s1 = GetEntry(0x0020,0x000e);
2989 s2 = document.GetEntry(0x0020,0x000e);
3006 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
3007 * @param filetype Type of the File to be written
3009 int Document::ComputeGroup0002Length( FileType filetype )
3014 int groupLength = 0;
3015 bool found0002 = false;
3017 // for each zero-level Tag in the DCM Header
3021 entry = GetNextEntry();
3024 gr = entry->GetGroup();
3030 el = entry->GetElement();
3031 vr = entry->GetVR();
3033 if (filetype == ExplicitVR)
3035 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
3037 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
3040 groupLength += 2 + 2 + 4 + entry->GetLength();
3042 else if (found0002 )
3045 entry = GetNextEntry();
3050 } // end namespace gdcm
3052 //-----------------------------------------------------------------------------