1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/10/10 16:43:59 $
7 Version: $Revision: 1.102 $
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 any form
454 * of Jpeg encoded Pixel data.
455 * @return True when any form of JPEG found. False otherwise.
457 bool gdcmDocument::IsJPEGTransferSyntax()
459 return ( IsJPEGBaseLineProcess1TransferSyntax()
460 || IsJPEGExtendedProcess2_4TransferSyntax()
461 || IsJPEGExtendedProcess3_5TransferSyntax()
462 || IsJPEGSpectralSelectionProcess6_8TransferSyntax()
469 * \brief Determines if the Transfer Syntax corresponds to encapsulated
470 * of encoded Pixel Data (as opposed to native).
471 * @return True when encapsulated. False when native.
473 bool gdcmDocument::IsEncapsulateTransferSyntax()
475 return ( IsJPEGTransferSyntax()
476 || IsRLELossLessTransferSyntax() );
480 * \brief Predicate for dicom version 3 file.
481 * @return True when the file is a dicom version 3.
483 bool gdcmDocument::IsDicomV3()
485 // Checking if Transfert Syntax exists is enough
486 // Anyway, it's to late check if the 'Preamble' was found ...
487 // And ... would it be a rich idea to check ?
488 // (some 'no Preamble' DICOM images exist !)
489 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
493 * \brief returns the File Type
494 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
495 * @return the FileType code
497 FileType gdcmDocument::GetFileType()
503 * \brief Tries to open the file \ref gdcmDocument::Filename and
504 * checks the preamble when existing.
505 * @return The FILE pointer on success.
507 FILE* gdcmDocument::OpenFile()
509 Fp = fopen(Filename.c_str(),"rb");
514 "gdcmDocument::OpenFile cannot open file: ",
520 fread(&zero, (size_t)2, (size_t)1, Fp);
522 //ACR -- or DICOM with no Preamble --
523 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
529 fseek(Fp, 126L, SEEK_CUR);
531 fread(dicm, (size_t)4, (size_t)1, Fp);
532 if( memcmp(dicm, "DICM", 4) == 0 )
539 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
546 * \brief closes the file
547 * @return TRUE if the close was successfull
549 bool gdcmDocument::CloseFile()
551 int closed = fclose(Fp);
558 * \brief Writes in a file all the Header Entries (Dicom Elements)
559 * @param fp file pointer on an already open file
560 * @param filetype Type of the File to be written
561 * (ACR-NEMA, ExplicitVR, ImplicitVR)
562 * \return Always true.
564 void gdcmDocument::Write(FILE* fp,FileType filetype)
566 /// \todo move the following lines (and a lot of others, to be written)
567 /// to a future function CheckAndCorrectHeader
568 /// (necessary if user wants to write a DICOM V3 file
569 /// starting from an ACR-NEMA (V2) gdcmHeader
571 if (filetype == gdcmImplicitVR)
573 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
574 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
576 /// \todo Refer to standards on page 21, chapter 6.2
577 /// "Value representation": values with a VR of UI shall be
578 /// padded with a single trailing null
579 /// in the following case we have to padd manually with a 0
581 SetEntryLengthByNumber(18, 0x0002, 0x0010);
584 if (filetype == gdcmExplicitVR)
586 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
587 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
589 /// \todo Refer to standards on page 21, chapter 6.2
590 /// "Value representation": values with a VR of UI shall be
591 /// padded with a single trailing null
592 /// Dans le cas suivant on doit pader manuellement avec un 0
594 SetEntryLengthByNumber(20, 0x0002, 0x0010);
598 * \todo rewrite later, if really usefull
599 * - 'Group Length' element is optional in DICOM
600 * - but un-updated odd groups lengthes can causes pb
603 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
604 * UpdateGroupLength(false,filetype);
605 * if ( filetype == ACR)
606 * UpdateGroupLength(true,ACR);
609 gdcmElementSet::Write(fp, filetype); // This one is recursive
614 * \brief Modifies the value of a given Header Entry (Dicom Element)
615 * when it exists. Create it with the given value when unexistant.
616 * @param value (string) Value to be set
617 * @param group Group number of the Entry
618 * @param elem Element number of the Entry
619 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
620 * \return pointer to the modified/created Header Entry (NULL when creation
623 gdcmValEntry* gdcmDocument::ReplaceOrCreateByNumber(
624 std::string const & value,
627 std::string const & VR )
629 gdcmValEntry* valEntry = 0;
630 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
634 // check if (group,element) DictEntry exists
635 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
638 // Find out if the tag we received is in the dictionaries:
639 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
640 gdcmDictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
643 currentEntry = NewDocEntryByNumber(group, elem,VR);
647 currentEntry = NewDocEntryByNumber(group, elem);
652 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
653 " NewDocEntryByNumber failed.");
656 valEntry = new gdcmValEntry(currentEntry);
657 if ( !AddEntry(valEntry))
659 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
660 " failed allthough this is a creation.");
665 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
666 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
667 // then we change it to a ValEntry ?
668 // Shouldn't it be considered as an error ?
670 // We need to promote the gdcmDocEntry to a gdcmValEntry:
671 valEntry = new gdcmValEntry(currentEntry);
672 if (!RemoveEntry(currentEntry))
674 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
675 " of previous DocEntry failed.");
678 if ( !AddEntry(valEntry))
680 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
681 " promoted ValEntry failed.");
687 SetEntryByNumber(value, group, elem);
693 * \brief Modifies the value of a given Header Entry (Dicom Element)
694 * when it exists. Create it with the given value when unexistant.
695 * @param binArea (binary) value to be set
696 * @param Group Group number of the Entry
697 * @param Elem Element number of the Entry
698 * \return pointer to the modified/created Header Entry (NULL when creation
701 gdcmBinEntry* gdcmDocument::ReplaceOrCreateByNumber(
706 std::string const& VR )
708 gdcmBinEntry* binEntry = 0;
709 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
713 // check if (group,element) DictEntry exists
714 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
717 // Find out if the tag we received is in the dictionaries:
718 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
719 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
723 currentEntry = NewDocEntryByNumber(group, elem, VR);
727 currentEntry = NewDocEntryByNumber(group, elem);
731 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
732 " NewDocEntryByNumber failed.");
735 binEntry = new gdcmBinEntry(currentEntry);
736 if ( !AddEntry(binEntry))
738 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
739 " failed allthough this is a creation.");
744 binEntry = dynamic_cast< gdcmBinEntry* >(currentEntry);
745 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
746 // then we change it to a BinEntry ?
747 // Shouldn't it be considered as an error ?
749 // We need to promote the gdcmDocEntry to a gdcmBinEntry:
750 binEntry = new gdcmBinEntry(currentEntry);
751 if (!RemoveEntry(currentEntry))
753 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
754 " of previous DocEntry failed.");
757 if ( !AddEntry(binEntry))
759 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
760 " promoted BinEntry failed.");
766 SetEntryByNumber(binArea, lgth, group, elem);
773 * \brief Modifies the value of a given Header Entry (Dicom Element)
774 * when it exists. Create it when unexistant.
775 * @param Group Group number of the Entry
776 * @param Elem Element number of the Entry
777 * \return pointer to the modified/created SeqEntry (NULL when creation
780 gdcmSeqEntry* gdcmDocument::ReplaceOrCreateByNumber(
785 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
788 a = NewSeqEntryByNumber(group, elem);
794 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
801 * \brief Set a new value if the invoked element exists
802 * Seems to be useless !!!
803 * @param value new element value
804 * @param group group number of the Entry
805 * @param elem element number of the Entry
808 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
809 uint16_t group, uint16_t elem )
811 SetEntryByNumber(value, group, elem);
816 //-----------------------------------------------------------------------------
820 * \brief Checks if a given Dicom Element exists within the H table
821 * @param group Group number of the searched Dicom Element
822 * @param element Element number of the searched Dicom Element
823 * @return true is found
825 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
827 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
828 return TagHT.count(key);
832 * \brief Searches within Header Entries (Dicom Elements) parsed with
833 * the public and private dictionaries
834 * for the element value of a given tag.
835 * \warning Don't use any longer : use GetPubEntryByName
836 * @param tagName name of the searched element.
837 * @return Corresponding element value when it exists,
838 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
840 std::string gdcmDocument::GetEntryByName(TagName const& tagName)
842 gdcmDictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
848 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
852 * \brief Searches within Header Entries (Dicom Elements) parsed with
853 * the public and private dictionaries
854 * for the element value representation of a given tag.
856 * Obtaining the VR (Value Representation) might be needed by caller
857 * to convert the string typed content to caller's native type
858 * (think of C++ vs Python). The VR is actually of a higher level
859 * of semantics than just the native C++ type.
860 * @param tagName name of the searched element.
861 * @return Corresponding element value representation when it exists,
862 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
864 std::string gdcmDocument::GetEntryVRByName(TagName const& tagName)
866 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
867 if( dictEntry == NULL)
872 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
873 dictEntry->GetElement());
874 return elem->GetVR();
878 * \brief Searches within Header Entries (Dicom Elements) parsed with
879 * the public and private dictionaries
880 * for the element value representation of a given tag.
881 * @param group Group number of the searched tag.
882 * @param element Element number of the searched tag.
883 * @return Corresponding element value representation when it exists,
884 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
886 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
888 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
889 /// \todo use map methods, instead of multimap JPR
890 if ( !TagHT.count(key))
895 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
899 * \brief Searches within Header Entries (Dicom Elements) parsed with
900 * the public and private dictionaries
901 * for the element value representation of a given tag..
903 * Obtaining the VR (Value Representation) might be needed by caller
904 * to convert the string typed content to caller's native type
905 * (think of C++ vs Python). The VR is actually of a higher level
906 * of semantics than just the native C++ type.
907 * @param group Group number of the searched tag.
908 * @param element Element number of the searched tag.
909 * @return Corresponding element value representation when it exists,
910 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
912 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
914 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
919 return elem->GetVR();
923 * \brief Searches within Header Entries (Dicom Elements) parsed with
924 * the public and private dictionaries
925 * for the value length of a given tag..
926 * @param group Group number of the searched tag.
927 * @param element Element number of the searched tag.
928 * @return Corresponding element length; -2 if not found
930 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
932 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
935 return -2; //magic number
937 return elem->GetLength();
940 * \brief Sets the value (string) of the Header Entry (Dicom Element)
941 * @param content string value of the Dicom Element
942 * @param tagName name of the searched Dicom Element.
943 * @return true when found
945 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
947 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
953 return SetEntryByNumber(content,dictEntry->GetGroup(),
954 dictEntry->GetElement());
958 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
959 * through it's (group, element) and modifies it's content with
961 * @param content new value (string) to substitute with
962 * @param group group number of the Dicom Element to modify
963 * @param element element number of the Dicom Element to modify
965 bool gdcmDocument::SetEntryByNumber(std::string const& content,
972 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
975 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
976 " ValEntry (try promotion first).");
979 // Non even content must be padded with a space (020H)...
980 std::string finalContent = content;
981 if( finalContent.length() % 2 )
983 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
985 valEntry->SetValue(finalContent);
987 // Integers have a special treatement for their length:
989 l = finalContent.length();
990 if ( l != 0) // To avoid to be cheated by 'zero length' integers
992 gdcmVRKey vr = valEntry->GetVR();
993 if( vr == "US" || vr == "SS" )
995 // for multivaluated items
996 c = gdcmUtil::CountSubstring(content, "\\") + 1;
999 else if( vr == "UL" || vr == "SL" )
1001 // for multivaluated items
1002 c = gdcmUtil::CountSubstring(content, "\\") + 1;
1006 valEntry->SetLength(l);
1011 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1012 * through it's (group, element) and modifies it's content with
1014 * @param content new value (void* -> uint8_t*) to substitute with
1015 * @param lgth new value length
1016 * @param group group number of the Dicom Element to modify
1017 * @param element element number of the Dicom Element to modify
1019 bool gdcmDocument::SetEntryByNumber(uint8_t*content,
1024 (void)lgth; //not used
1025 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1026 if ( !TagHT.count(key))
1031 /* Hope Binary field length is *never* wrong
1032 if(lgth%2) // Non even length are padded with a space (020H).
1035 //content = content + '\0'; // fing a trick to enlarge a binary field?
1038 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1039 a->SetBinArea(content);
1041 a->SetValue(GDCM_BINLOADED);
1047 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1048 * in the PubDocEntrySet of this instance
1049 * through it's (group, element) and modifies it's length with
1051 * \warning Use with extreme caution.
1052 * @param l new length to substitute with
1053 * @param group group number of the Entry to modify
1054 * @param element element number of the Entry to modify
1055 * @return true on success, false otherwise.
1057 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1061 /// \todo use map methods, instead of multimap JPR
1062 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1063 if ( !TagHT.count(key) )
1069 l++; // length must be even
1071 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1077 * \brief Gets (from Header) the offset of a 'non string' element value
1078 * (LoadElementValues has already be executed)
1079 * @param group group number of the Entry
1080 * @param elem element number of the Entry
1081 * @return File Offset of the Element Value
1083 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1085 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1088 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1091 return entry->GetOffset();
1095 * \brief Gets (from Header) a 'non string' element value
1096 * (LoadElementValues has already be executed)
1097 * @param group group number of the Entry
1098 * @param elem element number of the Entry
1099 * @return Pointer to the 'non string' area
1101 void* gdcmDocument::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1103 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1106 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1109 return ((gdcmBinEntry *)entry)->GetBinArea();
1113 * \brief Loads (from disk) the element content
1114 * when a string is not suitable
1115 * @param group group number of the Entry
1116 * @param elem element number of the Entry
1118 void* gdcmDocument::LoadEntryBinArea(uint16_t group, uint16_t elem)
1120 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1125 size_t o =(size_t)docElement->GetOffset();
1126 fseek(Fp, o, SEEK_SET);
1127 size_t l = docElement->GetLength();
1128 uint8_t* a = new uint8_t[l];
1131 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea cannot allocate a");
1134 size_t l2 = fread(a, 1, l , Fp);
1140 /// \todo Drop any already existing void area! JPR
1141 if( !SetEntryBinAreaByNumber( a, group, elem ) );
1143 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea setting failed.");
1148 * \brief Loads (from disk) the element content
1149 * when a string is not suitable
1150 * @param element Entry whose binArea is going to be loaded
1152 void* gdcmDocument::LoadEntryBinArea(gdcmBinEntry* element)
1154 size_t o =(size_t)element->GetOffset();
1155 fseek(Fp, o, SEEK_SET);
1156 size_t l = element->GetLength();
1157 uint8_t* a = new uint8_t[l];
1160 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea cannot allocate a");
1163 element->SetBinArea((uint8_t*)a);
1164 /// \todo check the result
1165 size_t l2 = fread(a, 1, l , Fp);
1176 * \brief Sets a 'non string' value to a given Dicom Element
1177 * @param area area containing the 'non string' value
1178 * @param group Group number of the searched Dicom Element
1179 * @param element Element number of the searched Dicom Element
1182 bool gdcmDocument::SetEntryBinAreaByNumber(uint8_t* area,
1186 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1187 if ( !currentEntry )
1191 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1193 binEntry->SetBinArea( area );
1200 * \brief Update the entries with the shadow dictionary.
1201 * Only non even entries are analyzed
1203 void gdcmDocument::UpdateShaEntries()
1205 //gdcmDictEntry *entry;
1208 /// \todo TODO : still any use to explore recursively the whole structure?
1210 for(ListTag::iterator it=listEntries.begin();
1211 it!=listEntries.end();
1214 // Odd group => from public dictionary
1215 if((*it)->GetGroup()%2==0)
1218 // Peer group => search the corresponding dict entry
1220 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1224 if((*it)->IsImplicitVR())
1229 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1231 // Set the new entry and the new value
1232 (*it)->SetDictEntry(entry);
1233 CheckDocEntryVR(*it,vr);
1235 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1240 // Remove precedent value transformation
1241 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1248 * \brief Searches within the Header Entries for a Dicom Element of
1250 * @param tagName name of the searched Dicom Element.
1251 * @return Corresponding Dicom Element when it exists, and NULL
1254 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1256 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1262 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1266 * \brief retrieves a Dicom Element (the first one) using (group, element)
1267 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1268 * if you think it's NOT UNIQUE, check the count number
1269 * and use iterators to retrieve ALL the Dicoms Elements within
1270 * a given couple (group, element)
1271 * @param group Group number of the searched Dicom Element
1272 * @param element Element number of the searched Dicom Element
1275 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1278 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1279 if ( !TagHT.count(key))
1283 return TagHT.find(key)->second;
1287 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1288 * returns a result when the corresponding entry is of type
1290 * @return When present, the corresponding ValEntry.
1292 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1295 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1296 if ( !currentEntry )
1300 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1304 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1310 * \brief Loads the element while preserving the current
1311 * underlying file position indicator as opposed to
1312 * to LoadDocEntry that modifies it.
1313 * @param entry Header Entry whose value shall be loaded.
1316 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1318 long PositionOnEntry = ftell(Fp);
1319 LoadDocEntry(entry);
1320 fseek(Fp, PositionOnEntry, SEEK_SET);
1324 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1326 * @return The properly swaped 32 bits integer.
1328 uint32_t gdcmDocument::SwapLong(uint32_t a)
1335 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1336 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1340 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1344 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1347 //std::cout << "swapCode= " << SwapCode << std::endl;
1348 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1355 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1357 * @return The properly unswaped 32 bits integer.
1359 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1365 * \brief Swaps the bytes so they agree with the processor order
1366 * @return The properly swaped 16 bits integer.
1368 uint16_t gdcmDocument::SwapShort(uint16_t a)
1370 if ( SwapCode == 4321 || SwapCode == 2143 )
1372 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1378 * \brief Unswaps the bytes so they agree with the processor order
1379 * @return The properly unswaped 16 bits integer.
1381 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1383 return SwapShort(a);
1386 //-----------------------------------------------------------------------------
1390 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1391 * @return length of the parsed set.
1393 void gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1398 gdcmDocEntry *newDocEntry = 0;
1402 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1406 newDocEntry = ReadNextDocEntry( );
1412 gdcmVRKey vr = newDocEntry->GetVR();
1416 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1418 /////////////////////// ValEntry
1419 gdcmValEntry* newValEntry =
1420 new gdcmValEntry( newDocEntry->GetDictEntry() );
1421 newValEntry->Copy( newDocEntry );
1423 // When "set" is a gdcmDocument, then we are at the top of the
1424 // hierarchy and the Key is simply of the form ( group, elem )...
1425 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1428 newValEntry->SetKey( newValEntry->GetKey() );
1430 // ...but when "set" is a gdcmSQItem, we are inserting this new
1431 // valEntry in a sequence item. Hence the key has the
1432 // generalized form (refer to \ref gdcmBaseTagKey):
1433 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1435 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1436 + newValEntry->GetKey() );
1439 set->AddEntry( newValEntry );
1440 LoadDocEntry( newValEntry );
1441 if (newValEntry->IsItemDelimitor())
1445 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1452 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1454 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1455 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1456 "nor BinEntry. Probably unknown VR.");
1459 //////////////////// BinEntry or UNKOWN VR:
1460 gdcmBinEntry* newBinEntry =
1461 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1462 newBinEntry->Copy( newDocEntry );
1464 // When "this" is a gdcmDocument the Key is simply of the
1465 // form ( group, elem )...
1466 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1469 newBinEntry->SetKey( newBinEntry->GetKey() );
1471 // but when "this" is a SQItem, we are inserting this new
1472 // valEntry in a sequence item, and the kay has the
1473 // generalized form (refer to \ref gdcmBaseTagKey):
1474 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1476 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1477 + newBinEntry->GetKey() );
1480 set->AddEntry( newBinEntry );
1481 LoadDocEntry( newBinEntry );
1484 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1485 && ( newDocEntry->GetElement() == 0x0010 ) )
1487 if ( IsRLELossLessTransferSyntax() )
1489 long PositionOnEntry = ftell(Fp);
1490 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1492 fseek( Fp, PositionOnEntry, SEEK_SET );
1495 if ( IsJPEGTransferSyntax() )
1497 long PositionOnEntry = ftell(Fp);
1498 fseek( Fp, newDocEntry->GetOffset(), SEEK_SET );
1499 ComputeJPEGFragmentInfo();
1500 fseek( Fp, PositionOnEntry, SEEK_SET );
1504 // Just to make sure we are at the beginning of next entry.
1505 SkipToNextDocEntry(newDocEntry);
1510 unsigned long l = newDocEntry->GetReadLength();
1511 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1513 if ( l == 0xffffffff )
1522 // no other way to create it ...
1523 gdcmSeqEntry* newSeqEntry =
1524 new gdcmSeqEntry( newDocEntry->GetDictEntry() );
1525 newSeqEntry->Copy( newDocEntry );
1526 newSeqEntry->SetDelimitorMode( delim_mode );
1528 // At the top of the hierarchy, stands a gdcmDocument. When "set"
1529 // is a gdcmDocument, then we are building the first depth level.
1530 // Hence the gdcmSeqEntry we are building simply has a depth
1532 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1535 newSeqEntry->SetDepthLevel( 1 );
1536 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1538 // But when "set" is allready a SQItem, we are building a nested
1539 // sequence, and hence the depth level of the new gdcmSeqEntry
1540 // we are building, is one level deeper:
1541 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1543 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1544 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1545 + newSeqEntry->GetKey() );
1549 { // Don't try to parse zero-length sequences
1550 ParseSQ( newSeqEntry,
1551 newDocEntry->GetOffset(),
1554 set->AddEntry( newSeqEntry );
1555 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1565 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1566 * @return parsed length for this level
1568 void gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1569 long offset, long l_max, bool delim_mode)
1571 int SQItemNumber = 0;
1576 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1579 // FIXME Should warn user
1584 if ( newDocEntry->IsSequenceDelimitor() )
1586 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1590 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1595 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1596 std::ostringstream newBase;
1597 newBase << seqEntry->GetKey()
1601 itemSQ->SetBaseTagKey( newBase.str() );
1602 unsigned int l = newDocEntry->GetReadLength();
1604 if ( l == 0xffffffff )
1613 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1615 seqEntry->AddEntry( itemSQ, SQItemNumber );
1617 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1625 * \brief Loads the element content if its length doesn't exceed
1626 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1627 * @param entry Header Entry (Dicom Element) to be dealt with
1629 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1632 uint16_t group = entry->GetGroup();
1633 std::string vr = entry->GetVR();
1634 uint32_t length = entry->GetLength();
1636 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1638 // A SeQuence "contains" a set of Elements.
1639 // (fffe e000) tells us an Element is beginning
1640 // (fffe e00d) tells us an Element just ended
1641 // (fffe e0dd) tells us the current SeQuence just ended
1642 if( group == 0xfffe )
1644 // NO more value field for SQ !
1648 // When the length is zero things are easy:
1651 ((gdcmValEntry *)entry)->SetValue("");
1655 // The elements whose length is bigger than the specified upper bound
1656 // are not loaded. Instead we leave a short notice of the offset of
1657 // the element content and it's length.
1659 std::ostringstream s;
1660 if (length > MaxSizeLoadEntry)
1662 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1664 //s << "gdcm::NotLoaded (BinEntry)";
1665 s << GDCM_NOTLOADED;
1666 s << " Address:" << (long)entry->GetOffset();
1667 s << " Length:" << entry->GetLength();
1668 s << " x(" << std::hex << entry->GetLength() << ")";
1669 binEntryPtr->SetValue(s.str());
1671 // Be carefull : a BinEntry IS_A ValEntry ...
1672 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1674 // s << "gdcm::NotLoaded. (ValEntry)";
1675 s << GDCM_NOTLOADED;
1676 s << " Address:" << (long)entry->GetOffset();
1677 s << " Length:" << entry->GetLength();
1678 s << " x(" << std::hex << entry->GetLength() << ")";
1679 valEntryPtr->SetValue(s.str());
1684 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1685 << "nor a ValEntry ?! Should never print that !" << std::endl;
1688 // to be sure we are at the end of the value ...
1689 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1693 // When we find a BinEntry not very much can be done :
1694 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1696 s << GDCM_BINLOADED;
1697 binEntryPtr->SetValue(s.str());
1698 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1702 /// \todo Any compacter code suggested (?)
1703 if ( IsDocEntryAnInteger(entry) )
1707 // When short integer(s) are expected, read and convert the following
1708 // n *two characters properly i.e. consider them as short integers as
1709 // opposed to strings.
1710 // Elements with Value Multiplicity > 1
1711 // contain a set of integers (not a single one)
1712 if (vr == "US" || vr == "SS")
1715 NewInt = ReadInt16();
1719 for (int i=1; i < nbInt; i++)
1722 NewInt = ReadInt16();
1727 // See above comment on multiple integers (mutatis mutandis).
1728 else if (vr == "UL" || vr == "SL")
1731 NewInt = ReadInt32();
1735 for (int i=1; i < nbInt; i++)
1738 NewInt = ReadInt32();
1743 #ifdef GDCM_NO_ANSI_STRING_STREAM
1744 s << std::ends; // to avoid oddities on Solaris
1745 #endif //GDCM_NO_ANSI_STRING_STREAM
1747 ((gdcmValEntry *)entry)->SetValue(s.str());
1751 // We need an additional byte for storing \0 that is not on disk
1752 //std::string newValue(length,0);
1753 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1754 //rah !! I can't believe it could work, normally this is a const char* !!!
1755 char *str = new char[length+1];
1756 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1758 std::string newValue = str;
1760 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1762 if ( item_read != 1 )
1764 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1765 "unread element value");
1766 valEntry->SetValue(GDCM_UNREAD);
1772 // Because of correspondance with the VR dic
1773 valEntry->SetValue(newValue);
1777 valEntry->SetValue(newValue);
1782 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1783 "Should have a ValEntry, here !");
1789 * \brief Find the value Length of the passed Header Entry
1790 * @param entry Header Entry whose length of the value shall be loaded.
1792 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1793 throw ( gdcmFormatError )
1795 uint16_t element = entry->GetElement();
1796 std::string vr = entry->GetVR();
1799 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1801 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1803 // The following reserved two bytes (see PS 3.5-2003, section
1804 // "7.1.2 Data element structure with explicit vr", p 27) must be
1805 // skipped before proceeding on reading the length on 4 bytes.
1806 fseek(Fp, 2L, SEEK_CUR);
1807 uint32_t length32 = ReadInt32();
1809 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1814 /// \todo rename that to FindDocEntryLengthOBOrOW since
1815 /// the above test is on both OB and OW...
1816 lengthOB = FindDocEntryLengthOB();
1818 catch ( gdcmFormatUnexpected )
1820 // Computing the length failed (this happens with broken
1821 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1822 // chance to get the pixels by deciding the element goes
1823 // until the end of the file. Hence we artificially fix the
1824 // the length and proceed.
1825 long currentPosition = ftell(Fp);
1826 fseek(Fp,0L,SEEK_END);
1827 long lengthUntilEOF = ftell(Fp) - currentPosition;
1828 fseek(Fp, currentPosition, SEEK_SET);
1829 entry->SetLength(lengthUntilEOF);
1832 entry->SetLength(lengthOB);
1835 FixDocEntryFoundLength(entry, length32);
1839 // Length is encoded on 2 bytes.
1840 length16 = ReadInt16();
1842 // We can tell the current file is encoded in big endian (like
1843 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1844 // and it's value is the one of the encoding of a big endian file.
1845 // In order to deal with such big endian encoded files, we have
1846 // (at least) two strategies:
1847 // * when we load the "Transfer Syntax" tag with value of big endian
1848 // encoding, we raise the proper flags. Then we wait for the end
1849 // of the META group (0x0002) among which is "Transfer Syntax",
1850 // before switching the swap code to big endian. We have to postpone
1851 // the switching of the swap code since the META group is fully encoded
1852 // in little endian, and big endian coding only starts at the next
1853 // group. The corresponding code can be hard to analyse and adds
1854 // many additional unnecessary tests for regular tags.
1855 // * the second strategy consists in waiting for trouble, that shall
1856 // appear when we find the first group with big endian encoding. This
1857 // is easy to detect since the length of a "Group Length" tag (the
1858 // ones with zero as element number) has to be of 4 (0x0004). When we
1859 // encounter 1024 (0x0400) chances are the encoding changed and we
1860 // found a group with big endian encoding.
1861 // We shall use this second strategy. In order to make sure that we
1862 // can interpret the presence of an apparently big endian encoded
1863 // length of a "Group Length" without committing a big mistake, we
1864 // add an additional check: we look in the already parsed elements
1865 // for the presence of a "Transfer Syntax" whose value has to be "big
1866 // endian encoding". When this is the case, chances are we have got our
1867 // hands on a big endian encoded file: we switch the swap code to
1868 // big endian and proceed...
1869 if ( element == 0x0000 && length16 == 0x0400 )
1871 if ( !IsExplicitVRBigEndianTransferSyntax() )
1873 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1874 " not explicit VR." );
1878 SwitchSwapToBigEndian();
1879 // Restore the unproperly loaded values i.e. the group, the element
1880 // and the dictionary entry depending on them.
1881 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1882 uint16_t correctElem = SwapShort( entry->GetElement() );
1883 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1887 // This correct tag is not in the dictionary. Create a new one.
1888 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1890 // FIXME this can create a memory leaks on the old entry that be
1891 // left unreferenced.
1892 entry->SetDictEntry( newTag );
1895 // Heuristic: well, some files are really ill-formed.
1896 if ( length16 == 0xffff)
1898 // 0xffff means that we deal with 'Unknown Length' Sequence
1901 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1906 // Either implicit VR or a non DICOM conformal (see note below) explicit
1907 // VR that ommited the VR of (at least) this element. Farts happen.
1908 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1909 // on Data elements "Implicit and Explicit VR Data Elements shall
1910 // not coexist in a Data Set and Data Sets nested within it".]
1911 // Length is on 4 bytes.
1913 FixDocEntryFoundLength( entry, ReadInt32() );
1919 * \brief Find the Value Representation of the current Dicom Element.
1922 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1924 if ( Filetype != gdcmExplicitVR )
1931 long positionOnEntry = ftell(Fp);
1932 // Warning: we believe this is explicit VR (Value Representation) because
1933 // we used a heuristic that found "UL" in the first tag. Alas this
1934 // doesn't guarantee that all the tags will be in explicit VR. In some
1935 // cases (see e-film filtered files) one finds implicit VR tags mixed
1936 // within an explicit VR file. Hence we make sure the present tag
1937 // is in explicit VR and try to fix things if it happens not to be
1940 fread (vr, (size_t)2,(size_t)1, Fp);
1943 if( !CheckDocEntryVR(entry, vr) )
1945 fseek(Fp, positionOnEntry, SEEK_SET);
1946 // When this element is known in the dictionary we shall use, e.g. for
1947 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1948 // dictionary entry. Still we have to flag the element as implicit since
1949 // we know now our assumption on expliciteness is not furfilled.
1951 if ( entry->IsVRUnknown() )
1953 entry->SetVR("Implicit");
1955 entry->SetImplicitVR();
1960 * \brief Check the correspondance between the VR of the header entry
1961 * and the taken VR. If they are different, the header entry is
1962 * updated with the new VR.
1963 * @param entry Header Entry to check
1964 * @param vr Dicom Value Representation
1965 * @return false if the VR is incorrect of if the VR isn't referenced
1966 * otherwise, it returns true
1968 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1971 bool realExplicit = true;
1973 // Assume we are reading a falsely explicit VR file i.e. we reached
1974 // a tag where we expect reading a VR but are in fact we read the
1975 // first to bytes of the length. Then we will interogate (through find)
1976 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1977 // both GCC and VC++ implementations of the STL map. Hence when the
1978 // expected VR read happens to be non-ascii characters we consider
1979 // we hit falsely explicit VR tag.
1981 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1983 realExplicit = false;
1986 // CLEANME searching the dicom_vr at each occurence is expensive.
1987 // PostPone this test in an optional integrity check at the end
1988 // of parsing or only in debug mode.
1989 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1991 realExplicit = false;
1994 if ( !realExplicit )
1996 // We thought this was explicit VR, but we end up with an
1997 // implicit VR tag. Let's backtrack.
1998 msg = gdcmUtil::Format("Falsely explicit vr file (%04x,%04x)\n",
1999 entry->GetGroup(), entry->GetElement());
2000 dbg.Verbose(1, "gdcmDocument::FindVR: ", msg.c_str());
2002 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2004 // Group length is UL !
2005 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2006 entry->GetGroup(), entry->GetElement(),
2007 "UL", "FIXME", "Group Length");
2008 entry->SetDictEntry( newEntry );
2013 if ( entry->IsVRUnknown() )
2015 // When not a dictionary entry, we can safely overwrite the VR.
2016 if( entry->GetElement() == 0x0000 )
2018 // Group length is UL !
2026 else if ( entry->GetVR() != vr )
2028 // The VR present in the file and the dictionary disagree. We assume
2029 // the file writer knew best and use the VR of the file. Since it would
2030 // be unwise to overwrite the VR of a dictionary (since it would
2031 // compromise it's next user), we need to clone the actual DictEntry
2032 // and change the VR for the read one.
2033 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2034 entry->GetGroup(), entry->GetElement(),
2035 vr, "FIXME", entry->GetName());
2036 entry->SetDictEntry(newEntry);
2043 * \brief Get the transformed value of the header entry. The VR value
2044 * is used to define the transformation to operate on the value
2045 * \warning NOT end user intended method !
2046 * @param entry entry to tranform
2047 * @return Transformed entry value
2049 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2051 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2053 std::string val = ((gdcmValEntry *)entry)->GetValue();
2054 std::string vr = entry->GetVR();
2055 uint32_t length = entry->GetLength();
2056 std::ostringstream s;
2059 // When short integer(s) are expected, read and convert the following
2060 // n * 2 bytes properly i.e. as a multivaluated strings
2061 // (each single value is separated fromthe next one by '\'
2062 // as usual for standard multivaluated filels
2063 // Elements with Value Multiplicity > 1
2064 // contain a set of short integers (not a single one)
2066 if( vr == "US" || vr == "SS" )
2071 for (int i=0; i < nbInt; i++)
2077 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2078 newInt16 = SwapShort( newInt16 );
2083 // When integer(s) are expected, read and convert the following
2084 // n * 4 bytes properly i.e. as a multivaluated strings
2085 // (each single value is separated fromthe next one by '\'
2086 // as usual for standard multivaluated filels
2087 // Elements with Value Multiplicity > 1
2088 // contain a set of integers (not a single one)
2089 else if( vr == "UL" || vr == "SL" )
2094 for (int i=0; i < nbInt; i++)
2100 newInt32 = ( val[4*i+0] & 0xFF )
2101 + (( val[4*i+1] & 0xFF ) << 8 )
2102 + (( val[4*i+2] & 0xFF ) << 16 )
2103 + (( val[4*i+3] & 0xFF ) << 24 );
2104 newInt32 = SwapLong( newInt32 );
2108 #ifdef GDCM_NO_ANSI_STRING_STREAM
2109 s << std::ends; // to avoid oddities on Solaris
2110 #endif //GDCM_NO_ANSI_STRING_STREAM
2114 return ((gdcmValEntry *)entry)->GetValue();
2118 * \brief Get the reverse transformed value of the header entry. The VR
2119 * value is used to define the reverse transformation to operate on
2121 * \warning NOT end user intended method !
2122 * @param entry Entry to reverse transform
2123 * @return Reverse transformed entry value
2125 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2127 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2129 std::string vr = entry->GetVR();
2130 std::vector<std::string> tokens;
2131 std::ostringstream s;
2133 if ( vr == "US" || vr == "SS" )
2137 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2138 gdcmUtil::Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2139 for (unsigned int i=0; i<tokens.size(); i++)
2141 newInt16 = atoi(tokens[i].c_str());
2142 s << ( newInt16 & 0xFF )
2143 << (( newInt16 >> 8 ) & 0xFF );
2147 if ( vr == "UL" || vr == "SL")
2151 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2152 gdcmUtil::Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2153 for (unsigned int i=0; i<tokens.size();i++)
2155 newInt32 = atoi(tokens[i].c_str());
2156 s << (char)( newInt32 & 0xFF )
2157 << (char)(( newInt32 >> 8 ) & 0xFF )
2158 << (char)(( newInt32 >> 16 ) & 0xFF )
2159 << (char)(( newInt32 >> 24 ) & 0xFF );
2164 #ifdef GDCM_NO_ANSI_STRING_STREAM
2165 s << std::ends; // to avoid oddities on Solaris
2166 #endif //GDCM_NO_ANSI_STRING_STREAM
2170 return ((gdcmValEntry *)entry)->GetValue();
2174 * \brief Skip a given Header Entry
2175 * \warning NOT end user intended method !
2176 * @param entry entry to skip
2178 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2180 SkipBytes(entry->GetLength());
2184 * \brief Skips to the begining of the next Header Entry
2185 * \warning NOT end user intended method !
2186 * @param entry entry to skip
2188 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2190 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2191 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2195 * \brief When the length of an element value is obviously wrong (because
2196 * the parser went Jabberwocky) one can hope improving things by
2197 * applying some heuristics.
2198 * @param entry entry to check
2199 * @param foundLength fist assumption about length
2201 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2202 uint32_t foundLength)
2204 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2205 if ( foundLength == 0xffffffff)
2210 uint16_t gr = entry->GetGroup();
2211 uint16_t el = entry->GetElement();
2213 if ( foundLength % 2)
2215 std::ostringstream s;
2216 s << "Warning : Tag with uneven length "
2218 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2219 dbg.Verbose(0, s.str().c_str());
2222 //////// Fix for some naughty General Electric images.
2223 // Allthough not recent many such GE corrupted images are still present
2224 // on Creatis hard disks. Hence this fix shall remain when such images
2225 // are no longer in user (we are talking a few years, here)...
2226 // Note: XMedCom probably uses such a trick since it is able to read
2227 // those pesky GE images ...
2228 if ( foundLength == 13)
2230 // Only happens for this length !
2231 if ( entry->GetGroup() != 0x0008
2232 || ( entry->GetElement() != 0x0070
2233 && entry->GetElement() != 0x0080 ) )
2236 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2240 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2241 // Occurence of such images is quite low (unless one leaves close to a
2242 // 'Leonardo' source. Hence, one might consider commenting out the
2243 // following fix on efficiency reasons.
2244 else if ( entry->GetGroup() == 0x0009
2245 && ( entry->GetElement() == 0x1113
2246 || entry->GetElement() == 0x1114 ) )
2249 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2252 else if ( entry->GetVR() == "SQ" )
2254 foundLength = 0; // ReadLength is unchanged
2257 //////// We encountered a 'delimiter' element i.e. a tag of the form
2258 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2259 // taken into account.
2260 else if( entry->GetGroup() == 0xfffe )
2262 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2263 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2264 // causes extra troubles...
2265 if( entry->GetElement() != 0x0000 )
2271 entry->SetUsableLength(foundLength);
2275 * \brief Apply some heuristics to predict whether the considered
2276 * element value contains/represents an integer or not.
2277 * @param entry The element value on which to apply the predicate.
2278 * @return The result of the heuristical predicate.
2280 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2282 uint16_t element = entry->GetElement();
2283 uint16_t group = entry->GetGroup();
2284 std::string vr = entry->GetVR();
2285 uint32_t length = entry->GetLength();
2287 // When we have some semantics on the element we just read, and if we
2288 // a priori know we are dealing with an integer, then we shall be
2289 // able to swap it's element value properly.
2290 if ( element == 0 ) // This is the group length of the group
2298 // Allthough this should never happen, still some images have a
2299 // corrupted group length [e.g. have a glance at offset x(8336) of
2300 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2301 // Since for dicom compliant and well behaved headers, the present
2302 // test is useless (and might even look a bit paranoid), when we
2303 // encounter such an ill-formed image, we simply display a warning
2304 // message and proceed on parsing (while crossing fingers).
2305 std::ostringstream s;
2306 int filePosition = ftell(Fp);
2307 s << "Erroneous Group Length element length on : (" \
2308 << std::hex << group << " , " << element
2309 << ") -before- position x(" << filePosition << ")"
2310 << "lgt : " << length;
2311 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2315 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2324 * \brief Find the Length till the next sequence delimiter
2325 * \warning NOT end user intended method !
2329 uint32_t gdcmDocument::FindDocEntryLengthOB()
2330 throw( gdcmFormatUnexpected )
2332 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2333 long positionOnEntry = ftell(Fp);
2334 bool foundSequenceDelimiter = false;
2335 uint32_t totalLength = 0;
2337 while ( !foundSequenceDelimiter )
2343 group = ReadInt16();
2346 catch ( gdcmFormatError )
2348 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2349 " group or element not present.");
2352 // We have to decount the group and element we just read
2355 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2357 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2358 "tag nor a Sequence delimiter tag.");
2359 fseek(Fp, positionOnEntry, SEEK_SET);
2360 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2361 "Neither an Item tag nor a Sequence "
2365 if ( elem == 0xe0dd )
2367 foundSequenceDelimiter = true;
2370 uint32_t itemLength = ReadInt32();
2371 // We add 4 bytes since we just read the ItemLength with ReadInt32
2372 totalLength += itemLength + 4;
2373 SkipBytes(itemLength);
2375 if ( foundSequenceDelimiter )
2380 fseek(Fp, positionOnEntry, SEEK_SET);
2385 * \brief Reads a supposed to be 16 Bits integer
2386 * (swaps it depending on processor endianity)
2387 * @return read value
2389 uint16_t gdcmDocument::ReadInt16()
2390 throw( gdcmFormatError )
2393 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2394 if ( item_read != 1 )
2398 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2400 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2407 * \brief Reads a supposed to be 32 Bits integer
2408 * (swaps it depending on processor endianity)
2409 * @return read value
2411 uint32_t gdcmDocument::ReadInt32()
2412 throw( gdcmFormatError )
2415 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2416 if ( item_read != 1 )
2420 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2422 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2429 * \brief skips bytes inside the source file
2430 * \warning NOT end user intended method !
2433 void gdcmDocument::SkipBytes(uint32_t nBytes)
2435 //FIXME don't dump the returned value
2436 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2440 * \brief Loads all the needed Dictionaries
2441 * \warning NOT end user intended method !
2443 void gdcmDocument::Initialise()
2445 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2450 * \brief Discover what the swap code is (among little endian, big endian,
2451 * bad little endian, bad big endian).
2453 * @return false when we are absolutely sure
2454 * it's neither ACR-NEMA nor DICOM
2455 * true when we hope ours assuptions are OK
2457 bool gdcmDocument::CheckSwap()
2459 // The only guaranted way of finding the swap code is to find a
2460 // group tag since we know it's length has to be of four bytes i.e.
2461 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2462 // occurs when we can't find such group...
2464 uint32_t x = 4; // x : for ntohs
2465 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2469 char deb[HEADER_LENGTH_TO_READ];
2471 // First, compare HostByteOrder and NetworkByteOrder in order to
2472 // determine if we shall need to swap bytes (i.e. the Endian type).
2473 if ( x == ntohs(x) )
2482 // The easiest case is the one of a DICOM header, since it possesses a
2483 // file preamble where it suffice to look for the string "DICM".
2484 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2485 (void)lgrLue; //FIXME not used
2487 char *entCur = deb + 128;
2488 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2490 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2492 // Next, determine the value representation (VR). Let's skip to the
2493 // first element (0002, 0000) and check there if we find "UL"
2494 // - or "OB" if the 1st one is (0002,0001) -,
2495 // in which case we (almost) know it is explicit VR.
2496 // WARNING: if it happens to be implicit VR then what we will read
2497 // is the length of the group. If this ascii representation of this
2498 // length happens to be "UL" then we shall believe it is explicit VR.
2499 // FIXME: in order to fix the above warning, we could read the next
2500 // element value (or a couple of elements values) in order to make
2501 // sure we are not commiting a big mistake.
2502 // We need to skip :
2503 // * the 128 bytes of File Preamble (often padded with zeroes),
2504 // * the 4 bytes of "DICM" string,
2505 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2506 // i.e. a total of 136 bytes.
2510 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2511 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2512 // *Implicit* VR. -and it is !-
2514 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2515 memcmp(entCur, "OB", (size_t)2) == 0 ||
2516 memcmp(entCur, "UI", (size_t)2) == 0 ||
2517 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2518 // when Write DCM *adds*
2520 // Use gdcmDocument::dicom_vr to test all the possibilities
2521 // instead of just checking for UL, OB and UI !? group 0000
2523 Filetype = gdcmExplicitVR;
2524 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2525 "explicit Value Representation");
2529 Filetype = gdcmImplicitVR;
2530 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2531 "not an explicit Value Representation");
2537 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2538 "HostByteOrder != NetworkByteOrder");
2543 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2544 "HostByteOrder = NetworkByteOrder");
2547 // Position the file position indicator at first tag (i.e.
2548 // after the file preamble and the "DICM" string).
2550 fseek (Fp, 132L, SEEK_SET);
2554 // Alas, this is not a DicomV3 file and whatever happens there is no file
2555 // preamble. We can reset the file position indicator to where the data
2556 // is (i.e. the beginning of the file).
2557 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2560 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2561 // By clean we mean that the length of the first tag is written down.
2562 // If this is the case and since the length of the first group HAS to be
2563 // four (bytes), then determining the proper swap code is straightforward.
2566 // We assume the array of char we are considering contains the binary
2567 // representation of a 32 bits integer. Hence the following dirty
2569 s32 = *((uint32_t *)(entCur));
2590 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2591 // It is time for despaired wild guesses.
2592 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2593 // i.e. the 'group length' element is not present :
2595 // check the supposed to be 'group number'
2596 // 0x0002 or 0x0004 or 0x0008
2597 // to determine ' SwapCode' value .
2598 // Only 0 or 4321 will be possible
2599 // (no oportunity to check for the formerly well known
2600 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2601 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2602 // the file IS NOT ACR-NEMA nor DICOM V3
2603 // Find a trick to tell it the caller...
2605 s16 = *((uint16_t *)(deb));
2622 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2623 "ACR/NEMA unfound swap info (Really hopeless !)");
2624 Filetype = gdcmUnknown;
2627 // Then the only info we have is the net2host one.
2637 * \brief Restore the unproperly loaded values i.e. the group, the element
2638 * and the dictionary entry depending on them.
2640 void gdcmDocument::SwitchSwapToBigEndian()
2642 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2643 "Switching to BigEndian mode.");
2644 if ( SwapCode == 0 )
2648 else if ( SwapCode == 4321 )
2652 else if ( SwapCode == 3412 )
2656 else if ( SwapCode == 2143 )
2663 * \brief during parsing, Header Elements too long are not loaded in memory
2666 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2672 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2674 MaxSizeLoadEntry = 0xffffffff;
2677 MaxSizeLoadEntry = newSize;
2682 * \brief Header Elements too long will not be printed
2683 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2686 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2688 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2693 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2695 MaxSizePrintEntry = 0xffffffff;
2698 MaxSizePrintEntry = newSize;
2704 * \brief Read the next tag but WITHOUT loading it's value
2705 * (read the 'Group Number', the 'Element Number',
2706 * gets the Dict Entry
2707 * gets the VR, gets the length, gets the offset value)
2708 * @return On succes the newly created DocEntry, NULL on failure.
2710 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2717 group = ReadInt16();
2720 catch ( gdcmFormatError e )
2722 // We reached the EOF (or an error occured) therefore
2723 // header parsing has to be considered as finished.
2728 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2729 FindDocEntryVR(newEntry);
2733 FindDocEntryLength(newEntry);
2735 catch ( gdcmFormatError e )
2743 newEntry->SetOffset(ftell(Fp));
2750 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2751 * in the TagHt dictionary.
2752 * @param group The generated tag must belong to this group.
2753 * @return The element of tag with given group which is fee.
2755 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2757 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2759 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2760 if (TagHT.count(key) == 0)
2769 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2770 * is placed at the beginning of a tag check whether this
2771 * tag is (TestGroup, TestElement).
2772 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2773 * is modified to point after the tag.
2774 * On failure (i.e. when the tag wasn't the expected tag
2775 * (TestGroup, TestElement) the internal file pointer
2776 * \ref gdcmDocument::Fp is restored to it's original position.
2777 * @param testGroup The expected group of the tag.
2778 * @param testElement The expected Element of the tag.
2779 * @return True on success, false otherwise.
2781 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2783 long positionOnEntry = ftell(Fp);
2784 long currentPosition = ftell(Fp); // On debugging purposes
2786 //// Read the Item Tag group and element, and make
2787 // sure they are what we expected:
2788 uint16_t itemTagGroup = ReadInt16();
2789 uint16_t itemTagElement = ReadInt16();
2790 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2792 std::ostringstream s;
2793 s << " We should have found tag (";
2794 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2795 s << " but instead we encountered tag (";
2796 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2798 s << " at address: " << (unsigned)currentPosition << std::endl;
2799 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2800 dbg.Verbose(0, s.str().c_str());
2801 fseek(Fp, positionOnEntry, SEEK_SET);
2809 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2810 * is placed at the beginning of a tag (TestGroup, TestElement),
2811 * read the length associated to the Tag.
2812 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2813 * is modified to point after the tag and it's length.
2814 * On failure (i.e. when the tag wasn't the expected tag
2815 * (TestGroup, TestElement) the internal file pointer
2816 * \ref gdcmDocument::Fp is restored to it's original position.
2817 * @param testGroup The expected group of the tag.
2818 * @param testElement The expected Element of the tag.
2819 * @return On success returns the length associated to the tag. On failure
2822 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2824 long positionOnEntry = ftell(Fp);
2825 (void)positionOnEntry;
2827 if ( !ReadTag(testGroup, testElement) )
2832 //// Then read the associated Item Length
2833 long currentPosition = ftell(Fp);
2834 uint32_t itemLength = ReadInt32();
2836 std::ostringstream s;
2837 s << "Basic Item Length is: "
2838 << itemLength << std::endl;
2839 s << " at address: " << (unsigned)currentPosition << std::endl;
2840 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2846 * \brief When parsing the Pixel Data of an encapsulated file, read
2847 * the basic offset table (when present, and BTW dump it).
2849 void gdcmDocument::ReadAndSkipEncapsulatedBasicOffsetTable()
2851 //// Read the Basic Offset Table Item Tag length...
2852 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2854 // When present, read the basic offset table itself.
2855 // Notes: - since the presence of this basic offset table is optional
2856 // we can't rely on it for the implementation, and we will simply
2857 // trash it's content (when present).
2858 // - still, when present, we could add some further checks on the
2859 // lengths, but we won't bother with such fuses for the time being.
2860 if ( itemLength != 0 )
2862 char* basicOffsetTableItemValue = new char[itemLength + 1];
2863 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2866 for (unsigned int i=0; i < itemLength; i += 4 )
2868 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2870 std::ostringstream s;
2871 s << " Read one length: ";
2872 s << std::hex << individualLength << std::endl;
2874 "gdcmDocument::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2879 delete[] basicOffsetTableItemValue;
2884 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2885 * Compute the RLE extra information and store it in \ref RLEInfo
2886 * for later pixel retrieval usage.
2888 void gdcmDocument::ComputeRLEInfo()
2890 if ( ! IsRLELossLessTransferSyntax() )
2895 // Encoded pixel data: for the time being we are only concerned with
2896 // Jpeg or RLE Pixel data encodings.
2897 // As stated in PS 3.5-2003, section 8.2 p44:
2898 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2899 // value representation OB is used".
2900 // Hence we expect an OB value representation. Concerning OB VR,
2901 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2902 // "For the Value Representations OB and OW, the encoding shall meet the
2903 // following specifications depending on the Data element tag:"
2905 // - the first item in the sequence of items before the encoded pixel
2906 // data stream shall be basic offset table item. The basic offset table
2907 // item value, however, is not required to be present"
2909 ReadAndSkipEncapsulatedBasicOffsetTable();
2911 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2912 // Loop on the individual frame[s] and store the information
2913 // on the RLE fragments in a gdcmRLEFramesInfo.
2914 // Note: - when only a single frame is present, this is a
2916 // - when more than one frame are present, then we are in
2917 // the case of a multi-frame image.
2919 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2921 // Parse the RLE Header and store the corresponding RLE Segment
2922 // Offset Table information on fragments of this current Frame.
2923 // Note that the fragment pixels themselves are not loaded
2924 // (but just skipped).
2925 long frameOffset = ftell(Fp);
2927 uint32_t nbRleSegments = ReadInt32();
2929 uint32_t rleSegmentOffsetTable[15];
2930 for( int k = 1; k <= 15; k++ )
2932 rleSegmentOffsetTable[k] = ReadInt32();
2935 // Deduce from both the RLE Header and the frameLength the
2936 // fragment length, and again store this info in a
2937 // gdcmRLEFramesInfo.
2938 long rleSegmentLength[15];
2939 // skipping (not reading) RLE Segments
2940 if ( nbRleSegments > 1)
2942 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2944 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2945 - rleSegmentOffsetTable[k];
2946 SkipBytes(rleSegmentLength[k]);
2950 rleSegmentLength[nbRleSegments] = frameLength
2951 - rleSegmentOffsetTable[nbRleSegments];
2952 SkipBytes(rleSegmentLength[nbRleSegments]);
2954 // Store the collected info
2955 gdcmRLEFrame* newFrameInfo = new gdcmRLEFrame;
2956 newFrameInfo->NumberFragments = nbRleSegments;
2957 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2959 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2960 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2962 RLEInfo.Frames.push_back( newFrameInfo );
2965 // Make sure that at the end of the item we encounter a 'Sequence
2967 if ( !ReadTag(0xfffe, 0xe0dd) )
2969 dbg.Verbose(0, "gdcmDocument::ComputeRLEInfo: no sequence delimiter ");
2970 dbg.Verbose(0, " item at end of RLE item sequence");
2975 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2976 * Compute the jpeg extra information (fragment[s] offset[s] and
2977 * length) and store it[them] in \ref JPEGInfo for later pixel
2980 void gdcmDocument::ComputeJPEGFragmentInfo()
2982 // If you need to, look for comments of ComputeRLEInfo().
2983 if ( ! IsJPEGTransferSyntax() )
2988 ReadAndSkipEncapsulatedBasicOffsetTable();
2990 // Loop on the fragments[s] and store the parsed information in a
2992 long fragmentLength;
2993 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2995 long fragmentOffset = ftell(Fp);
2997 // Store the collected info
2998 gdcmJPEGFragment* newFragment = new gdcmJPEGFragment;
2999 newFragment->Offset = fragmentOffset;
3000 newFragment->Length = fragmentLength;
3001 JPEGInfo.Fragments.push_back( newFragment );
3003 SkipBytes( fragmentLength );
3006 // Make sure that at the end of the item we encounter a 'Sequence
3008 if ( !ReadTag(0xfffe, 0xe0dd) )
3010 dbg.Verbose(0, "gdcmDocument::ComputeRLEInfo: no sequence delimiter ");
3011 dbg.Verbose(0, " item at end of JPEG item sequence");
3016 * \brief Walk recursively the given \ref gdcmDocEntrySet, and feed
3017 * the given hash table (\ref TagDocEntryHT) with all the
3018 * \ref gdcmDocEntry (Dicom entries) encountered.
3019 * This method does the job for \ref BuildFlatHashTable.
3020 * @param builtHT Where to collect all the \ref gdcmDocEntry encountered
3021 * when recursively walking the given set.
3022 * @param set The structure to be traversed (recursively).
3024 void gdcmDocument::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3025 gdcmDocEntrySet* set )
3027 if (gdcmElementSet* elementSet = dynamic_cast< gdcmElementSet* > ( set ) )
3029 TagDocEntryHT* currentHT = elementSet->GetTagHT();
3030 for( TagDocEntryHT::const_iterator i = currentHT->begin();
3031 i != currentHT->end();
3034 gdcmDocEntry* entry = i->second;
3035 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
3037 ListSQItem& items = seqEntry->GetSQItems();
3038 for( ListSQItem::const_iterator item = items.begin();
3039 item != items.end();
3042 BuildFlatHashTableRecurse( builtHT, *item );
3046 builtHT[entry->GetKey()] = entry;
3051 if (gdcmSQItem* SQItemSet = dynamic_cast< gdcmSQItem* > ( set ) )
3053 ListDocEntry& currentList = SQItemSet->GetDocEntries();
3054 for (ListDocEntry::iterator i = currentList.begin();
3055 i != currentList.end();
3058 gdcmDocEntry* entry = *i;
3059 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
3061 ListSQItem& items = seqEntry->GetSQItems();
3062 for( ListSQItem::const_iterator item = items.begin();
3063 item != items.end();
3066 BuildFlatHashTableRecurse( builtHT, *item );
3070 builtHT[entry->GetKey()] = entry;
3077 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3080 * The structure used by a gdcmDocument (through \ref gdcmElementSet),
3081 * in order to old the parsed entries of a Dicom header, is a recursive
3082 * one. This is due to the fact that the sequences (when present)
3083 * can be nested. Additionaly, the sequence items (represented in
3084 * gdcm as \ref gdcmSQItem) add an extra complexity to the data
3085 * structure. Hence, a gdcm user whishing to visit all the entries of
3086 * a Dicom header will need to dig in the gdcm internals (which
3087 * implies exposing all the internal data structures to the API).
3088 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3089 * recursively builds a temporary hash table, which holds all the
3090 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3092 * \warning Of course there is NO integrity constrain between the
3093 * returned \ref TagDocEntryHT and the \ref gdcmElementSet used
3094 * to build it. Hence if the underlying \ref gdcmElementSet is
3095 * altered, then it is the caller responsability to invoke
3096 * \ref BuildFlatHashTable again...
3097 * @return The flat std::map<> we juste build.
3099 TagDocEntryHT* gdcmDocument::BuildFlatHashTable()
3101 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3102 BuildFlatHashTableRecurse( *FlatHT, this );
3109 * \brief Compares two documents, according to \ref gdcmDicomDir rules
3110 * \warning Does NOT work with ACR-NEMA files
3111 * \todo Find a trick to solve the pb (use RET fields ?)
3113 * @return true if 'smaller'
3115 bool gdcmDocument::operator<(gdcmDocument &document)
3118 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3119 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3131 s1 = GetEntryByNumber(0x0010,0x0020);
3132 s2 = document.GetEntryByNumber(0x0010,0x0020);
3143 // Study Instance UID
3144 s1 = GetEntryByNumber(0x0020,0x000d);
3145 s2 = document.GetEntryByNumber(0x0020,0x000d);
3156 // Serie Instance UID
3157 s1 = GetEntryByNumber(0x0020,0x000e);
3158 s2 = document.GetEntryByNumber(0x0020,0x000e);
3174 //-----------------------------------------------------------------------------