1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/10/12 17:31:56 $
7 Version: $Revision: 1.104 $
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 return ((BinEntry *)entry)->GetBinArea();
1116 * \brief Loads (from disk) the element content
1117 * when a string is not suitable
1118 * @param group group number of the Entry
1119 * @param elem element number of the Entry
1121 void* Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1123 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1128 size_t o =(size_t)docElement->GetOffset();
1129 fseek(Fp, o, SEEK_SET);
1130 size_t l = docElement->GetLength();
1131 uint8_t* a = new uint8_t[l];
1134 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1137 size_t l2 = fread(a, 1, l , Fp);
1143 /// \todo Drop any already existing void area! JPR
1144 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1146 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1151 * \brief Loads (from disk) the element content
1152 * when a string is not suitable
1153 * @param element Entry whose binArea is going to be loaded
1155 void* Document::LoadEntryBinArea(BinEntry* element)
1157 size_t o =(size_t)element->GetOffset();
1158 fseek(Fp, o, SEEK_SET);
1159 size_t l = element->GetLength();
1160 uint8_t* a = new uint8_t[l];
1163 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1166 element->SetBinArea((uint8_t*)a);
1167 /// \todo check the result
1168 size_t l2 = fread(a, 1, l , Fp);
1179 * \brief Sets a 'non string' value to a given Dicom Element
1180 * @param area area containing the 'non string' value
1181 * @param group Group number of the searched Dicom Element
1182 * @param element Element number of the searched Dicom Element
1185 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1189 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1190 if ( !currentEntry )
1194 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1196 binEntry->SetBinArea( area );
1203 * \brief Update the entries with the shadow dictionary.
1204 * Only non even entries are analyzed
1206 void Document::UpdateShaEntries()
1211 /// \todo TODO : still any use to explore recursively the whole structure?
1213 for(ListTag::iterator it=listEntries.begin();
1214 it!=listEntries.end();
1217 // Odd group => from public dictionary
1218 if((*it)->GetGroup()%2==0)
1221 // Peer group => search the corresponding dict entry
1223 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1227 if((*it)->IsImplicitVR())
1232 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1234 // Set the new entry and the new value
1235 (*it)->SetDictEntry(entry);
1236 CheckDocEntryVR(*it,vr);
1238 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1243 // Remove precedent value transformation
1244 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1251 * \brief Searches within the Header Entries for a Dicom Element of
1253 * @param tagName name of the searched Dicom Element.
1254 * @return Corresponding Dicom Element when it exists, and NULL
1257 DocEntry* Document::GetDocEntryByName(std::string const & tagName)
1259 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1265 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1269 * \brief retrieves a Dicom Element (the first one) using (group, element)
1270 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1271 * if you think it's NOT UNIQUE, check the count number
1272 * and use iterators to retrieve ALL the Dicoms Elements within
1273 * a given couple (group, element)
1274 * @param group Group number of the searched Dicom Element
1275 * @param element Element number of the searched Dicom Element
1278 DocEntry* Document::GetDocEntryByNumber(uint16_t group,
1281 TagKey key = DictEntry::TranslateToKey(group, element);
1282 if ( !TagHT.count(key))
1286 return TagHT.find(key)->second;
1290 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1291 * returns a result when the corresponding entry is of type
1293 * @return When present, the corresponding ValEntry.
1295 ValEntry* Document::GetValEntryByNumber(uint16_t group,
1298 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1299 if ( !currentEntry )
1303 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1307 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1313 * \brief Loads the element while preserving the current
1314 * underlying file position indicator as opposed to
1315 * to LoadDocEntry that modifies it.
1316 * @param entry Header Entry whose value shall be loaded.
1319 void Document::LoadDocEntrySafe(DocEntry * entry)
1321 long PositionOnEntry = ftell(Fp);
1322 LoadDocEntry(entry);
1323 fseek(Fp, PositionOnEntry, SEEK_SET);
1327 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1329 * @return The properly swaped 32 bits integer.
1331 uint32_t Document::SwapLong(uint32_t a)
1338 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1339 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1343 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1347 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1350 //std::cout << "swapCode= " << SwapCode << std::endl;
1351 dbg.Error(" Document::SwapLong : unset swap code");
1358 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1360 * @return The properly unswaped 32 bits integer.
1362 uint32_t Document::UnswapLong(uint32_t a)
1368 * \brief Swaps the bytes so they agree with the processor order
1369 * @return The properly swaped 16 bits integer.
1371 uint16_t Document::SwapShort(uint16_t a)
1373 if ( SwapCode == 4321 || SwapCode == 2143 )
1375 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1381 * \brief Unswaps the bytes so they agree with the processor order
1382 * @return The properly unswaped 16 bits integer.
1384 uint16_t Document::UnswapShort(uint16_t a)
1386 return SwapShort(a);
1389 //-----------------------------------------------------------------------------
1393 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1394 * @return length of the parsed set.
1396 void Document::ParseDES(DocEntrySet *set,
1401 DocEntry *newDocEntry = 0;
1405 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1409 newDocEntry = ReadNextDocEntry( );
1415 VRKey vr = newDocEntry->GetVR();
1419 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1421 /////////////////////// ValEntry
1422 ValEntry* newValEntry =
1423 new ValEntry( newDocEntry->GetDictEntry() );
1424 newValEntry->Copy( newDocEntry );
1426 // When "set" is a Document, then we are at the top of the
1427 // hierarchy and the Key is simply of the form ( group, elem )...
1428 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1431 newValEntry->SetKey( newValEntry->GetKey() );
1433 // ...but when "set" is a SQItem, we are inserting this new
1434 // valEntry in a sequence item. Hence the key has the
1435 // generalized form (refer to \ref BaseTagKey):
1436 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1438 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1439 + newValEntry->GetKey() );
1442 set->AddEntry( newValEntry );
1443 LoadDocEntry( newValEntry );
1444 if (newValEntry->IsItemDelimitor())
1448 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1455 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1457 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1458 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1459 "nor BinEntry. Probably unknown VR.");
1462 //////////////////// BinEntry or UNKOWN VR:
1463 BinEntry* newBinEntry =
1464 new BinEntry( newDocEntry->GetDictEntry() );
1465 newBinEntry->Copy( newDocEntry );
1467 // When "this" is a Document the Key is simply of the
1468 // form ( group, elem )...
1469 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1472 newBinEntry->SetKey( newBinEntry->GetKey() );
1474 // but when "this" is a SQItem, we are inserting this new
1475 // valEntry in a sequence item, and the kay has the
1476 // generalized form (refer to \ref BaseTagKey):
1477 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1479 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1480 + newBinEntry->GetKey() );
1483 set->AddEntry( newBinEntry );
1484 LoadDocEntry( newBinEntry );
1487 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1488 && ( newDocEntry->GetElement() == 0x0010 ) )
1490 if ( IsRLELossLessTransferSyntax() )
1492 long PositionOnEntry = ftell(Fp);
1493 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1495 fseek( Fp, PositionOnEntry, SEEK_SET );
1498 if ( IsJPEGTransferSyntax() )
1500 long PositionOnEntry = ftell(Fp);
1501 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1502 ComputeJPEGFragmentInfo();
1503 fseek( Fp, PositionOnEntry, SEEK_SET );
1507 // Just to make sure we are at the beginning of next entry.
1508 SkipToNextDocEntry(newDocEntry);
1513 unsigned long l = newDocEntry->GetReadLength();
1514 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1516 if ( l == 0xffffffff )
1525 // no other way to create it ...
1526 SeqEntry* newSeqEntry =
1527 new SeqEntry( newDocEntry->GetDictEntry() );
1528 newSeqEntry->Copy( newDocEntry );
1529 newSeqEntry->SetDelimitorMode( delim_mode );
1531 // At the top of the hierarchy, stands a Document. When "set"
1532 // is a Document, then we are building the first depth level.
1533 // Hence the SeqEntry we are building simply has a depth
1535 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1538 newSeqEntry->SetDepthLevel( 1 );
1539 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1541 // But when "set" is allready a SQItem, we are building a nested
1542 // sequence, and hence the depth level of the new SeqEntry
1543 // we are building, is one level deeper:
1544 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1546 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1547 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1548 + newSeqEntry->GetKey() );
1552 { // Don't try to parse zero-length sequences
1553 ParseSQ( newSeqEntry,
1554 newDocEntry->GetOffset(),
1557 set->AddEntry( newSeqEntry );
1558 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1568 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1569 * @return parsed length for this level
1571 void Document::ParseSQ( SeqEntry* seqEntry,
1572 long offset, long l_max, bool delim_mode)
1574 int SQItemNumber = 0;
1579 DocEntry* newDocEntry = ReadNextDocEntry();
1582 // FIXME Should warn user
1587 if ( newDocEntry->IsSequenceDelimitor() )
1589 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1593 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1598 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1599 std::ostringstream newBase;
1600 newBase << seqEntry->GetKey()
1604 itemSQ->SetBaseTagKey( newBase.str() );
1605 unsigned int l = newDocEntry->GetReadLength();
1607 if ( l == 0xffffffff )
1616 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1618 seqEntry->AddEntry( itemSQ, SQItemNumber );
1620 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1628 * \brief Loads the element content if its length doesn't exceed
1629 * the value specified with Document::SetMaxSizeLoadEntry()
1630 * @param entry Header Entry (Dicom Element) to be dealt with
1632 void Document::LoadDocEntry(DocEntry* entry)
1635 uint16_t group = entry->GetGroup();
1636 std::string vr = entry->GetVR();
1637 uint32_t length = entry->GetLength();
1639 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1641 // A SeQuence "contains" a set of Elements.
1642 // (fffe e000) tells us an Element is beginning
1643 // (fffe e00d) tells us an Element just ended
1644 // (fffe e0dd) tells us the current SeQuence just ended
1645 if( group == 0xfffe )
1647 // NO more value field for SQ !
1651 // When the length is zero things are easy:
1654 ((ValEntry *)entry)->SetValue("");
1658 // The elements whose length is bigger than the specified upper bound
1659 // are not loaded. Instead we leave a short notice of the offset of
1660 // the element content and it's length.
1662 std::ostringstream s;
1663 if (length > MaxSizeLoadEntry)
1665 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1667 //s << "gdcm::NotLoaded (BinEntry)";
1668 s << GDCM_NOTLOADED;
1669 s << " Address:" << (long)entry->GetOffset();
1670 s << " Length:" << entry->GetLength();
1671 s << " x(" << std::hex << entry->GetLength() << ")";
1672 binEntryPtr->SetValue(s.str());
1674 // Be carefull : a BinEntry IS_A ValEntry ...
1675 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1677 // s << "gdcm::NotLoaded. (ValEntry)";
1678 s << GDCM_NOTLOADED;
1679 s << " Address:" << (long)entry->GetOffset();
1680 s << " Length:" << entry->GetLength();
1681 s << " x(" << std::hex << entry->GetLength() << ")";
1682 valEntryPtr->SetValue(s.str());
1687 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1688 << "nor a ValEntry ?! Should never print that !" << std::endl;
1691 // to be sure we are at the end of the value ...
1692 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1696 // When we find a BinEntry not very much can be done :
1697 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1699 s << GDCM_BINLOADED;
1700 binEntryPtr->SetValue(s.str());
1701 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1705 /// \todo Any compacter code suggested (?)
1706 if ( IsDocEntryAnInteger(entry) )
1710 // When short integer(s) are expected, read and convert the following
1711 // n *two characters properly i.e. consider them as short integers as
1712 // opposed to strings.
1713 // Elements with Value Multiplicity > 1
1714 // contain a set of integers (not a single one)
1715 if (vr == "US" || vr == "SS")
1718 NewInt = ReadInt16();
1722 for (int i=1; i < nbInt; i++)
1725 NewInt = ReadInt16();
1730 // See above comment on multiple integers (mutatis mutandis).
1731 else if (vr == "UL" || vr == "SL")
1734 NewInt = ReadInt32();
1738 for (int i=1; i < nbInt; i++)
1741 NewInt = ReadInt32();
1746 #ifdef GDCM_NO_ANSI_STRING_STREAM
1747 s << std::ends; // to avoid oddities on Solaris
1748 #endif //GDCM_NO_ANSI_STRING_STREAM
1750 ((ValEntry *)entry)->SetValue(s.str());
1754 // We need an additional byte for storing \0 that is not on disk
1755 //std::string newValue(length,0);
1756 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1757 //rah !! I can't believe it could work, normally this is a const char* !!!
1758 char *str = new char[length+1];
1759 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1761 std::string newValue = str;
1763 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1765 if ( item_read != 1 )
1767 dbg.Verbose(1, "Document::LoadDocEntry",
1768 "unread element value");
1769 valEntry->SetValue(GDCM_UNREAD);
1775 // Because of correspondance with the VR dic
1776 valEntry->SetValue(newValue);
1780 valEntry->SetValue(newValue);
1785 dbg.Error(true, "Document::LoadDocEntry"
1786 "Should have a ValEntry, here !");
1792 * \brief Find the value Length of the passed Header Entry
1793 * @param entry Header Entry whose length of the value shall be loaded.
1795 void Document::FindDocEntryLength( DocEntry *entry )
1796 throw ( FormatError )
1798 uint16_t element = entry->GetElement();
1799 std::string vr = entry->GetVR();
1802 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1804 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1806 // The following reserved two bytes (see PS 3.5-2003, section
1807 // "7.1.2 Data element structure with explicit vr", p 27) must be
1808 // skipped before proceeding on reading the length on 4 bytes.
1809 fseek(Fp, 2L, SEEK_CUR);
1810 uint32_t length32 = ReadInt32();
1812 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1817 /// \todo rename that to FindDocEntryLengthOBOrOW since
1818 /// the above test is on both OB and OW...
1819 lengthOB = FindDocEntryLengthOB();
1821 catch ( FormatUnexpected )
1823 // Computing the length failed (this happens with broken
1824 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1825 // chance to get the pixels by deciding the element goes
1826 // until the end of the file. Hence we artificially fix the
1827 // the length and proceed.
1828 long currentPosition = ftell(Fp);
1829 fseek(Fp,0L,SEEK_END);
1830 long lengthUntilEOF = ftell(Fp) - currentPosition;
1831 fseek(Fp, currentPosition, SEEK_SET);
1832 entry->SetLength(lengthUntilEOF);
1835 entry->SetLength(lengthOB);
1838 FixDocEntryFoundLength(entry, length32);
1842 // Length is encoded on 2 bytes.
1843 length16 = ReadInt16();
1845 // We can tell the current file is encoded in big endian (like
1846 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1847 // and it's value is the one of the encoding of a big endian file.
1848 // In order to deal with such big endian encoded files, we have
1849 // (at least) two strategies:
1850 // * when we load the "Transfer Syntax" tag with value of big endian
1851 // encoding, we raise the proper flags. Then we wait for the end
1852 // of the META group (0x0002) among which is "Transfer Syntax",
1853 // before switching the swap code to big endian. We have to postpone
1854 // the switching of the swap code since the META group is fully encoded
1855 // in little endian, and big endian coding only starts at the next
1856 // group. The corresponding code can be hard to analyse and adds
1857 // many additional unnecessary tests for regular tags.
1858 // * the second strategy consists in waiting for trouble, that shall
1859 // appear when we find the first group with big endian encoding. This
1860 // is easy to detect since the length of a "Group Length" tag (the
1861 // ones with zero as element number) has to be of 4 (0x0004). When we
1862 // encounter 1024 (0x0400) chances are the encoding changed and we
1863 // found a group with big endian encoding.
1864 // We shall use this second strategy. In order to make sure that we
1865 // can interpret the presence of an apparently big endian encoded
1866 // length of a "Group Length" without committing a big mistake, we
1867 // add an additional check: we look in the already parsed elements
1868 // for the presence of a "Transfer Syntax" whose value has to be "big
1869 // endian encoding". When this is the case, chances are we have got our
1870 // hands on a big endian encoded file: we switch the swap code to
1871 // big endian and proceed...
1872 if ( element == 0x0000 && length16 == 0x0400 )
1874 if ( !IsExplicitVRBigEndianTransferSyntax() )
1876 throw FormatError( "Document::FindDocEntryLength()",
1877 " not explicit VR." );
1881 SwitchSwapToBigEndian();
1882 // Restore the unproperly loaded values i.e. the group, the element
1883 // and the dictionary entry depending on them.
1884 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1885 uint16_t correctElem = SwapShort( entry->GetElement() );
1886 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1890 // This correct tag is not in the dictionary. Create a new one.
1891 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1893 // FIXME this can create a memory leaks on the old entry that be
1894 // left unreferenced.
1895 entry->SetDictEntry( newTag );
1898 // Heuristic: well, some files are really ill-formed.
1899 if ( length16 == 0xffff)
1901 // 0xffff means that we deal with 'Unknown Length' Sequence
1904 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1909 // Either implicit VR or a non DICOM conformal (see note below) explicit
1910 // VR that ommited the VR of (at least) this element. Farts happen.
1911 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1912 // on Data elements "Implicit and Explicit VR Data Elements shall
1913 // not coexist in a Data Set and Data Sets nested within it".]
1914 // Length is on 4 bytes.
1916 FixDocEntryFoundLength( entry, ReadInt32() );
1922 * \brief Find the Value Representation of the current Dicom Element.
1925 void Document::FindDocEntryVR( DocEntry *entry )
1927 if ( Filetype != ExplicitVR )
1934 long positionOnEntry = ftell(Fp);
1935 // Warning: we believe this is explicit VR (Value Representation) because
1936 // we used a heuristic that found "UL" in the first tag. Alas this
1937 // doesn't guarantee that all the tags will be in explicit VR. In some
1938 // cases (see e-film filtered files) one finds implicit VR tags mixed
1939 // within an explicit VR file. Hence we make sure the present tag
1940 // is in explicit VR and try to fix things if it happens not to be
1943 fread (vr, (size_t)2,(size_t)1, Fp);
1946 if( !CheckDocEntryVR(entry, vr) )
1948 fseek(Fp, positionOnEntry, SEEK_SET);
1949 // When this element is known in the dictionary we shall use, e.g. for
1950 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1951 // dictionary entry. Still we have to flag the element as implicit since
1952 // we know now our assumption on expliciteness is not furfilled.
1954 if ( entry->IsVRUnknown() )
1956 entry->SetVR("Implicit");
1958 entry->SetImplicitVR();
1963 * \brief Check the correspondance between the VR of the header entry
1964 * and the taken VR. If they are different, the header entry is
1965 * updated with the new VR.
1966 * @param entry Header Entry to check
1967 * @param vr Dicom Value Representation
1968 * @return false if the VR is incorrect of if the VR isn't referenced
1969 * otherwise, it returns true
1971 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1974 bool realExplicit = true;
1976 // Assume we are reading a falsely explicit VR file i.e. we reached
1977 // a tag where we expect reading a VR but are in fact we read the
1978 // first to bytes of the length. Then we will interogate (through find)
1979 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1980 // both GCC and VC++ implementations of the STL map. Hence when the
1981 // expected VR read happens to be non-ascii characters we consider
1982 // we hit falsely explicit VR tag.
1984 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1986 realExplicit = false;
1989 // CLEANME searching the dicom_vr at each occurence is expensive.
1990 // PostPone this test in an optional integrity check at the end
1991 // of parsing or only in debug mode.
1992 if ( realExplicit && !Global::GetVR()->Count(vr) )
1994 realExplicit = false;
1997 if ( !realExplicit )
1999 // We thought this was explicit VR, but we end up with an
2000 // implicit VR tag. Let's backtrack.
2001 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
2002 entry->GetGroup(), entry->GetElement());
2003 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
2005 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2007 // Group length is UL !
2008 DictEntry* newEntry = NewVirtualDictEntry(
2009 entry->GetGroup(), entry->GetElement(),
2010 "UL", "FIXME", "Group Length");
2011 entry->SetDictEntry( newEntry );
2016 if ( entry->IsVRUnknown() )
2018 // When not a dictionary entry, we can safely overwrite the VR.
2019 if( entry->GetElement() == 0x0000 )
2021 // Group length is UL !
2029 else if ( entry->GetVR() != vr )
2031 // The VR present in the file and the dictionary disagree. We assume
2032 // the file writer knew best and use the VR of the file. Since it would
2033 // be unwise to overwrite the VR of a dictionary (since it would
2034 // compromise it's next user), we need to clone the actual DictEntry
2035 // and change the VR for the read one.
2036 DictEntry* newEntry = NewVirtualDictEntry(
2037 entry->GetGroup(), entry->GetElement(),
2038 vr, "FIXME", entry->GetName());
2039 entry->SetDictEntry(newEntry);
2046 * \brief Get the transformed value of the header entry. The VR value
2047 * is used to define the transformation to operate on the value
2048 * \warning NOT end user intended method !
2049 * @param entry entry to tranform
2050 * @return Transformed entry value
2052 std::string Document::GetDocEntryValue(DocEntry *entry)
2054 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2056 std::string val = ((ValEntry *)entry)->GetValue();
2057 std::string vr = entry->GetVR();
2058 uint32_t length = entry->GetLength();
2059 std::ostringstream s;
2062 // When short integer(s) are expected, read and convert the following
2063 // n * 2 bytes properly i.e. as a multivaluated strings
2064 // (each single value is separated fromthe next one by '\'
2065 // as usual for standard multivaluated filels
2066 // Elements with Value Multiplicity > 1
2067 // contain a set of short integers (not a single one)
2069 if( vr == "US" || vr == "SS" )
2074 for (int i=0; i < nbInt; i++)
2080 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2081 newInt16 = SwapShort( newInt16 );
2086 // When integer(s) are expected, read and convert the following
2087 // n * 4 bytes properly i.e. as a multivaluated strings
2088 // (each single value is separated fromthe next one by '\'
2089 // as usual for standard multivaluated filels
2090 // Elements with Value Multiplicity > 1
2091 // contain a set of integers (not a single one)
2092 else if( vr == "UL" || vr == "SL" )
2097 for (int i=0; i < nbInt; i++)
2103 newInt32 = ( val[4*i+0] & 0xFF )
2104 + (( val[4*i+1] & 0xFF ) << 8 )
2105 + (( val[4*i+2] & 0xFF ) << 16 )
2106 + (( val[4*i+3] & 0xFF ) << 24 );
2107 newInt32 = SwapLong( newInt32 );
2111 #ifdef GDCM_NO_ANSI_STRING_STREAM
2112 s << std::ends; // to avoid oddities on Solaris
2113 #endif //GDCM_NO_ANSI_STRING_STREAM
2117 return ((ValEntry *)entry)->GetValue();
2121 * \brief Get the reverse transformed value of the header entry. The VR
2122 * value is used to define the reverse transformation to operate on
2124 * \warning NOT end user intended method !
2125 * @param entry Entry to reverse transform
2126 * @return Reverse transformed entry value
2128 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2130 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2132 std::string vr = entry->GetVR();
2133 std::vector<std::string> tokens;
2134 std::ostringstream s;
2136 if ( vr == "US" || vr == "SS" )
2140 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2141 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2142 for (unsigned int i=0; i<tokens.size(); i++)
2144 newInt16 = atoi(tokens[i].c_str());
2145 s << ( newInt16 & 0xFF )
2146 << (( newInt16 >> 8 ) & 0xFF );
2150 if ( vr == "UL" || vr == "SL")
2154 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2155 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2156 for (unsigned int i=0; i<tokens.size();i++)
2158 newInt32 = atoi(tokens[i].c_str());
2159 s << (char)( newInt32 & 0xFF )
2160 << (char)(( newInt32 >> 8 ) & 0xFF )
2161 << (char)(( newInt32 >> 16 ) & 0xFF )
2162 << (char)(( newInt32 >> 24 ) & 0xFF );
2167 #ifdef GDCM_NO_ANSI_STRING_STREAM
2168 s << std::ends; // to avoid oddities on Solaris
2169 #endif //GDCM_NO_ANSI_STRING_STREAM
2173 return ((ValEntry *)entry)->GetValue();
2177 * \brief Skip a given Header Entry
2178 * \warning NOT end user intended method !
2179 * @param entry entry to skip
2181 void Document::SkipDocEntry(DocEntry *entry)
2183 SkipBytes(entry->GetLength());
2187 * \brief Skips to the begining of the next Header Entry
2188 * \warning NOT end user intended method !
2189 * @param entry entry to skip
2191 void Document::SkipToNextDocEntry(DocEntry *entry)
2193 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2194 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2198 * \brief When the length of an element value is obviously wrong (because
2199 * the parser went Jabberwocky) one can hope improving things by
2200 * applying some heuristics.
2201 * @param entry entry to check
2202 * @param foundLength fist assumption about length
2204 void Document::FixDocEntryFoundLength(DocEntry *entry,
2205 uint32_t foundLength)
2207 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2208 if ( foundLength == 0xffffffff)
2213 uint16_t gr = entry->GetGroup();
2214 uint16_t el = entry->GetElement();
2216 if ( foundLength % 2)
2218 std::ostringstream s;
2219 s << "Warning : Tag with uneven length "
2221 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2222 dbg.Verbose(0, s.str().c_str());
2225 //////// Fix for some naughty General Electric images.
2226 // Allthough not recent many such GE corrupted images are still present
2227 // on Creatis hard disks. Hence this fix shall remain when such images
2228 // are no longer in user (we are talking a few years, here)...
2229 // Note: XMedCom probably uses such a trick since it is able to read
2230 // those pesky GE images ...
2231 if ( foundLength == 13)
2233 // Only happens for this length !
2234 if ( entry->GetGroup() != 0x0008
2235 || ( entry->GetElement() != 0x0070
2236 && entry->GetElement() != 0x0080 ) )
2239 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2243 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2244 // Occurence of such images is quite low (unless one leaves close to a
2245 // 'Leonardo' source. Hence, one might consider commenting out the
2246 // following fix on efficiency reasons.
2247 else if ( entry->GetGroup() == 0x0009
2248 && ( entry->GetElement() == 0x1113
2249 || entry->GetElement() == 0x1114 ) )
2252 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2255 else if ( entry->GetVR() == "SQ" )
2257 foundLength = 0; // ReadLength is unchanged
2260 //////// We encountered a 'delimiter' element i.e. a tag of the form
2261 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2262 // taken into account.
2263 else if( entry->GetGroup() == 0xfffe )
2265 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2266 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2267 // causes extra troubles...
2268 if( entry->GetElement() != 0x0000 )
2274 entry->SetUsableLength(foundLength);
2278 * \brief Apply some heuristics to predict whether the considered
2279 * element value contains/represents an integer or not.
2280 * @param entry The element value on which to apply the predicate.
2281 * @return The result of the heuristical predicate.
2283 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2285 uint16_t element = entry->GetElement();
2286 uint16_t group = entry->GetGroup();
2287 std::string vr = entry->GetVR();
2288 uint32_t length = entry->GetLength();
2290 // When we have some semantics on the element we just read, and if we
2291 // a priori know we are dealing with an integer, then we shall be
2292 // able to swap it's element value properly.
2293 if ( element == 0 ) // This is the group length of the group
2301 // Allthough this should never happen, still some images have a
2302 // corrupted group length [e.g. have a glance at offset x(8336) of
2303 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2304 // Since for dicom compliant and well behaved headers, the present
2305 // test is useless (and might even look a bit paranoid), when we
2306 // encounter such an ill-formed image, we simply display a warning
2307 // message and proceed on parsing (while crossing fingers).
2308 std::ostringstream s;
2309 int filePosition = ftell(Fp);
2310 s << "Erroneous Group Length element length on : (" \
2311 << std::hex << group << " , " << element
2312 << ") -before- position x(" << filePosition << ")"
2313 << "lgt : " << length;
2314 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2318 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2327 * \brief Find the Length till the next sequence delimiter
2328 * \warning NOT end user intended method !
2332 uint32_t Document::FindDocEntryLengthOB()
2333 throw( FormatUnexpected )
2335 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2336 long positionOnEntry = ftell(Fp);
2337 bool foundSequenceDelimiter = false;
2338 uint32_t totalLength = 0;
2340 while ( !foundSequenceDelimiter )
2346 group = ReadInt16();
2349 catch ( FormatError )
2351 throw FormatError("Document::FindDocEntryLengthOB()",
2352 " group or element not present.");
2355 // We have to decount the group and element we just read
2358 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2360 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2361 "tag nor a Sequence delimiter tag.");
2362 fseek(Fp, positionOnEntry, SEEK_SET);
2363 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2364 "Neither an Item tag nor a Sequence "
2368 if ( elem == 0xe0dd )
2370 foundSequenceDelimiter = true;
2373 uint32_t itemLength = ReadInt32();
2374 // We add 4 bytes since we just read the ItemLength with ReadInt32
2375 totalLength += itemLength + 4;
2376 SkipBytes(itemLength);
2378 if ( foundSequenceDelimiter )
2383 fseek(Fp, positionOnEntry, SEEK_SET);
2388 * \brief Reads a supposed to be 16 Bits integer
2389 * (swaps it depending on processor endianity)
2390 * @return read value
2392 uint16_t Document::ReadInt16()
2393 throw( FormatError )
2396 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2397 if ( item_read != 1 )
2401 throw FormatError( "Document::ReadInt16()", " file error." );
2403 throw FormatError( "Document::ReadInt16()", "EOF." );
2410 * \brief Reads a supposed to be 32 Bits integer
2411 * (swaps it depending on processor endianity)
2412 * @return read value
2414 uint32_t Document::ReadInt32()
2415 throw( FormatError )
2418 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2419 if ( item_read != 1 )
2423 throw FormatError( "Document::ReadInt16()", " file error." );
2425 throw FormatError( "Document::ReadInt32()", "EOF." );
2432 * \brief skips bytes inside the source file
2433 * \warning NOT end user intended method !
2436 void Document::SkipBytes(uint32_t nBytes)
2438 //FIXME don't dump the returned value
2439 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2443 * \brief Loads all the needed Dictionaries
2444 * \warning NOT end user intended method !
2446 void Document::Initialise()
2448 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2453 * \brief Discover what the swap code is (among little endian, big endian,
2454 * bad little endian, bad big endian).
2456 * @return false when we are absolutely sure
2457 * it's neither ACR-NEMA nor DICOM
2458 * true when we hope ours assuptions are OK
2460 bool Document::CheckSwap()
2462 // The only guaranted way of finding the swap code is to find a
2463 // group tag since we know it's length has to be of four bytes i.e.
2464 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2465 // occurs when we can't find such group...
2467 uint32_t x = 4; // x : for ntohs
2468 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2472 char deb[HEADER_LENGTH_TO_READ];
2474 // First, compare HostByteOrder and NetworkByteOrder in order to
2475 // determine if we shall need to swap bytes (i.e. the Endian type).
2476 if ( x == ntohs(x) )
2485 // The easiest case is the one of a DICOM header, since it possesses a
2486 // file preamble where it suffice to look for the string "DICM".
2487 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2488 (void)lgrLue; //FIXME not used
2490 char *entCur = deb + 128;
2491 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2493 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2495 // Next, determine the value representation (VR). Let's skip to the
2496 // first element (0002, 0000) and check there if we find "UL"
2497 // - or "OB" if the 1st one is (0002,0001) -,
2498 // in which case we (almost) know it is explicit VR.
2499 // WARNING: if it happens to be implicit VR then what we will read
2500 // is the length of the group. If this ascii representation of this
2501 // length happens to be "UL" then we shall believe it is explicit VR.
2502 // FIXME: in order to fix the above warning, we could read the next
2503 // element value (or a couple of elements values) in order to make
2504 // sure we are not commiting a big mistake.
2505 // We need to skip :
2506 // * the 128 bytes of File Preamble (often padded with zeroes),
2507 // * the 4 bytes of "DICM" string,
2508 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2509 // i.e. a total of 136 bytes.
2513 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2514 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2515 // *Implicit* VR. -and it is !-
2517 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2518 memcmp(entCur, "OB", (size_t)2) == 0 ||
2519 memcmp(entCur, "UI", (size_t)2) == 0 ||
2520 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2521 // when Write DCM *adds*
2523 // Use Document::dicom_vr to test all the possibilities
2524 // instead of just checking for UL, OB and UI !? group 0000
2526 Filetype = ExplicitVR;
2527 dbg.Verbose(1, "Document::CheckSwap:",
2528 "explicit Value Representation");
2532 Filetype = ImplicitVR;
2533 dbg.Verbose(1, "Document::CheckSwap:",
2534 "not an explicit Value Representation");
2540 dbg.Verbose(1, "Document::CheckSwap:",
2541 "HostByteOrder != NetworkByteOrder");
2546 dbg.Verbose(1, "Document::CheckSwap:",
2547 "HostByteOrder = NetworkByteOrder");
2550 // Position the file position indicator at first tag (i.e.
2551 // after the file preamble and the "DICM" string).
2553 fseek (Fp, 132L, SEEK_SET);
2557 // Alas, this is not a DicomV3 file and whatever happens there is no file
2558 // preamble. We can reset the file position indicator to where the data
2559 // is (i.e. the beginning of the file).
2560 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2563 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2564 // By clean we mean that the length of the first tag is written down.
2565 // If this is the case and since the length of the first group HAS to be
2566 // four (bytes), then determining the proper swap code is straightforward.
2569 // We assume the array of char we are considering contains the binary
2570 // representation of a 32 bits integer. Hence the following dirty
2572 s32 = *((uint32_t *)(entCur));
2593 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2594 // It is time for despaired wild guesses.
2595 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2596 // i.e. the 'group length' element is not present :
2598 // check the supposed to be 'group number'
2599 // 0x0002 or 0x0004 or 0x0008
2600 // to determine ' SwapCode' value .
2601 // Only 0 or 4321 will be possible
2602 // (no oportunity to check for the formerly well known
2603 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2604 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2605 // the file IS NOT ACR-NEMA nor DICOM V3
2606 // Find a trick to tell it the caller...
2608 s16 = *((uint16_t *)(deb));
2625 dbg.Verbose(0, "Document::CheckSwap:",
2626 "ACR/NEMA unfound swap info (Really hopeless !)");
2630 // Then the only info we have is the net2host one.
2640 * \brief Restore the unproperly loaded values i.e. the group, the element
2641 * and the dictionary entry depending on them.
2643 void Document::SwitchSwapToBigEndian()
2645 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2646 "Switching to BigEndian mode.");
2647 if ( SwapCode == 0 )
2651 else if ( SwapCode == 4321 )
2655 else if ( SwapCode == 3412 )
2659 else if ( SwapCode == 2143 )
2666 * \brief during parsing, Header Elements too long are not loaded in memory
2669 void Document::SetMaxSizeLoadEntry(long newSize)
2675 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2677 MaxSizeLoadEntry = 0xffffffff;
2680 MaxSizeLoadEntry = newSize;
2685 * \brief Header Elements too long will not be printed
2686 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2689 void Document::SetMaxSizePrintEntry(long newSize)
2691 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2696 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2698 MaxSizePrintEntry = 0xffffffff;
2701 MaxSizePrintEntry = newSize;
2707 * \brief Read the next tag but WITHOUT loading it's value
2708 * (read the 'Group Number', the 'Element Number',
2709 * gets the Dict Entry
2710 * gets the VR, gets the length, gets the offset value)
2711 * @return On succes the newly created DocEntry, NULL on failure.
2713 DocEntry* Document::ReadNextDocEntry()
2720 group = ReadInt16();
2723 catch ( FormatError e )
2725 // We reached the EOF (or an error occured) therefore
2726 // header parsing has to be considered as finished.
2731 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2732 FindDocEntryVR(newEntry);
2736 FindDocEntryLength(newEntry);
2738 catch ( FormatError e )
2746 newEntry->SetOffset(ftell(Fp));
2753 * \brief Generate a free TagKey i.e. a TagKey that is not present
2754 * in the TagHt dictionary.
2755 * @param group The generated tag must belong to this group.
2756 * @return The element of tag with given group which is fee.
2758 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2760 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2762 TagKey key = DictEntry::TranslateToKey(group, elem);
2763 if (TagHT.count(key) == 0)
2772 * \brief Assuming the internal file pointer \ref Document::Fp
2773 * is placed at the beginning of a tag check whether this
2774 * tag is (TestGroup, TestElement).
2775 * \warning On success the internal file pointer \ref Document::Fp
2776 * is modified to point after the tag.
2777 * On failure (i.e. when the tag wasn't the expected tag
2778 * (TestGroup, TestElement) the internal file pointer
2779 * \ref Document::Fp is restored to it's original position.
2780 * @param testGroup The expected group of the tag.
2781 * @param testElement The expected Element of the tag.
2782 * @return True on success, false otherwise.
2784 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2786 long positionOnEntry = ftell(Fp);
2787 long currentPosition = ftell(Fp); // On debugging purposes
2789 //// Read the Item Tag group and element, and make
2790 // sure they are what we expected:
2791 uint16_t itemTagGroup = ReadInt16();
2792 uint16_t itemTagElement = ReadInt16();
2793 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2795 std::ostringstream s;
2796 s << " We should have found tag (";
2797 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2798 s << " but instead we encountered tag (";
2799 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2801 s << " at address: " << (unsigned)currentPosition << std::endl;
2802 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2803 dbg.Verbose(0, s.str().c_str());
2804 fseek(Fp, positionOnEntry, SEEK_SET);
2812 * \brief Assuming the internal file pointer \ref Document::Fp
2813 * is placed at the beginning of a tag (TestGroup, TestElement),
2814 * read the length associated to the Tag.
2815 * \warning On success the internal file pointer \ref Document::Fp
2816 * is modified to point after the tag and it's length.
2817 * On failure (i.e. when the tag wasn't the expected tag
2818 * (TestGroup, TestElement) the internal file pointer
2819 * \ref Document::Fp is restored to it's original position.
2820 * @param testGroup The expected group of the tag.
2821 * @param testElement The expected Element of the tag.
2822 * @return On success returns the length associated to the tag. On failure
2825 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2827 long positionOnEntry = ftell(Fp);
2828 (void)positionOnEntry;
2830 if ( !ReadTag(testGroup, testElement) )
2835 //// Then read the associated Item Length
2836 long currentPosition = ftell(Fp);
2837 uint32_t itemLength = ReadInt32();
2839 std::ostringstream s;
2840 s << "Basic Item Length is: "
2841 << itemLength << std::endl;
2842 s << " at address: " << (unsigned)currentPosition << std::endl;
2843 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2849 * \brief When parsing the Pixel Data of an encapsulated file, read
2850 * the basic offset table (when present, and BTW dump it).
2852 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2854 //// Read the Basic Offset Table Item Tag length...
2855 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2857 // When present, read the basic offset table itself.
2858 // Notes: - since the presence of this basic offset table is optional
2859 // we can't rely on it for the implementation, and we will simply
2860 // trash it's content (when present).
2861 // - still, when present, we could add some further checks on the
2862 // lengths, but we won't bother with such fuses for the time being.
2863 if ( itemLength != 0 )
2865 char* basicOffsetTableItemValue = new char[itemLength + 1];
2866 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2869 for (unsigned int i=0; i < itemLength; i += 4 )
2871 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2873 std::ostringstream s;
2874 s << " Read one length: ";
2875 s << std::hex << individualLength << std::endl;
2877 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2882 delete[] basicOffsetTableItemValue;
2887 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2888 * Compute the RLE extra information and store it in \ref RLEInfo
2889 * for later pixel retrieval usage.
2891 void Document::ComputeRLEInfo()
2893 if ( ! IsRLELossLessTransferSyntax() )
2898 // Encoded pixel data: for the time being we are only concerned with
2899 // Jpeg or RLE Pixel data encodings.
2900 // As stated in PS 3.5-2003, section 8.2 p44:
2901 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2902 // value representation OB is used".
2903 // Hence we expect an OB value representation. Concerning OB VR,
2904 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2905 // "For the Value Representations OB and OW, the encoding shall meet the
2906 // following specifications depending on the Data element tag:"
2908 // - the first item in the sequence of items before the encoded pixel
2909 // data stream shall be basic offset table item. The basic offset table
2910 // item value, however, is not required to be present"
2912 ReadAndSkipEncapsulatedBasicOffsetTable();
2914 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2915 // Loop on the individual frame[s] and store the information
2916 // on the RLE fragments in a RLEFramesInfo.
2917 // Note: - when only a single frame is present, this is a
2919 // - when more than one frame are present, then we are in
2920 // the case of a multi-frame image.
2922 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2924 // Parse the RLE Header and store the corresponding RLE Segment
2925 // Offset Table information on fragments of this current Frame.
2926 // Note that the fragment pixels themselves are not loaded
2927 // (but just skipped).
2928 long frameOffset = ftell(Fp);
2930 uint32_t nbRleSegments = ReadInt32();
2932 uint32_t rleSegmentOffsetTable[15];
2933 for( int k = 1; k <= 15; k++ )
2935 rleSegmentOffsetTable[k] = ReadInt32();
2938 // Deduce from both the RLE Header and the frameLength the
2939 // fragment length, and again store this info in a
2941 long rleSegmentLength[15];
2942 // skipping (not reading) RLE Segments
2943 if ( nbRleSegments > 1)
2945 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2947 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2948 - rleSegmentOffsetTable[k];
2949 SkipBytes(rleSegmentLength[k]);
2953 rleSegmentLength[nbRleSegments] = frameLength
2954 - rleSegmentOffsetTable[nbRleSegments];
2955 SkipBytes(rleSegmentLength[nbRleSegments]);
2957 // Store the collected info
2958 RLEFrame* newFrameInfo = new RLEFrame;
2959 newFrameInfo->NumberFragments = nbRleSegments;
2960 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2962 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2963 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2965 RLEInfo.Frames.push_back( newFrameInfo );
2968 // Make sure that at the end of the item we encounter a 'Sequence
2970 if ( !ReadTag(0xfffe, 0xe0dd) )
2972 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2973 dbg.Verbose(0, " item at end of RLE item sequence");
2978 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2979 * Compute the jpeg extra information (fragment[s] offset[s] and
2980 * length) and store it[them] in \ref JPEGInfo for later pixel
2983 void Document::ComputeJPEGFragmentInfo()
2985 // If you need to, look for comments of ComputeRLEInfo().
2986 if ( ! IsJPEGTransferSyntax() )
2991 ReadAndSkipEncapsulatedBasicOffsetTable();
2993 // Loop on the fragments[s] and store the parsed information in a
2995 long fragmentLength;
2996 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2998 long fragmentOffset = ftell(Fp);
3000 // Store the collected info
3001 JPEGFragment* newFragment = new JPEGFragment;
3002 newFragment->Offset = fragmentOffset;
3003 newFragment->Length = fragmentLength;
3004 JPEGInfo.Fragments.push_back( newFragment );
3006 SkipBytes( fragmentLength );
3009 // Make sure that at the end of the item we encounter a 'Sequence
3011 if ( !ReadTag(0xfffe, 0xe0dd) )
3013 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3014 dbg.Verbose(0, " item at end of JPEG item sequence");
3019 * \brief Walk recursively the given \ref DocEntrySet, and feed
3020 * the given hash table (\ref TagDocEntryHT) with all the
3021 * \ref DocEntry (Dicom entries) encountered.
3022 * This method does the job for \ref BuildFlatHashTable.
3023 * @param builtHT Where to collect all the \ref DocEntry encountered
3024 * when recursively walking the given set.
3025 * @param set The structure to be traversed (recursively).
3027 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3030 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3032 TagDocEntryHT* currentHT = elementSet->GetTagHT();
3033 for( TagDocEntryHT::const_iterator i = currentHT->begin();
3034 i != currentHT->end();
3037 DocEntry* entry = i->second;
3038 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3040 ListSQItem& items = seqEntry->GetSQItems();
3041 for( ListSQItem::const_iterator item = items.begin();
3042 item != items.end();
3045 BuildFlatHashTableRecurse( builtHT, *item );
3049 builtHT[entry->GetKey()] = entry;
3054 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3056 ListDocEntry& currentList = SQItemSet->GetDocEntries();
3057 for (ListDocEntry::iterator i = currentList.begin();
3058 i != currentList.end();
3061 DocEntry* entry = *i;
3062 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3064 ListSQItem& items = seqEntry->GetSQItems();
3065 for( ListSQItem::const_iterator item = items.begin();
3066 item != items.end();
3069 BuildFlatHashTableRecurse( builtHT, *item );
3073 builtHT[entry->GetKey()] = entry;
3080 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3083 * The structure used by a Document (through \ref ElementSet),
3084 * in order to old the parsed entries of a Dicom header, is a recursive
3085 * one. This is due to the fact that the sequences (when present)
3086 * can be nested. Additionaly, the sequence items (represented in
3087 * gdcm as \ref SQItem) add an extra complexity to the data
3088 * structure. Hence, a gdcm user whishing to visit all the entries of
3089 * a Dicom header will need to dig in the gdcm internals (which
3090 * implies exposing all the internal data structures to the API).
3091 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3092 * recursively builds a temporary hash table, which holds all the
3093 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3095 * \warning Of course there is NO integrity constrain between the
3096 * returned \ref TagDocEntryHT and the \ref ElementSet used
3097 * to build it. Hence if the underlying \ref ElementSet is
3098 * altered, then it is the caller responsability to invoke
3099 * \ref BuildFlatHashTable again...
3100 * @return The flat std::map<> we juste build.
3102 TagDocEntryHT* Document::BuildFlatHashTable()
3104 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3105 BuildFlatHashTableRecurse( *FlatHT, this );
3112 * \brief Compares two documents, according to \ref DicomDir rules
3113 * \warning Does NOT work with ACR-NEMA files
3114 * \todo Find a trick to solve the pb (use RET fields ?)
3116 * @return true if 'smaller'
3118 bool Document::operator<(Document &document)
3121 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3122 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3134 s1 = GetEntryByNumber(0x0010,0x0020);
3135 s2 = document.GetEntryByNumber(0x0010,0x0020);
3146 // Study Instance UID
3147 s1 = GetEntryByNumber(0x0020,0x000d);
3148 s2 = document.GetEntryByNumber(0x0020,0x000d);
3159 // Serie Instance UID
3160 s1 = GetEntryByNumber(0x0020,0x000e);
3161 s2 = document.GetEntryByNumber(0x0020,0x000e);
3176 } // end namespace gdcm
3178 //-----------------------------------------------------------------------------