1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/10/20 22:31:52 $
7 Version: $Revision: 1.107 $
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"
33 #include <netinet/in.h>
41 // Implicit VR Little Endian
42 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
43 // Explicit VR Little Endian
44 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
45 // Deflated Explicit VR Little Endian
46 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
47 // Explicit VR Big Endian
48 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
49 // JPEG Baseline (Process 1)
50 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
51 // JPEG Extended (Process 2 & 4)
52 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
53 // JPEG Extended (Process 3 & 5)
54 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
55 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
56 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
57 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
58 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
59 // JPEG Lossless, Non-Hierarchical (Process 14)
60 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
61 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
62 // [Selection Value 1])
63 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
65 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
67 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
69 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
70 // UI1_1_2_840_10008_1_2_5
71 #define str2num(str, typeNum) *((typeNum *)(str))
73 //-----------------------------------------------------------------------------
74 // Refer to Document::CheckSwap()
75 const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
77 // Refer to Document::SetMaxSizeLoadEntry()
78 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
79 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
81 //-----------------------------------------------------------------------------
82 // Constructor / Destructor
86 * @param filename file to be opened for parsing
88 Document::Document( std::string const & filename )
91 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
100 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
104 fseek(Fp,0L,SEEK_END);
105 long lgt = ftell(Fp);
109 long beg = ftell(Fp);
112 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
116 // Load 'non string' values
118 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
119 if( PhotometricInterpretation == "PALETTE COLOR " )
121 LoadEntryBinArea(0x0028,0x1200); // gray LUT
122 /// FIXME FIXME FIXME
123 /// The tags refered by the three following lines used to be CORRECTLY
124 /// defined as having an US Value Representation in the public
125 /// dictionnary. BUT the semantics implied by the three following
126 /// lines state that the corresponding tag contents are in fact
127 /// the ones of a BinEntry.
128 /// In order to fix things "Quick and Dirty" the dictionnary was
129 /// altered on PURPOUS but now contains a WRONG value.
130 /// In order to fix things and restore the dictionary to its
131 /// correct value, one needs to decided of the semantics by deciding
132 /// wether the following tags are either:
133 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
134 /// also used as BinEntry, which requires the proper conversion,
135 /// - OW, and hence loaded as BinEntry, but afterwards also used
136 /// as ValEntry, which requires the proper conversion.
137 LoadEntryBinArea(0x0028,0x1201); // R LUT
138 LoadEntryBinArea(0x0028,0x1202); // G LUT
139 LoadEntryBinArea(0x0028,0x1203); // B LUT
141 // Segmented Red Palette Color LUT Data
142 LoadEntryBinArea(0x0028,0x1221);
143 // Segmented Green Palette Color LUT Data
144 LoadEntryBinArea(0x0028,0x1222);
145 // Segmented Blue Palette Color LUT Data
146 LoadEntryBinArea(0x0028,0x1223);
148 //FIXME later : how to use it?
149 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
153 // --------------------------------------------------------------
154 // Specific code to allow gdcm to read ACR-LibIDO formated images
155 // Note: ACR-LibIDO is an extension of the ACR standard that was
156 // used at CREATIS. For the time being (say a couple years)
157 // we keep this kludge to allow a smooth move to gdcm for
158 // CREATIS developpers (sorry folks).
160 // if recognition code tells us we deal with a LibIDO image
161 // we switch lineNumber and columnNumber
164 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
165 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
166 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
167 // with "little-endian strings"
169 Filetype = ACR_LIBIDO;
170 std::string rows = GetEntryByNumber(0x0028, 0x0010);
171 std::string columns = GetEntryByNumber(0x0028, 0x0011);
172 SetEntryByNumber(columns, 0x0028, 0x0010);
173 SetEntryByNumber(rows , 0x0028, 0x0011);
175 // ----------------- End of ACR-LibIDO kludge ------------------
177 PrintLevel = 1; // 'Medium' print level by default
181 * \brief This default constructor doesn't parse the file. You should
182 * then invoke \ref Document::SetFileName and then the parsing.
187 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
189 PrintLevel = 1; // 'Medium' print level by default
193 * \brief Canonical destructor.
195 Document::~Document ()
200 // Recursive clean up of sequences
201 for (TagDocEntryHT::const_iterator it = TagHT.begin();
202 it != TagHT.end(); ++it )
204 //delete it->second; //temp remove
209 //-----------------------------------------------------------------------------
213 * \brief Prints The Dict Entries of THE public Dicom Dictionary
216 void Document::PrintPubDict(std::ostream & os)
218 RefPubDict->Print(os);
222 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
225 void Document::PrintShaDict(std::ostream & os)
227 RefShaDict->Print(os);
230 //-----------------------------------------------------------------------------
233 * \brief Get the public dictionary used
235 Dict* Document::GetPubDict()
241 * \brief Get the shadow dictionary used
243 Dict* Document::GetShaDict()
249 * \brief Set the shadow dictionary used
250 * \param dict dictionary to use in shadow
252 bool Document::SetShaDict(Dict *dict)
259 * \brief Set the shadow dictionary used
260 * \param dictName name of the dictionary to use in shadow
262 bool Document::SetShaDict(DictKey const & dictName)
264 RefShaDict = Global::GetDicts()->GetDict(dictName);
269 * \brief This predicate, based on hopefully reasonable heuristics,
270 * decides whether or not the current Document was properly parsed
271 * and contains the mandatory information for being considered as
272 * a well formed and usable Dicom/Acr File.
273 * @return true when Document is the one of a reasonable Dicom/Acr file,
276 bool Document::IsReadable()
278 if( Filetype == Unknown)
280 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
286 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
296 * \brief Internal function that checks whether the Transfer Syntax given
297 * as argument is the one present in the current document.
298 * @param syntaxToCheck The transfert syntax we need to check against.
299 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
300 * the current document. False either when the document contains
301 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
303 bool Document::IsGivenTransferSyntax(std::string const & syntaxToCheck)
305 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
311 // The entry might be present but not loaded (parsing and loading
312 // happen at different stages): try loading and proceed with check...
313 LoadDocEntrySafe(entry);
314 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
316 std::string transfer = valEntry->GetValue();
317 // The actual transfer (as read from disk) might be padded. We
318 // first need to remove the potential padding. We can make the
319 // weak assumption that padding was not executed with digits...
320 if ( transfer.length() == 0 ) { // for brain damaged headers
323 while ( ! isdigit(transfer[transfer.length()-1]) )
325 transfer.erase(transfer.length()-1, 1);
327 if ( transfer == syntaxToCheck )
336 * \brief Determines if the Transfer Syntax of the present document
337 * corresponds to a Implicit Value Representation of
339 * \sa \ref Document::IsGivenTransferSyntax.
340 * @return True when ImplicitVRLittleEndian found. False in all other cases.
342 bool Document::IsImplicitVRLittleEndianTransferSyntax()
344 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
348 * \brief Determines if the Transfer Syntax was already encountered
349 * and if it corresponds to a ExplicitVRLittleEndian one.
350 * @return True when ExplicitVRLittleEndian found. False in all other cases.
352 bool Document::IsExplicitVRLittleEndianTransferSyntax()
354 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
358 * \brief Determines if the Transfer Syntax was already encountered
359 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
360 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
362 bool Document::IsDeflatedExplicitVRLittleEndianTransferSyntax()
364 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
368 * \brief Determines if the Transfer Syntax was already encountered
369 * and if it corresponds to a Explicit VR Big Endian one.
370 * @return True when big endian found. False in all other cases.
372 bool Document::IsExplicitVRBigEndianTransferSyntax()
374 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
378 * \brief Determines if the Transfer Syntax was already encountered
379 * and if it corresponds to a JPEGBaseLineProcess1 one.
380 * @return True when JPEGBaseLineProcess1found. False in all other cases.
382 bool Document::IsJPEGBaseLineProcess1TransferSyntax()
384 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
388 * \brief Determines if the Transfer Syntax was already encountered
389 * and if it corresponds to a JPEGExtendedProcess2-4 one.
390 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
392 bool Document::IsJPEGExtendedProcess2_4TransferSyntax()
394 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
398 * \brief Determines if the Transfer Syntax was already encountered
399 * and if it corresponds to a JPEGExtendeProcess3-5 one.
400 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
402 bool Document::IsJPEGExtendedProcess3_5TransferSyntax()
404 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
408 * \brief Determines if the Transfer Syntax was already encountered
409 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
410 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
413 bool Document::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
415 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
419 * \brief Determines if the Transfer Syntax was already encountered
420 * and if it corresponds to a RLE Lossless one.
421 * @return True when RLE Lossless found. False in all
424 bool Document::IsRLELossLessTransferSyntax()
426 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
430 * \brief Determines if Transfer Syntax was already encountered
431 * and if it corresponds to a JPEG Lossless one.
432 * @return True when RLE Lossless found. False in all
436 bool Document::IsJPEGLossless()
438 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
439 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
440 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
444 * \brief Determines if the Transfer Syntax was already encountered
445 * and if it corresponds to a JPEG2000 one
446 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
449 bool Document::IsJPEG2000()
451 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
452 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
456 * \brief Determines if the Transfer Syntax corresponds to any form
457 * of Jpeg encoded Pixel data.
458 * @return True when any form of JPEG found. False otherwise.
460 bool Document::IsJPEGTransferSyntax()
462 return ( IsJPEGBaseLineProcess1TransferSyntax()
463 || IsJPEGExtendedProcess2_4TransferSyntax()
464 || IsJPEGExtendedProcess3_5TransferSyntax()
465 || IsJPEGSpectralSelectionProcess6_8TransferSyntax()
472 * \brief Determines if the Transfer Syntax corresponds to encapsulated
473 * of encoded Pixel Data (as opposed to native).
474 * @return True when encapsulated. False when native.
476 bool Document::IsEncapsulateTransferSyntax()
478 return ( IsJPEGTransferSyntax()
479 || IsRLELossLessTransferSyntax() );
483 * \brief Predicate for dicom version 3 file.
484 * @return True when the file is a dicom version 3.
486 bool Document::IsDicomV3()
488 // Checking if Transfert Syntax exists is enough
489 // Anyway, it's to late check if the 'Preamble' was found ...
490 // And ... would it be a rich idea to check ?
491 // (some 'no Preamble' DICOM images exist !)
492 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
496 * \brief returns the File Type
497 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
498 * @return the FileType code
500 FileType Document::GetFileType()
506 * \brief Tries to open the file \ref Document::Filename and
507 * checks the preamble when existing.
508 * @return The FILE pointer on success.
510 FILE* Document::OpenFile()
512 Fp = fopen(Filename.c_str(),"rb");
517 "Document::OpenFile cannot open file: ",
523 fread(&zero, (size_t)2, (size_t)1, Fp);
525 //ACR -- or DICOM with no Preamble --
526 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
532 fseek(Fp, 126L, SEEK_CUR);
534 fread(dicm, (size_t)4, (size_t)1, Fp);
535 if( memcmp(dicm, "DICM", 4) == 0 )
542 "Document::OpenFile not DICOM/ACR (missing preamble)",
549 * \brief closes the file
550 * @return TRUE if the close was successfull
552 bool Document::CloseFile()
554 int closed = fclose(Fp);
568 * \brief Writes in a file all the Header Entries (Dicom Elements)
569 * @param fp file pointer on an already open file
570 * @param filetype Type of the File to be written
571 * (ACR-NEMA, ExplicitVR, ImplicitVR)
572 * \return Always true.
574 void Document::Write(FILE* fp,FileType filetype)
576 /// \todo move the following lines (and a lot of others, to be written)
577 /// to a future function CheckAndCorrectHeader
578 /// (necessary if user wants to write a DICOM V3 file
579 /// starting from an ACR-NEMA (V2) Header
581 if (filetype == ImplicitVR)
583 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
584 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
586 /// \todo Refer to standards on page 21, chapter 6.2
587 /// "Value representation": values with a VR of UI shall be
588 /// padded with a single trailing null
589 /// in the following case we have to padd manually with a 0
591 SetEntryLengthByNumber(18, 0x0002, 0x0010);
594 if (filetype == ExplicitVR)
596 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
597 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
599 /// \todo Refer to standards on page 21, chapter 6.2
600 /// "Value representation": values with a VR of UI shall be
601 /// padded with a single trailing null
602 /// Dans le cas suivant on doit pader manuellement avec un 0
604 SetEntryLengthByNumber(20, 0x0002, 0x0010);
608 * \todo rewrite later, if really usefull
609 * - 'Group Length' element is optional in DICOM
610 * - but un-updated odd groups lengthes can causes pb
613 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
614 * UpdateGroupLength(false,filetype);
615 * if ( filetype == ACR)
616 * UpdateGroupLength(true,ACR);
619 ElementSet::Write(fp, filetype); // This one is recursive
624 * \brief Modifies the value of a given Header Entry (Dicom Element)
625 * when it exists. Create it with the given value when unexistant.
626 * @param value (string) Value to be set
627 * @param group Group number of the Entry
628 * @param elem Element number of the Entry
629 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
630 * \return pointer to the modified/created Header Entry (NULL when creation
633 ValEntry* Document::ReplaceOrCreateByNumber(
634 std::string const & value,
637 std::string const & VR )
639 ValEntry* valEntry = 0;
640 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
644 // check if (group,element) DictEntry exists
645 // if it doesn't, create an entry in DictSet::VirtualEntry
648 // Find out if the tag we received is in the dictionaries:
649 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
650 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
653 currentEntry = NewDocEntryByNumber(group, elem,VR);
657 currentEntry = NewDocEntryByNumber(group, elem);
662 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
663 " NewDocEntryByNumber failed.");
666 valEntry = new ValEntry(currentEntry);
667 if ( !AddEntry(valEntry))
669 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
670 " failed allthough this is a creation.");
675 valEntry = dynamic_cast< ValEntry* >(currentEntry);
676 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
677 // then we change it to a ValEntry ?
678 // Shouldn't it be considered as an error ?
680 // We need to promote the DocEntry to a ValEntry:
681 valEntry = new ValEntry(currentEntry);
682 if (!RemoveEntry(currentEntry))
684 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
685 " of previous DocEntry failed.");
688 if ( !AddEntry(valEntry))
690 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
691 " promoted ValEntry failed.");
697 SetEntryByNumber(value, group, elem);
703 * \brief Modifies the value of a given Header Entry (Dicom Element)
704 * when it exists. Create it with the given value when unexistant.
705 * @param binArea (binary) value to be set
706 * @param Group Group number of the Entry
707 * @param Elem Element number of the Entry
708 * \return pointer to the modified/created Header Entry (NULL when creation
711 BinEntry* Document::ReplaceOrCreateByNumber(
716 std::string const& VR )
718 BinEntry* binEntry = 0;
719 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
723 // check if (group,element) DictEntry exists
724 // if it doesn't, create an entry in DictSet::VirtualEntry
727 // Find out if the tag we received is in the dictionaries:
728 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
729 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
733 currentEntry = NewDocEntryByNumber(group, elem, VR);
737 currentEntry = NewDocEntryByNumber(group, elem);
741 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
742 " NewDocEntryByNumber failed.");
745 binEntry = new BinEntry(currentEntry);
746 if ( !AddEntry(binEntry))
748 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
749 " failed allthough this is a creation.");
754 binEntry = dynamic_cast< BinEntry* >(currentEntry);
755 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
756 // then we change it to a BinEntry ?
757 // Shouldn't it be considered as an error ?
759 // We need to promote the DocEntry to a BinEntry:
760 binEntry = new BinEntry(currentEntry);
761 if (!RemoveEntry(currentEntry))
763 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
764 " of previous DocEntry failed.");
767 if ( !AddEntry(binEntry))
769 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
770 " promoted BinEntry failed.");
776 SetEntryByNumber(binArea, lgth, group, elem);
783 * \brief Modifies the value of a given Header Entry (Dicom Element)
784 * when it exists. Create it when unexistant.
785 * @param Group Group number of the Entry
786 * @param Elem Element number of the Entry
787 * \return pointer to the modified/created SeqEntry (NULL when creation
790 SeqEntry* Document::ReplaceOrCreateByNumber(
795 DocEntry* a = GetDocEntryByNumber( group, elem);
798 a = NewSeqEntryByNumber(group, elem);
804 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
811 * \brief Set a new value if the invoked element exists
812 * Seems to be useless !!!
813 * @param value new element value
814 * @param group group number of the Entry
815 * @param elem element number of the Entry
818 bool Document::ReplaceIfExistByNumber(std::string const & value,
819 uint16_t group, uint16_t elem )
821 SetEntryByNumber(value, group, elem);
826 //-----------------------------------------------------------------------------
830 * \brief Checks if a given Dicom Element exists within the H table
831 * @param group Group number of the searched Dicom Element
832 * @param element Element number of the searched Dicom Element
833 * @return true is found
835 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
837 const std::string &key = DictEntry::TranslateToKey(group, element );
838 return TagHT.count(key);
842 * \brief Searches within Header Entries (Dicom Elements) parsed with
843 * the public and private dictionaries
844 * for the element value of a given tag.
845 * \warning Don't use any longer : use GetPubEntryByName
846 * @param tagName name of the searched element.
847 * @return Corresponding element value when it exists,
848 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
850 std::string Document::GetEntryByName(TagName const& tagName)
852 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
858 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
862 * \brief Searches within Header Entries (Dicom Elements) parsed with
863 * the public and private dictionaries
864 * for the element value representation of a given tag.
866 * Obtaining the VR (Value Representation) might be needed by caller
867 * to convert the string typed content to caller's native type
868 * (think of C++ vs Python). The VR is actually of a higher level
869 * of semantics than just the native C++ type.
870 * @param tagName name of the searched element.
871 * @return Corresponding element value representation when it exists,
872 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
874 std::string Document::GetEntryVRByName(TagName const& tagName)
876 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
877 if( dictEntry == NULL)
882 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
883 dictEntry->GetElement());
884 return elem->GetVR();
888 * \brief Searches within Header Entries (Dicom Elements) parsed with
889 * the public and private dictionaries
890 * for the element value representation of a given tag.
891 * @param group Group number of the searched tag.
892 * @param element Element number of the searched tag.
893 * @return Corresponding element value representation when it exists,
894 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
896 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
898 TagKey key = DictEntry::TranslateToKey(group, element);
899 /// \todo use map methods, instead of multimap JPR
900 if ( !TagHT.count(key))
905 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
909 * \brief Searches within Header Entries (Dicom Elements) parsed with
910 * the public and private dictionaries
911 * for the element value representation of a given tag..
913 * Obtaining the VR (Value Representation) might be needed by caller
914 * to convert the string typed content to caller's native type
915 * (think of C++ vs Python). The VR is actually of a higher level
916 * of semantics than just the native C++ type.
917 * @param group Group number of the searched tag.
918 * @param element Element number of the searched tag.
919 * @return Corresponding element value representation when it exists,
920 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
922 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
924 DocEntry* elem = GetDocEntryByNumber(group, element);
929 return elem->GetVR();
933 * \brief Searches within Header Entries (Dicom Elements) parsed with
934 * the public and private dictionaries
935 * for the value length of a given tag..
936 * @param group Group number of the searched tag.
937 * @param element Element number of the searched tag.
938 * @return Corresponding element length; -2 if not found
940 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
942 DocEntry* elem = GetDocEntryByNumber(group, element);
945 return -2; //magic number
947 return elem->GetLength();
950 * \brief Sets the value (string) of the Header Entry (Dicom Element)
951 * @param content string value of the Dicom Element
952 * @param tagName name of the searched Dicom Element.
953 * @return true when found
955 bool Document::SetEntryByName(std::string const & content,std::string const & tagName)
957 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
963 return SetEntryByNumber(content,dictEntry->GetGroup(),
964 dictEntry->GetElement());
968 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
969 * through it's (group, element) and modifies it's content with
971 * @param content new value (string) to substitute with
972 * @param group group number of the Dicom Element to modify
973 * @param element element number of the Dicom Element to modify
975 bool Document::SetEntryByNumber(std::string const& content,
982 ValEntry* valEntry = GetValEntryByNumber(group, element);
985 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
986 " ValEntry (try promotion first).");
989 // Non even content must be padded with a space (020H)...
990 std::string finalContent = content;
991 if( finalContent.length() % 2 )
993 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
995 valEntry->SetValue(finalContent);
997 // Integers have a special treatement for their length:
999 l = finalContent.length();
1000 if ( l != 0) // To avoid to be cheated by 'zero length' integers
1002 VRKey vr = valEntry->GetVR();
1003 if( vr == "US" || vr == "SS" )
1005 // for multivaluated items
1006 c = Util::CountSubstring(content, "\\") + 1;
1009 else if( vr == "UL" || vr == "SL" )
1011 // for multivaluated items
1012 c = Util::CountSubstring(content, "\\") + 1;
1016 valEntry->SetLength(l);
1021 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
1022 * through it's (group, element) and modifies it's content with
1024 * @param content new value (void* -> uint8_t*) to substitute with
1025 * @param lgth new value length
1026 * @param group group number of the Dicom Element to modify
1027 * @param element element number of the Dicom Element to modify
1029 bool Document::SetEntryByNumber(uint8_t*content,
1034 (void)lgth; //not used
1035 TagKey key = DictEntry::TranslateToKey(group, element);
1036 if ( !TagHT.count(key))
1041 /* Hope Binary field length is *never* wrong
1042 if(lgth%2) // Non even length are padded with a space (020H).
1045 //content = content + '\0'; // fing a trick to enlarge a binary field?
1048 BinEntry* a = (BinEntry *)TagHT[key];
1049 a->SetBinArea(content);
1051 a->SetValue(GDCM_BINLOADED);
1057 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
1058 * in the PubDocEntrySet of this instance
1059 * through it's (group, element) and modifies it's length with
1061 * \warning Use with extreme caution.
1062 * @param l new length to substitute with
1063 * @param group group number of the Entry to modify
1064 * @param element element number of the Entry to modify
1065 * @return true on success, false otherwise.
1067 bool Document::SetEntryLengthByNumber(uint32_t l,
1071 /// \todo use map methods, instead of multimap JPR
1072 TagKey key = DictEntry::TranslateToKey(group, element);
1073 if ( !TagHT.count(key) )
1079 l++; // length must be even
1081 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1087 * \brief Gets (from Header) the offset of a 'non string' element value
1088 * (LoadElementValues has already be executed)
1089 * @param group group number of the Entry
1090 * @param elem element number of the Entry
1091 * @return File Offset of the Element Value
1093 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1095 DocEntry* entry = GetDocEntryByNumber(group, elem);
1098 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1101 return entry->GetOffset();
1105 * \brief Gets (from Header) a 'non string' element value
1106 * (LoadElementValues has already be executed)
1107 * @param group group number of the Entry
1108 * @param elem element number of the Entry
1109 * @return Pointer to the 'non string' area
1111 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1113 DocEntry* entry = GetDocEntryByNumber(group, elem);
1116 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1119 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1121 return binEntry->GetBinArea();
1128 * \brief Loads (from disk) the element content
1129 * when a string is not suitable
1130 * @param group group number of the Entry
1131 * @param elem element number of the Entry
1133 void* Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1135 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1140 size_t o =(size_t)docElement->GetOffset();
1141 fseek(Fp, o, SEEK_SET);
1142 size_t l = docElement->GetLength();
1143 uint8_t* a = new uint8_t[l];
1146 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1149 size_t l2 = fread(a, 1, l , Fp);
1155 /// \todo Drop any already existing void area! JPR
1156 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1158 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1163 * \brief Loads (from disk) the element content
1164 * when a string is not suitable
1165 * @param element Entry whose binArea is going to be loaded
1167 void* Document::LoadEntryBinArea(BinEntry* element)
1169 size_t o =(size_t)element->GetOffset();
1170 fseek(Fp, o, SEEK_SET);
1171 size_t l = element->GetLength();
1172 uint8_t* a = new uint8_t[l];
1175 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1178 element->SetBinArea((uint8_t*)a);
1179 /// \todo check the result
1180 size_t l2 = fread(a, 1, l , Fp);
1191 * \brief Sets a 'non string' value to a given Dicom Element
1192 * @param area area containing the 'non string' value
1193 * @param group Group number of the searched Dicom Element
1194 * @param element Element number of the searched Dicom Element
1197 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1201 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1202 if ( !currentEntry )
1206 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1208 binEntry->SetBinArea( area );
1215 * \brief Update the entries with the shadow dictionary.
1216 * Only non even entries are analyzed
1218 void Document::UpdateShaEntries()
1223 /// \todo TODO : still any use to explore recursively the whole structure?
1225 for(ListTag::iterator it=listEntries.begin();
1226 it!=listEntries.end();
1229 // Odd group => from public dictionary
1230 if((*it)->GetGroup()%2==0)
1233 // Peer group => search the corresponding dict entry
1235 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1239 if((*it)->IsImplicitVR())
1244 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1246 // Set the new entry and the new value
1247 (*it)->SetDictEntry(entry);
1248 CheckDocEntryVR(*it,vr);
1250 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1255 // Remove precedent value transformation
1256 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1263 * \brief Searches within the Header Entries for a Dicom Element of
1265 * @param tagName name of the searched Dicom Element.
1266 * @return Corresponding Dicom Element when it exists, and NULL
1269 DocEntry* Document::GetDocEntryByName(std::string const & tagName)
1271 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1277 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1281 * \brief retrieves a Dicom Element (the first one) using (group, element)
1282 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1283 * if you think it's NOT UNIQUE, check the count number
1284 * and use iterators to retrieve ALL the Dicoms Elements within
1285 * a given couple (group, element)
1286 * @param group Group number of the searched Dicom Element
1287 * @param element Element number of the searched Dicom Element
1290 DocEntry* Document::GetDocEntryByNumber(uint16_t group,
1293 TagKey key = DictEntry::TranslateToKey(group, element);
1294 if ( !TagHT.count(key))
1298 return TagHT.find(key)->second;
1302 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1303 * returns a result when the corresponding entry is of type
1305 * @return When present, the corresponding ValEntry.
1307 ValEntry* Document::GetValEntryByNumber(uint16_t group,
1310 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1311 if ( !currentEntry )
1315 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1319 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1325 * \brief Loads the element while preserving the current
1326 * underlying file position indicator as opposed to
1327 * to LoadDocEntry that modifies it.
1328 * @param entry Header Entry whose value shall be loaded.
1331 void Document::LoadDocEntrySafe(DocEntry * entry)
1333 long PositionOnEntry = ftell(Fp);
1334 LoadDocEntry(entry);
1335 fseek(Fp, PositionOnEntry, SEEK_SET);
1339 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1341 * @return The properly swaped 32 bits integer.
1343 uint32_t Document::SwapLong(uint32_t a)
1350 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1351 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1355 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1359 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1362 //std::cout << "swapCode= " << SwapCode << std::endl;
1363 dbg.Error(" Document::SwapLong : unset swap code");
1370 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1372 * @return The properly unswaped 32 bits integer.
1374 uint32_t Document::UnswapLong(uint32_t a)
1380 * \brief Swaps the bytes so they agree with the processor order
1381 * @return The properly swaped 16 bits integer.
1383 uint16_t Document::SwapShort(uint16_t a)
1385 if ( SwapCode == 4321 || SwapCode == 2143 )
1387 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1393 * \brief Unswaps the bytes so they agree with the processor order
1394 * @return The properly unswaped 16 bits integer.
1396 uint16_t Document::UnswapShort(uint16_t a)
1398 return SwapShort(a);
1401 //-----------------------------------------------------------------------------
1405 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1406 * @return length of the parsed set.
1408 void Document::ParseDES(DocEntrySet *set,
1413 DocEntry *newDocEntry = 0;
1417 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1421 newDocEntry = ReadNextDocEntry( );
1427 VRKey vr = newDocEntry->GetVR();
1431 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1433 /////////////////////// ValEntry
1434 ValEntry* newValEntry =
1435 new ValEntry( newDocEntry->GetDictEntry() );
1436 newValEntry->Copy( newDocEntry );
1438 // When "set" is a Document, then we are at the top of the
1439 // hierarchy and the Key is simply of the form ( group, elem )...
1440 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1443 newValEntry->SetKey( newValEntry->GetKey() );
1445 // ...but when "set" is a SQItem, we are inserting this new
1446 // valEntry in a sequence item. Hence the key has the
1447 // generalized form (refer to \ref BaseTagKey):
1448 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1450 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1451 + newValEntry->GetKey() );
1454 set->AddEntry( newValEntry );
1455 LoadDocEntry( newValEntry );
1456 if (newValEntry->IsItemDelimitor())
1460 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1467 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1469 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1470 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1471 "nor BinEntry. Probably unknown VR.");
1474 //////////////////// BinEntry or UNKOWN VR:
1475 BinEntry* newBinEntry =
1476 new BinEntry( newDocEntry->GetDictEntry() );
1477 newBinEntry->Copy( newDocEntry );
1479 // When "this" is a Document the Key is simply of the
1480 // form ( group, elem )...
1481 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1484 newBinEntry->SetKey( newBinEntry->GetKey() );
1486 // but when "this" is a SQItem, we are inserting this new
1487 // valEntry in a sequence item, and the kay has the
1488 // generalized form (refer to \ref BaseTagKey):
1489 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1491 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1492 + newBinEntry->GetKey() );
1495 set->AddEntry( newBinEntry );
1496 LoadDocEntry( newBinEntry );
1499 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1500 && ( newDocEntry->GetElement() == 0x0010 ) )
1502 if ( IsRLELossLessTransferSyntax() )
1504 long PositionOnEntry = ftell(Fp);
1505 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1507 fseek( Fp, PositionOnEntry, SEEK_SET );
1510 if ( IsJPEGTransferSyntax() )
1512 long PositionOnEntry = ftell(Fp);
1513 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1514 ComputeJPEGFragmentInfo();
1515 fseek( Fp, PositionOnEntry, SEEK_SET );
1519 // Just to make sure we are at the beginning of next entry.
1520 SkipToNextDocEntry(newDocEntry);
1525 unsigned long l = newDocEntry->GetReadLength();
1526 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1528 if ( l == 0xffffffff )
1537 // no other way to create it ...
1538 SeqEntry* newSeqEntry =
1539 new SeqEntry( newDocEntry->GetDictEntry() );
1540 newSeqEntry->Copy( newDocEntry );
1541 newSeqEntry->SetDelimitorMode( delim_mode );
1543 // At the top of the hierarchy, stands a Document. When "set"
1544 // is a Document, then we are building the first depth level.
1545 // Hence the SeqEntry we are building simply has a depth
1547 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1550 newSeqEntry->SetDepthLevel( 1 );
1551 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1553 // But when "set" is allready a SQItem, we are building a nested
1554 // sequence, and hence the depth level of the new SeqEntry
1555 // we are building, is one level deeper:
1556 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1558 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1559 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1560 + newSeqEntry->GetKey() );
1564 { // Don't try to parse zero-length sequences
1565 ParseSQ( newSeqEntry,
1566 newDocEntry->GetOffset(),
1569 set->AddEntry( newSeqEntry );
1570 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1580 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1581 * @return parsed length for this level
1583 void Document::ParseSQ( SeqEntry* seqEntry,
1584 long offset, long l_max, bool delim_mode)
1586 int SQItemNumber = 0;
1591 DocEntry* newDocEntry = ReadNextDocEntry();
1594 // FIXME Should warn user
1599 if ( newDocEntry->IsSequenceDelimitor() )
1601 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1605 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1610 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1611 std::ostringstream newBase;
1612 newBase << seqEntry->GetKey()
1616 itemSQ->SetBaseTagKey( newBase.str() );
1617 unsigned int l = newDocEntry->GetReadLength();
1619 if ( l == 0xffffffff )
1628 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1630 seqEntry->AddEntry( itemSQ, SQItemNumber );
1632 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1640 * \brief Loads the element content if its length doesn't exceed
1641 * the value specified with Document::SetMaxSizeLoadEntry()
1642 * @param entry Header Entry (Dicom Element) to be dealt with
1644 void Document::LoadDocEntry(DocEntry* entry)
1647 uint16_t group = entry->GetGroup();
1648 std::string vr = entry->GetVR();
1649 uint32_t length = entry->GetLength();
1651 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1653 // A SeQuence "contains" a set of Elements.
1654 // (fffe e000) tells us an Element is beginning
1655 // (fffe e00d) tells us an Element just ended
1656 // (fffe e0dd) tells us the current SeQuence just ended
1657 if( group == 0xfffe )
1659 // NO more value field for SQ !
1663 // When the length is zero things are easy:
1666 ((ValEntry *)entry)->SetValue("");
1670 // The elements whose length is bigger than the specified upper bound
1671 // are not loaded. Instead we leave a short notice of the offset of
1672 // the element content and it's length.
1674 std::ostringstream s;
1675 if (length > MaxSizeLoadEntry)
1677 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1679 //s << "gdcm::NotLoaded (BinEntry)";
1680 s << GDCM_NOTLOADED;
1681 s << " Address:" << (long)entry->GetOffset();
1682 s << " Length:" << entry->GetLength();
1683 s << " x(" << std::hex << entry->GetLength() << ")";
1684 binEntryPtr->SetValue(s.str());
1686 // Be carefull : a BinEntry IS_A ValEntry ...
1687 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1689 // s << "gdcm::NotLoaded. (ValEntry)";
1690 s << GDCM_NOTLOADED;
1691 s << " Address:" << (long)entry->GetOffset();
1692 s << " Length:" << entry->GetLength();
1693 s << " x(" << std::hex << entry->GetLength() << ")";
1694 valEntryPtr->SetValue(s.str());
1699 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1700 << "nor a ValEntry ?! Should never print that !" << std::endl;
1703 // to be sure we are at the end of the value ...
1704 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1708 // When we find a BinEntry not very much can be done :
1709 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1711 s << GDCM_BINLOADED;
1712 binEntryPtr->SetValue(s.str());
1713 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1717 /// \todo Any compacter code suggested (?)
1718 if ( IsDocEntryAnInteger(entry) )
1722 // When short integer(s) are expected, read and convert the following
1723 // n *two characters properly i.e. consider them as short integers as
1724 // opposed to strings.
1725 // Elements with Value Multiplicity > 1
1726 // contain a set of integers (not a single one)
1727 if (vr == "US" || vr == "SS")
1730 NewInt = ReadInt16();
1734 for (int i=1; i < nbInt; i++)
1737 NewInt = ReadInt16();
1742 // See above comment on multiple integers (mutatis mutandis).
1743 else if (vr == "UL" || vr == "SL")
1746 NewInt = ReadInt32();
1750 for (int i=1; i < nbInt; i++)
1753 NewInt = ReadInt32();
1758 #ifdef GDCM_NO_ANSI_STRING_STREAM
1759 s << std::ends; // to avoid oddities on Solaris
1760 #endif //GDCM_NO_ANSI_STRING_STREAM
1762 ((ValEntry *)entry)->SetValue(s.str());
1766 // We need an additional byte for storing \0 that is not on disk
1767 //std::string newValue(length,0);
1768 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1769 //rah !! I can't believe it could work, normally this is a const char* !!!
1770 char *str = new char[length+1];
1771 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1773 std::string newValue = str;
1775 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1777 if ( item_read != 1 )
1779 dbg.Verbose(1, "Document::LoadDocEntry",
1780 "unread element value");
1781 valEntry->SetValue(GDCM_UNREAD);
1787 // Because of correspondance with the VR dic
1788 valEntry->SetValue(newValue);
1792 valEntry->SetValue(newValue);
1797 dbg.Error(true, "Document::LoadDocEntry"
1798 "Should have a ValEntry, here !");
1804 * \brief Find the value Length of the passed Header Entry
1805 * @param entry Header Entry whose length of the value shall be loaded.
1807 void Document::FindDocEntryLength( DocEntry *entry )
1808 throw ( FormatError )
1810 uint16_t element = entry->GetElement();
1811 std::string vr = entry->GetVR();
1814 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1816 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1818 // The following reserved two bytes (see PS 3.5-2003, section
1819 // "7.1.2 Data element structure with explicit vr", p 27) must be
1820 // skipped before proceeding on reading the length on 4 bytes.
1821 fseek(Fp, 2L, SEEK_CUR);
1822 uint32_t length32 = ReadInt32();
1824 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1829 /// \todo rename that to FindDocEntryLengthOBOrOW since
1830 /// the above test is on both OB and OW...
1831 lengthOB = FindDocEntryLengthOB();
1833 catch ( FormatUnexpected )
1835 // Computing the length failed (this happens with broken
1836 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1837 // chance to get the pixels by deciding the element goes
1838 // until the end of the file. Hence we artificially fix the
1839 // the length and proceed.
1840 long currentPosition = ftell(Fp);
1841 fseek(Fp,0L,SEEK_END);
1842 long lengthUntilEOF = ftell(Fp) - currentPosition;
1843 fseek(Fp, currentPosition, SEEK_SET);
1844 entry->SetLength(lengthUntilEOF);
1847 entry->SetLength(lengthOB);
1850 FixDocEntryFoundLength(entry, length32);
1854 // Length is encoded on 2 bytes.
1855 length16 = ReadInt16();
1857 // We can tell the current file is encoded in big endian (like
1858 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1859 // and it's value is the one of the encoding of a big endian file.
1860 // In order to deal with such big endian encoded files, we have
1861 // (at least) two strategies:
1862 // * when we load the "Transfer Syntax" tag with value of big endian
1863 // encoding, we raise the proper flags. Then we wait for the end
1864 // of the META group (0x0002) among which is "Transfer Syntax",
1865 // before switching the swap code to big endian. We have to postpone
1866 // the switching of the swap code since the META group is fully encoded
1867 // in little endian, and big endian coding only starts at the next
1868 // group. The corresponding code can be hard to analyse and adds
1869 // many additional unnecessary tests for regular tags.
1870 // * the second strategy consists in waiting for trouble, that shall
1871 // appear when we find the first group with big endian encoding. This
1872 // is easy to detect since the length of a "Group Length" tag (the
1873 // ones with zero as element number) has to be of 4 (0x0004). When we
1874 // encounter 1024 (0x0400) chances are the encoding changed and we
1875 // found a group with big endian encoding.
1876 // We shall use this second strategy. In order to make sure that we
1877 // can interpret the presence of an apparently big endian encoded
1878 // length of a "Group Length" without committing a big mistake, we
1879 // add an additional check: we look in the already parsed elements
1880 // for the presence of a "Transfer Syntax" whose value has to be "big
1881 // endian encoding". When this is the case, chances are we have got our
1882 // hands on a big endian encoded file: we switch the swap code to
1883 // big endian and proceed...
1884 if ( element == 0x0000 && length16 == 0x0400 )
1886 if ( !IsExplicitVRBigEndianTransferSyntax() )
1888 throw FormatError( "Document::FindDocEntryLength()",
1889 " not explicit VR." );
1893 SwitchSwapToBigEndian();
1894 // Restore the unproperly loaded values i.e. the group, the element
1895 // and the dictionary entry depending on them.
1896 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1897 uint16_t correctElem = SwapShort( entry->GetElement() );
1898 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1902 // This correct tag is not in the dictionary. Create a new one.
1903 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1905 // FIXME this can create a memory leaks on the old entry that be
1906 // left unreferenced.
1907 entry->SetDictEntry( newTag );
1910 // Heuristic: well, some files are really ill-formed.
1911 if ( length16 == 0xffff)
1913 // 0xffff means that we deal with 'Unknown Length' Sequence
1916 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1921 // Either implicit VR or a non DICOM conformal (see note below) explicit
1922 // VR that ommited the VR of (at least) this element. Farts happen.
1923 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1924 // on Data elements "Implicit and Explicit VR Data Elements shall
1925 // not coexist in a Data Set and Data Sets nested within it".]
1926 // Length is on 4 bytes.
1928 FixDocEntryFoundLength( entry, ReadInt32() );
1934 * \brief Find the Value Representation of the current Dicom Element.
1937 void Document::FindDocEntryVR( DocEntry *entry )
1939 if ( Filetype != ExplicitVR )
1946 long positionOnEntry = ftell(Fp);
1947 // Warning: we believe this is explicit VR (Value Representation) because
1948 // we used a heuristic that found "UL" in the first tag. Alas this
1949 // doesn't guarantee that all the tags will be in explicit VR. In some
1950 // cases (see e-film filtered files) one finds implicit VR tags mixed
1951 // within an explicit VR file. Hence we make sure the present tag
1952 // is in explicit VR and try to fix things if it happens not to be
1955 fread (vr, (size_t)2,(size_t)1, Fp);
1958 if( !CheckDocEntryVR(entry, vr) )
1960 fseek(Fp, positionOnEntry, SEEK_SET);
1961 // When this element is known in the dictionary we shall use, e.g. for
1962 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1963 // dictionary entry. Still we have to flag the element as implicit since
1964 // we know now our assumption on expliciteness is not furfilled.
1966 if ( entry->IsVRUnknown() )
1968 entry->SetVR("Implicit");
1970 entry->SetImplicitVR();
1975 * \brief Check the correspondance between the VR of the header entry
1976 * and the taken VR. If they are different, the header entry is
1977 * updated with the new VR.
1978 * @param entry Header Entry to check
1979 * @param vr Dicom Value Representation
1980 * @return false if the VR is incorrect of if the VR isn't referenced
1981 * otherwise, it returns true
1983 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1986 bool realExplicit = true;
1988 // Assume we are reading a falsely explicit VR file i.e. we reached
1989 // a tag where we expect reading a VR but are in fact we read the
1990 // first to bytes of the length. Then we will interogate (through find)
1991 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1992 // both GCC and VC++ implementations of the STL map. Hence when the
1993 // expected VR read happens to be non-ascii characters we consider
1994 // we hit falsely explicit VR tag.
1996 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1998 realExplicit = false;
2001 // CLEANME searching the dicom_vr at each occurence is expensive.
2002 // PostPone this test in an optional integrity check at the end
2003 // of parsing or only in debug mode.
2004 if ( realExplicit && !Global::GetVR()->Count(vr) )
2006 realExplicit = false;
2009 if ( !realExplicit )
2011 // We thought this was explicit VR, but we end up with an
2012 // implicit VR tag. Let's backtrack.
2013 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
2014 entry->GetGroup(), entry->GetElement());
2015 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
2017 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2019 // Group length is UL !
2020 DictEntry* newEntry = NewVirtualDictEntry(
2021 entry->GetGroup(), entry->GetElement(),
2022 "UL", "FIXME", "Group Length");
2023 entry->SetDictEntry( newEntry );
2028 if ( entry->IsVRUnknown() )
2030 // When not a dictionary entry, we can safely overwrite the VR.
2031 if( entry->GetElement() == 0x0000 )
2033 // Group length is UL !
2041 else if ( entry->GetVR() != vr )
2043 // The VR present in the file and the dictionary disagree. We assume
2044 // the file writer knew best and use the VR of the file. Since it would
2045 // be unwise to overwrite the VR of a dictionary (since it would
2046 // compromise it's next user), we need to clone the actual DictEntry
2047 // and change the VR for the read one.
2048 DictEntry* newEntry = NewVirtualDictEntry(
2049 entry->GetGroup(), entry->GetElement(),
2050 vr, "FIXME", entry->GetName());
2051 entry->SetDictEntry(newEntry);
2058 * \brief Get the transformed value of the header entry. The VR value
2059 * is used to define the transformation to operate on the value
2060 * \warning NOT end user intended method !
2061 * @param entry entry to tranform
2062 * @return Transformed entry value
2064 std::string Document::GetDocEntryValue(DocEntry *entry)
2066 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2068 std::string val = ((ValEntry *)entry)->GetValue();
2069 std::string vr = entry->GetVR();
2070 uint32_t length = entry->GetLength();
2071 std::ostringstream s;
2074 // When short integer(s) are expected, read and convert the following
2075 // n * 2 bytes properly i.e. as a multivaluated strings
2076 // (each single value is separated fromthe next one by '\'
2077 // as usual for standard multivaluated filels
2078 // Elements with Value Multiplicity > 1
2079 // contain a set of short integers (not a single one)
2081 if( vr == "US" || vr == "SS" )
2086 for (int i=0; i < nbInt; i++)
2092 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2093 newInt16 = SwapShort( newInt16 );
2098 // When integer(s) are expected, read and convert the following
2099 // n * 4 bytes properly i.e. as a multivaluated strings
2100 // (each single value is separated fromthe next one by '\'
2101 // as usual for standard multivaluated filels
2102 // Elements with Value Multiplicity > 1
2103 // contain a set of integers (not a single one)
2104 else if( vr == "UL" || vr == "SL" )
2109 for (int i=0; i < nbInt; i++)
2115 newInt32 = ( val[4*i+0] & 0xFF )
2116 + (( val[4*i+1] & 0xFF ) << 8 )
2117 + (( val[4*i+2] & 0xFF ) << 16 )
2118 + (( val[4*i+3] & 0xFF ) << 24 );
2119 newInt32 = SwapLong( newInt32 );
2123 #ifdef GDCM_NO_ANSI_STRING_STREAM
2124 s << std::ends; // to avoid oddities on Solaris
2125 #endif //GDCM_NO_ANSI_STRING_STREAM
2129 return ((ValEntry *)entry)->GetValue();
2133 * \brief Get the reverse transformed value of the header entry. The VR
2134 * value is used to define the reverse transformation to operate on
2136 * \warning NOT end user intended method !
2137 * @param entry Entry to reverse transform
2138 * @return Reverse transformed entry value
2140 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2142 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2144 std::string vr = entry->GetVR();
2145 std::vector<std::string> tokens;
2146 std::ostringstream s;
2148 if ( vr == "US" || vr == "SS" )
2152 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2153 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2154 for (unsigned int i=0; i<tokens.size(); i++)
2156 newInt16 = atoi(tokens[i].c_str());
2157 s << ( newInt16 & 0xFF )
2158 << (( newInt16 >> 8 ) & 0xFF );
2162 if ( vr == "UL" || vr == "SL")
2166 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2167 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2168 for (unsigned int i=0; i<tokens.size();i++)
2170 newInt32 = atoi(tokens[i].c_str());
2171 s << (char)( newInt32 & 0xFF )
2172 << (char)(( newInt32 >> 8 ) & 0xFF )
2173 << (char)(( newInt32 >> 16 ) & 0xFF )
2174 << (char)(( newInt32 >> 24 ) & 0xFF );
2179 #ifdef GDCM_NO_ANSI_STRING_STREAM
2180 s << std::ends; // to avoid oddities on Solaris
2181 #endif //GDCM_NO_ANSI_STRING_STREAM
2185 return ((ValEntry *)entry)->GetValue();
2189 * \brief Skip a given Header Entry
2190 * \warning NOT end user intended method !
2191 * @param entry entry to skip
2193 void Document::SkipDocEntry(DocEntry *entry)
2195 SkipBytes(entry->GetLength());
2199 * \brief Skips to the begining of the next Header Entry
2200 * \warning NOT end user intended method !
2201 * @param entry entry to skip
2203 void Document::SkipToNextDocEntry(DocEntry *entry)
2205 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2206 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2210 * \brief When the length of an element value is obviously wrong (because
2211 * the parser went Jabberwocky) one can hope improving things by
2212 * applying some heuristics.
2213 * @param entry entry to check
2214 * @param foundLength fist assumption about length
2216 void Document::FixDocEntryFoundLength(DocEntry *entry,
2217 uint32_t foundLength)
2219 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2220 if ( foundLength == 0xffffffff)
2225 uint16_t gr = entry->GetGroup();
2226 uint16_t el = entry->GetElement();
2228 if ( foundLength % 2)
2230 std::ostringstream s;
2231 s << "Warning : Tag with uneven length "
2233 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2234 dbg.Verbose(0, s.str().c_str());
2237 //////// Fix for some naughty General Electric images.
2238 // Allthough not recent many such GE corrupted images are still present
2239 // on Creatis hard disks. Hence this fix shall remain when such images
2240 // are no longer in user (we are talking a few years, here)...
2241 // Note: XMedCom probably uses such a trick since it is able to read
2242 // those pesky GE images ...
2243 if ( foundLength == 13)
2245 // Only happens for this length !
2246 if ( entry->GetGroup() != 0x0008
2247 || ( entry->GetElement() != 0x0070
2248 && entry->GetElement() != 0x0080 ) )
2251 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2255 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2256 // Occurence of such images is quite low (unless one leaves close to a
2257 // 'Leonardo' source. Hence, one might consider commenting out the
2258 // following fix on efficiency reasons.
2259 else if ( entry->GetGroup() == 0x0009
2260 && ( entry->GetElement() == 0x1113
2261 || entry->GetElement() == 0x1114 ) )
2264 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2267 else if ( entry->GetVR() == "SQ" )
2269 foundLength = 0; // ReadLength is unchanged
2272 //////// We encountered a 'delimiter' element i.e. a tag of the form
2273 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2274 // taken into account.
2275 else if( entry->GetGroup() == 0xfffe )
2277 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2278 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2279 // causes extra troubles...
2280 if( entry->GetElement() != 0x0000 )
2286 entry->SetUsableLength(foundLength);
2290 * \brief Apply some heuristics to predict whether the considered
2291 * element value contains/represents an integer or not.
2292 * @param entry The element value on which to apply the predicate.
2293 * @return The result of the heuristical predicate.
2295 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2297 uint16_t element = entry->GetElement();
2298 uint16_t group = entry->GetGroup();
2299 std::string vr = entry->GetVR();
2300 uint32_t length = entry->GetLength();
2302 // When we have some semantics on the element we just read, and if we
2303 // a priori know we are dealing with an integer, then we shall be
2304 // able to swap it's element value properly.
2305 if ( element == 0 ) // This is the group length of the group
2313 // Allthough this should never happen, still some images have a
2314 // corrupted group length [e.g. have a glance at offset x(8336) of
2315 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2316 // Since for dicom compliant and well behaved headers, the present
2317 // test is useless (and might even look a bit paranoid), when we
2318 // encounter such an ill-formed image, we simply display a warning
2319 // message and proceed on parsing (while crossing fingers).
2320 std::ostringstream s;
2321 long filePosition = ftell(Fp);
2322 s << "Erroneous Group Length element length on : (" \
2323 << std::hex << group << " , " << element
2324 << ") -before- position x(" << filePosition << ")"
2325 << "lgt : " << length;
2326 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2330 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2339 * \brief Find the Length till the next sequence delimiter
2340 * \warning NOT end user intended method !
2344 uint32_t Document::FindDocEntryLengthOB()
2345 throw( FormatUnexpected )
2347 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2348 long positionOnEntry = ftell(Fp);
2349 bool foundSequenceDelimiter = false;
2350 uint32_t totalLength = 0;
2352 while ( !foundSequenceDelimiter )
2358 group = ReadInt16();
2361 catch ( FormatError )
2363 throw FormatError("Document::FindDocEntryLengthOB()",
2364 " group or element not present.");
2367 // We have to decount the group and element we just read
2370 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2372 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2373 "tag nor a Sequence delimiter tag.");
2374 fseek(Fp, positionOnEntry, SEEK_SET);
2375 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2376 "Neither an Item tag nor a Sequence "
2380 if ( elem == 0xe0dd )
2382 foundSequenceDelimiter = true;
2385 uint32_t itemLength = ReadInt32();
2386 // We add 4 bytes since we just read the ItemLength with ReadInt32
2387 totalLength += itemLength + 4;
2388 SkipBytes(itemLength);
2390 if ( foundSequenceDelimiter )
2395 fseek(Fp, positionOnEntry, SEEK_SET);
2400 * \brief Reads a supposed to be 16 Bits integer
2401 * (swaps it depending on processor endianity)
2402 * @return read value
2404 uint16_t Document::ReadInt16()
2405 throw( FormatError )
2408 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2409 if ( item_read != 1 )
2413 throw FormatError( "Document::ReadInt16()", " file error." );
2415 throw FormatError( "Document::ReadInt16()", "EOF." );
2422 * \brief Reads a supposed to be 32 Bits integer
2423 * (swaps it depending on processor endianity)
2424 * @return read value
2426 uint32_t Document::ReadInt32()
2427 throw( FormatError )
2430 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2431 if ( item_read != 1 )
2435 throw FormatError( "Document::ReadInt16()", " file error." );
2437 throw FormatError( "Document::ReadInt32()", "EOF." );
2444 * \brief skips bytes inside the source file
2445 * \warning NOT end user intended method !
2448 void Document::SkipBytes(uint32_t nBytes)
2450 //FIXME don't dump the returned value
2451 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2455 * \brief Loads all the needed Dictionaries
2456 * \warning NOT end user intended method !
2458 void Document::Initialise()
2460 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2462 RLEInfo = new RLEFramesInfo;
2463 JPEGInfo = new JPEGFragmentsInfo;
2467 * \brief Discover what the swap code is (among little endian, big endian,
2468 * bad little endian, bad big endian).
2470 * @return false when we are absolutely sure
2471 * it's neither ACR-NEMA nor DICOM
2472 * true when we hope ours assuptions are OK
2474 bool Document::CheckSwap()
2476 // The only guaranted way of finding the swap code is to find a
2477 // group tag since we know it's length has to be of four bytes i.e.
2478 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2479 // occurs when we can't find such group...
2481 uint32_t x = 4; // x : for ntohs
2482 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2486 char deb[HEADER_LENGTH_TO_READ];
2488 // First, compare HostByteOrder and NetworkByteOrder in order to
2489 // determine if we shall need to swap bytes (i.e. the Endian type).
2490 if ( x == ntohs(x) )
2499 // The easiest case is the one of a DICOM header, since it possesses a
2500 // file preamble where it suffice to look for the string "DICM".
2501 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2502 (void)lgrLue; //FIXME not used
2504 char *entCur = deb + 128;
2505 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2507 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2509 // Next, determine the value representation (VR). Let's skip to the
2510 // first element (0002, 0000) and check there if we find "UL"
2511 // - or "OB" if the 1st one is (0002,0001) -,
2512 // in which case we (almost) know it is explicit VR.
2513 // WARNING: if it happens to be implicit VR then what we will read
2514 // is the length of the group. If this ascii representation of this
2515 // length happens to be "UL" then we shall believe it is explicit VR.
2516 // FIXME: in order to fix the above warning, we could read the next
2517 // element value (or a couple of elements values) in order to make
2518 // sure we are not commiting a big mistake.
2519 // We need to skip :
2520 // * the 128 bytes of File Preamble (often padded with zeroes),
2521 // * the 4 bytes of "DICM" string,
2522 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2523 // i.e. a total of 136 bytes.
2527 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2528 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2529 // *Implicit* VR. -and it is !-
2531 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2532 memcmp(entCur, "OB", (size_t)2) == 0 ||
2533 memcmp(entCur, "UI", (size_t)2) == 0 ||
2534 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2535 // when Write DCM *adds*
2537 // Use Document::dicom_vr to test all the possibilities
2538 // instead of just checking for UL, OB and UI !? group 0000
2540 Filetype = ExplicitVR;
2541 dbg.Verbose(1, "Document::CheckSwap:",
2542 "explicit Value Representation");
2546 Filetype = ImplicitVR;
2547 dbg.Verbose(1, "Document::CheckSwap:",
2548 "not an explicit Value Representation");
2554 dbg.Verbose(1, "Document::CheckSwap:",
2555 "HostByteOrder != NetworkByteOrder");
2560 dbg.Verbose(1, "Document::CheckSwap:",
2561 "HostByteOrder = NetworkByteOrder");
2564 // Position the file position indicator at first tag (i.e.
2565 // after the file preamble and the "DICM" string).
2567 fseek (Fp, 132L, SEEK_SET);
2571 // Alas, this is not a DicomV3 file and whatever happens there is no file
2572 // preamble. We can reset the file position indicator to where the data
2573 // is (i.e. the beginning of the file).
2574 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2577 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2578 // By clean we mean that the length of the first tag is written down.
2579 // If this is the case and since the length of the first group HAS to be
2580 // four (bytes), then determining the proper swap code is straightforward.
2583 // We assume the array of char we are considering contains the binary
2584 // representation of a 32 bits integer. Hence the following dirty
2586 s32 = *((uint32_t *)(entCur));
2607 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2608 // It is time for despaired wild guesses.
2609 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2610 // i.e. the 'group length' element is not present :
2612 // check the supposed to be 'group number'
2613 // 0x0002 or 0x0004 or 0x0008
2614 // to determine ' SwapCode' value .
2615 // Only 0 or 4321 will be possible
2616 // (no oportunity to check for the formerly well known
2617 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2618 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2619 // the file IS NOT ACR-NEMA nor DICOM V3
2620 // Find a trick to tell it the caller...
2622 s16 = *((uint16_t *)(deb));
2639 dbg.Verbose(0, "Document::CheckSwap:",
2640 "ACR/NEMA unfound swap info (Really hopeless !)");
2644 // Then the only info we have is the net2host one.
2654 * \brief Restore the unproperly loaded values i.e. the group, the element
2655 * and the dictionary entry depending on them.
2657 void Document::SwitchSwapToBigEndian()
2659 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2660 "Switching to BigEndian mode.");
2661 if ( SwapCode == 0 )
2665 else if ( SwapCode == 4321 )
2669 else if ( SwapCode == 3412 )
2673 else if ( SwapCode == 2143 )
2680 * \brief during parsing, Header Elements too long are not loaded in memory
2683 void Document::SetMaxSizeLoadEntry(long newSize)
2689 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2691 MaxSizeLoadEntry = 0xffffffff;
2694 MaxSizeLoadEntry = newSize;
2699 * \brief Header Elements too long will not be printed
2700 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2703 void Document::SetMaxSizePrintEntry(long newSize)
2705 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2710 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2712 MaxSizePrintEntry = 0xffffffff;
2715 MaxSizePrintEntry = newSize;
2721 * \brief Read the next tag but WITHOUT loading it's value
2722 * (read the 'Group Number', the 'Element Number',
2723 * gets the Dict Entry
2724 * gets the VR, gets the length, gets the offset value)
2725 * @return On succes the newly created DocEntry, NULL on failure.
2727 DocEntry* Document::ReadNextDocEntry()
2734 group = ReadInt16();
2737 catch ( FormatError e )
2739 // We reached the EOF (or an error occured) therefore
2740 // header parsing has to be considered as finished.
2745 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2746 FindDocEntryVR(newEntry);
2750 FindDocEntryLength(newEntry);
2752 catch ( FormatError e )
2760 newEntry->SetOffset(ftell(Fp));
2767 * \brief Generate a free TagKey i.e. a TagKey that is not present
2768 * in the TagHt dictionary.
2769 * @param group The generated tag must belong to this group.
2770 * @return The element of tag with given group which is fee.
2772 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2774 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2776 TagKey key = DictEntry::TranslateToKey(group, elem);
2777 if (TagHT.count(key) == 0)
2786 * \brief Assuming the internal file pointer \ref Document::Fp
2787 * is placed at the beginning of a tag check whether this
2788 * tag is (TestGroup, TestElement).
2789 * \warning On success the internal file pointer \ref Document::Fp
2790 * is modified to point after the tag.
2791 * On failure (i.e. when the tag wasn't the expected tag
2792 * (TestGroup, TestElement) the internal file pointer
2793 * \ref Document::Fp is restored to it's original position.
2794 * @param testGroup The expected group of the tag.
2795 * @param testElement The expected Element of the tag.
2796 * @return True on success, false otherwise.
2798 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2800 long positionOnEntry = ftell(Fp);
2801 long currentPosition = ftell(Fp); // On debugging purposes
2803 //// Read the Item Tag group and element, and make
2804 // sure they are what we expected:
2805 uint16_t itemTagGroup = ReadInt16();
2806 uint16_t itemTagElement = ReadInt16();
2807 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2809 std::ostringstream s;
2810 s << " We should have found tag (";
2811 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2812 s << " but instead we encountered tag (";
2813 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2815 s << " at address: " << (unsigned)currentPosition << std::endl;
2816 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2817 dbg.Verbose(0, s.str().c_str());
2818 fseek(Fp, positionOnEntry, SEEK_SET);
2826 * \brief Assuming the internal file pointer \ref Document::Fp
2827 * is placed at the beginning of a tag (TestGroup, TestElement),
2828 * read the length associated to the Tag.
2829 * \warning On success the internal file pointer \ref Document::Fp
2830 * is modified to point after the tag and it's length.
2831 * On failure (i.e. when the tag wasn't the expected tag
2832 * (TestGroup, TestElement) the internal file pointer
2833 * \ref Document::Fp is restored to it's original position.
2834 * @param testGroup The expected group of the tag.
2835 * @param testElement The expected Element of the tag.
2836 * @return On success returns the length associated to the tag. On failure
2839 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2841 long positionOnEntry = ftell(Fp);
2842 (void)positionOnEntry;
2844 if ( !ReadTag(testGroup, testElement) )
2849 //// Then read the associated Item Length
2850 long currentPosition = ftell(Fp);
2851 uint32_t itemLength = ReadInt32();
2853 std::ostringstream s;
2854 s << "Basic Item Length is: "
2855 << itemLength << std::endl;
2856 s << " at address: " << (unsigned)currentPosition << std::endl;
2857 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2863 * \brief When parsing the Pixel Data of an encapsulated file, read
2864 * the basic offset table (when present, and BTW dump it).
2866 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2868 //// Read the Basic Offset Table Item Tag length...
2869 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2871 // When present, read the basic offset table itself.
2872 // Notes: - since the presence of this basic offset table is optional
2873 // we can't rely on it for the implementation, and we will simply
2874 // trash it's content (when present).
2875 // - still, when present, we could add some further checks on the
2876 // lengths, but we won't bother with such fuses for the time being.
2877 if ( itemLength != 0 )
2879 char* basicOffsetTableItemValue = new char[itemLength + 1];
2880 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2883 for (unsigned int i=0; i < itemLength; i += 4 )
2885 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2887 std::ostringstream s;
2888 s << " Read one length: ";
2889 s << std::hex << individualLength << std::endl;
2891 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2896 delete[] basicOffsetTableItemValue;
2901 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2902 * Compute the RLE extra information and store it in \ref RLEInfo
2903 * for later pixel retrieval usage.
2905 void Document::ComputeRLEInfo()
2907 if ( ! IsRLELossLessTransferSyntax() )
2912 // Encoded pixel data: for the time being we are only concerned with
2913 // Jpeg or RLE Pixel data encodings.
2914 // As stated in PS 3.5-2003, section 8.2 p44:
2915 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2916 // value representation OB is used".
2917 // Hence we expect an OB value representation. Concerning OB VR,
2918 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2919 // "For the Value Representations OB and OW, the encoding shall meet the
2920 // following specifications depending on the Data element tag:"
2922 // - the first item in the sequence of items before the encoded pixel
2923 // data stream shall be basic offset table item. The basic offset table
2924 // item value, however, is not required to be present"
2926 ReadAndSkipEncapsulatedBasicOffsetTable();
2928 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2929 // Loop on the individual frame[s] and store the information
2930 // on the RLE fragments in a RLEFramesInfo.
2931 // Note: - when only a single frame is present, this is a
2933 // - when more than one frame are present, then we are in
2934 // the case of a multi-frame image.
2936 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2938 // Parse the RLE Header and store the corresponding RLE Segment
2939 // Offset Table information on fragments of this current Frame.
2940 // Note that the fragment pixels themselves are not loaded
2941 // (but just skipped).
2942 long frameOffset = ftell(Fp);
2944 uint32_t nbRleSegments = ReadInt32();
2946 uint32_t rleSegmentOffsetTable[15];
2947 for( int k = 1; k <= 15; k++ )
2949 rleSegmentOffsetTable[k] = ReadInt32();
2952 // Deduce from both the RLE Header and the frameLength the
2953 // fragment length, and again store this info in a
2955 long rleSegmentLength[15];
2956 // skipping (not reading) RLE Segments
2957 if ( nbRleSegments > 1)
2959 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2961 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2962 - rleSegmentOffsetTable[k];
2963 SkipBytes(rleSegmentLength[k]);
2967 rleSegmentLength[nbRleSegments] = frameLength
2968 - rleSegmentOffsetTable[nbRleSegments];
2969 SkipBytes(rleSegmentLength[nbRleSegments]);
2971 // Store the collected info
2972 RLEFrame* newFrameInfo = new RLEFrame;
2973 newFrameInfo->NumberFragments = nbRleSegments;
2974 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2976 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2977 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2979 RLEInfo->Frames.push_back( newFrameInfo );
2982 // Make sure that at the end of the item we encounter a 'Sequence
2984 if ( !ReadTag(0xfffe, 0xe0dd) )
2986 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2987 dbg.Verbose(0, " item at end of RLE item sequence");
2992 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2993 * Compute the jpeg extra information (fragment[s] offset[s] and
2994 * length) and store it[them] in \ref JPEGInfo for later pixel
2997 void Document::ComputeJPEGFragmentInfo()
2999 // If you need to, look for comments of ComputeRLEInfo().
3000 if ( ! IsJPEGTransferSyntax() )
3005 ReadAndSkipEncapsulatedBasicOffsetTable();
3007 // Loop on the fragments[s] and store the parsed information in a
3009 long fragmentLength;
3010 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3012 long fragmentOffset = ftell(Fp);
3014 // Store the collected info
3015 JPEGFragment* newFragment = new JPEGFragment;
3016 newFragment->Offset = fragmentOffset;
3017 newFragment->Length = fragmentLength;
3018 JPEGInfo->Fragments.push_back( newFragment );
3020 SkipBytes( fragmentLength );
3023 // Make sure that at the end of the item we encounter a 'Sequence
3025 if ( !ReadTag(0xfffe, 0xe0dd) )
3027 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3028 dbg.Verbose(0, " item at end of JPEG item sequence");
3033 * \brief Walk recursively the given \ref DocEntrySet, and feed
3034 * the given hash table (\ref TagDocEntryHT) with all the
3035 * \ref DocEntry (Dicom entries) encountered.
3036 * This method does the job for \ref BuildFlatHashTable.
3037 * @param builtHT Where to collect all the \ref DocEntry encountered
3038 * when recursively walking the given set.
3039 * @param set The structure to be traversed (recursively).
3041 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3044 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3046 TagDocEntryHT* currentHT = elementSet->GetTagHT();
3047 for( TagDocEntryHT::const_iterator i = currentHT->begin();
3048 i != currentHT->end();
3051 DocEntry* entry = i->second;
3052 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3054 ListSQItem& items = seqEntry->GetSQItems();
3055 for( ListSQItem::const_iterator item = items.begin();
3056 item != items.end();
3059 BuildFlatHashTableRecurse( builtHT, *item );
3063 builtHT[entry->GetKey()] = entry;
3068 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3070 ListDocEntry& currentList = SQItemSet->GetDocEntries();
3071 for (ListDocEntry::iterator i = currentList.begin();
3072 i != currentList.end();
3075 DocEntry* entry = *i;
3076 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3078 ListSQItem& items = seqEntry->GetSQItems();
3079 for( ListSQItem::const_iterator item = items.begin();
3080 item != items.end();
3083 BuildFlatHashTableRecurse( builtHT, *item );
3087 builtHT[entry->GetKey()] = entry;
3094 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3097 * The structure used by a Document (through \ref ElementSet),
3098 * in order to old the parsed entries of a Dicom header, is a recursive
3099 * one. This is due to the fact that the sequences (when present)
3100 * can be nested. Additionaly, the sequence items (represented in
3101 * gdcm as \ref SQItem) add an extra complexity to the data
3102 * structure. Hence, a gdcm user whishing to visit all the entries of
3103 * a Dicom header will need to dig in the gdcm internals (which
3104 * implies exposing all the internal data structures to the API).
3105 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3106 * recursively builds a temporary hash table, which holds all the
3107 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3109 * \warning Of course there is NO integrity constrain between the
3110 * returned \ref TagDocEntryHT and the \ref ElementSet used
3111 * to build it. Hence if the underlying \ref ElementSet is
3112 * altered, then it is the caller responsability to invoke
3113 * \ref BuildFlatHashTable again...
3114 * @return The flat std::map<> we juste build.
3116 TagDocEntryHT* Document::BuildFlatHashTable()
3118 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3119 BuildFlatHashTableRecurse( *FlatHT, this );
3126 * \brief Compares two documents, according to \ref DicomDir rules
3127 * \warning Does NOT work with ACR-NEMA files
3128 * \todo Find a trick to solve the pb (use RET fields ?)
3130 * @return true if 'smaller'
3132 bool Document::operator<(Document &document)
3135 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3136 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3148 s1 = GetEntryByNumber(0x0010,0x0020);
3149 s2 = document.GetEntryByNumber(0x0010,0x0020);
3160 // Study Instance UID
3161 s1 = GetEntryByNumber(0x0020,0x000d);
3162 s2 = document.GetEntryByNumber(0x0020,0x000d);
3173 // Serie Instance UID
3174 s1 = GetEntryByNumber(0x0020,0x000e);
3175 s2 = document.GetEntryByNumber(0x0020,0x000e);
3190 } // end namespace gdcm
3192 //-----------------------------------------------------------------------------