1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/10/06 22:31:31 $
7 Version: $Revision: 1.96 $
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>
38 // Implicit VR Little Endian
39 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
40 // Explicit VR Little Endian
41 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
42 // Deflated Explicit VR Little Endian
43 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
44 // Explicit VR Big Endian
45 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
46 // JPEG Baseline (Process 1)
47 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
48 // JPEG Extended (Process 2 & 4)
49 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
50 // JPEG Extended (Process 3 & 5)
51 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
52 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
53 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
54 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
55 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
56 // JPEG Lossless, Non-Hierarchical (Process 14)
57 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
58 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
59 // [Selection Value 1])
60 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
62 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
64 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
66 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
67 // UI1_1_2_840_10008_1_2_5
68 #define str2num(str, typeNum) *((typeNum *)(str))
70 //-----------------------------------------------------------------------------
71 // Refer to gdcmDocument::CheckSwap()
72 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
74 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
75 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
76 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
78 //-----------------------------------------------------------------------------
79 // Constructor / Destructor
83 * @param filename file to be opened for parsing
85 gdcmDocument::gdcmDocument( std::string const & filename )
88 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
97 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
101 fseek(Fp,0L,SEEK_END);
102 long lgt = ftell(Fp);
106 long beg = ftell(Fp);
109 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
113 // Load 'non string' values
115 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
116 if( PhotometricInterpretation == "PALETTE COLOR " )
118 LoadEntryBinArea(0x0028,0x1200); // gray LUT
119 /// FIXME FIXME FIXME
120 /// The tags refered by the three following lines used to be CORRECTLY
121 /// defined as having an US Value Representation in the public
122 /// dictionnary. BUT the semantics implied by the three following
123 /// lines state that the corresponding tag contents are in fact
124 /// the ones of a gdcmBinEntry.
125 /// In order to fix things "Quick and Dirty" the dictionnary was
126 /// altered on PURPOUS but now contains a WRONG value.
127 /// In order to fix things and restore the dictionary to its
128 /// correct value, one needs to decided of the semantics by deciding
129 /// wether the following tags are either:
130 /// - multivaluated US, and hence loaded as gdcmValEntry, but afterwards
131 /// also used as gdcmBinEntry, which requires the proper conversion,
132 /// - OW, and hence loaded as gdcmBinEntry, but afterwards also used
133 /// as gdcmValEntry, which requires the proper conversion.
134 LoadEntryBinArea(0x0028,0x1201); // R LUT
135 LoadEntryBinArea(0x0028,0x1202); // G LUT
136 LoadEntryBinArea(0x0028,0x1203); // B LUT
138 // Segmented Red Palette Color LUT Data
139 LoadEntryBinArea(0x0028,0x1221);
140 // Segmented Green Palette Color LUT Data
141 LoadEntryBinArea(0x0028,0x1222);
142 // Segmented Blue Palette Color LUT Data
143 LoadEntryBinArea(0x0028,0x1223);
145 //FIXME later : how to use it?
146 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
150 // --------------------------------------------------------------
151 // Specific code to allow gdcm to read ACR-LibIDO formated images
152 // Note: ACR-LibIDO is an extension of the ACR standard that was
153 // used at CREATIS. For the time being (say a couple years)
154 // we keep this kludge to allow a smooth move to gdcm for
155 // CREATIS developpers (sorry folks).
157 // if recognition code tells us we deal with a LibIDO image
158 // we switch lineNumber and columnNumber
161 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
162 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
163 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
164 // with "little-endian strings"
166 Filetype = gdcmACR_LIBIDO;
167 std::string rows = GetEntryByNumber(0x0028, 0x0010);
168 std::string columns = GetEntryByNumber(0x0028, 0x0011);
169 SetEntryByNumber(columns, 0x0028, 0x0010);
170 SetEntryByNumber(rows , 0x0028, 0x0011);
172 // ----------------- End of ACR-LibIDO kludge ------------------
174 PrintLevel = 1; // 'Medium' print level by default
178 * \brief This default constructor doesn't parse the file. You should
179 * then invoke \ref gdcmDocument::SetFileName and then the parsing.
181 gdcmDocument::gdcmDocument()
184 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
186 PrintLevel = 1; // 'Medium' print level by default
190 * \brief Canonical destructor.
192 gdcmDocument::~gdcmDocument ()
197 // Recursive clean up of sequences
198 for (TagDocEntryHT::const_iterator it = TagHT.begin();
199 it != TagHT.end(); ++it )
201 //delete it->second; //temp remove
206 //-----------------------------------------------------------------------------
210 * \brief Prints The Dict Entries of THE public Dicom Dictionary
213 void gdcmDocument::PrintPubDict(std::ostream & os)
215 RefPubDict->Print(os);
219 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
222 void gdcmDocument::PrintShaDict(std::ostream & os)
224 RefShaDict->Print(os);
227 //-----------------------------------------------------------------------------
230 * \brief Get the public dictionary used
232 gdcmDict* gdcmDocument::GetPubDict()
238 * \brief Get the shadow dictionary used
240 gdcmDict* gdcmDocument::GetShaDict()
246 * \brief Set the shadow dictionary used
247 * \param dict dictionary to use in shadow
249 bool gdcmDocument::SetShaDict(gdcmDict *dict)
256 * \brief Set the shadow dictionary used
257 * \param dictName name of the dictionary to use in shadow
259 bool gdcmDocument::SetShaDict(DictKey const & dictName)
261 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
266 * \brief This predicate, based on hopefully reasonable heuristics,
267 * decides whether or not the current gdcmDocument was properly parsed
268 * and contains the mandatory information for being considered as
269 * a well formed and usable Dicom/Acr File.
270 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
273 bool gdcmDocument::IsReadable()
275 if( Filetype == gdcmUnknown)
277 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
283 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
293 * \brief Internal function that checks whether the Transfer Syntax given
294 * as argument is the one present in the current document.
295 * @param syntaxToCheck The transfert syntax we need to check against.
296 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
297 * the current document. False either when the document contains
298 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
300 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
302 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
308 // The entry might be present but not loaded (parsing and loading
309 // happen at different stages): try loading and proceed with check...
310 LoadDocEntrySafe(entry);
311 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
313 std::string transfer = valEntry->GetValue();
314 // The actual transfer (as read from disk) might be padded. We
315 // first need to remove the potential padding. We can make the
316 // weak assumption that padding was not executed with digits...
317 if ( transfer.length() == 0 ) { // for brain damaged headers
320 while ( ! isdigit(transfer[transfer.length()-1]) )
322 transfer.erase(transfer.length()-1, 1);
324 if ( transfer == syntaxToCheck )
333 * \brief Determines if the Transfer Syntax of the present document
334 * corresponds to a Implicit Value Representation of
336 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
337 * @return True when ImplicitVRLittleEndian found. False in all other cases.
339 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
341 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
345 * \brief Determines if the Transfer Syntax was already encountered
346 * and if it corresponds to a ExplicitVRLittleEndian one.
347 * @return True when ExplicitVRLittleEndian found. False in all other cases.
349 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
351 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
355 * \brief Determines if the Transfer Syntax was already encountered
356 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
357 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
359 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
361 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
365 * \brief Determines if the Transfer Syntax was already encountered
366 * and if it corresponds to a Explicit VR Big Endian one.
367 * @return True when big endian found. False in all other cases.
369 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
371 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
375 * \brief Determines if the Transfer Syntax was already encountered
376 * and if it corresponds to a JPEGBaseLineProcess1 one.
377 * @return True when JPEGBaseLineProcess1found. False in all other cases.
379 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
381 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
385 * \brief Determines if the Transfer Syntax was already encountered
386 * and if it corresponds to a JPEGExtendedProcess2-4 one.
387 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
389 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
391 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
395 * \brief Determines if the Transfer Syntax was already encountered
396 * and if it corresponds to a JPEGExtendeProcess3-5 one.
397 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
399 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
401 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
405 * \brief Determines if the Transfer Syntax was already encountered
406 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
407 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
410 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
412 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
416 * \brief Determines if the Transfer Syntax was already encountered
417 * and if it corresponds to a RLE Lossless one.
418 * @return True when RLE Lossless found. False in all
421 bool gdcmDocument::IsRLELossLessTransferSyntax()
423 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
427 * \brief Determines if Transfer Syntax was already encountered
428 * and if it corresponds to a JPEG Lossless one.
429 * @return True when RLE Lossless found. False in all
433 bool gdcmDocument::IsJPEGLossless()
435 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
436 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
437 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
441 * \brief Determines if the Transfer Syntax was already encountered
442 * and if it corresponds to a JPEG2000 one
443 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
446 bool gdcmDocument::IsJPEG2000()
448 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
449 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
453 * \brief Determines if the Transfer Syntax corresponds to encapsulated
454 * of encoded Pixel Data (as opposed to native).
455 * @return True when encapsulated. False when native.
457 bool gdcmDocument::IsEncapsulateTransferSyntax()
459 return ( IsJPEGBaseLineProcess1TransferSyntax()
460 || IsJPEGExtendedProcess2_4TransferSyntax()
461 || IsJPEGExtendedProcess3_5TransferSyntax()
462 || IsJPEGSpectralSelectionProcess6_8TransferSyntax()
463 || IsRLELossLessTransferSyntax()
469 * \brief Predicate for dicom version 3 file.
470 * @return True when the file is a dicom version 3.
472 bool gdcmDocument::IsDicomV3()
474 // Checking if Transfert Syntax exists is enough
475 // Anyway, it's to late check if the 'Preamble' was found ...
476 // And ... would it be a rich idea to check ?
477 // (some 'no Preamble' DICOM images exist !)
478 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
482 * \brief returns the File Type
483 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
484 * @return the FileType code
486 FileType gdcmDocument::GetFileType()
492 * \brief Tries to open the file \ref gdcmDocument::Filename and
493 * checks the preamble when existing.
494 * @return The FILE pointer on success.
496 FILE* gdcmDocument::OpenFile()
498 Fp = fopen(Filename.c_str(),"rb");
503 "gdcmDocument::OpenFile cannot open file: ",
509 fread(&zero, (size_t)2, (size_t)1, Fp);
511 //ACR -- or DICOM with no Preamble --
512 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
518 fseek(Fp, 126L, SEEK_CUR);
520 fread(dicm, (size_t)4, (size_t)1, Fp);
521 if( memcmp(dicm, "DICM", 4) == 0 )
528 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
535 * \brief closes the file
536 * @return TRUE if the close was successfull
538 bool gdcmDocument::CloseFile()
540 int closed = fclose(Fp);
547 * \brief Writes in a file all the Header Entries (Dicom Elements)
548 * @param fp file pointer on an already open file
549 * @param filetype Type of the File to be written
550 * (ACR-NEMA, ExplicitVR, ImplicitVR)
551 * \return Always true.
553 void gdcmDocument::Write(FILE* fp,FileType filetype)
555 /// \todo move the following lines (and a lot of others, to be written)
556 /// to a future function CheckAndCorrectHeader
557 /// (necessary if user wants to write a DICOM V3 file
558 /// starting from an ACR-NEMA (V2) gdcmHeader
560 if (filetype == gdcmImplicitVR)
562 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
563 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
565 /// \todo Refer to standards on page 21, chapter 6.2
566 /// "Value representation": values with a VR of UI shall be
567 /// padded with a single trailing null
568 /// in the following case we have to padd manually with a 0
570 SetEntryLengthByNumber(18, 0x0002, 0x0010);
573 if (filetype == gdcmExplicitVR)
575 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
576 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
578 /// \todo Refer to standards on page 21, chapter 6.2
579 /// "Value representation": values with a VR of UI shall be
580 /// padded with a single trailing null
581 /// Dans le cas suivant on doit pader manuellement avec un 0
583 SetEntryLengthByNumber(20, 0x0002, 0x0010);
587 * \todo rewrite later, if really usefull
588 * - 'Group Length' element is optional in DICOM
589 * - but un-updated odd groups lengthes can causes pb
592 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
593 * UpdateGroupLength(false,filetype);
594 * if ( filetype == ACR)
595 * UpdateGroupLength(true,ACR);
598 gdcmElementSet::Write(fp, filetype); // This one is recursive
603 * \brief Modifies the value of a given Header Entry (Dicom Element)
604 * when it exists. Create it with the given value when unexistant.
605 * @param value (string) Value to be set
606 * @param group Group number of the Entry
607 * @param elem Element number of the Entry
608 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
609 * \return pointer to the modified/created Header Entry (NULL when creation
612 gdcmValEntry* gdcmDocument::ReplaceOrCreateByNumber(
613 std::string const & value,
616 std::string const & VR )
618 gdcmValEntry* valEntry = 0;
619 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
623 // check if (group,element) DictEntry exists
624 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
627 // Find out if the tag we received is in the dictionaries:
628 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
629 gdcmDictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
632 currentEntry = NewDocEntryByNumber(group, elem,VR);
636 currentEntry = NewDocEntryByNumber(group, elem);
641 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
642 " NewDocEntryByNumber failed.");
645 valEntry = new gdcmValEntry(currentEntry);
646 if ( !AddEntry(valEntry))
648 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
649 " failed allthough this is a creation.");
654 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
655 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
656 // then we change it to a ValEntry ?
657 // Shouldn't it be considered as an error ?
659 // We need to promote the gdcmDocEntry to a gdcmValEntry:
660 valEntry = new gdcmValEntry(currentEntry);
661 if (!RemoveEntry(currentEntry))
663 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
664 " of previous DocEntry failed.");
667 if ( !AddEntry(valEntry))
669 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
670 " promoted ValEntry failed.");
676 SetEntryByNumber(value, group, elem);
682 * \brief Modifies the value of a given Header Entry (Dicom Element)
683 * when it exists. Create it with the given value when unexistant.
684 * @param binArea (binary) value to be set
685 * @param Group Group number of the Entry
686 * @param Elem Element number of the Entry
687 * \return pointer to the modified/created Header Entry (NULL when creation
690 gdcmBinEntry* gdcmDocument::ReplaceOrCreateByNumber(
695 std::string const& VR )
697 gdcmBinEntry* binEntry = 0;
698 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
702 // check if (group,element) DictEntry exists
703 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
706 // Find out if the tag we received is in the dictionaries:
707 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
708 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
712 currentEntry = NewDocEntryByNumber(group, elem, VR);
716 currentEntry = NewDocEntryByNumber(group, elem);
720 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
721 " NewDocEntryByNumber failed.");
724 binEntry = new gdcmBinEntry(currentEntry);
725 if ( !AddEntry(binEntry))
727 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
728 " failed allthough this is a creation.");
733 binEntry = dynamic_cast< gdcmBinEntry* >(currentEntry);
734 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
735 // then we change it to a BinEntry ?
736 // Shouldn't it be considered as an error ?
738 // We need to promote the gdcmDocEntry to a gdcmBinEntry:
739 binEntry = new gdcmBinEntry(currentEntry);
740 if (!RemoveEntry(currentEntry))
742 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
743 " of previous DocEntry failed.");
746 if ( !AddEntry(binEntry))
748 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
749 " promoted BinEntry failed.");
755 SetEntryByNumber(binArea, lgth, group, elem);
762 * \brief Modifies the value of a given Header Entry (Dicom Element)
763 * when it exists. Create it when unexistant.
764 * @param Group Group number of the Entry
765 * @param Elem Element number of the Entry
766 * \return pointer to the modified/created SeqEntry (NULL when creation
769 gdcmSeqEntry* gdcmDocument::ReplaceOrCreateByNumber(
774 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
777 a = NewSeqEntryByNumber(group, elem);
783 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
790 * \brief Set a new value if the invoked element exists
791 * Seems to be useless !!!
792 * @param value new element value
793 * @param group group number of the Entry
794 * @param elem element number of the Entry
797 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
798 uint16_t group, uint16_t elem )
800 SetEntryByNumber(value, group, elem);
805 //-----------------------------------------------------------------------------
809 * \brief Checks if a given Dicom Element exists within the H table
810 * @param group Group number of the searched Dicom Element
811 * @param element Element number of the searched Dicom Element
812 * @return true is found
814 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
816 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
817 return TagHT.count(key);
821 * \brief Searches within Header Entries (Dicom Elements) parsed with
822 * the public and private dictionaries
823 * for the element value of a given tag.
824 * \warning Don't use any longer : use GetPubEntryByName
825 * @param tagName name of the searched element.
826 * @return Corresponding element value when it exists,
827 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
829 std::string gdcmDocument::GetEntryByName(TagName const& tagName)
831 gdcmDictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
837 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
841 * \brief Searches within Header Entries (Dicom Elements) parsed with
842 * the public and private dictionaries
843 * for the element value representation of a given tag.
845 * Obtaining the VR (Value Representation) might be needed by caller
846 * to convert the string typed content to caller's native type
847 * (think of C++ vs Python). The VR is actually of a higher level
848 * of semantics than just the native C++ type.
849 * @param tagName name of the searched element.
850 * @return Corresponding element value representation when it exists,
851 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
853 std::string gdcmDocument::GetEntryVRByName(TagName const& tagName)
855 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
856 if( dictEntry == NULL)
861 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
862 dictEntry->GetElement());
863 return elem->GetVR();
867 * \brief Searches within Header Entries (Dicom Elements) parsed with
868 * the public and private dictionaries
869 * for the element value representation of a given tag.
870 * @param group Group number of the searched tag.
871 * @param element Element number of the searched tag.
872 * @return Corresponding element value representation when it exists,
873 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
875 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
877 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
878 /// \todo use map methods, instead of multimap JPR
879 if ( !TagHT.count(key))
884 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
888 * \brief Searches within Header Entries (Dicom Elements) parsed with
889 * the public and private dictionaries
890 * for the element value representation of a given tag..
892 * Obtaining the VR (Value Representation) might be needed by caller
893 * to convert the string typed content to caller's native type
894 * (think of C++ vs Python). The VR is actually of a higher level
895 * of semantics than just the native C++ type.
896 * @param group Group number of the searched tag.
897 * @param element Element number of the searched tag.
898 * @return Corresponding element value representation when it exists,
899 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
901 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
903 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
908 return elem->GetVR();
912 * \brief Searches within Header Entries (Dicom Elements) parsed with
913 * the public and private dictionaries
914 * for the value length of a given tag..
915 * @param group Group number of the searched tag.
916 * @param element Element number of the searched tag.
917 * @return Corresponding element length; -2 if not found
919 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
921 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
924 return -2; //magic number
926 return elem->GetLength();
929 * \brief Sets the value (string) of the Header Entry (Dicom Element)
930 * @param content string value of the Dicom Element
931 * @param tagName name of the searched Dicom Element.
932 * @return true when found
934 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
936 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
942 return SetEntryByNumber(content,dictEntry->GetGroup(),
943 dictEntry->GetElement());
947 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
948 * through it's (group, element) and modifies it's content with
950 * @param content new value (string) to substitute with
951 * @param group group number of the Dicom Element to modify
952 * @param element element number of the Dicom Element to modify
954 bool gdcmDocument::SetEntryByNumber(std::string const& content,
961 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
964 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
965 " ValEntry (try promotion first).");
968 // Non even content must be padded with a space (020H)...
969 std::string finalContent = content;
970 if( finalContent.length() % 2 )
972 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
974 valEntry->SetValue(finalContent);
976 // Integers have a special treatement for their length:
978 l = finalContent.length();
979 if ( l != 0) // To avoid to be cheated by 'zero length' integers
981 gdcmVRKey vr = valEntry->GetVR();
982 if( vr == "US" || vr == "SS" )
984 c = CountSubstring(content, "\\") + 1; // for multivaluated items
987 else if( vr == "UL" || vr == "SL" )
989 c = CountSubstring(content, "\\") + 1; // for multivaluated items
993 valEntry->SetLength(l);
998 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
999 * through it's (group, element) and modifies it's content with
1001 * @param content new value (void* -> uint8_t*) to substitute with
1002 * @param lgth new value length
1003 * @param group group number of the Dicom Element to modify
1004 * @param element element number of the Dicom Element to modify
1006 bool gdcmDocument::SetEntryByNumber(uint8_t*content,
1011 (void)lgth; //not used
1012 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1013 if ( !TagHT.count(key))
1018 /* Hope Binary field length is *never* wrong
1019 if(lgth%2) // Non even length are padded with a space (020H).
1022 //content = content + '\0'; // fing a trick to enlarge a binary field?
1025 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1026 a->SetBinArea(content);
1028 a->SetValue(GDCM_BINLOADED);
1034 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1035 * in the PubDocEntrySet of this instance
1036 * through it's (group, element) and modifies it's length with
1038 * \warning Use with extreme caution.
1039 * @param l new length to substitute with
1040 * @param group group number of the Entry to modify
1041 * @param element element number of the Entry to modify
1042 * @return true on success, false otherwise.
1044 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1048 /// \todo use map methods, instead of multimap JPR
1049 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1050 if ( !TagHT.count(key) )
1056 l++; // length must be even
1058 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1064 * \brief Gets (from Header) the offset of a 'non string' element value
1065 * (LoadElementValues has already be executed)
1066 * @param group group number of the Entry
1067 * @param elem element number of the Entry
1068 * @return File Offset of the Element Value
1070 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1072 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1075 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1078 return entry->GetOffset();
1082 * \brief Gets (from Header) a 'non string' element value
1083 * (LoadElementValues has already be executed)
1084 * @param group group number of the Entry
1085 * @param elem element number of the Entry
1086 * @return Pointer to the 'non string' area
1088 void* gdcmDocument::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1090 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1093 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1096 return ((gdcmBinEntry *)entry)->GetBinArea();
1100 * \brief Loads (from disk) the element content
1101 * when a string is not suitable
1102 * @param group group number of the Entry
1103 * @param elem element number of the Entry
1105 void* gdcmDocument::LoadEntryBinArea(uint16_t group, uint16_t elem)
1107 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1112 size_t o =(size_t)docElement->GetOffset();
1113 fseek(Fp, o, SEEK_SET);
1114 size_t l = docElement->GetLength();
1115 uint8_t* a = new uint8_t[l];
1118 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea cannot allocate a");
1121 size_t l2 = fread(a, 1, l , Fp);
1127 /// \todo Drop any already existing void area! JPR
1128 if( !SetEntryBinAreaByNumber( a, group, elem ) );
1130 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea setting failed.");
1135 * \brief Loads (from disk) the element content
1136 * when a string is not suitable
1137 * @param element Entry whose binArea is going to be loaded
1139 void* gdcmDocument::LoadEntryBinArea(gdcmBinEntry* element)
1141 size_t o =(size_t)element->GetOffset();
1142 fseek(Fp, o, SEEK_SET);
1143 size_t l = element->GetLength();
1144 uint8_t* a = new uint8_t[l];
1147 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea cannot allocate a");
1150 element->SetBinArea((uint8_t*)a);
1151 /// \todo check the result
1152 size_t l2 = fread(a, 1, l , Fp);
1163 * \brief Sets a 'non string' value to a given Dicom Element
1164 * @param area area containing the 'non string' value
1165 * @param group Group number of the searched Dicom Element
1166 * @param element Element number of the searched Dicom Element
1169 bool gdcmDocument::SetEntryBinAreaByNumber(uint8_t* area,
1173 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1174 if ( !currentEntry )
1178 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1180 binEntry->SetBinArea( area );
1187 * \brief Update the entries with the shadow dictionary.
1188 * Only non even entries are analyzed
1190 void gdcmDocument::UpdateShaEntries()
1192 //gdcmDictEntry *entry;
1195 /// \todo TODO : still any use to explore recursively the whole structure?
1197 for(ListTag::iterator it=listEntries.begin();
1198 it!=listEntries.end();
1201 // Odd group => from public dictionary
1202 if((*it)->GetGroup()%2==0)
1205 // Peer group => search the corresponding dict entry
1207 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1211 if((*it)->IsImplicitVR())
1216 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1218 // Set the new entry and the new value
1219 (*it)->SetDictEntry(entry);
1220 CheckDocEntryVR(*it,vr);
1222 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1227 // Remove precedent value transformation
1228 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1235 * \brief Searches within the Header Entries for a Dicom Element of
1237 * @param tagName name of the searched Dicom Element.
1238 * @return Corresponding Dicom Element when it exists, and NULL
1241 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1243 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1249 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1253 * \brief retrieves a Dicom Element (the first one) using (group, element)
1254 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1255 * if you think it's NOT UNIQUE, check the count number
1256 * and use iterators to retrieve ALL the Dicoms Elements within
1257 * a given couple (group, element)
1258 * @param group Group number of the searched Dicom Element
1259 * @param element Element number of the searched Dicom Element
1262 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1265 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1266 if ( !TagHT.count(key))
1270 return TagHT.find(key)->second;
1274 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1275 * returns a result when the corresponding entry is of type
1277 * @return When present, the corresponding ValEntry.
1279 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1282 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1283 if ( !currentEntry )
1287 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1291 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1297 * \brief Loads the element while preserving the current
1298 * underlying file position indicator as opposed to
1299 * to LoadDocEntry that modifies it.
1300 * @param entry Header Entry whose value shall be loaded.
1303 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1305 long PositionOnEntry = ftell(Fp);
1306 LoadDocEntry(entry);
1307 fseek(Fp, PositionOnEntry, SEEK_SET);
1311 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1313 * @return The properly swaped 32 bits integer.
1315 uint32_t gdcmDocument::SwapLong(uint32_t a)
1322 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1323 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1327 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1331 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1334 //std::cout << "swapCode= " << SwapCode << std::endl;
1335 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1342 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1344 * @return The properly unswaped 32 bits integer.
1346 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1352 * \brief Swaps the bytes so they agree with the processor order
1353 * @return The properly swaped 16 bits integer.
1355 uint16_t gdcmDocument::SwapShort(uint16_t a)
1357 if ( SwapCode == 4321 || SwapCode == 2143 )
1359 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1365 * \brief Unswaps the bytes so they agree with the processor order
1366 * @return The properly unswaped 16 bits integer.
1368 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1370 return SwapShort(a);
1373 //-----------------------------------------------------------------------------
1377 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1378 * @return length of the parsed set.
1380 void gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1385 gdcmDocEntry *newDocEntry = 0;
1389 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1393 newDocEntry = ReadNextDocEntry( );
1399 gdcmVRKey vr = newDocEntry->GetVR();
1403 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1405 /////////////////////// ValEntry
1406 gdcmValEntry* newValEntry =
1407 new gdcmValEntry( newDocEntry->GetDictEntry() );
1408 newValEntry->Copy( newDocEntry );
1410 // When "set" is a gdcmDocument, then we are at the top of the
1411 // hierarchy and the Key is simply of the form ( group, elem )...
1412 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1415 newValEntry->SetKey( newValEntry->GetKey() );
1417 // ...but when "set" is a gdcmSQItem, we are inserting this new
1418 // valEntry in a sequence item. Hence the key has the
1419 // generalized form (refer to \ref gdcmBaseTagKey):
1420 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1422 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1423 + newValEntry->GetKey() );
1426 set->AddEntry( newValEntry );
1427 LoadDocEntry( newValEntry );
1428 if (newValEntry->IsItemDelimitor())
1432 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1439 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1441 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1442 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1443 "nor BinEntry. Probably unknown VR.");
1446 //////////////////// BinEntry or UNKOWN VR:
1447 gdcmBinEntry* newBinEntry =
1448 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1449 newBinEntry->Copy( newDocEntry );
1451 // When "this" is a gdcmDocument the Key is simply of the
1452 // form ( group, elem )...
1453 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1455 newBinEntry->SetKey( newBinEntry->GetKey() );
1457 // but when "this" is a SQItem, we are inserting this new
1458 // valEntry in a sequence item, and the kay has the
1459 // generalized form (refer to \ref gdcmBaseTagKey):
1460 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1462 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1463 + newBinEntry->GetKey() );
1466 set->AddEntry( newBinEntry );
1467 LoadDocEntry( newBinEntry );
1470 if (newDocEntry->GetGroup() == 0x7fe0 &&
1471 newDocEntry->GetElement() == 0x0010 )
1473 if ( IsRLELossLessTransferSyntax() )
1475 long PositionOnEntry = ftell(Fp);
1476 fseek(Fp, newDocEntry->GetOffset(), SEEK_SET);
1478 fseek(Fp, PositionOnEntry, SEEK_SET);
1482 SkipToNextDocEntry(newDocEntry);
1487 // to be sure we are at the beginning
1488 SkipToNextDocEntry(newDocEntry);
1494 unsigned long l = newDocEntry->GetReadLength();
1495 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1497 if ( l == 0xffffffff )
1506 // no other way to create it ...
1507 gdcmSeqEntry* newSeqEntry =
1508 new gdcmSeqEntry( newDocEntry->GetDictEntry() );
1509 newSeqEntry->Copy( newDocEntry );
1510 newSeqEntry->SetDelimitorMode( delim_mode );
1512 // At the top of the hierarchy, stands a gdcmDocument. When "set"
1513 // is a gdcmDocument, then we are building the first depth level.
1514 // Hence the gdcmSeqEntry we are building simply has a depth
1516 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1519 newSeqEntry->SetDepthLevel( 1 );
1520 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1522 // But when "set" is allready a SQItem, we are building a nested
1523 // sequence, and hence the depth level of the new gdcmSeqEntry
1524 // we are building, is one level deeper:
1525 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1527 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1528 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1529 + newSeqEntry->GetKey() );
1533 { // Don't try to parse zero-length sequences
1534 ParseSQ( newSeqEntry,
1535 newDocEntry->GetOffset(),
1538 set->AddEntry( newSeqEntry );
1539 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1549 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1550 * @return parsed length for this level
1552 void gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1553 long offset, long l_max, bool delim_mode)
1555 int SQItemNumber = 0;
1560 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1563 // FIXME Should warn user
1568 if ( newDocEntry->IsSequenceDelimitor() )
1570 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1574 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1579 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1580 std::ostringstream newBase;
1581 newBase << seqEntry->GetKey()
1585 itemSQ->SetBaseTagKey( newBase.str() );
1586 unsigned int l = newDocEntry->GetReadLength();
1588 if ( l == 0xffffffff )
1597 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1599 seqEntry->AddEntry( itemSQ, SQItemNumber );
1601 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1609 * \brief Loads the element content if its length doesn't exceed
1610 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1611 * @param entry Header Entry (Dicom Element) to be dealt with
1613 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1616 uint16_t group = entry->GetGroup();
1617 std::string vr = entry->GetVR();
1618 uint32_t length = entry->GetLength();
1620 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1622 // A SeQuence "contains" a set of Elements.
1623 // (fffe e000) tells us an Element is beginning
1624 // (fffe e00d) tells us an Element just ended
1625 // (fffe e0dd) tells us the current SeQuence just ended
1626 if( group == 0xfffe )
1628 // NO more value field for SQ !
1632 // When the length is zero things are easy:
1635 ((gdcmValEntry *)entry)->SetValue("");
1639 // The elements whose length is bigger than the specified upper bound
1640 // are not loaded. Instead we leave a short notice of the offset of
1641 // the element content and it's length.
1643 std::ostringstream s;
1644 if (length > MaxSizeLoadEntry)
1646 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1648 //s << "gdcm::NotLoaded (BinEntry)";
1649 s << GDCM_NOTLOADED;
1650 s << " Address:" << (long)entry->GetOffset();
1651 s << " Length:" << entry->GetLength();
1652 s << " x(" << std::hex << entry->GetLength() << ")";
1653 binEntryPtr->SetValue(s.str());
1655 // Be carefull : a BinEntry IS_A ValEntry ...
1656 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1658 // s << "gdcm::NotLoaded. (ValEntry)";
1659 s << GDCM_NOTLOADED;
1660 s << " Address:" << (long)entry->GetOffset();
1661 s << " Length:" << entry->GetLength();
1662 s << " x(" << std::hex << entry->GetLength() << ")";
1663 valEntryPtr->SetValue(s.str());
1668 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1669 << "nor a ValEntry ?! Should never print that !" << std::endl;
1672 // to be sure we are at the end of the value ...
1673 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1677 // When we find a BinEntry not very much can be done :
1678 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1680 s << GDCM_BINLOADED;
1681 binEntryPtr->SetValue(s.str());
1682 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1686 /// \todo Any compacter code suggested (?)
1687 if ( IsDocEntryAnInteger(entry) )
1691 // When short integer(s) are expected, read and convert the following
1692 // n *two characters properly i.e. consider them as short integers as
1693 // opposed to strings.
1694 // Elements with Value Multiplicity > 1
1695 // contain a set of integers (not a single one)
1696 if (vr == "US" || vr == "SS")
1699 NewInt = ReadInt16();
1703 for (int i=1; i < nbInt; i++)
1706 NewInt = ReadInt16();
1711 // See above comment on multiple integers (mutatis mutandis).
1712 else if (vr == "UL" || vr == "SL")
1715 NewInt = ReadInt32();
1719 for (int i=1; i < nbInt; i++)
1722 NewInt = ReadInt32();
1727 #ifdef GDCM_NO_ANSI_STRING_STREAM
1728 s << std::ends; // to avoid oddities on Solaris
1729 #endif //GDCM_NO_ANSI_STRING_STREAM
1731 ((gdcmValEntry *)entry)->SetValue(s.str());
1735 // We need an additional byte for storing \0 that is not on disk
1736 //std::string newValue(length,0);
1737 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1738 //rah !! I can't believe it could work, normally this is a const char* !!!
1739 char *str = new char[length+1];
1740 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1742 std::string newValue = str;
1744 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1746 if ( item_read != 1 )
1748 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1749 "unread element value");
1750 valEntry->SetValue(GDCM_UNREAD);
1756 // Because of correspondance with the VR dic
1757 valEntry->SetValue(newValue);
1761 valEntry->SetValue(newValue);
1766 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1767 "Should have a ValEntry, here !");
1773 * \brief Find the value Length of the passed Header Entry
1774 * @param entry Header Entry whose length of the value shall be loaded.
1776 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1777 throw ( gdcmFormatError )
1779 uint16_t element = entry->GetElement();
1780 std::string vr = entry->GetVR();
1783 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1785 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1787 // The following reserved two bytes (see PS 3.5-2001, section
1788 // 7.1.2 Data element structure with explicit vr p27) must be
1789 // skipped before proceeding on reading the length on 4 bytes.
1790 fseek(Fp, 2L, SEEK_CUR);
1791 uint32_t length32 = ReadInt32();
1793 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1798 /// \todo rename that to FindDocEntryLengthOBOrOW since
1799 /// the above test is on both OB and OW...
1800 lengthOB = FindDocEntryLengthOB();
1802 catch ( gdcmFormatUnexpected )
1804 // Computing the length failed (this happens with broken
1805 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1806 // chance to get the pixels by deciding the element goes
1807 // until the end of the file. Hence we artificially fix the
1808 // the length and proceed.
1809 long currentPosition = ftell(Fp);
1810 fseek(Fp,0L,SEEK_END);
1811 long lengthUntilEOF = ftell(Fp) - currentPosition;
1812 fseek(Fp, currentPosition, SEEK_SET);
1813 entry->SetLength(lengthUntilEOF);
1816 entry->SetLength(lengthOB);
1819 FixDocEntryFoundLength(entry, length32);
1823 // Length is encoded on 2 bytes.
1824 length16 = ReadInt16();
1826 // We can tell the current file is encoded in big endian (like
1827 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1828 // and it's value is the one of the encoding of a big endian file.
1829 // In order to deal with such big endian encoded files, we have
1830 // (at least) two strategies:
1831 // * when we load the "Transfer Syntax" tag with value of big endian
1832 // encoding, we raise the proper flags. Then we wait for the end
1833 // of the META group (0x0002) among which is "Transfer Syntax",
1834 // before switching the swap code to big endian. We have to postpone
1835 // the switching of the swap code since the META group is fully encoded
1836 // in little endian, and big endian coding only starts at the next
1837 // group. The corresponding code can be hard to analyse and adds
1838 // many additional unnecessary tests for regular tags.
1839 // * the second strategy consists in waiting for trouble, that shall
1840 // appear when we find the first group with big endian encoding. This
1841 // is easy to detect since the length of a "Group Length" tag (the
1842 // ones with zero as element number) has to be of 4 (0x0004). When we
1843 // encounter 1024 (0x0400) chances are the encoding changed and we
1844 // found a group with big endian encoding.
1845 // We shall use this second strategy. In order to make sure that we
1846 // can interpret the presence of an apparently big endian encoded
1847 // length of a "Group Length" without committing a big mistake, we
1848 // add an additional check: we look in the already parsed elements
1849 // for the presence of a "Transfer Syntax" whose value has to be "big
1850 // endian encoding". When this is the case, chances are we have got our
1851 // hands on a big endian encoded file: we switch the swap code to
1852 // big endian and proceed...
1853 if ( element == 0x0000 && length16 == 0x0400 )
1855 if ( !IsExplicitVRBigEndianTransferSyntax() )
1857 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1858 " not explicit VR." );
1862 SwitchSwapToBigEndian();
1863 // Restore the unproperly loaded values i.e. the group, the element
1864 // and the dictionary entry depending on them.
1865 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1866 uint16_t correctElem = SwapShort( entry->GetElement() );
1867 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1871 // This correct tag is not in the dictionary. Create a new one.
1872 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1874 // FIXME this can create a memory leaks on the old entry that be
1875 // left unreferenced.
1876 entry->SetDictEntry( newTag );
1879 // Heuristic: well, some files are really ill-formed.
1880 if ( length16 == 0xffff)
1882 // 0xffff means that we deal with 'Unknown Length' Sequence
1885 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1890 // Either implicit VR or a non DICOM conformal (see note below) explicit
1891 // VR that ommited the VR of (at least) this element. Farts happen.
1892 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1893 // on Data elements "Implicit and Explicit VR Data Elements shall
1894 // not coexist in a Data Set and Data Sets nested within it".]
1895 // Length is on 4 bytes.
1897 FixDocEntryFoundLength( entry, ReadInt32() );
1903 * \brief Find the Value Representation of the current Dicom Element.
1906 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1908 if ( Filetype != gdcmExplicitVR )
1915 long positionOnEntry = ftell(Fp);
1916 // Warning: we believe this is explicit VR (Value Representation) because
1917 // we used a heuristic that found "UL" in the first tag. Alas this
1918 // doesn't guarantee that all the tags will be in explicit VR. In some
1919 // cases (see e-film filtered files) one finds implicit VR tags mixed
1920 // within an explicit VR file. Hence we make sure the present tag
1921 // is in explicit VR and try to fix things if it happens not to be
1924 fread (vr, (size_t)2,(size_t)1, Fp);
1927 if( !CheckDocEntryVR(entry, vr) )
1929 fseek(Fp, positionOnEntry, SEEK_SET);
1930 // When this element is known in the dictionary we shall use, e.g. for
1931 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1932 // dictionary entry. Still we have to flag the element as implicit since
1933 // we know now our assumption on expliciteness is not furfilled.
1935 if ( entry->IsVRUnknown() )
1937 entry->SetVR("Implicit");
1939 entry->SetImplicitVR();
1944 * \brief Check the correspondance between the VR of the header entry
1945 * and the taken VR. If they are different, the header entry is
1946 * updated with the new VR.
1947 * @param entry Header Entry to check
1948 * @param vr Dicom Value Representation
1949 * @return false if the VR is incorrect of if the VR isn't referenced
1950 * otherwise, it returns true
1952 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1954 char msg[100]; // for sprintf
1955 bool realExplicit = true;
1957 // Assume we are reading a falsely explicit VR file i.e. we reached
1958 // a tag where we expect reading a VR but are in fact we read the
1959 // first to bytes of the length. Then we will interogate (through find)
1960 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1961 // both GCC and VC++ implementations of the STL map. Hence when the
1962 // expected VR read happens to be non-ascii characters we consider
1963 // we hit falsely explicit VR tag.
1965 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1967 realExplicit = false;
1970 // CLEANME searching the dicom_vr at each occurence is expensive.
1971 // PostPone this test in an optional integrity check at the end
1972 // of parsing or only in debug mode.
1973 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1975 realExplicit = false;
1978 if ( !realExplicit )
1980 // We thought this was explicit VR, but we end up with an
1981 // implicit VR tag. Let's backtrack.
1982 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1983 entry->GetGroup(), entry->GetElement());
1984 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1986 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1988 // Group length is UL !
1989 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1990 entry->GetGroup(), entry->GetElement(),
1991 "UL", "FIXME", "Group Length");
1992 entry->SetDictEntry( newEntry );
1997 if ( entry->IsVRUnknown() )
1999 // When not a dictionary entry, we can safely overwrite the VR.
2000 if( entry->GetElement() == 0x0000 )
2002 // Group length is UL !
2010 else if ( entry->GetVR() != vr )
2012 // The VR present in the file and the dictionary disagree. We assume
2013 // the file writer knew best and use the VR of the file. Since it would
2014 // be unwise to overwrite the VR of a dictionary (since it would
2015 // compromise it's next user), we need to clone the actual DictEntry
2016 // and change the VR for the read one.
2017 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2018 entry->GetGroup(), entry->GetElement(),
2019 vr, "FIXME", entry->GetName());
2020 entry->SetDictEntry(newEntry);
2027 * \brief Get the transformed value of the header entry. The VR value
2028 * is used to define the transformation to operate on the value
2029 * \warning NOT end user intended method !
2030 * @param entry entry to tranform
2031 * @return Transformed entry value
2033 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2035 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2037 std::string val = ((gdcmValEntry *)entry)->GetValue();
2038 std::string vr = entry->GetVR();
2039 uint32_t length = entry->GetLength();
2040 std::ostringstream s;
2043 // When short integer(s) are expected, read and convert the following
2044 // n * 2 bytes properly i.e. as a multivaluated strings
2045 // (each single value is separated fromthe next one by '\'
2046 // as usual for standard multivaluated filels
2047 // Elements with Value Multiplicity > 1
2048 // contain a set of short integers (not a single one)
2050 if( vr == "US" || vr == "SS" )
2055 for (int i=0; i < nbInt; i++)
2061 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2062 newInt16 = SwapShort( newInt16 );
2067 // When integer(s) are expected, read and convert the following
2068 // n * 4 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 integers (not a single one)
2073 else if( vr == "UL" || vr == "SL" )
2078 for (int i=0; i < nbInt; i++)
2084 newInt32 = ( val[4*i+0] & 0xFF )
2085 + (( val[4*i+1] & 0xFF ) << 8 )
2086 + (( val[4*i+2] & 0xFF ) << 16 )
2087 + (( val[4*i+3] & 0xFF ) << 24 );
2088 newInt32 = SwapLong( newInt32 );
2092 #ifdef GDCM_NO_ANSI_STRING_STREAM
2093 s << std::ends; // to avoid oddities on Solaris
2094 #endif //GDCM_NO_ANSI_STRING_STREAM
2098 return ((gdcmValEntry *)entry)->GetValue();
2102 * \brief Get the reverse transformed value of the header entry. The VR
2103 * value is used to define the reverse transformation to operate on
2105 * \warning NOT end user intended method !
2106 * @param entry Entry to reverse transform
2107 * @return Reverse transformed entry value
2109 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2111 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2113 std::string vr = entry->GetVR();
2114 std::vector<std::string> tokens;
2115 std::ostringstream s;
2117 if ( vr == "US" || vr == "SS" )
2121 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2122 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2123 for (unsigned int i=0; i<tokens.size(); i++)
2125 newInt16 = atoi(tokens[i].c_str());
2126 s << ( newInt16 & 0xFF )
2127 << (( newInt16 >> 8 ) & 0xFF );
2131 if ( vr == "UL" || vr == "SL")
2135 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2136 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2137 for (unsigned int i=0; i<tokens.size();i++)
2139 newInt32 = atoi(tokens[i].c_str());
2140 s << (char)( newInt32 & 0xFF )
2141 << (char)(( newInt32 >> 8 ) & 0xFF )
2142 << (char)(( newInt32 >> 16 ) & 0xFF )
2143 << (char)(( newInt32 >> 24 ) & 0xFF );
2148 #ifdef GDCM_NO_ANSI_STRING_STREAM
2149 s << std::ends; // to avoid oddities on Solaris
2150 #endif //GDCM_NO_ANSI_STRING_STREAM
2154 return ((gdcmValEntry *)entry)->GetValue();
2158 * \brief Skip a given Header Entry
2159 * \warning NOT end user intended method !
2160 * @param entry entry to skip
2162 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2164 SkipBytes(entry->GetLength());
2168 * \brief Skips to the begining of the next Header Entry
2169 * \warning NOT end user intended method !
2170 * @param entry entry to skip
2172 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2174 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2175 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2179 * \brief When the length of an element value is obviously wrong (because
2180 * the parser went Jabberwocky) one can hope improving things by
2181 * applying some heuristics.
2182 * @param entry entry to check
2183 * @param foundLength fist assumption about length
2185 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2186 uint32_t foundLength)
2188 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2189 if ( foundLength == 0xffffffff)
2194 uint16_t gr = entry->GetGroup();
2195 uint16_t el = entry->GetElement();
2197 if ( foundLength % 2)
2199 std::ostringstream s;
2200 s << "Warning : Tag with uneven length "
2202 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2203 dbg.Verbose(0, s.str().c_str());
2206 //////// Fix for some naughty General Electric images.
2207 // Allthough not recent many such GE corrupted images are still present
2208 // on Creatis hard disks. Hence this fix shall remain when such images
2209 // are no longer in user (we are talking a few years, here)...
2210 // Note: XMedCom probably uses such a trick since it is able to read
2211 // those pesky GE images ...
2212 if ( foundLength == 13)
2214 // Only happens for this length !
2215 if ( entry->GetGroup() != 0x0008
2216 || ( entry->GetElement() != 0x0070
2217 && entry->GetElement() != 0x0080 ) )
2220 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2224 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2225 // Occurence of such images is quite low (unless one leaves close to a
2226 // 'Leonardo' source. Hence, one might consider commenting out the
2227 // following fix on efficiency reasons.
2228 else if ( entry->GetGroup() == 0x0009
2229 && ( entry->GetElement() == 0x1113
2230 || entry->GetElement() == 0x1114 ) )
2233 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2236 else if ( entry->GetVR() == "SQ" )
2238 foundLength = 0; // ReadLength is unchanged
2241 //////// We encountered a 'delimiter' element i.e. a tag of the form
2242 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2243 // taken into account.
2244 else if( entry->GetGroup() == 0xfffe )
2246 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2247 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2248 // causes extra troubles...
2249 if( entry->GetElement() != 0x0000 )
2255 entry->SetUsableLength(foundLength);
2259 * \brief Apply some heuristics to predict whether the considered
2260 * element value contains/represents an integer or not.
2261 * @param entry The element value on which to apply the predicate.
2262 * @return The result of the heuristical predicate.
2264 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2266 uint16_t element = entry->GetElement();
2267 uint16_t group = entry->GetGroup();
2268 std::string vr = entry->GetVR();
2269 uint32_t length = entry->GetLength();
2271 // When we have some semantics on the element we just read, and if we
2272 // a priori know we are dealing with an integer, then we shall be
2273 // able to swap it's element value properly.
2274 if ( element == 0 ) // This is the group length of the group
2282 // Allthough this should never happen, still some images have a
2283 // corrupted group length [e.g. have a glance at offset x(8336) of
2284 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2285 // Since for dicom compliant and well behaved headers, the present
2286 // test is useless (and might even look a bit paranoid), when we
2287 // encounter such an ill-formed image, we simply display a warning
2288 // message and proceed on parsing (while crossing fingers).
2289 std::ostringstream s;
2290 int filePosition = ftell(Fp);
2291 s << "Erroneous Group Length element length on : (" \
2292 << std::hex << group << " , " << element
2293 << ") -before- position x(" << filePosition << ")"
2294 << "lgt : " << length;
2295 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2299 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2308 * \brief Find the Length till the next sequence delimiter
2309 * \warning NOT end user intended method !
2313 uint32_t gdcmDocument::FindDocEntryLengthOB()
2314 throw( gdcmFormatUnexpected )
2316 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2317 long positionOnEntry = ftell(Fp);
2318 bool foundSequenceDelimiter = false;
2319 uint32_t totalLength = 0;
2321 while ( !foundSequenceDelimiter )
2327 group = ReadInt16();
2330 catch ( gdcmFormatError )
2332 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2333 " group or element not present.");
2336 // We have to decount the group and element we just read
2339 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2341 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2342 "tag nor a Sequence delimiter tag.");
2343 fseek(Fp, positionOnEntry, SEEK_SET);
2344 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2345 "Neither an Item tag nor a Sequence "
2349 if ( elem == 0xe0dd )
2351 foundSequenceDelimiter = true;
2354 uint32_t itemLength = ReadInt32();
2355 // We add 4 bytes since we just read the ItemLength with ReadInt32
2356 totalLength += itemLength + 4;
2357 SkipBytes(itemLength);
2359 if ( foundSequenceDelimiter )
2364 fseek(Fp, positionOnEntry, SEEK_SET);
2369 * \brief Reads a supposed to be 16 Bits integer
2370 * (swaps it depending on processor endianity)
2371 * @return read value
2373 uint16_t gdcmDocument::ReadInt16()
2374 throw( gdcmFormatError )
2377 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2378 if ( item_read != 1 )
2382 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2384 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2391 * \brief Reads a supposed to be 32 Bits integer
2392 * (swaps it depending on processor endianity)
2393 * @return read value
2395 uint32_t gdcmDocument::ReadInt32()
2396 throw( gdcmFormatError )
2399 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2400 if ( item_read != 1 )
2404 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2406 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2413 * \brief skips bytes inside the source file
2414 * \warning NOT end user intended method !
2417 void gdcmDocument::SkipBytes(uint32_t nBytes)
2419 //FIXME don't dump the returned value
2420 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2424 * \brief Loads all the needed Dictionaries
2425 * \warning NOT end user intended method !
2427 void gdcmDocument::Initialise()
2429 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2434 * \brief Discover what the swap code is (among little endian, big endian,
2435 * bad little endian, bad big endian).
2437 * @return false when we are absolutely sure
2438 * it's neither ACR-NEMA nor DICOM
2439 * true when we hope ours assuptions are OK
2441 bool gdcmDocument::CheckSwap()
2443 // The only guaranted way of finding the swap code is to find a
2444 // group tag since we know it's length has to be of four bytes i.e.
2445 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2446 // occurs when we can't find such group...
2448 uint32_t x = 4; // x : for ntohs
2449 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2453 char deb[HEADER_LENGTH_TO_READ];
2455 // First, compare HostByteOrder and NetworkByteOrder in order to
2456 // determine if we shall need to swap bytes (i.e. the Endian type).
2457 if ( x == ntohs(x) )
2466 // The easiest case is the one of a DICOM header, since it possesses a
2467 // file preamble where it suffice to look for the string "DICM".
2468 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2469 (void)lgrLue; //FIXME not used
2471 char *entCur = deb + 128;
2472 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2474 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2476 // Next, determine the value representation (VR). Let's skip to the
2477 // first element (0002, 0000) and check there if we find "UL"
2478 // - or "OB" if the 1st one is (0002,0001) -,
2479 // in which case we (almost) know it is explicit VR.
2480 // WARNING: if it happens to be implicit VR then what we will read
2481 // is the length of the group. If this ascii representation of this
2482 // length happens to be "UL" then we shall believe it is explicit VR.
2483 // FIXME: in order to fix the above warning, we could read the next
2484 // element value (or a couple of elements values) in order to make
2485 // sure we are not commiting a big mistake.
2486 // We need to skip :
2487 // * the 128 bytes of File Preamble (often padded with zeroes),
2488 // * the 4 bytes of "DICM" string,
2489 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2490 // i.e. a total of 136 bytes.
2494 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2495 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2496 // *Implicit* VR. -and it is !-
2498 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2499 memcmp(entCur, "OB", (size_t)2) == 0 ||
2500 memcmp(entCur, "UI", (size_t)2) == 0 ||
2501 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2502 // when Write DCM *adds*
2504 // Use gdcmDocument::dicom_vr to test all the possibilities
2505 // instead of just checking for UL, OB and UI !? group 0000
2507 Filetype = gdcmExplicitVR;
2508 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2509 "explicit Value Representation");
2513 Filetype = gdcmImplicitVR;
2514 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2515 "not an explicit Value Representation");
2521 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2522 "HostByteOrder != NetworkByteOrder");
2527 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2528 "HostByteOrder = NetworkByteOrder");
2531 // Position the file position indicator at first tag (i.e.
2532 // after the file preamble and the "DICM" string).
2534 fseek (Fp, 132L, SEEK_SET);
2538 // Alas, this is not a DicomV3 file and whatever happens there is no file
2539 // preamble. We can reset the file position indicator to where the data
2540 // is (i.e. the beginning of the file).
2541 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2544 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2545 // By clean we mean that the length of the first tag is written down.
2546 // If this is the case and since the length of the first group HAS to be
2547 // four (bytes), then determining the proper swap code is straightforward.
2550 // We assume the array of char we are considering contains the binary
2551 // representation of a 32 bits integer. Hence the following dirty
2553 s32 = *((uint32_t *)(entCur));
2574 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2575 // It is time for despaired wild guesses.
2576 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2577 // i.e. the 'group length' element is not present :
2579 // check the supposed to be 'group number'
2580 // 0x0002 or 0x0004 or 0x0008
2581 // to determine ' SwapCode' value .
2582 // Only 0 or 4321 will be possible
2583 // (no oportunity to check for the formerly well known
2584 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2585 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2586 // the file IS NOT ACR-NEMA nor DICOM V3
2587 // Find a trick to tell it the caller...
2589 s16 = *((uint16_t *)(deb));
2606 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2607 "ACR/NEMA unfound swap info (Really hopeless !)");
2608 Filetype = gdcmUnknown;
2611 // Then the only info we have is the net2host one.
2621 * \brief Restore the unproperly loaded values i.e. the group, the element
2622 * and the dictionary entry depending on them.
2624 void gdcmDocument::SwitchSwapToBigEndian()
2626 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2627 "Switching to BigEndian mode.");
2628 if ( SwapCode == 0 )
2632 else if ( SwapCode == 4321 )
2636 else if ( SwapCode == 3412 )
2640 else if ( SwapCode == 2143 )
2647 * \brief during parsing, Header Elements too long are not loaded in memory
2650 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2656 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2658 MaxSizeLoadEntry = 0xffffffff;
2661 MaxSizeLoadEntry = newSize;
2666 * \brief Header Elements too long will not be printed
2667 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2670 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2672 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2677 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2679 MaxSizePrintEntry = 0xffffffff;
2682 MaxSizePrintEntry = newSize;
2688 * \brief Read the next tag but WITHOUT loading it's value
2689 * (read the 'Group Number', the 'Element Number',
2690 * gets the Dict Entry
2691 * gets the VR, gets the length, gets the offset value)
2692 * @return On succes the newly created DocEntry, NULL on failure.
2694 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2701 group = ReadInt16();
2704 catch ( gdcmFormatError e )
2706 // We reached the EOF (or an error occured) therefore
2707 // header parsing has to be considered as finished.
2712 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2713 FindDocEntryVR(newEntry);
2717 FindDocEntryLength(newEntry);
2719 catch ( gdcmFormatError e )
2727 newEntry->SetOffset(ftell(Fp));
2734 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2735 * in the TagHt dictionary.
2736 * @param group The generated tag must belong to this group.
2737 * @return The element of tag with given group which is fee.
2739 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2741 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2743 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2744 if (TagHT.count(key) == 0)
2753 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2754 * is placed at the beginning of a tag check whether this
2755 * tag is (TestGroup, TestElement).
2756 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2757 * is modified to point after the tag.
2758 * On failure (i.e. when the tag wasn't the expected tag
2759 * (TestGroup, TestElement) the internal file pointer
2760 * \ref gdcmDocument::Fp is restored to it's original position.
2761 * @param testGroup The expected group of the tag.
2762 * @param testElement The expected Element of the tag.
2763 * @return True on success, false otherwise.
2765 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2767 long positionOnEntry = ftell(Fp);
2768 long currentPosition = ftell(Fp); // On debugging purposes
2770 //// Read the Item Tag group and element, and make
2771 // sure they are what we expected:
2772 uint16_t itemTagGroup = ReadInt16();
2773 uint16_t itemTagElement = ReadInt16();
2774 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2776 std::ostringstream s;
2777 s << " We should have found tag (";
2778 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2779 s << " but instead we encountered tag (";
2780 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2782 s << " at address: " << (unsigned)currentPosition << std::endl;
2783 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2784 dbg.Verbose(0, s.str().c_str());
2785 fseek(Fp, positionOnEntry, SEEK_SET);
2793 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2794 * is placed at the beginning of a tag (TestGroup, TestElement),
2795 * read the length associated to the Tag.
2796 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2797 * is modified to point after the tag and it's length.
2798 * On failure (i.e. when the tag wasn't the expected tag
2799 * (TestGroup, TestElement) the internal file pointer
2800 * \ref gdcmDocument::Fp is restored to it's original position.
2801 * @param testGroup The expected group of the tag.
2802 * @param testElement The expected Element of the tag.
2803 * @return On success returns the length associated to the tag. On failure
2806 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2808 long positionOnEntry = ftell(Fp);
2809 (void)positionOnEntry;
2811 if ( !ReadTag(testGroup, testElement) )
2816 //// Then read the associated Item Length
2817 long currentPosition = ftell(Fp);
2818 uint32_t itemLength = ReadInt32();
2820 std::ostringstream s;
2821 s << "Basic Item Length is: "
2822 << itemLength << std::endl;
2823 s << " at address: " << (unsigned)currentPosition << std::endl;
2824 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2830 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2831 * Compute the RLE extra information and store it in \ref RLEInfo
2832 * for later pixel retrieval usage.
2834 void gdcmDocument::ComputeRLEInfo()
2836 if ( ! IsRLELossLessTransferSyntax() )
2840 // Encoded pixel data: for the time being we are only concerned with
2841 // Jpeg or RLE Pixel data encodings.
2842 // As stated in ps-3.3, 8.2:
2843 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2844 // value representation OB is used".
2845 // Hence we expect an OB value representation. Concerning OB VR,
2846 // the section PS3.3, A.4.c (p58 and p59), states:
2847 // "For the Value Representations OB and OW, the encoding shall meet the
2848 // following specifications depending on the Data element tag:"
2850 // - the first item in the sequence of items before the encoded pixel
2851 // data stream shall be basic offset table item. The basic offset table
2852 // item value, however, is not required to be present"
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);
2868 for (unsigned int i=0; i < itemLength; i += 4 )
2870 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2872 std::ostringstream s;
2873 s << " Read one length: ";
2874 s << std::hex << individualLength << std::endl;
2875 dbg.Verbose(0, "gdcmDocument::ComputeRLEInfo: ", s.str().c_str());
2877 delete[] basicOffsetTableItemValue;
2880 // Encapsulated RLE Compressed Images (see PS-3.3, Annex G).
2881 // Loop on the frame[s] and store the parsed information in a
2882 // gdcmRLEFramesInfo.
2885 // Loop on the individual frame[s] and store the information
2886 // on the RLE fragments in a gdcmRLEFramesInfo.
2887 // Note: - when only a single frame is present, this is a
2889 // - when more than one frame are present, then we are in
2890 // the case of a multi-frame image.
2891 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2893 // Parse the RLE Header and store the corresponding RLE Segment
2894 // Offset Table information on fragments of this current Frame.
2895 // Note that the fragment pixels themselves are not loaded
2896 // (but just skipped).
2897 long frameOffset = ftell(Fp);
2899 uint32_t nbRleSegments = ReadInt32();
2901 uint32_t rleSegmentOffsetTable[15];
2902 for( int k = 1; k <= 15; k++ )
2904 rleSegmentOffsetTable[k] = ReadInt32();
2907 // Deduce from both the RLE Header and the frameLength the
2908 // fragment length, and again store this info in a
2909 // gdcmRLEFramesInfo.
2910 long rleSegmentLength[15];
2911 // skipping (not reading) RLE Segments
2912 if ( nbRleSegments > 1)
2914 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2916 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2917 - rleSegmentOffsetTable[k];
2918 SkipBytes(rleSegmentLength[k]);
2922 rleSegmentLength[nbRleSegments] = frameLength
2923 - rleSegmentOffsetTable[nbRleSegments];
2924 SkipBytes(rleSegmentLength[nbRleSegments]);
2926 // Store the collected info
2927 gdcmRLEFrame* newFrameInfo = new gdcmRLEFrame;
2928 newFrameInfo->NumberFragments = nbRleSegments;
2929 for( unsigned int k = 1; k <= nbRleSegments; k++ )
2931 newFrameInfo->Offset[k] = frameOffset + rleSegmentOffsetTable[k];
2932 newFrameInfo->Length[k] = rleSegmentLength[k];
2934 RLEInfo.Frames.push_back( newFrameInfo );
2937 // Make sure that at the end of the item we encounter a 'Sequence
2939 if ( !ReadTag(0xfffe, 0xe0dd) )
2941 dbg.Verbose(0, "gdcmDocument::ComputeRLEInfo: no sequence delimiter ");
2942 dbg.Verbose(0, " item at end of RLE item sequence");
2947 * \brief Walk recursively the given \ref gdcmDocEntrySet, and feed
2948 * the given hash table (\ref TagDocEntryHT) with all the
2949 * \ref gdcmDocEntry (Dicom entries) encountered.
2950 * This method does the job for \ref BuildFlatHashTable.
2951 * @param builtHT Where to collect all the \ref gdcmDocEntry encountered
2952 * when recursively walking the given set.
2953 * @param set The structure to be traversed (recursively).
2955 void gdcmDocument::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
2956 gdcmDocEntrySet* set )
2958 if (gdcmElementSet* elementSet = dynamic_cast< gdcmElementSet* > ( set ) )
2960 TagDocEntryHT* currentHT = elementSet->GetTagHT();
2961 for( TagDocEntryHT::const_iterator i = currentHT->begin();
2962 i != currentHT->end();
2965 gdcmDocEntry* entry = i->second;
2966 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
2968 ListSQItem& items = seqEntry->GetSQItems();
2969 for( ListSQItem::const_iterator item = items.begin();
2970 item != items.end();
2973 BuildFlatHashTableRecurse( builtHT, *item );
2977 builtHT[entry->GetKey()] = entry;
2982 if (gdcmSQItem* SQItemSet = dynamic_cast< gdcmSQItem* > ( set ) )
2984 ListDocEntry& currentList = SQItemSet->GetDocEntries();
2985 for (ListDocEntry::iterator i = currentList.begin();
2986 i != currentList.end();
2989 gdcmDocEntry* entry = *i;
2990 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
2992 ListSQItem& items = seqEntry->GetSQItems();
2993 for( ListSQItem::const_iterator item = items.begin();
2994 item != items.end();
2997 BuildFlatHashTableRecurse( builtHT, *item );
3001 builtHT[entry->GetKey()] = entry;
3008 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3011 * The structure used by a gdcmDocument (through \ref gdcmElementSet),
3012 * in order to old the parsed entries of a Dicom header, is a recursive
3013 * one. This is due to the fact that the sequences (when present)
3014 * can be nested. Additionaly, the sequence items (represented in
3015 * gdcm as \ref gdcmSQItem) add an extra complexity to the data
3016 * structure. Hence, a gdcm user whishing to visit all the entries of
3017 * a Dicom header will need to dig in the gdcm internals (which
3018 * implies exposing all the internal data structures to the API).
3019 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3020 * recursively builds a temporary hash table, which holds all the
3021 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3023 * \warning Of course there is NO integrity constrain between the
3024 * returned \ref TagDocEntryHT and the \ref gdcmElementSet used
3025 * to build it. Hence if the underlying \ref gdcmElementSet is
3026 * altered, then it is the caller responsability to invoke
3027 * \ref BuildFlatHashTable again...
3028 * @return The flat std::map<> we juste build.
3030 TagDocEntryHT* gdcmDocument::BuildFlatHashTable()
3032 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3033 BuildFlatHashTableRecurse( *FlatHT, this );
3040 * \brief Compares two documents, according to \ref gdcmDicomDir rules
3041 * \warning Does NOT work with ACR-NEMA files
3042 * \todo Find a trick to solve the pb (use RET fields ?)
3044 * @return true if 'smaller'
3046 bool gdcmDocument::operator<(gdcmDocument &document)
3049 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3050 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3062 s1 = GetEntryByNumber(0x0010,0x0020);
3063 s2 = document.GetEntryByNumber(0x0010,0x0020);
3074 // Study Instance UID
3075 s1 = GetEntryByNumber(0x0020,0x000d);
3076 s2 = document.GetEntryByNumber(0x0020,0x000d);
3087 // Serie Instance UID
3088 s1 = GetEntryByNumber(0x0020,0x000e);
3089 s2 = document.GetEntryByNumber(0x0020,0x000e);
3105 //-----------------------------------------------------------------------------