1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/12/07 13:39:33 $
7 Version: $Revision: 1.149 $
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 Little Endian DLX G.E?
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 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
111 Fp->seekg( 0, std::ios::beg);
113 Fp->seekg(0, std::ios::end);
114 long lgt = Fp->tellg();
116 Fp->seekg( 0, std::ios::beg);
118 long beg = Fp->tellg();
121 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
123 Fp->seekg( 0, std::ios::beg);
125 // Load 'non string' values
127 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
128 if( PhotometricInterpretation == "PALETTE COLOR " )
130 LoadEntryBinArea(0x0028,0x1200); // gray LUT
131 /// FIXME FIXME FIXME
132 /// The tags refered by the three following lines used to be CORRECTLY
133 /// defined as having an US Value Representation in the public
134 /// dictionnary. BUT the semantics implied by the three following
135 /// lines state that the corresponding tag contents are in fact
136 /// the ones of a BinEntry.
137 /// In order to fix things "Quick and Dirty" the dictionnary was
138 /// altered on PURPOUS but now contains a WRONG value.
139 /// In order to fix things and restore the dictionary to its
140 /// correct value, one needs to decided of the semantics by deciding
141 /// wether the following tags are either:
142 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
143 /// also used as BinEntry, which requires the proper conversion,
144 /// - OW, and hence loaded as BinEntry, but afterwards also used
145 /// as ValEntry, which requires the proper conversion.
146 LoadEntryBinArea(0x0028,0x1201); // R LUT
147 LoadEntryBinArea(0x0028,0x1202); // G LUT
148 LoadEntryBinArea(0x0028,0x1203); // B LUT
150 // Segmented Red Palette Color LUT Data
151 LoadEntryBinArea(0x0028,0x1221);
152 // Segmented Green Palette Color LUT Data
153 LoadEntryBinArea(0x0028,0x1222);
154 // Segmented Blue Palette Color LUT Data
155 LoadEntryBinArea(0x0028,0x1223);
157 //FIXME later : how to use it?
158 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
162 // --------------------------------------------------------------
163 // Specific code to allow gdcm to read ACR-LibIDO formated images
164 // Note: ACR-LibIDO is an extension of the ACR standard that was
165 // used at CREATIS. For the time being (say a couple years)
166 // we keep this kludge to allow a smooth move to gdcm for
167 // CREATIS developpers (sorry folks).
169 // if recognition code tells us we deal with a LibIDO image
170 // we switch lineNumber and columnNumber
173 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
174 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
175 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
176 // with "little-endian strings"
178 Filetype = ACR_LIBIDO;
179 std::string rows = GetEntryByNumber(0x0028, 0x0010);
180 std::string columns = GetEntryByNumber(0x0028, 0x0011);
181 SetEntryByNumber(columns, 0x0028, 0x0010);
182 SetEntryByNumber(rows , 0x0028, 0x0011);
184 // ----------------- End of ACR-LibIDO kludge ------------------
186 PrintLevel = 1; // 'Medium' print level by default
190 * \brief This default constructor doesn't parse the file. You should
191 * then invoke \ref Document::SetFileName and then the parsing.
193 Document::Document() : ElementSet(-1)
197 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
200 Filetype = ExplicitVR;
201 PrintLevel = 1; // 'Medium' print level by default
205 * \brief Canonical destructor.
207 Document::~Document ()
216 //-----------------------------------------------------------------------------
220 * \brief Prints The Dict Entries of THE public Dicom Dictionary
223 void Document::PrintPubDict(std::ostream & os)
225 RefPubDict->Print(os);
229 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
232 void Document::PrintShaDict(std::ostream & os)
234 RefShaDict->Print(os);
237 //-----------------------------------------------------------------------------
240 * \brief Get the public dictionary used
242 Dict* Document::GetPubDict()
248 * \brief Get the shadow dictionary used
250 Dict* Document::GetShaDict()
256 * \brief Set the shadow dictionary used
257 * \param dict dictionary to use in shadow
259 bool Document::SetShaDict(Dict *dict)
266 * \brief Set the shadow dictionary used
267 * \param dictName name of the dictionary to use in shadow
269 bool Document::SetShaDict(DictKey const & dictName)
271 RefShaDict = Global::GetDicts()->GetDict(dictName);
276 * \brief This predicate, based on hopefully reasonable heuristics,
277 * decides whether or not the current Document was properly parsed
278 * and contains the mandatory information for being considered as
279 * a well formed and usable Dicom/Acr File.
280 * @return true when Document is the one of a reasonable Dicom/Acr file,
283 bool Document::IsReadable()
285 if( Filetype == Unknown)
287 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
293 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
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 = GetDocEntryByNumber(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 Transfert 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 GetDocEntryByNumber(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()
421 if (Filename.length() == 0)
429 "Document::OpenFile is already opened when opening: ",
433 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
437 "Document::OpenFile cannot open file: ",
445 Fp->read((char*)&zero, (size_t)2);
452 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
454 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
455 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
456 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
457 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
463 Fp->seekg(126L, std::ios::cur);
465 Fp->read(dicm, (size_t)4);
471 if( memcmp(dicm, "DICM", 4) == 0 )
478 "Document::OpenFile not DICOM/ACR (missing preamble)",
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 Header 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::ReplaceOrCreateByNumber(
549 std::string const & value,
554 ValEntry* valEntry = 0;
555 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
559 // check if (group,element) DictEntry exists
560 // if it doesn't, create an entry in DictSet::VirtualEntry
563 // Find out if the tag we received is in the dictionaries:
564 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
565 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
568 currentEntry = NewDocEntryByNumber(group, elem, vr);
572 currentEntry = NewDocEntryByNumber(group, elem);
577 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
578 " NewDocEntryByNumber failed.");
582 valEntry = new ValEntry(currentEntry);
585 if ( !AddEntry(valEntry))
588 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
589 " failed allthough this is a creation.");
595 valEntry = dynamic_cast< ValEntry* >(currentEntry);
596 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
597 // then we change it to a ValEntry ?
598 // Shouldn't it be considered as an error ?
600 // We need to promote the DocEntry to a ValEntry:
601 valEntry = new ValEntry(currentEntry);
602 if (!RemoveEntry(currentEntry))
605 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
606 " of previous DocEntry failed.");
609 if ( !AddEntry(valEntry))
612 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
613 " promoted ValEntry failed.");
619 SetEntryByNumber(value, group, elem);
625 * \brief Modifies the value of a given Header Entry (Dicom Element)
626 * when it exists. Create it with the given value when unexistant.
627 * A copy of the binArea is made to be kept in the Document.
628 * @param binArea (binary) value to be set
629 * @param Group Group number of the Entry
630 * @param Elem Element number of the Entry
631 * \return pointer to the modified/created Header Entry (NULL when creation
634 BinEntry* Document::ReplaceOrCreateByNumber(
641 BinEntry* binEntry = 0;
642 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
646 // check if (group,element) DictEntry exists
647 // if it doesn't, create an entry in DictSet::VirtualEntry
650 // Find out if the tag we received is in the dictionaries:
651 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
652 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
656 currentEntry = NewDocEntryByNumber(group, elem, vr);
660 currentEntry = NewDocEntryByNumber(group, elem);
664 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
665 " NewDocEntryByNumber failed.");
668 binEntry = new BinEntry(currentEntry);
669 if ( !AddEntry(binEntry))
671 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
672 " failed allthough this is a creation.");
678 binEntry = dynamic_cast< BinEntry* >(currentEntry);
679 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
680 // then we change it to a BinEntry ?
681 // Shouldn't it be considered as an error ?
683 // We need to promote the DocEntry to a BinEntry:
684 binEntry = new BinEntry(currentEntry);
685 if (!RemoveEntry(currentEntry))
687 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
688 " of previous DocEntry failed.");
691 if ( !AddEntry(binEntry))
693 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
694 " promoted BinEntry failed.");
701 if (lgth>0 && binArea)
703 tmpArea = new uint8_t[lgth];
704 memcpy(tmpArea,binArea,lgth);
710 if (!SetEntryByNumber(tmpArea, lgth, group, elem))
723 * \brief Modifies the value of a given Header Entry (Dicom Element)
724 * when it exists. Create it when unexistant.
725 * @param Group Group number of the Entry
726 * @param Elem Element number of the Entry
727 * \return pointer to the modified/created SeqEntry (NULL when creation
730 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
733 DocEntry* a = GetDocEntryByNumber( group, elem);
736 a = NewSeqEntryByNumber(group, elem);
742 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
749 * \brief Set a new value if the invoked element exists
750 * Seems to be useless !!!
751 * @param value new element value
752 * @param group group number of the Entry
753 * @param elem element number of the Entry
756 bool Document::ReplaceIfExistByNumber(std::string const & value,
757 uint16_t group, uint16_t elem )
759 SetEntryByNumber(value, group, elem);
764 std::string Document::GetTransferSyntaxValue(TransferSyntaxType type)
766 return TransferSyntaxStrings[type];
769 //-----------------------------------------------------------------------------
773 * \brief Checks if a given Dicom Element exists within the H table
774 * @param group Group number of the searched Dicom Element
775 * @param element Element number of the searched Dicom Element
776 * @return true is found
778 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
780 const std::string &key = DictEntry::TranslateToKey(group, element );
781 return TagHT.count(key) != 0;
785 * \brief Searches within Header Entries (Dicom Elements) parsed with
786 * the public and private dictionaries
787 * for the element value of a given tag.
788 * \warning Don't use any longer : use GetPubEntryByName
789 * @param tagName name of the searched element.
790 * @return Corresponding element value when it exists,
791 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
793 std::string Document::GetEntryByName(TagName const & tagName)
795 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
801 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
805 * \brief Searches within Header Entries (Dicom Elements) parsed with
806 * the public and private dictionaries
807 * for the element value representation of a given tag.
809 * Obtaining the VR (Value Representation) might be needed by caller
810 * to convert the string typed content to caller's native type
811 * (think of C++ vs Python). The VR is actually of a higher level
812 * of semantics than just the native C++ type.
813 * @param tagName name of the searched element.
814 * @return Corresponding element value representation when it exists,
815 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
817 std::string Document::GetEntryVRByName(TagName const& tagName)
819 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
820 if( dictEntry == NULL)
825 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
826 dictEntry->GetElement());
827 return elem->GetVR();
831 * \brief Searches within Header Entries (Dicom Elements) parsed with
832 * the public and private dictionaries
833 * for the element value representation of a given tag.
834 * @param group Group number of the searched tag.
835 * @param element Element number of the searched tag.
836 * @return Corresponding element value representation when it exists,
837 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
839 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
841 TagKey key = DictEntry::TranslateToKey(group, element);
842 if ( !TagHT.count(key))
847 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
851 * \brief Searches within Header Entries (Dicom Elements) parsed with
852 * the public and private dictionaries
853 * for the element value representation of a given tag..
855 * Obtaining the VR (Value Representation) might be needed by caller
856 * to convert the string typed content to caller's native type
857 * (think of C++ vs Python). The VR is actually of a higher level
858 * of semantics than just the native C++ type.
859 * @param group Group number of the searched tag.
860 * @param element Element number of the searched tag.
861 * @return Corresponding element value representation when it exists,
862 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
864 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
866 DocEntry* elem = GetDocEntryByNumber(group, element);
871 return elem->GetVR();
875 * \brief Searches within Header Entries (Dicom Elements) parsed with
876 * the public and private dictionaries
877 * for the value length of a given tag..
878 * @param group Group number of the searched tag.
879 * @param element Element number of the searched tag.
880 * @return Corresponding element length; -2 if not found
882 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
884 DocEntry* elem = GetDocEntryByNumber(group, element);
887 return -2; //magic number
889 return elem->GetLength();
892 * \brief Sets the value (string) of the Header Entry (Dicom Element)
893 * @param content string value of the Dicom Element
894 * @param tagName name of the searched Dicom Element.
895 * @return true when found
897 bool Document::SetEntryByName( std::string const & content,
898 TagName const & tagName)
900 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
906 return SetEntryByNumber(content,dictEntry->GetGroup(),
907 dictEntry->GetElement());
911 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
912 * through it's (group, element) and modifies it's content with
914 * @param content new value (string) to substitute with
915 * @param group group number of the Dicom Element to modify
916 * @param element element number of the Dicom Element to modify
918 bool Document::SetEntryByNumber(std::string const& content,
919 uint16_t group, uint16_t element)
921 ValEntry* valEntry = GetValEntryByNumber(group, element);
924 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
925 " ValEntry (try promotion first).");
928 // Non even content must be padded with a space (020H)...
929 valEntry->SetValue(content);
934 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
935 * through it's (group, element) and modifies it's content with
937 * @param content new value (void* -> uint8_t*) to substitute with
938 * @param lgth new value length
939 * @param group group number of the Dicom Element to modify
940 * @param element element number of the Dicom Element to modify
942 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
943 uint16_t group, uint16_t element)
945 (void)lgth; //not used
946 TagKey key = DictEntry::TranslateToKey(group, element);
947 if ( !TagHT.count(key))
952 /* Hope Binary field length is *never* wrong
953 if(lgth%2) // Non even length are padded with a space (020H).
956 //content = content + '\0'; // fing a trick to enlarge a binary field?
959 BinEntry* entry = (BinEntry *)TagHT[key];
960 entry->SetBinArea(content);
961 entry->SetLength(lgth);
962 entry->SetValue(GDCM_BINLOADED);
968 * \brief Gets (from Header) a 'non string' element value
969 * (LoadElementValues has already be executed)
970 * @param group group number of the Entry
971 * @param elem element number of the Entry
972 * @return Pointer to the 'non string' area
974 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
976 DocEntry* entry = GetDocEntryByNumber(group, elem);
979 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
982 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
984 return binEntry->GetBinArea();
991 * \brief Loads (from disk) the element content
992 * when a string is not suitable
993 * @param group group number of the Entry
994 * @param elem element number of the Entry
996 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
998 // Search the corresponding DocEntry
999 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1003 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1007 LoadEntryBinArea(binElement);
1011 * \brief Loads (from disk) the element content
1012 * when a string is not suitable
1013 * @param element Entry whose binArea is going to be loaded
1015 void Document::LoadEntryBinArea(BinEntry* element)
1017 if(element->GetBinArea())
1020 bool openFile = !Fp;
1024 size_t o =(size_t)element->GetOffset();
1025 Fp->seekg(o, std::ios::beg);
1027 size_t l = element->GetLength();
1028 uint8_t* a = new uint8_t[l];
1031 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1035 /// \todo check the result
1036 Fp->read((char*)a, l);
1037 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1043 element->SetBinArea(a);
1050 * \brief Sets a 'non string' value to a given Dicom Element
1051 * @param area area containing the 'non string' value
1052 * @param group Group number of the searched Dicom Element
1053 * @param element Element number of the searched Dicom Element
1056 /*bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1057 uint16_t group, uint16_t element)
1059 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1060 if ( !currentEntry )
1065 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1067 binEntry->SetBinArea( area );
1075 * \brief Update the entries with the shadow dictionary.
1076 * Only non even entries are analyzed
1078 void Document::UpdateShaEntries()
1083 /// \todo TODO : still any use to explore recursively the whole structure?
1085 for(ListTag::iterator it=listEntries.begin();
1086 it!=listEntries.end();
1089 // Odd group => from public dictionary
1090 if((*it)->GetGroup()%2==0)
1093 // Peer group => search the corresponding dict entry
1095 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1099 if((*it)->IsImplicitVR())
1104 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1106 // Set the new entry and the new value
1107 (*it)->SetDictEntry(entry);
1108 CheckDocEntryVR(*it,vr);
1110 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1115 // Remove precedent value transformation
1116 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1123 * \brief Searches within the Header Entries for a Dicom Element of
1125 * @param tagName name of the searched Dicom Element.
1126 * @return Corresponding Dicom Element when it exists, and NULL
1129 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1131 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1137 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1141 * \brief retrieves a Dicom Element (the first one) using (group, element)
1142 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1143 * if you think it's NOT UNIQUE, check the count number
1144 * and use iterators to retrieve ALL the Dicoms Elements within
1145 * a given couple (group, element)
1146 * @param group Group number of the searched Dicom Element
1147 * @param element Element number of the searched Dicom Element
1150 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1152 TagKey key = DictEntry::TranslateToKey(group, element);
1153 if ( !TagHT.count(key))
1157 return TagHT.find(key)->second;
1161 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1162 * returns a result when the corresponding entry is of type
1164 * @return When present, the corresponding ValEntry.
1166 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1168 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1169 if ( !currentEntry )
1173 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1177 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1183 * \brief Loads the element while preserving the current
1184 * underlying file position indicator as opposed to
1185 * to LoadDocEntry that modifies it.
1186 * @param entry Header Entry whose value shall be loaded.
1189 void Document::LoadDocEntrySafe(DocEntry * entry)
1193 long PositionOnEntry = Fp->tellg();
1194 LoadDocEntry(entry);
1195 Fp->seekg(PositionOnEntry, std::ios::beg);
1200 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1202 * @return The properly swaped 32 bits integer.
1204 uint32_t Document::SwapLong(uint32_t a)
1211 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1212 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1216 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1220 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1223 //std::cout << "swapCode= " << SwapCode << std::endl;
1224 dbg.Error(" Document::SwapLong : unset swap code");
1231 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1233 * @return The properly unswaped 32 bits integer.
1235 uint32_t Document::UnswapLong(uint32_t a)
1241 * \brief Swaps the bytes so they agree with the processor order
1242 * @return The properly swaped 16 bits integer.
1244 uint16_t Document::SwapShort(uint16_t a)
1246 if ( SwapCode == 4321 || SwapCode == 2143 )
1248 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1254 * \brief Unswaps the bytes so they agree with the processor order
1255 * @return The properly unswaped 16 bits integer.
1257 uint16_t Document::UnswapShort(uint16_t a)
1259 return SwapShort(a);
1262 //-----------------------------------------------------------------------------
1266 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1267 * @return length of the parsed set.
1269 void Document::ParseDES(DocEntrySet *set, long offset,
1270 long l_max, bool delim_mode)
1272 DocEntry *newDocEntry = 0;
1276 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1280 newDocEntry = ReadNextDocEntry( );
1286 VRKey vr = newDocEntry->GetVR();
1290 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1292 /////////////////////// ValEntry
1293 ValEntry* newValEntry =
1294 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1295 newValEntry->Copy( newDocEntry );
1297 // When "set" is a Document, then we are at the top of the
1298 // hierarchy and the Key is simply of the form ( group, elem )...
1299 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1302 newValEntry->SetKey( newValEntry->GetKey() );
1304 // ...but when "set" is a SQItem, we are inserting this new
1305 // valEntry in a sequence item. Hence the key has the
1306 // generalized form (refer to \ref BaseTagKey):
1307 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1309 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1310 + newValEntry->GetKey() );
1313 LoadDocEntry( newValEntry );
1314 bool delimitor=newValEntry->IsItemDelimitor();
1315 if( !set->AddEntry( newValEntry ) )
1317 // If here expect big troubles
1318 delete newValEntry; //otherwise mem leak
1326 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1334 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1336 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1337 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1338 "nor BinEntry. Probably unknown VR.");
1341 //////////////////// BinEntry or UNKOWN VR:
1342 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1344 // When "this" is a Document the Key is simply of the
1345 // form ( group, elem )...
1346 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1349 newBinEntry->SetKey( newBinEntry->GetKey() );
1351 // but when "this" is a SQItem, we are inserting this new
1352 // valEntry in a sequence item, and the kay has the
1353 // generalized form (refer to \ref BaseTagKey):
1354 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1356 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1357 + newBinEntry->GetKey() );
1360 LoadDocEntry( newBinEntry );
1361 if( !set->AddEntry( newBinEntry ) )
1363 //Expect big troubles if here
1368 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1369 && ( newDocEntry->GetElement() == 0x0010 ) )
1371 TransferSyntaxType ts = GetTransferSyntax();
1372 if ( ts == RLELossless )
1374 long PositionOnEntry = Fp->tellg();
1375 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1377 Fp->seekg( PositionOnEntry, std::ios::beg );
1379 else if ( IsJPEG() )
1381 long PositionOnEntry = Fp->tellg();
1382 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1383 ComputeJPEGFragmentInfo();
1384 Fp->seekg( PositionOnEntry, std::ios::beg );
1388 // Just to make sure we are at the beginning of next entry.
1389 SkipToNextDocEntry(newDocEntry);
1390 //delete newDocEntry;
1395 unsigned long l = newDocEntry->GetReadLength();
1396 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1398 if ( l == 0xffffffff )
1407 // no other way to create it ...
1408 SeqEntry* newSeqEntry =
1409 new SeqEntry( newDocEntry->GetDictEntry() );
1410 newSeqEntry->Copy( newDocEntry );
1411 newSeqEntry->SetDelimitorMode( delim_mode );
1413 // At the top of the hierarchy, stands a Document. When "set"
1414 // is a Document, then we are building the first depth level.
1415 // Hence the SeqEntry we are building simply has a depth
1417 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1420 newSeqEntry->SetDepthLevel( 1 );
1421 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1423 // But when "set" is allready a SQItem, we are building a nested
1424 // sequence, and hence the depth level of the new SeqEntry
1425 // we are building, is one level deeper:
1426 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1428 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1429 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1430 + newSeqEntry->GetKey() );
1434 { // Don't try to parse zero-length sequences
1435 ParseSQ( newSeqEntry,
1436 newDocEntry->GetOffset(),
1439 set->AddEntry( newSeqEntry );
1440 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1451 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1452 * @return parsed length for this level
1454 void Document::ParseSQ( SeqEntry* seqEntry,
1455 long offset, long l_max, bool delim_mode)
1457 int SQItemNumber = 0;
1462 DocEntry* newDocEntry = ReadNextDocEntry();
1465 // FIXME Should warn user
1470 if ( newDocEntry->IsSequenceDelimitor() )
1472 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1476 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1482 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1483 std::ostringstream newBase;
1484 newBase << seqEntry->GetKey()
1488 itemSQ->SetBaseTagKey( newBase.str() );
1489 unsigned int l = newDocEntry->GetReadLength();
1491 if ( l == 0xffffffff )
1500 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1503 seqEntry->AddEntry( itemSQ, SQItemNumber );
1505 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1513 * \brief Loads the element content if its length doesn't exceed
1514 * the value specified with Document::SetMaxSizeLoadEntry()
1515 * @param entry Header Entry (Dicom Element) to be dealt with
1517 void Document::LoadDocEntry(DocEntry* entry)
1519 uint16_t group = entry->GetGroup();
1520 std::string vr = entry->GetVR();
1521 uint32_t length = entry->GetLength();
1523 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1525 // A SeQuence "contains" a set of Elements.
1526 // (fffe e000) tells us an Element is beginning
1527 // (fffe e00d) tells us an Element just ended
1528 // (fffe e0dd) tells us the current SeQuence just ended
1529 if( group == 0xfffe )
1531 // NO more value field for SQ !
1535 // When the length is zero things are easy:
1538 ((ValEntry *)entry)->SetValue("");
1542 // The elements whose length is bigger than the specified upper bound
1543 // are not loaded. Instead we leave a short notice of the offset of
1544 // the element content and it's length.
1546 std::ostringstream s;
1547 if (length > MaxSizeLoadEntry)
1549 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1551 //s << "gdcm::NotLoaded (BinEntry)";
1552 s << GDCM_NOTLOADED;
1553 s << " Address:" << (long)entry->GetOffset();
1554 s << " Length:" << entry->GetLength();
1555 s << " x(" << std::hex << entry->GetLength() << ")";
1556 binEntryPtr->SetValue(s.str());
1558 // Be carefull : a BinEntry IS_A ValEntry ...
1559 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1561 // s << "gdcm::NotLoaded. (ValEntry)";
1562 s << GDCM_NOTLOADED;
1563 s << " Address:" << (long)entry->GetOffset();
1564 s << " Length:" << entry->GetLength();
1565 s << " x(" << std::hex << entry->GetLength() << ")";
1566 valEntryPtr->SetValue(s.str());
1571 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1572 << "nor a ValEntry ?! Should never print that !" << std::endl;
1575 // to be sure we are at the end of the value ...
1576 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1581 // When we find a BinEntry not very much can be done :
1582 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1584 s << GDCM_BINLOADED;
1585 binEntryPtr->SetValue(s.str());
1586 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1590 /// \todo Any compacter code suggested (?)
1591 if ( IsDocEntryAnInteger(entry) )
1595 // When short integer(s) are expected, read and convert the following
1596 // n *two characters properly i.e. consider them as short integers as
1597 // opposed to strings.
1598 // Elements with Value Multiplicity > 1
1599 // contain a set of integers (not a single one)
1600 if (vr == "US" || vr == "SS")
1603 NewInt = ReadInt16();
1607 for (int i=1; i < nbInt; i++)
1610 NewInt = ReadInt16();
1615 // See above comment on multiple integers (mutatis mutandis).
1616 else if (vr == "UL" || vr == "SL")
1619 NewInt = ReadInt32();
1623 for (int i=1; i < nbInt; i++)
1626 NewInt = ReadInt32();
1631 #ifdef GDCM_NO_ANSI_STRING_STREAM
1632 s << std::ends; // to avoid oddities on Solaris
1633 #endif //GDCM_NO_ANSI_STRING_STREAM
1635 ((ValEntry *)entry)->SetValue(s.str());
1639 // FIXME: We need an additional byte for storing \0 that is not on disk
1640 char *str = new char[length+1];
1641 Fp->read(str, (size_t)length);
1642 str[length] = '\0'; //this is only useful when length is odd
1643 // Special DicomString call to properly handle \0 and even length
1644 std::string newValue;
1647 newValue = Util::DicomString(str, length+1);
1648 //dbg.Verbose(0, "Warning: bad length: ", length );
1649 dbg.Verbose(0, "For string :", newValue.c_str());
1650 // Since we change the length of string update it length
1651 entry->SetReadLength(length+1);
1655 newValue = Util::DicomString(str, length);
1659 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1661 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1663 dbg.Verbose(1, "Document::LoadDocEntry",
1664 "unread element value");
1665 valEntry->SetValue(GDCM_UNREAD);
1671 // Because of correspondance with the VR dic
1672 valEntry->SetValue(newValue);
1676 valEntry->SetValue(newValue);
1681 dbg.Error(true, "Document::LoadDocEntry"
1682 "Should have a ValEntry, here !");
1688 * \brief Find the value Length of the passed Header Entry
1689 * @param entry Header Entry whose length of the value shall be loaded.
1691 void Document::FindDocEntryLength( DocEntry *entry )
1692 throw ( FormatError )
1694 uint16_t element = entry->GetElement();
1695 std::string vr = entry->GetVR();
1698 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1700 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1702 // The following reserved two bytes (see PS 3.5-2003, section
1703 // "7.1.2 Data element structure with explicit vr", p 27) must be
1704 // skipped before proceeding on reading the length on 4 bytes.
1705 Fp->seekg( 2L, std::ios::cur);
1706 uint32_t length32 = ReadInt32();
1708 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1713 /// \todo rename that to FindDocEntryLengthOBOrOW since
1714 /// the above test is on both OB and OW...
1715 lengthOB = FindDocEntryLengthOB();
1717 catch ( FormatUnexpected )
1719 // Computing the length failed (this happens with broken
1720 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1721 // chance to get the pixels by deciding the element goes
1722 // until the end of the file. Hence we artificially fix the
1723 // the length and proceed.
1724 long currentPosition = Fp->tellg();
1725 Fp->seekg(0L,std::ios::end);
1726 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1727 Fp->seekg(currentPosition, std::ios::beg);
1728 entry->SetLength(lengthUntilEOF);
1731 entry->SetLength(lengthOB);
1734 FixDocEntryFoundLength(entry, length32);
1738 // Length is encoded on 2 bytes.
1739 length16 = ReadInt16();
1741 // We can tell the current file is encoded in big endian (like
1742 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1743 // and it's value is the one of the encoding of a big endian file.
1744 // In order to deal with such big endian encoded files, we have
1745 // (at least) two strategies:
1746 // * when we load the "Transfer Syntax" tag with value of big endian
1747 // encoding, we raise the proper flags. Then we wait for the end
1748 // of the META group (0x0002) among which is "Transfer Syntax",
1749 // before switching the swap code to big endian. We have to postpone
1750 // the switching of the swap code since the META group is fully encoded
1751 // in little endian, and big endian coding only starts at the next
1752 // group. The corresponding code can be hard to analyse and adds
1753 // many additional unnecessary tests for regular tags.
1754 // * the second strategy consists in waiting for trouble, that shall
1755 // appear when we find the first group with big endian encoding. This
1756 // is easy to detect since the length of a "Group Length" tag (the
1757 // ones with zero as element number) has to be of 4 (0x0004). When we
1758 // encounter 1024 (0x0400) chances are the encoding changed and we
1759 // found a group with big endian encoding.
1760 // We shall use this second strategy. In order to make sure that we
1761 // can interpret the presence of an apparently big endian encoded
1762 // length of a "Group Length" without committing a big mistake, we
1763 // add an additional check: we look in the already parsed elements
1764 // for the presence of a "Transfer Syntax" whose value has to be "big
1765 // endian encoding". When this is the case, chances are we have got our
1766 // hands on a big endian encoded file: we switch the swap code to
1767 // big endian and proceed...
1768 if ( element == 0x0000 && length16 == 0x0400 )
1770 TransferSyntaxType ts = GetTransferSyntax();
1771 if ( ts != ExplicitVRBigEndian )
1773 throw FormatError( "Document::FindDocEntryLength()",
1774 " not explicit VR." );
1778 SwitchSwapToBigEndian();
1779 // Restore the unproperly loaded values i.e. the group, the element
1780 // and the dictionary entry depending on them.
1781 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1782 uint16_t correctElem = SwapShort( entry->GetElement() );
1783 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1787 // This correct tag is not in the dictionary. Create a new one.
1788 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1790 // FIXME this can create a memory leaks on the old entry that be
1791 // left unreferenced.
1792 entry->SetDictEntry( newTag );
1795 // Heuristic: well, some files are really ill-formed.
1796 if ( length16 == 0xffff)
1798 // 0xffff means that we deal with 'Unknown Length' Sequence
1801 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1806 // Either implicit VR or a non DICOM conformal (see note below) explicit
1807 // VR that ommited the VR of (at least) this element. Farts happen.
1808 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1809 // on Data elements "Implicit and Explicit VR Data Elements shall
1810 // not coexist in a Data Set and Data Sets nested within it".]
1811 // Length is on 4 bytes.
1813 FixDocEntryFoundLength( entry, ReadInt32() );
1819 * \brief Find the Value Representation of the current Dicom Element.
1822 void Document::FindDocEntryVR( DocEntry *entry )
1824 if ( Filetype != ExplicitVR )
1831 long positionOnEntry = Fp->tellg();
1832 // Warning: we believe this is explicit VR (Value Representation) because
1833 // we used a heuristic that found "UL" in the first tag. Alas this
1834 // doesn't guarantee that all the tags will be in explicit VR. In some
1835 // cases (see e-film filtered files) one finds implicit VR tags mixed
1836 // within an explicit VR file. Hence we make sure the present tag
1837 // is in explicit VR and try to fix things if it happens not to be
1839 Fp->read (vr, (size_t)2);
1842 if( !CheckDocEntryVR(entry, vr) )
1844 Fp->seekg(positionOnEntry, std::ios::beg);
1845 // When this element is known in the dictionary we shall use, e.g. for
1846 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1847 // dictionary entry. Still we have to flag the element as implicit since
1848 // we know now our assumption on expliciteness is not furfilled.
1850 if ( entry->IsVRUnknown() )
1852 entry->SetVR("Implicit");
1854 entry->SetImplicitVR();
1859 * \brief Check the correspondance between the VR of the header entry
1860 * and the taken VR. If they are different, the header entry is
1861 * updated with the new VR.
1862 * @param entry Header Entry to check
1863 * @param vr Dicom Value Representation
1864 * @return false if the VR is incorrect of if the VR isn't referenced
1865 * otherwise, it returns true
1867 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1870 bool realExplicit = true;
1872 // Assume we are reading a falsely explicit VR file i.e. we reached
1873 // a tag where we expect reading a VR but are in fact we read the
1874 // first to bytes of the length. Then we will interogate (through find)
1875 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1876 // both GCC and VC++ implementations of the STL map. Hence when the
1877 // expected VR read happens to be non-ascii characters we consider
1878 // we hit falsely explicit VR tag.
1880 if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1882 realExplicit = false;
1885 // CLEANME searching the dicom_vr at each occurence is expensive.
1886 // PostPone this test in an optional integrity check at the end
1887 // of parsing or only in debug mode.
1888 if ( realExplicit && !Global::GetVR()->Count(vr) )
1890 realExplicit = false;
1893 if ( !realExplicit )
1895 // We thought this was explicit VR, but we end up with an
1896 // implicit VR tag. Let's backtrack.
1897 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1898 entry->GetGroup(), entry->GetElement());
1899 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1901 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1903 // Group length is UL !
1904 DictEntry* newEntry = NewVirtualDictEntry(
1905 entry->GetGroup(), entry->GetElement(),
1906 "UL", "FIXME", "Group Length");
1907 entry->SetDictEntry( newEntry );
1912 if ( entry->IsVRUnknown() )
1914 // When not a dictionary entry, we can safely overwrite the VR.
1915 if( entry->GetElement() == 0x0000 )
1917 // Group length is UL !
1925 else if ( entry->GetVR() != vr )
1927 // The VR present in the file and the dictionary disagree. We assume
1928 // the file writer knew best and use the VR of the file. Since it would
1929 // be unwise to overwrite the VR of a dictionary (since it would
1930 // compromise it's next user), we need to clone the actual DictEntry
1931 // and change the VR for the read one.
1932 DictEntry* newEntry = NewVirtualDictEntry(
1933 entry->GetGroup(), entry->GetElement(),
1934 vr, "FIXME", entry->GetName());
1935 entry->SetDictEntry(newEntry);
1942 * \brief Get the transformed value of the header entry. The VR value
1943 * is used to define the transformation to operate on the value
1944 * \warning NOT end user intended method !
1945 * @param entry entry to tranform
1946 * @return Transformed entry value
1948 std::string Document::GetDocEntryValue(DocEntry *entry)
1950 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1952 std::string val = ((ValEntry *)entry)->GetValue();
1953 std::string vr = entry->GetVR();
1954 uint32_t length = entry->GetLength();
1955 std::ostringstream s;
1958 // When short integer(s) are expected, read and convert the following
1959 // n * 2 bytes properly i.e. as a multivaluated strings
1960 // (each single value is separated fromthe next one by '\'
1961 // as usual for standard multivaluated filels
1962 // Elements with Value Multiplicity > 1
1963 // contain a set of short integers (not a single one)
1965 if( vr == "US" || vr == "SS" )
1970 for (int i=0; i < nbInt; i++)
1976 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1977 newInt16 = SwapShort( newInt16 );
1982 // When integer(s) are expected, read and convert the following
1983 // n * 4 bytes properly i.e. as a multivaluated strings
1984 // (each single value is separated fromthe next one by '\'
1985 // as usual for standard multivaluated filels
1986 // Elements with Value Multiplicity > 1
1987 // contain a set of integers (not a single one)
1988 else if( vr == "UL" || vr == "SL" )
1993 for (int i=0; i < nbInt; i++)
1999 newInt32 = ( val[4*i+0] & 0xFF )
2000 + (( val[4*i+1] & 0xFF ) << 8 )
2001 + (( val[4*i+2] & 0xFF ) << 16 )
2002 + (( val[4*i+3] & 0xFF ) << 24 );
2003 newInt32 = SwapLong( newInt32 );
2007 #ifdef GDCM_NO_ANSI_STRING_STREAM
2008 s << std::ends; // to avoid oddities on Solaris
2009 #endif //GDCM_NO_ANSI_STRING_STREAM
2013 return ((ValEntry *)entry)->GetValue();
2017 * \brief Get the reverse transformed value of the header entry. The VR
2018 * value is used to define the reverse transformation to operate on
2020 * \warning NOT end user intended method !
2021 * @param entry Entry to reverse transform
2022 * @return Reverse transformed entry value
2024 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2026 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2028 std::string vr = entry->GetVR();
2029 std::vector<std::string> tokens;
2030 std::ostringstream s;
2032 if ( vr == "US" || vr == "SS" )
2036 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2037 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2038 for (unsigned int i=0; i<tokens.size(); i++)
2040 newInt16 = atoi(tokens[i].c_str());
2041 s << ( newInt16 & 0xFF )
2042 << (( newInt16 >> 8 ) & 0xFF );
2046 if ( vr == "UL" || vr == "SL")
2050 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2051 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2052 for (unsigned int i=0; i<tokens.size();i++)
2054 newInt32 = atoi(tokens[i].c_str());
2055 s << (char)( newInt32 & 0xFF )
2056 << (char)(( newInt32 >> 8 ) & 0xFF )
2057 << (char)(( newInt32 >> 16 ) & 0xFF )
2058 << (char)(( newInt32 >> 24 ) & 0xFF );
2063 #ifdef GDCM_NO_ANSI_STRING_STREAM
2064 s << std::ends; // to avoid oddities on Solaris
2065 #endif //GDCM_NO_ANSI_STRING_STREAM
2069 return ((ValEntry *)entry)->GetValue();
2073 * \brief Skip a given Header Entry
2074 * \warning NOT end user intended method !
2075 * @param entry entry to skip
2077 void Document::SkipDocEntry(DocEntry *entry)
2079 SkipBytes(entry->GetLength());
2083 * \brief Skips to the begining of the next Header Entry
2084 * \warning NOT end user intended method !
2085 * @param entry entry to skip
2087 void Document::SkipToNextDocEntry(DocEntry *entry)
2089 Fp->seekg((long)(entry->GetOffset()), std::ios::beg);
2090 Fp->seekg( (long)(entry->GetReadLength()), std::ios::cur);
2094 * \brief When the length of an element value is obviously wrong (because
2095 * the parser went Jabberwocky) one can hope improving things by
2096 * applying some heuristics.
2097 * @param entry entry to check
2098 * @param foundLength fist assumption about length
2100 void Document::FixDocEntryFoundLength(DocEntry *entry,
2101 uint32_t foundLength)
2103 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2104 if ( foundLength == 0xffffffff)
2109 uint16_t gr = entry->GetGroup();
2110 uint16_t el = entry->GetElement();
2112 if ( foundLength % 2)
2114 std::ostringstream s;
2115 s << "Warning : Tag with uneven length "
2117 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2118 dbg.Verbose(0, s.str().c_str());
2121 //////// Fix for some naughty General Electric images.
2122 // Allthough not recent many such GE corrupted images are still present
2123 // on Creatis hard disks. Hence this fix shall remain when such images
2124 // are no longer in user (we are talking a few years, here)...
2125 // Note: XMedCom probably uses such a trick since it is able to read
2126 // those pesky GE images ...
2127 if ( foundLength == 13)
2129 // Only happens for this length !
2130 if ( entry->GetGroup() != 0x0008
2131 || ( entry->GetElement() != 0x0070
2132 && entry->GetElement() != 0x0080 ) )
2135 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2139 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2140 // Occurence of such images is quite low (unless one leaves close to a
2141 // 'Leonardo' source. Hence, one might consider commenting out the
2142 // following fix on efficiency reasons.
2143 else if ( entry->GetGroup() == 0x0009
2144 && ( entry->GetElement() == 0x1113
2145 || entry->GetElement() == 0x1114 ) )
2148 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2151 else if ( entry->GetVR() == "SQ" )
2153 foundLength = 0; // ReadLength is unchanged
2156 //////// We encountered a 'delimiter' element i.e. a tag of the form
2157 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2158 // taken into account.
2159 else if( entry->GetGroup() == 0xfffe )
2161 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2162 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2163 // causes extra troubles...
2164 if( entry->GetElement() != 0x0000 )
2170 entry->SetUsableLength(foundLength);
2174 * \brief Apply some heuristics to predict whether the considered
2175 * element value contains/represents an integer or not.
2176 * @param entry The element value on which to apply the predicate.
2177 * @return The result of the heuristical predicate.
2179 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2181 uint16_t element = entry->GetElement();
2182 uint16_t group = entry->GetGroup();
2183 const std::string & vr = entry->GetVR();
2184 uint32_t length = entry->GetLength();
2186 // When we have some semantics on the element we just read, and if we
2187 // a priori know we are dealing with an integer, then we shall be
2188 // able to swap it's element value properly.
2189 if ( element == 0 ) // This is the group length of the group
2197 // Allthough this should never happen, still some images have a
2198 // corrupted group length [e.g. have a glance at offset x(8336) of
2199 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2200 // Since for dicom compliant and well behaved headers, the present
2201 // test is useless (and might even look a bit paranoid), when we
2202 // encounter such an ill-formed image, we simply display a warning
2203 // message and proceed on parsing (while crossing fingers).
2204 std::ostringstream s;
2205 long filePosition = Fp->tellg();
2206 s << "Erroneous Group Length element length on : (" \
2207 << std::hex << group << " , " << element
2208 << ") -before- position x(" << filePosition << ")"
2209 << "lgt : " << length;
2210 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2214 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2223 * \brief Find the Length till the next sequence delimiter
2224 * \warning NOT end user intended method !
2228 uint32_t Document::FindDocEntryLengthOB()
2229 throw( FormatUnexpected )
2231 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2232 long positionOnEntry = Fp->tellg();
2233 bool foundSequenceDelimiter = false;
2234 uint32_t totalLength = 0;
2236 while ( !foundSequenceDelimiter )
2242 group = ReadInt16();
2245 catch ( FormatError )
2247 throw FormatError("Document::FindDocEntryLengthOB()",
2248 " group or element not present.");
2251 // We have to decount the group and element we just read
2254 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2256 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2257 "tag nor a Sequence delimiter tag.");
2258 Fp->seekg(positionOnEntry, std::ios::beg);
2259 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2260 "Neither an Item tag nor a Sequence "
2264 if ( elem == 0xe0dd )
2266 foundSequenceDelimiter = true;
2269 uint32_t itemLength = ReadInt32();
2270 // We add 4 bytes since we just read the ItemLength with ReadInt32
2271 totalLength += itemLength + 4;
2272 SkipBytes(itemLength);
2274 if ( foundSequenceDelimiter )
2279 Fp->seekg( positionOnEntry, std::ios::beg);
2284 * \brief Reads a supposed to be 16 Bits integer
2285 * (swaps it depending on processor endianity)
2286 * @return read value
2288 uint16_t Document::ReadInt16()
2289 throw( FormatError )
2292 Fp->read ((char*)&g, (size_t)2);
2295 throw FormatError( "Document::ReadInt16()", " file error." );
2299 throw FormatError( "Document::ReadInt16()", "EOF." );
2306 * \brief Reads a supposed to be 32 Bits integer
2307 * (swaps it depending on processor endianity)
2308 * @return read value
2310 uint32_t Document::ReadInt32()
2311 throw( FormatError )
2314 Fp->read ((char*)&g, (size_t)4);
2317 throw FormatError( "Document::ReadInt32()", " file error." );
2321 throw FormatError( "Document::ReadInt32()", "EOF." );
2328 * \brief skips bytes inside the source file
2329 * \warning NOT end user intended method !
2332 void Document::SkipBytes(uint32_t nBytes)
2334 //FIXME don't dump the returned value
2335 Fp->seekg((long)nBytes, std::ios::cur);
2339 * \brief Loads all the needed Dictionaries
2340 * \warning NOT end user intended method !
2342 void Document::Initialise()
2344 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2346 RLEInfo = new RLEFramesInfo;
2347 JPEGInfo = new JPEGFragmentsInfo;
2352 * \brief Discover what the swap code is (among little endian, big endian,
2353 * bad little endian, bad big endian).
2355 * @return false when we are absolutely sure
2356 * it's neither ACR-NEMA nor DICOM
2357 * true when we hope ours assuptions are OK
2359 bool Document::CheckSwap()
2361 // The only guaranted way of finding the swap code is to find a
2362 // group tag since we know it's length has to be of four bytes i.e.
2363 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2364 // occurs when we can't find such group...
2366 uint32_t x = 4; // x : for ntohs
2367 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2373 // First, compare HostByteOrder and NetworkByteOrder in order to
2374 // determine if we shall need to swap bytes (i.e. the Endian type).
2375 if ( x == ntohs(x) )
2384 // The easiest case is the one of a DICOM header, since it possesses a
2385 // file preamble where it suffice to look for the string "DICM".
2388 char *entCur = deb + 128;
2389 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2391 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2393 // Next, determine the value representation (VR). Let's skip to the
2394 // first element (0002, 0000) and check there if we find "UL"
2395 // - or "OB" if the 1st one is (0002,0001) -,
2396 // in which case we (almost) know it is explicit VR.
2397 // WARNING: if it happens to be implicit VR then what we will read
2398 // is the length of the group. If this ascii representation of this
2399 // length happens to be "UL" then we shall believe it is explicit VR.
2400 // FIXME: in order to fix the above warning, we could read the next
2401 // element value (or a couple of elements values) in order to make
2402 // sure we are not commiting a big mistake.
2403 // We need to skip :
2404 // * the 128 bytes of File Preamble (often padded with zeroes),
2405 // * the 4 bytes of "DICM" string,
2406 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2407 // i.e. a total of 136 bytes.
2411 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2412 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2413 // *Implicit* VR. -and it is !-
2415 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2416 memcmp(entCur, "OB", (size_t)2) == 0 ||
2417 memcmp(entCur, "UI", (size_t)2) == 0 ||
2418 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2419 // when Write DCM *adds*
2421 // Use Document::dicom_vr to test all the possibilities
2422 // instead of just checking for UL, OB and UI !? group 0000
2424 Filetype = ExplicitVR;
2425 dbg.Verbose(1, "Document::CheckSwap:",
2426 "explicit Value Representation");
2430 Filetype = ImplicitVR;
2431 dbg.Verbose(1, "Document::CheckSwap:",
2432 "not an explicit Value Representation");
2438 dbg.Verbose(1, "Document::CheckSwap:",
2439 "HostByteOrder != NetworkByteOrder");
2444 dbg.Verbose(1, "Document::CheckSwap:",
2445 "HostByteOrder = NetworkByteOrder");
2448 // Position the file position indicator at first tag (i.e.
2449 // after the file preamble and the "DICM" string).
2450 Fp->seekg(0, std::ios::beg);
2451 Fp->seekg ( 132L, std::ios::beg);
2455 // Alas, this is not a DicomV3 file and whatever happens there is no file
2456 // preamble. We can reset the file position indicator to where the data
2457 // is (i.e. the beginning of the file).
2458 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2459 Fp->seekg(0, std::ios::beg);
2461 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2462 // By clean we mean that the length of the first tag is written down.
2463 // If this is the case and since the length of the first group HAS to be
2464 // four (bytes), then determining the proper swap code is straightforward.
2467 // We assume the array of char we are considering contains the binary
2468 // representation of a 32 bits integer. Hence the following dirty
2470 s32 = *((uint32_t *)(entCur));
2491 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2492 // It is time for despaired wild guesses.
2493 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2494 // i.e. the 'group length' element is not present :
2496 // check the supposed-to-be 'group number'
2497 // in ( 0x0001 .. 0x0008 )
2498 // to determine ' SwapCode' value .
2499 // Only 0 or 4321 will be possible
2500 // (no oportunity to check for the formerly well known
2501 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2502 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2503 // the file IS NOT ACR-NEMA nor DICOM V3
2504 // Find a trick to tell it the caller...
2506 s16 = *((uint16_t *)(deb));
2533 dbg.Verbose(0, "Document::CheckSwap:",
2534 "ACR/NEMA unfound swap info (Really hopeless !)");
2538 // Then the only info we have is the net2host one.
2550 * \brief Restore the unproperly loaded values i.e. the group, the element
2551 * and the dictionary entry depending on them.
2553 void Document::SwitchSwapToBigEndian()
2555 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2556 "Switching to BigEndian mode.");
2557 if ( SwapCode == 0 )
2561 else if ( SwapCode == 4321 )
2565 else if ( SwapCode == 3412 )
2569 else if ( SwapCode == 2143 )
2576 * \brief during parsing, Header Elements too long are not loaded in memory
2579 void Document::SetMaxSizeLoadEntry(long newSize)
2585 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2587 MaxSizeLoadEntry = 0xffffffff;
2590 MaxSizeLoadEntry = newSize;
2595 * \brief Header Elements too long will not be printed
2596 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2599 void Document::SetMaxSizePrintEntry(long newSize)
2601 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2606 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2608 MaxSizePrintEntry = 0xffffffff;
2611 MaxSizePrintEntry = newSize;
2617 * \brief Handle broken private tag from Philips NTSCAN
2618 * where the endianess is being switch to BigEndian for no
2622 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2624 // Endian reversion. Some files contain groups of tags with reversed endianess.
2625 static int reversedEndian = 0;
2626 // try to fix endian switching in the middle of headers
2627 if ((group == 0xfeff) && (elem == 0x00e0))
2629 // start endian swap mark for group found
2631 SwitchSwapToBigEndian();
2636 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2638 // end of reversed endian group
2640 SwitchSwapToBigEndian();
2646 * \brief Read the next tag but WITHOUT loading it's value
2647 * (read the 'Group Number', the 'Element Number',
2648 * gets the Dict Entry
2649 * gets the VR, gets the length, gets the offset value)
2650 * @return On succes the newly created DocEntry, NULL on failure.
2652 DocEntry* Document::ReadNextDocEntry()
2659 group = ReadInt16();
2662 catch ( FormatError e )
2664 // We reached the EOF (or an error occured) therefore
2665 // header parsing has to be considered as finished.
2670 HandleBrokenEndian(group, elem);
2671 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2672 FindDocEntryVR(newEntry);
2676 FindDocEntryLength(newEntry);
2678 catch ( FormatError e )
2686 newEntry->SetOffset(Fp->tellg());
2693 * \brief Generate a free TagKey i.e. a TagKey that is not present
2694 * in the TagHt dictionary.
2695 * @param group The generated tag must belong to this group.
2696 * @return The element of tag with given group which is fee.
2698 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2700 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2702 TagKey key = DictEntry::TranslateToKey(group, elem);
2703 if (TagHT.count(key) == 0)
2712 * \brief Assuming the internal file pointer \ref Document::Fp
2713 * is placed at the beginning of a tag check whether this
2714 * tag is (TestGroup, TestElement).
2715 * \warning On success the internal file pointer \ref Document::Fp
2716 * is modified to point after the tag.
2717 * On failure (i.e. when the tag wasn't the expected tag
2718 * (TestGroup, TestElement) the internal file pointer
2719 * \ref Document::Fp is restored to it's original position.
2720 * @param testGroup The expected group of the tag.
2721 * @param testElement The expected Element of the tag.
2722 * @return True on success, false otherwise.
2724 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2726 long positionOnEntry = Fp->tellg();
2727 long currentPosition = Fp->tellg(); // On debugging purposes
2729 //// Read the Item Tag group and element, and make
2730 // sure they are what we expected:
2731 uint16_t itemTagGroup;
2732 uint16_t itemTagElement;
2735 itemTagGroup = ReadInt16();
2736 itemTagElement = ReadInt16();
2738 catch ( FormatError e )
2740 //std::cerr << e << std::endl;
2743 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2745 std::ostringstream s;
2746 s << " We should have found tag (";
2747 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2748 s << " but instead we encountered tag (";
2749 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2751 s << " at address: " << (unsigned)currentPosition << std::endl;
2752 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2753 dbg.Verbose(0, s.str().c_str());
2754 Fp->seekg(positionOnEntry, std::ios::beg);
2762 * \brief Assuming the internal file pointer \ref Document::Fp
2763 * is placed at the beginning of a tag (TestGroup, TestElement),
2764 * read the length associated to the Tag.
2765 * \warning On success the internal file pointer \ref Document::Fp
2766 * is modified to point after the tag and it's length.
2767 * On failure (i.e. when the tag wasn't the expected tag
2768 * (TestGroup, TestElement) the internal file pointer
2769 * \ref Document::Fp is restored to it's original position.
2770 * @param testGroup The expected group of the tag.
2771 * @param testElement The expected Element of the tag.
2772 * @return On success returns the length associated to the tag. On failure
2775 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2777 long positionOnEntry = Fp->tellg();
2778 (void)positionOnEntry;
2780 if ( !ReadTag(testGroup, testElement) )
2785 //// Then read the associated Item Length
2786 long currentPosition = Fp->tellg();
2787 uint32_t itemLength = ReadInt32();
2789 std::ostringstream s;
2790 s << "Basic Item Length is: "
2791 << itemLength << std::endl;
2792 s << " at address: " << (unsigned)currentPosition << std::endl;
2793 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2799 * \brief When parsing the Pixel Data of an encapsulated file, read
2800 * the basic offset table (when present, and BTW dump it).
2802 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2804 //// Read the Basic Offset Table Item Tag length...
2805 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2807 // When present, read the basic offset table itself.
2808 // Notes: - since the presence of this basic offset table is optional
2809 // we can't rely on it for the implementation, and we will simply
2810 // trash it's content (when present).
2811 // - still, when present, we could add some further checks on the
2812 // lengths, but we won't bother with such fuses for the time being.
2813 if ( itemLength != 0 )
2815 char* basicOffsetTableItemValue = new char[itemLength + 1];
2816 Fp->read(basicOffsetTableItemValue, itemLength);
2819 for (unsigned int i=0; i < itemLength; i += 4 )
2821 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2823 std::ostringstream s;
2824 s << " Read one length: ";
2825 s << std::hex << individualLength << std::endl;
2827 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2832 delete[] basicOffsetTableItemValue;
2837 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2838 * Compute the RLE extra information and store it in \ref RLEInfo
2839 * for later pixel retrieval usage.
2841 void Document::ComputeRLEInfo()
2843 TransferSyntaxType ts = GetTransferSyntax();
2844 if ( ts != RLELossless )
2849 // Encoded pixel data: for the time being we are only concerned with
2850 // Jpeg or RLE Pixel data encodings.
2851 // As stated in PS 3.5-2003, section 8.2 p44:
2852 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2853 // value representation OB is used".
2854 // Hence we expect an OB value representation. Concerning OB VR,
2855 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2856 // "For the Value Representations OB and OW, the encoding shall meet the
2857 // following specifications depending on the Data element tag:"
2859 // - the first item in the sequence of items before the encoded pixel
2860 // data stream shall be basic offset table item. The basic offset table
2861 // item value, however, is not required to be present"
2863 ReadAndSkipEncapsulatedBasicOffsetTable();
2865 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2866 // Loop on the individual frame[s] and store the information
2867 // on the RLE fragments in a RLEFramesInfo.
2868 // Note: - when only a single frame is present, this is a
2870 // - when more than one frame are present, then we are in
2871 // the case of a multi-frame image.
2873 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2875 // Parse the RLE Header and store the corresponding RLE Segment
2876 // Offset Table information on fragments of this current Frame.
2877 // Note that the fragment pixels themselves are not loaded
2878 // (but just skipped).
2879 long frameOffset = Fp->tellg();
2881 uint32_t nbRleSegments = ReadInt32();
2882 if ( nbRleSegments > 16 )
2884 // There should be at most 15 segments (refer to RLEFrame class)
2885 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2888 uint32_t rleSegmentOffsetTable[16];
2889 for( int k = 1; k <= 15; k++ )
2891 rleSegmentOffsetTable[k] = ReadInt32();
2894 // Deduce from both the RLE Header and the frameLength the
2895 // fragment length, and again store this info in a
2897 long rleSegmentLength[15];
2898 // skipping (not reading) RLE Segments
2899 if ( nbRleSegments > 1)
2901 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2903 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2904 - rleSegmentOffsetTable[k];
2905 SkipBytes(rleSegmentLength[k]);
2909 rleSegmentLength[nbRleSegments] = frameLength
2910 - rleSegmentOffsetTable[nbRleSegments];
2911 SkipBytes(rleSegmentLength[nbRleSegments]);
2913 // Store the collected info
2914 RLEFrame* newFrameInfo = new RLEFrame;
2915 newFrameInfo->NumberFragments = nbRleSegments;
2916 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2918 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2919 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2921 RLEInfo->Frames.push_back( newFrameInfo );
2924 // Make sure that at the end of the item we encounter a 'Sequence
2926 if ( !ReadTag(0xfffe, 0xe0dd) )
2928 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2929 dbg.Verbose(0, " item at end of RLE item sequence");
2934 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2935 * Compute the jpeg extra information (fragment[s] offset[s] and
2936 * length) and store it[them] in \ref JPEGInfo for later pixel
2939 void Document::ComputeJPEGFragmentInfo()
2941 // If you need to, look for comments of ComputeRLEInfo().
2947 ReadAndSkipEncapsulatedBasicOffsetTable();
2949 // Loop on the fragments[s] and store the parsed information in a
2951 long fragmentLength;
2952 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2954 long fragmentOffset = Fp->tellg();
2956 // Store the collected info
2957 JPEGFragment* newFragment = new JPEGFragment;
2958 newFragment->Offset = fragmentOffset;
2959 newFragment->Length = fragmentLength;
2960 JPEGInfo->Fragments.push_back( newFragment );
2962 SkipBytes( fragmentLength );
2965 // Make sure that at the end of the item we encounter a 'Sequence
2967 if ( !ReadTag(0xfffe, 0xe0dd) )
2969 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2970 dbg.Verbose(0, " item at end of JPEG item sequence");
2975 * \brief Walk recursively the given \ref DocEntrySet, and feed
2976 * the given hash table (\ref TagDocEntryHT) with all the
2977 * \ref DocEntry (Dicom entries) encountered.
2978 * This method does the job for \ref BuildFlatHashTable.
2979 * @param builtHT Where to collect all the \ref DocEntry encountered
2980 * when recursively walking the given set.
2981 * @param set The structure to be traversed (recursively).
2983 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
2986 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
2988 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
2989 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2990 i != currentHT.end();
2993 DocEntry* entry = i->second;
2994 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
2996 const ListSQItem& items = seqEntry->GetSQItems();
2997 for( ListSQItem::const_iterator item = items.begin();
2998 item != items.end();
3001 BuildFlatHashTableRecurse( builtHT, *item );
3005 builtHT[entry->GetKey()] = entry;
3010 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3012 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3013 for (ListDocEntry::const_iterator i = currentList.begin();
3014 i != currentList.end();
3017 DocEntry* entry = *i;
3018 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3020 const ListSQItem& items = seqEntry->GetSQItems();
3021 for( ListSQItem::const_iterator item = items.begin();
3022 item != items.end();
3025 BuildFlatHashTableRecurse( builtHT, *item );
3029 builtHT[entry->GetKey()] = entry;
3036 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3039 * The structure used by a Document (through \ref ElementSet),
3040 * in order to hold the parsed entries of a Dicom header, is a recursive
3041 * one. This is due to the fact that the sequences (when present)
3042 * can be nested. Additionaly, the sequence items (represented in
3043 * gdcm as \ref SQItem) add an extra complexity to the data
3044 * structure. Hence, a gdcm user whishing to visit all the entries of
3045 * a Dicom header will need to dig in the gdcm internals (which
3046 * implies exposing all the internal data structures to the API).
3047 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3048 * recursively builds a temporary hash table, which holds all the
3049 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3051 * \warning Of course there is NO integrity constrain between the
3052 * returned \ref TagDocEntryHT and the \ref ElementSet used
3053 * to build it. Hence if the underlying \ref ElementSet is
3054 * altered, then it is the caller responsability to invoke
3055 * \ref BuildFlatHashTable again...
3056 * @return The flat std::map<> we juste build.
3058 TagDocEntryHT* Document::BuildFlatHashTable()
3060 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3061 BuildFlatHashTableRecurse( *FlatHT, this );
3068 * \brief Compares two documents, according to \ref DicomDir rules
3069 * \warning Does NOT work with ACR-NEMA files
3070 * \todo Find a trick to solve the pb (use RET fields ?)
3072 * @return true if 'smaller'
3074 bool Document::operator<(Document &document)
3077 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3078 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3090 s1 = GetEntryByNumber(0x0010,0x0020);
3091 s2 = document.GetEntryByNumber(0x0010,0x0020);
3102 // Study Instance UID
3103 s1 = GetEntryByNumber(0x0020,0x000d);
3104 s2 = document.GetEntryByNumber(0x0020,0x000d);
3115 // Serie Instance UID
3116 s1 = GetEntryByNumber(0x0020,0x000e);
3117 s2 = document.GetEntryByNumber(0x0020,0x000e);
3132 } // end namespace gdcm
3134 //-----------------------------------------------------------------------------