1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/10/20 14:30:40 $
7 Version: $Revision: 1.106 $
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);
561 * \brief Writes in a file all the Header Entries (Dicom Elements)
562 * @param fp file pointer on an already open file
563 * @param filetype Type of the File to be written
564 * (ACR-NEMA, ExplicitVR, ImplicitVR)
565 * \return Always true.
567 void Document::Write(FILE* fp,FileType filetype)
569 /// \todo move the following lines (and a lot of others, to be written)
570 /// to a future function CheckAndCorrectHeader
571 /// (necessary if user wants to write a DICOM V3 file
572 /// starting from an ACR-NEMA (V2) Header
574 if (filetype == ImplicitVR)
576 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
577 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
579 /// \todo Refer to standards on page 21, chapter 6.2
580 /// "Value representation": values with a VR of UI shall be
581 /// padded with a single trailing null
582 /// in the following case we have to padd manually with a 0
584 SetEntryLengthByNumber(18, 0x0002, 0x0010);
587 if (filetype == ExplicitVR)
589 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
590 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
592 /// \todo Refer to standards on page 21, chapter 6.2
593 /// "Value representation": values with a VR of UI shall be
594 /// padded with a single trailing null
595 /// Dans le cas suivant on doit pader manuellement avec un 0
597 SetEntryLengthByNumber(20, 0x0002, 0x0010);
601 * \todo rewrite later, if really usefull
602 * - 'Group Length' element is optional in DICOM
603 * - but un-updated odd groups lengthes can causes pb
606 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
607 * UpdateGroupLength(false,filetype);
608 * if ( filetype == ACR)
609 * UpdateGroupLength(true,ACR);
612 ElementSet::Write(fp, filetype); // This one is recursive
617 * \brief Modifies the value of a given Header Entry (Dicom Element)
618 * when it exists. Create it with the given value when unexistant.
619 * @param value (string) Value to be set
620 * @param group Group number of the Entry
621 * @param elem Element number of the Entry
622 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
623 * \return pointer to the modified/created Header Entry (NULL when creation
626 ValEntry* Document::ReplaceOrCreateByNumber(
627 std::string const & value,
630 std::string const & VR )
632 ValEntry* valEntry = 0;
633 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
637 // check if (group,element) DictEntry exists
638 // if it doesn't, create an entry in DictSet::VirtualEntry
641 // Find out if the tag we received is in the dictionaries:
642 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
643 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
646 currentEntry = NewDocEntryByNumber(group, elem,VR);
650 currentEntry = NewDocEntryByNumber(group, elem);
655 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
656 " NewDocEntryByNumber failed.");
659 valEntry = new ValEntry(currentEntry);
660 if ( !AddEntry(valEntry))
662 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
663 " failed allthough this is a creation.");
668 valEntry = dynamic_cast< ValEntry* >(currentEntry);
669 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
670 // then we change it to a ValEntry ?
671 // Shouldn't it be considered as an error ?
673 // We need to promote the DocEntry to a ValEntry:
674 valEntry = new ValEntry(currentEntry);
675 if (!RemoveEntry(currentEntry))
677 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
678 " of previous DocEntry failed.");
681 if ( !AddEntry(valEntry))
683 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
684 " promoted ValEntry failed.");
690 SetEntryByNumber(value, group, elem);
696 * \brief Modifies the value of a given Header Entry (Dicom Element)
697 * when it exists. Create it with the given value when unexistant.
698 * @param binArea (binary) value to be set
699 * @param Group Group number of the Entry
700 * @param Elem Element number of the Entry
701 * \return pointer to the modified/created Header Entry (NULL when creation
704 BinEntry* Document::ReplaceOrCreateByNumber(
709 std::string const& VR )
711 BinEntry* binEntry = 0;
712 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
716 // check if (group,element) DictEntry exists
717 // if it doesn't, create an entry in DictSet::VirtualEntry
720 // Find out if the tag we received is in the dictionaries:
721 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
722 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
726 currentEntry = NewDocEntryByNumber(group, elem, VR);
730 currentEntry = NewDocEntryByNumber(group, elem);
734 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
735 " NewDocEntryByNumber failed.");
738 binEntry = new BinEntry(currentEntry);
739 if ( !AddEntry(binEntry))
741 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
742 " failed allthough this is a creation.");
747 binEntry = dynamic_cast< BinEntry* >(currentEntry);
748 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
749 // then we change it to a BinEntry ?
750 // Shouldn't it be considered as an error ?
752 // We need to promote the DocEntry to a BinEntry:
753 binEntry = new BinEntry(currentEntry);
754 if (!RemoveEntry(currentEntry))
756 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
757 " of previous DocEntry failed.");
760 if ( !AddEntry(binEntry))
762 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
763 " promoted BinEntry failed.");
769 SetEntryByNumber(binArea, lgth, group, elem);
776 * \brief Modifies the value of a given Header Entry (Dicom Element)
777 * when it exists. Create it when unexistant.
778 * @param Group Group number of the Entry
779 * @param Elem Element number of the Entry
780 * \return pointer to the modified/created SeqEntry (NULL when creation
783 SeqEntry* Document::ReplaceOrCreateByNumber(
788 DocEntry* a = GetDocEntryByNumber( group, elem);
791 a = NewSeqEntryByNumber(group, elem);
797 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
804 * \brief Set a new value if the invoked element exists
805 * Seems to be useless !!!
806 * @param value new element value
807 * @param group group number of the Entry
808 * @param elem element number of the Entry
811 bool Document::ReplaceIfExistByNumber(std::string const & value,
812 uint16_t group, uint16_t elem )
814 SetEntryByNumber(value, group, elem);
819 //-----------------------------------------------------------------------------
823 * \brief Checks if a given Dicom Element exists within the H table
824 * @param group Group number of the searched Dicom Element
825 * @param element Element number of the searched Dicom Element
826 * @return true is found
828 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
830 const std::string &key = DictEntry::TranslateToKey(group, element );
831 return TagHT.count(key);
835 * \brief Searches within Header Entries (Dicom Elements) parsed with
836 * the public and private dictionaries
837 * for the element value of a given tag.
838 * \warning Don't use any longer : use GetPubEntryByName
839 * @param tagName name of the searched element.
840 * @return Corresponding element value when it exists,
841 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
843 std::string Document::GetEntryByName(TagName const& tagName)
845 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
851 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
855 * \brief Searches within Header Entries (Dicom Elements) parsed with
856 * the public and private dictionaries
857 * for the element value representation of a given tag.
859 * Obtaining the VR (Value Representation) might be needed by caller
860 * to convert the string typed content to caller's native type
861 * (think of C++ vs Python). The VR is actually of a higher level
862 * of semantics than just the native C++ type.
863 * @param tagName name of the searched element.
864 * @return Corresponding element value representation when it exists,
865 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
867 std::string Document::GetEntryVRByName(TagName const& tagName)
869 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
870 if( dictEntry == NULL)
875 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
876 dictEntry->GetElement());
877 return elem->GetVR();
881 * \brief Searches within Header Entries (Dicom Elements) parsed with
882 * the public and private dictionaries
883 * for the element value representation of a given tag.
884 * @param group Group number of the searched tag.
885 * @param element Element number of the searched tag.
886 * @return Corresponding element value representation when it exists,
887 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
889 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
891 TagKey key = DictEntry::TranslateToKey(group, element);
892 /// \todo use map methods, instead of multimap JPR
893 if ( !TagHT.count(key))
898 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
902 * \brief Searches within Header Entries (Dicom Elements) parsed with
903 * the public and private dictionaries
904 * for the element value representation of a given tag..
906 * Obtaining the VR (Value Representation) might be needed by caller
907 * to convert the string typed content to caller's native type
908 * (think of C++ vs Python). The VR is actually of a higher level
909 * of semantics than just the native C++ type.
910 * @param group Group number of the searched tag.
911 * @param element Element number of the searched tag.
912 * @return Corresponding element value representation when it exists,
913 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
915 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
917 DocEntry* elem = GetDocEntryByNumber(group, element);
922 return elem->GetVR();
926 * \brief Searches within Header Entries (Dicom Elements) parsed with
927 * the public and private dictionaries
928 * for the value length of a given tag..
929 * @param group Group number of the searched tag.
930 * @param element Element number of the searched tag.
931 * @return Corresponding element length; -2 if not found
933 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
935 DocEntry* elem = GetDocEntryByNumber(group, element);
938 return -2; //magic number
940 return elem->GetLength();
943 * \brief Sets the value (string) of the Header Entry (Dicom Element)
944 * @param content string value of the Dicom Element
945 * @param tagName name of the searched Dicom Element.
946 * @return true when found
948 bool Document::SetEntryByName(std::string const & content,std::string const & tagName)
950 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
956 return SetEntryByNumber(content,dictEntry->GetGroup(),
957 dictEntry->GetElement());
961 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
962 * through it's (group, element) and modifies it's content with
964 * @param content new value (string) to substitute with
965 * @param group group number of the Dicom Element to modify
966 * @param element element number of the Dicom Element to modify
968 bool Document::SetEntryByNumber(std::string const& content,
975 ValEntry* valEntry = GetValEntryByNumber(group, element);
978 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
979 " ValEntry (try promotion first).");
982 // Non even content must be padded with a space (020H)...
983 std::string finalContent = content;
984 if( finalContent.length() % 2 )
986 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
988 valEntry->SetValue(finalContent);
990 // Integers have a special treatement for their length:
992 l = finalContent.length();
993 if ( l != 0) // To avoid to be cheated by 'zero length' integers
995 VRKey vr = valEntry->GetVR();
996 if( vr == "US" || vr == "SS" )
998 // for multivaluated items
999 c = Util::CountSubstring(content, "\\") + 1;
1002 else if( vr == "UL" || vr == "SL" )
1004 // for multivaluated items
1005 c = Util::CountSubstring(content, "\\") + 1;
1009 valEntry->SetLength(l);
1014 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
1015 * through it's (group, element) and modifies it's content with
1017 * @param content new value (void* -> uint8_t*) to substitute with
1018 * @param lgth new value length
1019 * @param group group number of the Dicom Element to modify
1020 * @param element element number of the Dicom Element to modify
1022 bool Document::SetEntryByNumber(uint8_t*content,
1027 (void)lgth; //not used
1028 TagKey key = DictEntry::TranslateToKey(group, element);
1029 if ( !TagHT.count(key))
1034 /* Hope Binary field length is *never* wrong
1035 if(lgth%2) // Non even length are padded with a space (020H).
1038 //content = content + '\0'; // fing a trick to enlarge a binary field?
1041 BinEntry* a = (BinEntry *)TagHT[key];
1042 a->SetBinArea(content);
1044 a->SetValue(GDCM_BINLOADED);
1050 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
1051 * in the PubDocEntrySet of this instance
1052 * through it's (group, element) and modifies it's length with
1054 * \warning Use with extreme caution.
1055 * @param l new length to substitute with
1056 * @param group group number of the Entry to modify
1057 * @param element element number of the Entry to modify
1058 * @return true on success, false otherwise.
1060 bool Document::SetEntryLengthByNumber(uint32_t l,
1064 /// \todo use map methods, instead of multimap JPR
1065 TagKey key = DictEntry::TranslateToKey(group, element);
1066 if ( !TagHT.count(key) )
1072 l++; // length must be even
1074 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1080 * \brief Gets (from Header) the offset of a 'non string' element value
1081 * (LoadElementValues has already be executed)
1082 * @param group group number of the Entry
1083 * @param elem element number of the Entry
1084 * @return File Offset of the Element Value
1086 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1088 DocEntry* entry = GetDocEntryByNumber(group, elem);
1091 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1094 return entry->GetOffset();
1098 * \brief Gets (from Header) a 'non string' element value
1099 * (LoadElementValues has already be executed)
1100 * @param group group number of the Entry
1101 * @param elem element number of the Entry
1102 * @return Pointer to the 'non string' area
1104 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1106 DocEntry* entry = GetDocEntryByNumber(group, elem);
1109 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1112 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1114 return binEntry->GetBinArea();
1121 * \brief Loads (from disk) the element content
1122 * when a string is not suitable
1123 * @param group group number of the Entry
1124 * @param elem element number of the Entry
1126 void* Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1128 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1133 size_t o =(size_t)docElement->GetOffset();
1134 fseek(Fp, o, SEEK_SET);
1135 size_t l = docElement->GetLength();
1136 uint8_t* a = new uint8_t[l];
1139 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1142 size_t l2 = fread(a, 1, l , Fp);
1148 /// \todo Drop any already existing void area! JPR
1149 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1151 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1156 * \brief Loads (from disk) the element content
1157 * when a string is not suitable
1158 * @param element Entry whose binArea is going to be loaded
1160 void* Document::LoadEntryBinArea(BinEntry* element)
1162 size_t o =(size_t)element->GetOffset();
1163 fseek(Fp, o, SEEK_SET);
1164 size_t l = element->GetLength();
1165 uint8_t* a = new uint8_t[l];
1168 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1171 element->SetBinArea((uint8_t*)a);
1172 /// \todo check the result
1173 size_t l2 = fread(a, 1, l , Fp);
1184 * \brief Sets a 'non string' value to a given Dicom Element
1185 * @param area area containing the 'non string' value
1186 * @param group Group number of the searched Dicom Element
1187 * @param element Element number of the searched Dicom Element
1190 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1194 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1195 if ( !currentEntry )
1199 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1201 binEntry->SetBinArea( area );
1208 * \brief Update the entries with the shadow dictionary.
1209 * Only non even entries are analyzed
1211 void Document::UpdateShaEntries()
1216 /// \todo TODO : still any use to explore recursively the whole structure?
1218 for(ListTag::iterator it=listEntries.begin();
1219 it!=listEntries.end();
1222 // Odd group => from public dictionary
1223 if((*it)->GetGroup()%2==0)
1226 // Peer group => search the corresponding dict entry
1228 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1232 if((*it)->IsImplicitVR())
1237 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1239 // Set the new entry and the new value
1240 (*it)->SetDictEntry(entry);
1241 CheckDocEntryVR(*it,vr);
1243 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1248 // Remove precedent value transformation
1249 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1256 * \brief Searches within the Header Entries for a Dicom Element of
1258 * @param tagName name of the searched Dicom Element.
1259 * @return Corresponding Dicom Element when it exists, and NULL
1262 DocEntry* Document::GetDocEntryByName(std::string const & tagName)
1264 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1270 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1274 * \brief retrieves a Dicom Element (the first one) using (group, element)
1275 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1276 * if you think it's NOT UNIQUE, check the count number
1277 * and use iterators to retrieve ALL the Dicoms Elements within
1278 * a given couple (group, element)
1279 * @param group Group number of the searched Dicom Element
1280 * @param element Element number of the searched Dicom Element
1283 DocEntry* Document::GetDocEntryByNumber(uint16_t group,
1286 TagKey key = DictEntry::TranslateToKey(group, element);
1287 if ( !TagHT.count(key))
1291 return TagHT.find(key)->second;
1295 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1296 * returns a result when the corresponding entry is of type
1298 * @return When present, the corresponding ValEntry.
1300 ValEntry* Document::GetValEntryByNumber(uint16_t group,
1303 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1304 if ( !currentEntry )
1308 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1312 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1318 * \brief Loads the element while preserving the current
1319 * underlying file position indicator as opposed to
1320 * to LoadDocEntry that modifies it.
1321 * @param entry Header Entry whose value shall be loaded.
1324 void Document::LoadDocEntrySafe(DocEntry * entry)
1326 long PositionOnEntry = ftell(Fp);
1327 LoadDocEntry(entry);
1328 fseek(Fp, PositionOnEntry, SEEK_SET);
1332 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1334 * @return The properly swaped 32 bits integer.
1336 uint32_t Document::SwapLong(uint32_t a)
1343 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1344 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1348 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1352 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1355 //std::cout << "swapCode= " << SwapCode << std::endl;
1356 dbg.Error(" Document::SwapLong : unset swap code");
1363 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1365 * @return The properly unswaped 32 bits integer.
1367 uint32_t Document::UnswapLong(uint32_t a)
1373 * \brief Swaps the bytes so they agree with the processor order
1374 * @return The properly swaped 16 bits integer.
1376 uint16_t Document::SwapShort(uint16_t a)
1378 if ( SwapCode == 4321 || SwapCode == 2143 )
1380 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1386 * \brief Unswaps the bytes so they agree with the processor order
1387 * @return The properly unswaped 16 bits integer.
1389 uint16_t Document::UnswapShort(uint16_t a)
1391 return SwapShort(a);
1394 //-----------------------------------------------------------------------------
1398 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1399 * @return length of the parsed set.
1401 void Document::ParseDES(DocEntrySet *set,
1406 DocEntry *newDocEntry = 0;
1410 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1414 newDocEntry = ReadNextDocEntry( );
1420 VRKey vr = newDocEntry->GetVR();
1424 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1426 /////////////////////// ValEntry
1427 ValEntry* newValEntry =
1428 new ValEntry( newDocEntry->GetDictEntry() );
1429 newValEntry->Copy( newDocEntry );
1431 // When "set" is a Document, then we are at the top of the
1432 // hierarchy and the Key is simply of the form ( group, elem )...
1433 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1436 newValEntry->SetKey( newValEntry->GetKey() );
1438 // ...but when "set" is a SQItem, we are inserting this new
1439 // valEntry in a sequence item. Hence the key has the
1440 // generalized form (refer to \ref BaseTagKey):
1441 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1443 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1444 + newValEntry->GetKey() );
1447 set->AddEntry( newValEntry );
1448 LoadDocEntry( newValEntry );
1449 if (newValEntry->IsItemDelimitor())
1453 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1460 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1462 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1463 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1464 "nor BinEntry. Probably unknown VR.");
1467 //////////////////// BinEntry or UNKOWN VR:
1468 BinEntry* newBinEntry =
1469 new BinEntry( newDocEntry->GetDictEntry() );
1470 newBinEntry->Copy( newDocEntry );
1472 // When "this" is a Document the Key is simply of the
1473 // form ( group, elem )...
1474 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1477 newBinEntry->SetKey( newBinEntry->GetKey() );
1479 // but when "this" is a SQItem, we are inserting this new
1480 // valEntry in a sequence item, and the kay has the
1481 // generalized form (refer to \ref BaseTagKey):
1482 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1484 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1485 + newBinEntry->GetKey() );
1488 set->AddEntry( newBinEntry );
1489 LoadDocEntry( newBinEntry );
1492 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1493 && ( newDocEntry->GetElement() == 0x0010 ) )
1495 if ( IsRLELossLessTransferSyntax() )
1497 long PositionOnEntry = ftell(Fp);
1498 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1500 fseek( Fp, PositionOnEntry, SEEK_SET );
1503 if ( IsJPEGTransferSyntax() )
1505 long PositionOnEntry = ftell(Fp);
1506 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1507 ComputeJPEGFragmentInfo();
1508 fseek( Fp, PositionOnEntry, SEEK_SET );
1512 // Just to make sure we are at the beginning of next entry.
1513 SkipToNextDocEntry(newDocEntry);
1518 unsigned long l = newDocEntry->GetReadLength();
1519 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1521 if ( l == 0xffffffff )
1530 // no other way to create it ...
1531 SeqEntry* newSeqEntry =
1532 new SeqEntry( newDocEntry->GetDictEntry() );
1533 newSeqEntry->Copy( newDocEntry );
1534 newSeqEntry->SetDelimitorMode( delim_mode );
1536 // At the top of the hierarchy, stands a Document. When "set"
1537 // is a Document, then we are building the first depth level.
1538 // Hence the SeqEntry we are building simply has a depth
1540 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1543 newSeqEntry->SetDepthLevel( 1 );
1544 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1546 // But when "set" is allready a SQItem, we are building a nested
1547 // sequence, and hence the depth level of the new SeqEntry
1548 // we are building, is one level deeper:
1549 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1551 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1552 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1553 + newSeqEntry->GetKey() );
1557 { // Don't try to parse zero-length sequences
1558 ParseSQ( newSeqEntry,
1559 newDocEntry->GetOffset(),
1562 set->AddEntry( newSeqEntry );
1563 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1573 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1574 * @return parsed length for this level
1576 void Document::ParseSQ( SeqEntry* seqEntry,
1577 long offset, long l_max, bool delim_mode)
1579 int SQItemNumber = 0;
1584 DocEntry* newDocEntry = ReadNextDocEntry();
1587 // FIXME Should warn user
1592 if ( newDocEntry->IsSequenceDelimitor() )
1594 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1598 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1603 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1604 std::ostringstream newBase;
1605 newBase << seqEntry->GetKey()
1609 itemSQ->SetBaseTagKey( newBase.str() );
1610 unsigned int l = newDocEntry->GetReadLength();
1612 if ( l == 0xffffffff )
1621 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1623 seqEntry->AddEntry( itemSQ, SQItemNumber );
1625 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1633 * \brief Loads the element content if its length doesn't exceed
1634 * the value specified with Document::SetMaxSizeLoadEntry()
1635 * @param entry Header Entry (Dicom Element) to be dealt with
1637 void Document::LoadDocEntry(DocEntry* entry)
1640 uint16_t group = entry->GetGroup();
1641 std::string vr = entry->GetVR();
1642 uint32_t length = entry->GetLength();
1644 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1646 // A SeQuence "contains" a set of Elements.
1647 // (fffe e000) tells us an Element is beginning
1648 // (fffe e00d) tells us an Element just ended
1649 // (fffe e0dd) tells us the current SeQuence just ended
1650 if( group == 0xfffe )
1652 // NO more value field for SQ !
1656 // When the length is zero things are easy:
1659 ((ValEntry *)entry)->SetValue("");
1663 // The elements whose length is bigger than the specified upper bound
1664 // are not loaded. Instead we leave a short notice of the offset of
1665 // the element content and it's length.
1667 std::ostringstream s;
1668 if (length > MaxSizeLoadEntry)
1670 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1672 //s << "gdcm::NotLoaded (BinEntry)";
1673 s << GDCM_NOTLOADED;
1674 s << " Address:" << (long)entry->GetOffset();
1675 s << " Length:" << entry->GetLength();
1676 s << " x(" << std::hex << entry->GetLength() << ")";
1677 binEntryPtr->SetValue(s.str());
1679 // Be carefull : a BinEntry IS_A ValEntry ...
1680 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1682 // s << "gdcm::NotLoaded. (ValEntry)";
1683 s << GDCM_NOTLOADED;
1684 s << " Address:" << (long)entry->GetOffset();
1685 s << " Length:" << entry->GetLength();
1686 s << " x(" << std::hex << entry->GetLength() << ")";
1687 valEntryPtr->SetValue(s.str());
1692 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1693 << "nor a ValEntry ?! Should never print that !" << std::endl;
1696 // to be sure we are at the end of the value ...
1697 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1701 // When we find a BinEntry not very much can be done :
1702 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1704 s << GDCM_BINLOADED;
1705 binEntryPtr->SetValue(s.str());
1706 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1710 /// \todo Any compacter code suggested (?)
1711 if ( IsDocEntryAnInteger(entry) )
1715 // When short integer(s) are expected, read and convert the following
1716 // n *two characters properly i.e. consider them as short integers as
1717 // opposed to strings.
1718 // Elements with Value Multiplicity > 1
1719 // contain a set of integers (not a single one)
1720 if (vr == "US" || vr == "SS")
1723 NewInt = ReadInt16();
1727 for (int i=1; i < nbInt; i++)
1730 NewInt = ReadInt16();
1735 // See above comment on multiple integers (mutatis mutandis).
1736 else if (vr == "UL" || vr == "SL")
1739 NewInt = ReadInt32();
1743 for (int i=1; i < nbInt; i++)
1746 NewInt = ReadInt32();
1751 #ifdef GDCM_NO_ANSI_STRING_STREAM
1752 s << std::ends; // to avoid oddities on Solaris
1753 #endif //GDCM_NO_ANSI_STRING_STREAM
1755 ((ValEntry *)entry)->SetValue(s.str());
1759 // We need an additional byte for storing \0 that is not on disk
1760 //std::string newValue(length,0);
1761 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1762 //rah !! I can't believe it could work, normally this is a const char* !!!
1763 char *str = new char[length+1];
1764 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1766 std::string newValue = str;
1768 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1770 if ( item_read != 1 )
1772 dbg.Verbose(1, "Document::LoadDocEntry",
1773 "unread element value");
1774 valEntry->SetValue(GDCM_UNREAD);
1780 // Because of correspondance with the VR dic
1781 valEntry->SetValue(newValue);
1785 valEntry->SetValue(newValue);
1790 dbg.Error(true, "Document::LoadDocEntry"
1791 "Should have a ValEntry, here !");
1797 * \brief Find the value Length of the passed Header Entry
1798 * @param entry Header Entry whose length of the value shall be loaded.
1800 void Document::FindDocEntryLength( DocEntry *entry )
1801 throw ( FormatError )
1803 uint16_t element = entry->GetElement();
1804 std::string vr = entry->GetVR();
1807 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1809 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1811 // The following reserved two bytes (see PS 3.5-2003, section
1812 // "7.1.2 Data element structure with explicit vr", p 27) must be
1813 // skipped before proceeding on reading the length on 4 bytes.
1814 fseek(Fp, 2L, SEEK_CUR);
1815 uint32_t length32 = ReadInt32();
1817 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1822 /// \todo rename that to FindDocEntryLengthOBOrOW since
1823 /// the above test is on both OB and OW...
1824 lengthOB = FindDocEntryLengthOB();
1826 catch ( FormatUnexpected )
1828 // Computing the length failed (this happens with broken
1829 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1830 // chance to get the pixels by deciding the element goes
1831 // until the end of the file. Hence we artificially fix the
1832 // the length and proceed.
1833 long currentPosition = ftell(Fp);
1834 fseek(Fp,0L,SEEK_END);
1835 long lengthUntilEOF = ftell(Fp) - currentPosition;
1836 fseek(Fp, currentPosition, SEEK_SET);
1837 entry->SetLength(lengthUntilEOF);
1840 entry->SetLength(lengthOB);
1843 FixDocEntryFoundLength(entry, length32);
1847 // Length is encoded on 2 bytes.
1848 length16 = ReadInt16();
1850 // We can tell the current file is encoded in big endian (like
1851 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1852 // and it's value is the one of the encoding of a big endian file.
1853 // In order to deal with such big endian encoded files, we have
1854 // (at least) two strategies:
1855 // * when we load the "Transfer Syntax" tag with value of big endian
1856 // encoding, we raise the proper flags. Then we wait for the end
1857 // of the META group (0x0002) among which is "Transfer Syntax",
1858 // before switching the swap code to big endian. We have to postpone
1859 // the switching of the swap code since the META group is fully encoded
1860 // in little endian, and big endian coding only starts at the next
1861 // group. The corresponding code can be hard to analyse and adds
1862 // many additional unnecessary tests for regular tags.
1863 // * the second strategy consists in waiting for trouble, that shall
1864 // appear when we find the first group with big endian encoding. This
1865 // is easy to detect since the length of a "Group Length" tag (the
1866 // ones with zero as element number) has to be of 4 (0x0004). When we
1867 // encounter 1024 (0x0400) chances are the encoding changed and we
1868 // found a group with big endian encoding.
1869 // We shall use this second strategy. In order to make sure that we
1870 // can interpret the presence of an apparently big endian encoded
1871 // length of a "Group Length" without committing a big mistake, we
1872 // add an additional check: we look in the already parsed elements
1873 // for the presence of a "Transfer Syntax" whose value has to be "big
1874 // endian encoding". When this is the case, chances are we have got our
1875 // hands on a big endian encoded file: we switch the swap code to
1876 // big endian and proceed...
1877 if ( element == 0x0000 && length16 == 0x0400 )
1879 if ( !IsExplicitVRBigEndianTransferSyntax() )
1881 throw FormatError( "Document::FindDocEntryLength()",
1882 " not explicit VR." );
1886 SwitchSwapToBigEndian();
1887 // Restore the unproperly loaded values i.e. the group, the element
1888 // and the dictionary entry depending on them.
1889 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1890 uint16_t correctElem = SwapShort( entry->GetElement() );
1891 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1895 // This correct tag is not in the dictionary. Create a new one.
1896 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1898 // FIXME this can create a memory leaks on the old entry that be
1899 // left unreferenced.
1900 entry->SetDictEntry( newTag );
1903 // Heuristic: well, some files are really ill-formed.
1904 if ( length16 == 0xffff)
1906 // 0xffff means that we deal with 'Unknown Length' Sequence
1909 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1914 // Either implicit VR or a non DICOM conformal (see note below) explicit
1915 // VR that ommited the VR of (at least) this element. Farts happen.
1916 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1917 // on Data elements "Implicit and Explicit VR Data Elements shall
1918 // not coexist in a Data Set and Data Sets nested within it".]
1919 // Length is on 4 bytes.
1921 FixDocEntryFoundLength( entry, ReadInt32() );
1927 * \brief Find the Value Representation of the current Dicom Element.
1930 void Document::FindDocEntryVR( DocEntry *entry )
1932 if ( Filetype != ExplicitVR )
1939 long positionOnEntry = ftell(Fp);
1940 // Warning: we believe this is explicit VR (Value Representation) because
1941 // we used a heuristic that found "UL" in the first tag. Alas this
1942 // doesn't guarantee that all the tags will be in explicit VR. In some
1943 // cases (see e-film filtered files) one finds implicit VR tags mixed
1944 // within an explicit VR file. Hence we make sure the present tag
1945 // is in explicit VR and try to fix things if it happens not to be
1948 fread (vr, (size_t)2,(size_t)1, Fp);
1951 if( !CheckDocEntryVR(entry, vr) )
1953 fseek(Fp, positionOnEntry, SEEK_SET);
1954 // When this element is known in the dictionary we shall use, e.g. for
1955 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1956 // dictionary entry. Still we have to flag the element as implicit since
1957 // we know now our assumption on expliciteness is not furfilled.
1959 if ( entry->IsVRUnknown() )
1961 entry->SetVR("Implicit");
1963 entry->SetImplicitVR();
1968 * \brief Check the correspondance between the VR of the header entry
1969 * and the taken VR. If they are different, the header entry is
1970 * updated with the new VR.
1971 * @param entry Header Entry to check
1972 * @param vr Dicom Value Representation
1973 * @return false if the VR is incorrect of if the VR isn't referenced
1974 * otherwise, it returns true
1976 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1979 bool realExplicit = true;
1981 // Assume we are reading a falsely explicit VR file i.e. we reached
1982 // a tag where we expect reading a VR but are in fact we read the
1983 // first to bytes of the length. Then we will interogate (through find)
1984 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1985 // both GCC and VC++ implementations of the STL map. Hence when the
1986 // expected VR read happens to be non-ascii characters we consider
1987 // we hit falsely explicit VR tag.
1989 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1991 realExplicit = false;
1994 // CLEANME searching the dicom_vr at each occurence is expensive.
1995 // PostPone this test in an optional integrity check at the end
1996 // of parsing or only in debug mode.
1997 if ( realExplicit && !Global::GetVR()->Count(vr) )
1999 realExplicit = false;
2002 if ( !realExplicit )
2004 // We thought this was explicit VR, but we end up with an
2005 // implicit VR tag. Let's backtrack.
2006 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
2007 entry->GetGroup(), entry->GetElement());
2008 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
2010 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2012 // Group length is UL !
2013 DictEntry* newEntry = NewVirtualDictEntry(
2014 entry->GetGroup(), entry->GetElement(),
2015 "UL", "FIXME", "Group Length");
2016 entry->SetDictEntry( newEntry );
2021 if ( entry->IsVRUnknown() )
2023 // When not a dictionary entry, we can safely overwrite the VR.
2024 if( entry->GetElement() == 0x0000 )
2026 // Group length is UL !
2034 else if ( entry->GetVR() != vr )
2036 // The VR present in the file and the dictionary disagree. We assume
2037 // the file writer knew best and use the VR of the file. Since it would
2038 // be unwise to overwrite the VR of a dictionary (since it would
2039 // compromise it's next user), we need to clone the actual DictEntry
2040 // and change the VR for the read one.
2041 DictEntry* newEntry = NewVirtualDictEntry(
2042 entry->GetGroup(), entry->GetElement(),
2043 vr, "FIXME", entry->GetName());
2044 entry->SetDictEntry(newEntry);
2051 * \brief Get the transformed value of the header entry. The VR value
2052 * is used to define the transformation to operate on the value
2053 * \warning NOT end user intended method !
2054 * @param entry entry to tranform
2055 * @return Transformed entry value
2057 std::string Document::GetDocEntryValue(DocEntry *entry)
2059 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2061 std::string val = ((ValEntry *)entry)->GetValue();
2062 std::string vr = entry->GetVR();
2063 uint32_t length = entry->GetLength();
2064 std::ostringstream s;
2067 // When short integer(s) are expected, read and convert the following
2068 // n * 2 bytes properly i.e. as a multivaluated strings
2069 // (each single value is separated fromthe next one by '\'
2070 // as usual for standard multivaluated filels
2071 // Elements with Value Multiplicity > 1
2072 // contain a set of short integers (not a single one)
2074 if( vr == "US" || vr == "SS" )
2079 for (int i=0; i < nbInt; i++)
2085 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2086 newInt16 = SwapShort( newInt16 );
2091 // When integer(s) are expected, read and convert the following
2092 // n * 4 bytes properly i.e. as a multivaluated strings
2093 // (each single value is separated fromthe next one by '\'
2094 // as usual for standard multivaluated filels
2095 // Elements with Value Multiplicity > 1
2096 // contain a set of integers (not a single one)
2097 else if( vr == "UL" || vr == "SL" )
2102 for (int i=0; i < nbInt; i++)
2108 newInt32 = ( val[4*i+0] & 0xFF )
2109 + (( val[4*i+1] & 0xFF ) << 8 )
2110 + (( val[4*i+2] & 0xFF ) << 16 )
2111 + (( val[4*i+3] & 0xFF ) << 24 );
2112 newInt32 = SwapLong( newInt32 );
2116 #ifdef GDCM_NO_ANSI_STRING_STREAM
2117 s << std::ends; // to avoid oddities on Solaris
2118 #endif //GDCM_NO_ANSI_STRING_STREAM
2122 return ((ValEntry *)entry)->GetValue();
2126 * \brief Get the reverse transformed value of the header entry. The VR
2127 * value is used to define the reverse transformation to operate on
2129 * \warning NOT end user intended method !
2130 * @param entry Entry to reverse transform
2131 * @return Reverse transformed entry value
2133 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2135 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2137 std::string vr = entry->GetVR();
2138 std::vector<std::string> tokens;
2139 std::ostringstream s;
2141 if ( vr == "US" || vr == "SS" )
2145 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2146 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2147 for (unsigned int i=0; i<tokens.size(); i++)
2149 newInt16 = atoi(tokens[i].c_str());
2150 s << ( newInt16 & 0xFF )
2151 << (( newInt16 >> 8 ) & 0xFF );
2155 if ( vr == "UL" || vr == "SL")
2159 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2160 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2161 for (unsigned int i=0; i<tokens.size();i++)
2163 newInt32 = atoi(tokens[i].c_str());
2164 s << (char)( newInt32 & 0xFF )
2165 << (char)(( newInt32 >> 8 ) & 0xFF )
2166 << (char)(( newInt32 >> 16 ) & 0xFF )
2167 << (char)(( newInt32 >> 24 ) & 0xFF );
2172 #ifdef GDCM_NO_ANSI_STRING_STREAM
2173 s << std::ends; // to avoid oddities on Solaris
2174 #endif //GDCM_NO_ANSI_STRING_STREAM
2178 return ((ValEntry *)entry)->GetValue();
2182 * \brief Skip a given Header Entry
2183 * \warning NOT end user intended method !
2184 * @param entry entry to skip
2186 void Document::SkipDocEntry(DocEntry *entry)
2188 SkipBytes(entry->GetLength());
2192 * \brief Skips to the begining of the next Header Entry
2193 * \warning NOT end user intended method !
2194 * @param entry entry to skip
2196 void Document::SkipToNextDocEntry(DocEntry *entry)
2198 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2199 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2203 * \brief When the length of an element value is obviously wrong (because
2204 * the parser went Jabberwocky) one can hope improving things by
2205 * applying some heuristics.
2206 * @param entry entry to check
2207 * @param foundLength fist assumption about length
2209 void Document::FixDocEntryFoundLength(DocEntry *entry,
2210 uint32_t foundLength)
2212 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2213 if ( foundLength == 0xffffffff)
2218 uint16_t gr = entry->GetGroup();
2219 uint16_t el = entry->GetElement();
2221 if ( foundLength % 2)
2223 std::ostringstream s;
2224 s << "Warning : Tag with uneven length "
2226 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2227 dbg.Verbose(0, s.str().c_str());
2230 //////// Fix for some naughty General Electric images.
2231 // Allthough not recent many such GE corrupted images are still present
2232 // on Creatis hard disks. Hence this fix shall remain when such images
2233 // are no longer in user (we are talking a few years, here)...
2234 // Note: XMedCom probably uses such a trick since it is able to read
2235 // those pesky GE images ...
2236 if ( foundLength == 13)
2238 // Only happens for this length !
2239 if ( entry->GetGroup() != 0x0008
2240 || ( entry->GetElement() != 0x0070
2241 && entry->GetElement() != 0x0080 ) )
2244 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2248 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2249 // Occurence of such images is quite low (unless one leaves close to a
2250 // 'Leonardo' source. Hence, one might consider commenting out the
2251 // following fix on efficiency reasons.
2252 else if ( entry->GetGroup() == 0x0009
2253 && ( entry->GetElement() == 0x1113
2254 || entry->GetElement() == 0x1114 ) )
2257 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2260 else if ( entry->GetVR() == "SQ" )
2262 foundLength = 0; // ReadLength is unchanged
2265 //////// We encountered a 'delimiter' element i.e. a tag of the form
2266 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2267 // taken into account.
2268 else if( entry->GetGroup() == 0xfffe )
2270 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2271 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2272 // causes extra troubles...
2273 if( entry->GetElement() != 0x0000 )
2279 entry->SetUsableLength(foundLength);
2283 * \brief Apply some heuristics to predict whether the considered
2284 * element value contains/represents an integer or not.
2285 * @param entry The element value on which to apply the predicate.
2286 * @return The result of the heuristical predicate.
2288 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2290 uint16_t element = entry->GetElement();
2291 uint16_t group = entry->GetGroup();
2292 std::string vr = entry->GetVR();
2293 uint32_t length = entry->GetLength();
2295 // When we have some semantics on the element we just read, and if we
2296 // a priori know we are dealing with an integer, then we shall be
2297 // able to swap it's element value properly.
2298 if ( element == 0 ) // This is the group length of the group
2306 // Allthough this should never happen, still some images have a
2307 // corrupted group length [e.g. have a glance at offset x(8336) of
2308 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2309 // Since for dicom compliant and well behaved headers, the present
2310 // test is useless (and might even look a bit paranoid), when we
2311 // encounter such an ill-formed image, we simply display a warning
2312 // message and proceed on parsing (while crossing fingers).
2313 std::ostringstream s;
2314 long filePosition = ftell(Fp);
2315 s << "Erroneous Group Length element length on : (" \
2316 << std::hex << group << " , " << element
2317 << ") -before- position x(" << filePosition << ")"
2318 << "lgt : " << length;
2319 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2323 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2332 * \brief Find the Length till the next sequence delimiter
2333 * \warning NOT end user intended method !
2337 uint32_t Document::FindDocEntryLengthOB()
2338 throw( FormatUnexpected )
2340 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2341 long positionOnEntry = ftell(Fp);
2342 bool foundSequenceDelimiter = false;
2343 uint32_t totalLength = 0;
2345 while ( !foundSequenceDelimiter )
2351 group = ReadInt16();
2354 catch ( FormatError )
2356 throw FormatError("Document::FindDocEntryLengthOB()",
2357 " group or element not present.");
2360 // We have to decount the group and element we just read
2363 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2365 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2366 "tag nor a Sequence delimiter tag.");
2367 fseek(Fp, positionOnEntry, SEEK_SET);
2368 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2369 "Neither an Item tag nor a Sequence "
2373 if ( elem == 0xe0dd )
2375 foundSequenceDelimiter = true;
2378 uint32_t itemLength = ReadInt32();
2379 // We add 4 bytes since we just read the ItemLength with ReadInt32
2380 totalLength += itemLength + 4;
2381 SkipBytes(itemLength);
2383 if ( foundSequenceDelimiter )
2388 fseek(Fp, positionOnEntry, SEEK_SET);
2393 * \brief Reads a supposed to be 16 Bits integer
2394 * (swaps it depending on processor endianity)
2395 * @return read value
2397 uint16_t Document::ReadInt16()
2398 throw( FormatError )
2401 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2402 if ( item_read != 1 )
2406 throw FormatError( "Document::ReadInt16()", " file error." );
2408 throw FormatError( "Document::ReadInt16()", "EOF." );
2415 * \brief Reads a supposed to be 32 Bits integer
2416 * (swaps it depending on processor endianity)
2417 * @return read value
2419 uint32_t Document::ReadInt32()
2420 throw( FormatError )
2423 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2424 if ( item_read != 1 )
2428 throw FormatError( "Document::ReadInt16()", " file error." );
2430 throw FormatError( "Document::ReadInt32()", "EOF." );
2437 * \brief skips bytes inside the source file
2438 * \warning NOT end user intended method !
2441 void Document::SkipBytes(uint32_t nBytes)
2443 //FIXME don't dump the returned value
2444 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2448 * \brief Loads all the needed Dictionaries
2449 * \warning NOT end user intended method !
2451 void Document::Initialise()
2453 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2455 RLEInfo = new RLEFramesInfo;
2456 JPEGInfo = new JPEGFragmentsInfo;
2460 * \brief Discover what the swap code is (among little endian, big endian,
2461 * bad little endian, bad big endian).
2463 * @return false when we are absolutely sure
2464 * it's neither ACR-NEMA nor DICOM
2465 * true when we hope ours assuptions are OK
2467 bool Document::CheckSwap()
2469 // The only guaranted way of finding the swap code is to find a
2470 // group tag since we know it's length has to be of four bytes i.e.
2471 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2472 // occurs when we can't find such group...
2474 uint32_t x = 4; // x : for ntohs
2475 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2479 char deb[HEADER_LENGTH_TO_READ];
2481 // First, compare HostByteOrder and NetworkByteOrder in order to
2482 // determine if we shall need to swap bytes (i.e. the Endian type).
2483 if ( x == ntohs(x) )
2492 // The easiest case is the one of a DICOM header, since it possesses a
2493 // file preamble where it suffice to look for the string "DICM".
2494 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2495 (void)lgrLue; //FIXME not used
2497 char *entCur = deb + 128;
2498 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2500 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2502 // Next, determine the value representation (VR). Let's skip to the
2503 // first element (0002, 0000) and check there if we find "UL"
2504 // - or "OB" if the 1st one is (0002,0001) -,
2505 // in which case we (almost) know it is explicit VR.
2506 // WARNING: if it happens to be implicit VR then what we will read
2507 // is the length of the group. If this ascii representation of this
2508 // length happens to be "UL" then we shall believe it is explicit VR.
2509 // FIXME: in order to fix the above warning, we could read the next
2510 // element value (or a couple of elements values) in order to make
2511 // sure we are not commiting a big mistake.
2512 // We need to skip :
2513 // * the 128 bytes of File Preamble (often padded with zeroes),
2514 // * the 4 bytes of "DICM" string,
2515 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2516 // i.e. a total of 136 bytes.
2520 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2521 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2522 // *Implicit* VR. -and it is !-
2524 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2525 memcmp(entCur, "OB", (size_t)2) == 0 ||
2526 memcmp(entCur, "UI", (size_t)2) == 0 ||
2527 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2528 // when Write DCM *adds*
2530 // Use Document::dicom_vr to test all the possibilities
2531 // instead of just checking for UL, OB and UI !? group 0000
2533 Filetype = ExplicitVR;
2534 dbg.Verbose(1, "Document::CheckSwap:",
2535 "explicit Value Representation");
2539 Filetype = ImplicitVR;
2540 dbg.Verbose(1, "Document::CheckSwap:",
2541 "not an explicit Value Representation");
2547 dbg.Verbose(1, "Document::CheckSwap:",
2548 "HostByteOrder != NetworkByteOrder");
2553 dbg.Verbose(1, "Document::CheckSwap:",
2554 "HostByteOrder = NetworkByteOrder");
2557 // Position the file position indicator at first tag (i.e.
2558 // after the file preamble and the "DICM" string).
2560 fseek (Fp, 132L, SEEK_SET);
2564 // Alas, this is not a DicomV3 file and whatever happens there is no file
2565 // preamble. We can reset the file position indicator to where the data
2566 // is (i.e. the beginning of the file).
2567 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2570 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2571 // By clean we mean that the length of the first tag is written down.
2572 // If this is the case and since the length of the first group HAS to be
2573 // four (bytes), then determining the proper swap code is straightforward.
2576 // We assume the array of char we are considering contains the binary
2577 // representation of a 32 bits integer. Hence the following dirty
2579 s32 = *((uint32_t *)(entCur));
2600 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2601 // It is time for despaired wild guesses.
2602 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2603 // i.e. the 'group length' element is not present :
2605 // check the supposed to be 'group number'
2606 // 0x0002 or 0x0004 or 0x0008
2607 // to determine ' SwapCode' value .
2608 // Only 0 or 4321 will be possible
2609 // (no oportunity to check for the formerly well known
2610 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2611 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2612 // the file IS NOT ACR-NEMA nor DICOM V3
2613 // Find a trick to tell it the caller...
2615 s16 = *((uint16_t *)(deb));
2632 dbg.Verbose(0, "Document::CheckSwap:",
2633 "ACR/NEMA unfound swap info (Really hopeless !)");
2637 // Then the only info we have is the net2host one.
2647 * \brief Restore the unproperly loaded values i.e. the group, the element
2648 * and the dictionary entry depending on them.
2650 void Document::SwitchSwapToBigEndian()
2652 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2653 "Switching to BigEndian mode.");
2654 if ( SwapCode == 0 )
2658 else if ( SwapCode == 4321 )
2662 else if ( SwapCode == 3412 )
2666 else if ( SwapCode == 2143 )
2673 * \brief during parsing, Header Elements too long are not loaded in memory
2676 void Document::SetMaxSizeLoadEntry(long newSize)
2682 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2684 MaxSizeLoadEntry = 0xffffffff;
2687 MaxSizeLoadEntry = newSize;
2692 * \brief Header Elements too long will not be printed
2693 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2696 void Document::SetMaxSizePrintEntry(long newSize)
2698 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2703 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2705 MaxSizePrintEntry = 0xffffffff;
2708 MaxSizePrintEntry = newSize;
2714 * \brief Read the next tag but WITHOUT loading it's value
2715 * (read the 'Group Number', the 'Element Number',
2716 * gets the Dict Entry
2717 * gets the VR, gets the length, gets the offset value)
2718 * @return On succes the newly created DocEntry, NULL on failure.
2720 DocEntry* Document::ReadNextDocEntry()
2727 group = ReadInt16();
2730 catch ( FormatError e )
2732 // We reached the EOF (or an error occured) therefore
2733 // header parsing has to be considered as finished.
2738 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2739 FindDocEntryVR(newEntry);
2743 FindDocEntryLength(newEntry);
2745 catch ( FormatError e )
2753 newEntry->SetOffset(ftell(Fp));
2760 * \brief Generate a free TagKey i.e. a TagKey that is not present
2761 * in the TagHt dictionary.
2762 * @param group The generated tag must belong to this group.
2763 * @return The element of tag with given group which is fee.
2765 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2767 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2769 TagKey key = DictEntry::TranslateToKey(group, elem);
2770 if (TagHT.count(key) == 0)
2779 * \brief Assuming the internal file pointer \ref Document::Fp
2780 * is placed at the beginning of a tag check whether this
2781 * tag is (TestGroup, TestElement).
2782 * \warning On success the internal file pointer \ref Document::Fp
2783 * is modified to point after the tag.
2784 * On failure (i.e. when the tag wasn't the expected tag
2785 * (TestGroup, TestElement) the internal file pointer
2786 * \ref Document::Fp is restored to it's original position.
2787 * @param testGroup The expected group of the tag.
2788 * @param testElement The expected Element of the tag.
2789 * @return True on success, false otherwise.
2791 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2793 long positionOnEntry = ftell(Fp);
2794 long currentPosition = ftell(Fp); // On debugging purposes
2796 //// Read the Item Tag group and element, and make
2797 // sure they are what we expected:
2798 uint16_t itemTagGroup = ReadInt16();
2799 uint16_t itemTagElement = ReadInt16();
2800 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2802 std::ostringstream s;
2803 s << " We should have found tag (";
2804 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2805 s << " but instead we encountered tag (";
2806 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2808 s << " at address: " << (unsigned)currentPosition << std::endl;
2809 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2810 dbg.Verbose(0, s.str().c_str());
2811 fseek(Fp, positionOnEntry, SEEK_SET);
2819 * \brief Assuming the internal file pointer \ref Document::Fp
2820 * is placed at the beginning of a tag (TestGroup, TestElement),
2821 * read the length associated to the Tag.
2822 * \warning On success the internal file pointer \ref Document::Fp
2823 * is modified to point after the tag and it's length.
2824 * On failure (i.e. when the tag wasn't the expected tag
2825 * (TestGroup, TestElement) the internal file pointer
2826 * \ref Document::Fp is restored to it's original position.
2827 * @param testGroup The expected group of the tag.
2828 * @param testElement The expected Element of the tag.
2829 * @return On success returns the length associated to the tag. On failure
2832 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2834 long positionOnEntry = ftell(Fp);
2835 (void)positionOnEntry;
2837 if ( !ReadTag(testGroup, testElement) )
2842 //// Then read the associated Item Length
2843 long currentPosition = ftell(Fp);
2844 uint32_t itemLength = ReadInt32();
2846 std::ostringstream s;
2847 s << "Basic Item Length is: "
2848 << itemLength << std::endl;
2849 s << " at address: " << (unsigned)currentPosition << std::endl;
2850 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2856 * \brief When parsing the Pixel Data of an encapsulated file, read
2857 * the basic offset table (when present, and BTW dump it).
2859 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2861 //// Read the Basic Offset Table Item Tag length...
2862 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2864 // When present, read the basic offset table itself.
2865 // Notes: - since the presence of this basic offset table is optional
2866 // we can't rely on it for the implementation, and we will simply
2867 // trash it's content (when present).
2868 // - still, when present, we could add some further checks on the
2869 // lengths, but we won't bother with such fuses for the time being.
2870 if ( itemLength != 0 )
2872 char* basicOffsetTableItemValue = new char[itemLength + 1];
2873 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2876 for (unsigned int i=0; i < itemLength; i += 4 )
2878 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2880 std::ostringstream s;
2881 s << " Read one length: ";
2882 s << std::hex << individualLength << std::endl;
2884 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2889 delete[] basicOffsetTableItemValue;
2894 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2895 * Compute the RLE extra information and store it in \ref RLEInfo
2896 * for later pixel retrieval usage.
2898 void Document::ComputeRLEInfo()
2900 if ( ! IsRLELossLessTransferSyntax() )
2905 // Encoded pixel data: for the time being we are only concerned with
2906 // Jpeg or RLE Pixel data encodings.
2907 // As stated in PS 3.5-2003, section 8.2 p44:
2908 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2909 // value representation OB is used".
2910 // Hence we expect an OB value representation. Concerning OB VR,
2911 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2912 // "For the Value Representations OB and OW, the encoding shall meet the
2913 // following specifications depending on the Data element tag:"
2915 // - the first item in the sequence of items before the encoded pixel
2916 // data stream shall be basic offset table item. The basic offset table
2917 // item value, however, is not required to be present"
2919 ReadAndSkipEncapsulatedBasicOffsetTable();
2921 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2922 // Loop on the individual frame[s] and store the information
2923 // on the RLE fragments in a RLEFramesInfo.
2924 // Note: - when only a single frame is present, this is a
2926 // - when more than one frame are present, then we are in
2927 // the case of a multi-frame image.
2929 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2931 // Parse the RLE Header and store the corresponding RLE Segment
2932 // Offset Table information on fragments of this current Frame.
2933 // Note that the fragment pixels themselves are not loaded
2934 // (but just skipped).
2935 long frameOffset = ftell(Fp);
2937 uint32_t nbRleSegments = ReadInt32();
2939 uint32_t rleSegmentOffsetTable[15];
2940 for( int k = 1; k <= 15; k++ )
2942 rleSegmentOffsetTable[k] = ReadInt32();
2945 // Deduce from both the RLE Header and the frameLength the
2946 // fragment length, and again store this info in a
2948 long rleSegmentLength[15];
2949 // skipping (not reading) RLE Segments
2950 if ( nbRleSegments > 1)
2952 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2954 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2955 - rleSegmentOffsetTable[k];
2956 SkipBytes(rleSegmentLength[k]);
2960 rleSegmentLength[nbRleSegments] = frameLength
2961 - rleSegmentOffsetTable[nbRleSegments];
2962 SkipBytes(rleSegmentLength[nbRleSegments]);
2964 // Store the collected info
2965 RLEFrame* newFrameInfo = new RLEFrame;
2966 newFrameInfo->NumberFragments = nbRleSegments;
2967 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2969 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2970 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2972 RLEInfo->Frames.push_back( newFrameInfo );
2975 // Make sure that at the end of the item we encounter a 'Sequence
2977 if ( !ReadTag(0xfffe, 0xe0dd) )
2979 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2980 dbg.Verbose(0, " item at end of RLE item sequence");
2985 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2986 * Compute the jpeg extra information (fragment[s] offset[s] and
2987 * length) and store it[them] in \ref JPEGInfo for later pixel
2990 void Document::ComputeJPEGFragmentInfo()
2992 // If you need to, look for comments of ComputeRLEInfo().
2993 if ( ! IsJPEGTransferSyntax() )
2998 ReadAndSkipEncapsulatedBasicOffsetTable();
3000 // Loop on the fragments[s] and store the parsed information in a
3002 long fragmentLength;
3003 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3005 long fragmentOffset = ftell(Fp);
3007 // Store the collected info
3008 JPEGFragment* newFragment = new JPEGFragment;
3009 newFragment->Offset = fragmentOffset;
3010 newFragment->Length = fragmentLength;
3011 JPEGInfo->Fragments.push_back( newFragment );
3013 SkipBytes( fragmentLength );
3016 // Make sure that at the end of the item we encounter a 'Sequence
3018 if ( !ReadTag(0xfffe, 0xe0dd) )
3020 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3021 dbg.Verbose(0, " item at end of JPEG item sequence");
3026 * \brief Walk recursively the given \ref DocEntrySet, and feed
3027 * the given hash table (\ref TagDocEntryHT) with all the
3028 * \ref DocEntry (Dicom entries) encountered.
3029 * This method does the job for \ref BuildFlatHashTable.
3030 * @param builtHT Where to collect all the \ref DocEntry encountered
3031 * when recursively walking the given set.
3032 * @param set The structure to be traversed (recursively).
3034 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3037 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3039 TagDocEntryHT* currentHT = elementSet->GetTagHT();
3040 for( TagDocEntryHT::const_iterator i = currentHT->begin();
3041 i != currentHT->end();
3044 DocEntry* entry = i->second;
3045 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3047 ListSQItem& items = seqEntry->GetSQItems();
3048 for( ListSQItem::const_iterator item = items.begin();
3049 item != items.end();
3052 BuildFlatHashTableRecurse( builtHT, *item );
3056 builtHT[entry->GetKey()] = entry;
3061 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3063 ListDocEntry& currentList = SQItemSet->GetDocEntries();
3064 for (ListDocEntry::iterator i = currentList.begin();
3065 i != currentList.end();
3068 DocEntry* entry = *i;
3069 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3071 ListSQItem& items = seqEntry->GetSQItems();
3072 for( ListSQItem::const_iterator item = items.begin();
3073 item != items.end();
3076 BuildFlatHashTableRecurse( builtHT, *item );
3080 builtHT[entry->GetKey()] = entry;
3087 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3090 * The structure used by a Document (through \ref ElementSet),
3091 * in order to old the parsed entries of a Dicom header, is a recursive
3092 * one. This is due to the fact that the sequences (when present)
3093 * can be nested. Additionaly, the sequence items (represented in
3094 * gdcm as \ref SQItem) add an extra complexity to the data
3095 * structure. Hence, a gdcm user whishing to visit all the entries of
3096 * a Dicom header will need to dig in the gdcm internals (which
3097 * implies exposing all the internal data structures to the API).
3098 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3099 * recursively builds a temporary hash table, which holds all the
3100 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3102 * \warning Of course there is NO integrity constrain between the
3103 * returned \ref TagDocEntryHT and the \ref ElementSet used
3104 * to build it. Hence if the underlying \ref ElementSet is
3105 * altered, then it is the caller responsability to invoke
3106 * \ref BuildFlatHashTable again...
3107 * @return The flat std::map<> we juste build.
3109 TagDocEntryHT* Document::BuildFlatHashTable()
3111 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3112 BuildFlatHashTableRecurse( *FlatHT, this );
3119 * \brief Compares two documents, according to \ref DicomDir rules
3120 * \warning Does NOT work with ACR-NEMA files
3121 * \todo Find a trick to solve the pb (use RET fields ?)
3123 * @return true if 'smaller'
3125 bool Document::operator<(Document &document)
3128 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3129 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3141 s1 = GetEntryByNumber(0x0010,0x0020);
3142 s2 = document.GetEntryByNumber(0x0010,0x0020);
3153 // Study Instance UID
3154 s1 = GetEntryByNumber(0x0020,0x000d);
3155 s2 = document.GetEntryByNumber(0x0020,0x000d);
3166 // Serie Instance UID
3167 s1 = GetEntryByNumber(0x0020,0x000e);
3168 s2 = document.GetEntryByNumber(0x0020,0x000e);
3183 } // end namespace gdcm
3185 //-----------------------------------------------------------------------------