1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/16 06:48:00 $
7 Version: $Revision: 1.79 $
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.htm 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"
24 #include "gdcmGlobal.h"
26 #include "gdcmDebug.h"
34 #include <netinet/in.h>
39 // Implicit VR Little Endian
40 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
41 // Explicit VR Little Endian
42 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
43 // Deflated Explicit VR Little Endian
44 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
45 // Explicit VR Big Endian
46 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
47 // JPEG Baseline (Process 1)
48 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
49 // JPEG Extended (Process 2 & 4)
50 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
51 // JPEG Extended (Process 3 & 5)
52 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
53 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
54 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
55 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
56 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
57 // JPEG Lossless, Non-Hierarchical (Process 14)
58 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
59 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
60 // [Selection Value 1])
61 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
63 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
65 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
67 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
68 // UI1_1_2_840_10008_1_2_5
69 #define str2num(str, typeNum) *((typeNum *)(str))
71 //-----------------------------------------------------------------------------
72 // Refer to gdcmDocument::CheckSwap()
73 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
75 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
76 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
77 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
79 //-----------------------------------------------------------------------------
80 // Constructor / Destructor
84 * @param filename file to be opened for parsing
86 gdcmDocument::gdcmDocument( std::string const & filename )
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
102 fseek(Fp,0L,SEEK_END);
103 long lgt = ftell(Fp);
107 long beg = ftell(Fp);
112 (void)ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
116 // Load 'non string' values
118 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
119 if( PhotometricInterpretation == "PALETTE COLOR " )
121 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
122 /// FIXME FIXME FIXME
123 /// The tags refered by the three following lines used to be CORRECTLY
124 /// defined as having an US Value Representation in the public
125 /// dictionnary. BUT the semantics implied by the three following
126 /// lines state that the corresponding tag contents are in fact
127 /// the ones of a gdcmBinEntry.
128 /// In order to fix things "Quick and Dirty" the dictionnary was
129 /// altered on PURPOUS but now contains a WRONG value.
130 /// In order to fix things and restore the dictionary to its
131 /// correct value, one needs to decided of the semantics by deciding
132 /// wether the following tags are either:
133 /// - multivaluated US, and hence loaded as gdcmValEntry, but afterwards
134 /// also used as gdcmBinEntry, which requires the proper conversion,
135 /// - OW, and hence loaded as gdcmBinEntry, but afterwards also used
136 /// as gdcmValEntry, which requires the proper conversion.
137 LoadEntryVoidArea(0x0028,0x1201); // R LUT
138 LoadEntryVoidArea(0x0028,0x1202); // G LUT
139 LoadEntryVoidArea(0x0028,0x1203); // B LUT
141 // Segmented Red Palette Color LUT Data
142 LoadEntryVoidArea(0x0028,0x1221);
143 // Segmented Green Palette Color LUT Data
144 LoadEntryVoidArea(0x0028,0x1222);
145 // Segmented Blue Palette Color LUT Data
146 LoadEntryVoidArea(0x0028,0x1223);
148 //FIXME later : how to use it?
149 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
153 // --------------------------------------------------------------
154 // Specific code to allow gdcm to read ACR-LibIDO formated images
155 // Note: ACR-LibIDO is an extension of the ACR standard that was
156 // used at CREATIS. For the time being (say a couple years)
157 // we keep this kludge to allow a smooth move to gdcm for
158 // CREATIS developpers (sorry folks).
160 // if recognition code tells us we deal with a LibIDO image
161 // we switch lineNumber and columnNumber
164 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
165 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
166 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
167 // with "little-endian strings"
169 Filetype = gdcmACR_LIBIDO;
170 std::string rows = GetEntryByNumber(0x0028, 0x0010);
171 std::string columns = GetEntryByNumber(0x0028, 0x0011);
172 SetEntryByNumber(columns, 0x0028, 0x0010);
173 SetEntryByNumber(rows , 0x0028, 0x0011);
175 // ----------------- End of ACR-LibIDO kludge ------------------
177 PrintLevel = 1; // 'Medium' print level by default
181 * \brief This default constructor doesn't parse the file. You should
182 * then invoke \ref gdcmDocument::SetFileName and then the parsing.
184 gdcmDocument::gdcmDocument()
187 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
189 PrintLevel = 1; // 'Medium' print level by default
193 * \brief Canonical destructor.
195 gdcmDocument::~gdcmDocument ()
200 // Recursive clean up of sequences
201 for (TagDocEntryHT::const_iterator it = TagHT.begin();
202 it != TagHT.end(); ++it )
204 //delete it->second; //temp remove
209 //-----------------------------------------------------------------------------
213 * \brief Prints The Dict Entries of THE public Dicom Dictionary
216 void gdcmDocument::PrintPubDict(std::ostream & os)
218 RefPubDict->Print(os);
222 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
225 void gdcmDocument::PrintShaDict(std::ostream & os)
227 RefShaDict->Print(os);
230 //-----------------------------------------------------------------------------
233 * \brief Get the public dictionary used
235 gdcmDict *gdcmDocument::GetPubDict()
241 * \brief Get the shadow dictionary used
243 gdcmDict *gdcmDocument::GetShaDict()
249 * \brief Set the shadow dictionary used
250 * \param dict dictionary to use in shadow
252 bool gdcmDocument::SetShaDict(gdcmDict *dict)
259 * \brief Set the shadow dictionary used
260 * \param dictName name of the dictionary to use in shadow
262 bool gdcmDocument::SetShaDict(DictKey const & dictName)
264 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
269 * \brief This predicate, based on hopefully reasonable heuristics,
270 * decides whether or not the current gdcmDocument was properly parsed
271 * and contains the mandatory information for being considered as
272 * a well formed and usable Dicom/Acr File.
273 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
276 bool gdcmDocument::IsReadable()
278 if( Filetype == gdcmUnknown)
280 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
286 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
296 * \brief Internal function that checks whether the Transfer Syntax given
297 * as argument is the one present in the current document.
298 * @param syntaxToCheck The transfert syntax we need to check against.
299 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
300 * the current document. False either when the document contains
301 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
303 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
305 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
311 // The entry might be present but not loaded (parsing and loading
312 // happen at different stages): try loading and proceed with check...
313 LoadDocEntrySafe(entry);
314 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
316 std::string transfer = valEntry->GetValue();
317 // The actual transfer (as read from disk) might be padded. We
318 // first need to remove the potential padding. We can make the
319 // weak assumption that padding was not executed with digits...
320 if ( transfer.length() == 0 ) { // for brain damaged headers
323 while ( ! isdigit(transfer[transfer.length()-1]) )
325 transfer.erase(transfer.length()-1, 1);
327 if ( transfer == syntaxToCheck )
336 * \brief Determines if the Transfer Syntax of the present document
337 * corresponds to a Implicit Value Representation of
339 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
340 * @return True when ImplicitVRLittleEndian found. False in all other cases.
342 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
344 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
348 * \brief Determines if the Transfer Syntax was already encountered
349 * and if it corresponds to a ExplicitVRLittleEndian one.
350 * @return True when ExplicitVRLittleEndian found. False in all other cases.
352 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
354 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
358 * \brief Determines if the Transfer Syntax was already encountered
359 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
360 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
362 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
364 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
368 * \brief Determines if the Transfer Syntax was already encountered
369 * and if it corresponds to a Explicit VR Big Endian one.
370 * @return True when big endian found. False in all other cases.
372 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
374 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
378 * \brief Determines if the Transfer Syntax was already encountered
379 * and if it corresponds to a JPEGBaseLineProcess1 one.
380 * @return True when JPEGBaseLineProcess1found. False in all other cases.
382 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
384 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
388 * \brief Determines if the Transfer Syntax was already encountered
389 * and if it corresponds to a JPEGExtendedProcess2-4 one.
390 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
392 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
394 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
398 * \brief Determines if the Transfer Syntax was already encountered
399 * and if it corresponds to a JPEGExtendeProcess3-5 one.
400 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
402 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
404 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
408 * \brief Determines if the Transfer Syntax was already encountered
409 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
410 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
413 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
415 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
419 * \brief Determines if the Transfer Syntax was already encountered
420 * and if it corresponds to a RLE Lossless one.
421 * @return True when RLE Lossless found. False in all
424 bool gdcmDocument::IsRLELossLessTransferSyntax()
426 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
430 * \brief Determines if Transfer Syntax was already encountered
431 * and if it corresponds to a JPEG Lossless one.
432 * @return True when RLE Lossless found. False in all
436 bool gdcmDocument::IsJPEGLossless()
438 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
439 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
440 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
444 * \brief Determines if the Transfer Syntax was already encountered
445 * and if it corresponds to a JPEG2000 one
446 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
449 bool gdcmDocument::IsJPEG2000()
451 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
452 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
456 * \brief Predicate for dicom version 3 file.
457 * @return True when the file is a dicom version 3.
459 bool gdcmDocument::IsDicomV3()
461 // Checking if Transfert Syntax exists is enough
462 // Anyway, it's to late check if the 'Preamble' was found ...
463 // And ... would it be a rich idea to check ?
464 // (some 'no Preamble' DICOM images exist !)
465 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
469 * \brief returns the File Type
470 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
471 * @return the FileType code
473 FileType gdcmDocument::GetFileType()
479 * \brief Tries to open the file \ref gdcmDocument::Filename and
480 * checks the preamble when existing.
481 * @return The FILE pointer on success.
483 FILE* gdcmDocument::OpenFile()
485 Fp = fopen(Filename.c_str(),"rb");
490 "gdcmDocument::OpenFile cannot open file: ",
496 fread(&zero, (size_t)2, (size_t)1, Fp);
498 //ACR -- or DICOM with no Preamble --
499 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
505 fseek(Fp, 126L, SEEK_CUR);
507 fread(dicm, (size_t)4, (size_t)1, Fp);
508 if( memcmp(dicm, "DICM", 4) == 0 )
515 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
522 * \brief closes the file
523 * @return TRUE if the close was successfull
525 bool gdcmDocument::CloseFile()
527 int closed = fclose(Fp);
534 * \brief Writes in a file all the Header Entries (Dicom Elements)
535 * @param fp file pointer on an already open file
536 * @param filetype Type of the File to be written
537 * (ACR-NEMA, ExplicitVR, ImplicitVR)
538 * \return Always true.
540 void gdcmDocument::Write(FILE* fp,FileType filetype)
542 /// \todo move the following lines (and a lot of others, to be written)
543 /// to a future function CheckAndCorrectHeader
545 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
546 /// no way (check : FileType est un champ de gdcmDocument ...)
547 /// a moins de se livrer a un tres complique ajout des champs manquants.
548 /// faire un CheckAndCorrectHeader (?)
550 if (filetype == gdcmImplicitVR)
552 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
553 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
555 /// \todo Refer to standards on page 21, chapter 6.2
556 /// "Value representation": values with a VR of UI shall be
557 /// padded with a single trailing null
558 /// in the following case we have to padd manually with a 0
560 SetEntryLengthByNumber(18, 0x0002, 0x0010);
563 if (filetype == gdcmExplicitVR)
565 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
566 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
568 /// \todo Refer to standards on page 21, chapter 6.2
569 /// "Value representation": values with a VR of UI shall be
570 /// padded with a single trailing null
571 /// Dans le cas suivant on doit pader manuellement avec un 0
573 SetEntryLengthByNumber(20, 0x0002, 0x0010);
577 * \todo rewrite later, if really usefull
578 * - 'Group Length' element is optional in DICOM
579 * - but un-updated odd groups lengthes can causes pb
582 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
583 * UpdateGroupLength(false,filetype);
584 * if ( filetype == ACR)
585 * UpdateGroupLength(true,ACR);
588 gdcmElementSet::Write(fp, filetype); // This one is recursive
593 * \brief Modifies the value of a given Header Entry (Dicom Element)
594 * when it exists. Create it with the given value when unexistant.
595 * @param value (string) Value to be set
596 * @param group Group number of the Entry
597 * @param elem Element number of the Entry
598 * \return pointer to the modified/created Header Entry (NULL when creation
603 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
604 std::string const & value,
608 gdcmValEntry* valEntry = 0;
609 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
613 // The entry wasn't present and we simply create the required ValEntry:
614 currentEntry = NewDocEntryByNumber(group, elem);
617 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
618 " NewDocEntryByNumber failed.");
621 valEntry = new gdcmValEntry(currentEntry);
622 if ( !AddEntry(valEntry))
624 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
625 " failed allthough this is a creation.");
630 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
631 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
632 // then we change it to a ValEntry ?
633 // Shouldn't it be considered as an error ?
635 // We need to promote the gdcmDocEntry to a gdcmValEntry:
636 valEntry = new gdcmValEntry(currentEntry);
637 if (!RemoveEntry(currentEntry))
639 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
640 " of previous DocEntry failed.");
643 if ( !AddEntry(valEntry))
645 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
646 " promoted ValEntry failed.");
652 SetEntryByNumber(value, group, elem);
659 * \brief Modifies the value of a given Header Entry (Dicom Element)
660 * when it exists. Create it with the given value when unexistant.
661 * @param value (string) Value to be set
662 * @param group Group number of the Entry
663 * @param elem Element number of the Entry
664 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
665 * \return pointer to the modified/created Header Entry (NULL when creation
669 // TODO : write something clever, using default value for VR
670 // to avoid code duplication
671 // (I don't know how to tell NewDocEntryByNumber
672 // that ReplaceOrCreateByNumber was called with a default value)
674 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
675 std::string const & value,
678 std::string const & VR )
680 gdcmValEntry* valEntry = 0;
681 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
685 // check if (group,element) DictEntry exists
686 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
689 // Find out if the tag we received is in the dictionaries:
690 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
691 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
694 currentEntry = NewDocEntryByNumber(group, elem,VR);
698 currentEntry = NewDocEntryByNumber(group, elem);
703 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
704 " NewDocEntryByNumber failed.");
707 valEntry = new gdcmValEntry(currentEntry);
708 if ( !AddEntry(valEntry))
710 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
711 " failed allthough this is a creation.");
716 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
717 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
718 // then we change it to a ValEntry ?
719 // Shouldn't it be considered as an error ?
721 // We need to promote the gdcmDocEntry to a gdcmValEntry:
722 valEntry = new gdcmValEntry(currentEntry);
723 if (!RemoveEntry(currentEntry))
725 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
726 " of previous DocEntry failed.");
729 if ( !AddEntry(valEntry))
731 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
732 " promoted ValEntry failed.");
738 SetEntryByNumber(value, group, elem);
744 * \brief Modifies the value of a given Header Entry (Dicom Element)
745 * when it exists. Create it with the given value when unexistant.
746 * @param voidArea (binary) value to be set
747 * @param Group Group number of the Entry
748 * @param Elem Element number of the Entry
749 * \return pointer to the modified/created Header Entry (NULL when creation
752 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
757 std::string const & VR )
759 gdcmBinEntry* binEntry = 0;
760 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
764 // check if (group,element) DictEntry exists
765 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
768 // Find out if the tag we received is in the dictionaries:
769 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
770 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
774 currentEntry = NewDocEntryByNumber(group, elem,VR);
778 currentEntry = NewDocEntryByNumber(group, elem);
782 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
783 " NewDocEntryByNumber failed.");
786 binEntry = new gdcmBinEntry(currentEntry);
787 if ( !AddEntry(binEntry))
789 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
790 " failed allthough this is a creation.");
795 binEntry = dynamic_cast< gdcmBinEntry* >(currentEntry);
796 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
797 // then we change it to a BinEntry ?
798 // Shouldn't it be considered as an error ?
800 // We need to promote the gdcmDocEntry to a gdcmBinEntry:
801 binEntry = new gdcmBinEntry(currentEntry);
802 if (!RemoveEntry(currentEntry))
804 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
805 " of previous DocEntry failed.");
808 if ( !AddEntry(binEntry))
810 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
811 " promoted BinEntry failed.");
817 SetEntryByNumber(voidArea, lgth, group, elem);
824 * \brief Modifies the value of a given Header Entry (Dicom Element)
825 * when it exists. Create it when unexistant.
826 * @param Group Group number of the Entry
827 * @param Elem Element number of the Entry
828 * \return pointer to the modified/created SeqEntry (NULL when creation
831 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
836 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
839 a = NewSeqEntryByNumber(group, elem);
845 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
852 * \brief Set a new value if the invoked element exists
853 * Seems to be useless !!!
854 * @param value new element value
855 * @param group group number of the Entry
856 * @param elem element number of the Entry
859 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
860 uint16_t group, uint16_t elem )
862 SetEntryByNumber(value, group, elem);
867 //-----------------------------------------------------------------------------
871 * \brief Checks if a given Dicom Element exists within the H table
872 * @param group Group number of the searched Dicom Element
873 * @param element Element number of the searched Dicom Element
874 * @return true is found
876 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
878 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
879 return TagHT.count(key);
883 * \brief Searches within Header Entries (Dicom Elements) parsed with
884 * the public and private dictionaries
885 * for the element value of a given tag.
886 * \warning Don't use any longer : use GetPubEntryByName
887 * @param tagName name of the searched element.
888 * @return Corresponding element value when it exists,
889 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
891 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
893 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
899 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
903 * \brief Searches within Header Entries (Dicom Elements) parsed with
904 * the public and private dictionaries
905 * for the element value representation of a given tag.
907 * Obtaining the VR (Value Representation) might be needed by caller
908 * to convert the string typed content to caller's native type
909 * (think of C++ vs Python). The VR is actually of a higher level
910 * of semantics than just the native C++ type.
911 * @param tagName name of the searched element.
912 * @return Corresponding element value representation when it exists,
913 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
915 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
917 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
918 if( dictEntry == NULL)
923 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
924 dictEntry->GetElement());
925 return elem->GetVR();
930 * \brief Searches within Header Entries (Dicom Elements) parsed with
931 * the public and private dictionaries
932 * for the element value representation of a given tag.
933 * @param group Group number of the searched tag.
934 * @param element Element number of the searched tag.
935 * @return Corresponding element value representation when it exists,
936 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
938 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
940 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
941 /// \todo use map methods, instead of multimap JPR
942 if ( !TagHT.count(key))
947 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
951 * \brief Searches within Header Entries (Dicom Elements) parsed with
952 * the public and private dictionaries
953 * for the element value representation of a given tag..
955 * Obtaining the VR (Value Representation) might be needed by caller
956 * to convert the string typed content to caller's native type
957 * (think of C++ vs Python). The VR is actually of a higher level
958 * of semantics than just the native C++ type.
959 * @param group Group number of the searched tag.
960 * @param element Element number of the searched tag.
961 * @return Corresponding element value representation when it exists,
962 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
964 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
966 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
971 return elem->GetVR();
975 * \brief Searches within Header Entries (Dicom Elements) parsed with
976 * the public and private dictionaries
977 * for the value length of a given tag..
978 * @param group Group number of the searched tag.
979 * @param element Element number of the searched tag.
980 * @return Corresponding element length; -2 if not found
982 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
984 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
987 return -2; //magic number
989 return elem->GetLength();
992 * \brief Sets the value (string) of the Header Entry (Dicom Element)
993 * @param content string value of the Dicom Element
994 * @param tagName name of the searched Dicom Element.
995 * @return true when found
997 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
999 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1005 return SetEntryByNumber(content,dictEntry->GetGroup(),
1006 dictEntry->GetElement());
1010 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1011 * through it's (group, element) and modifies it's content with
1013 * @param content new value (string) to substitute with
1014 * @param group group number of the Dicom Element to modify
1015 * @param element element number of the Dicom Element to modify
1017 bool gdcmDocument::SetEntryByNumber(std::string const & content,
1024 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
1027 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
1028 " ValEntry (try promotion first).");
1031 // Non even content must be padded with a space (020H)...
1032 std::string finalContent = content;
1033 if( finalContent.length() % 2 )
1035 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
1037 valEntry->SetValue(finalContent);
1039 // Integers have a special treatement for their length:
1041 l = finalContent.length();
1042 if ( l != 0) // To avoid to be cheated by 'zero length' integers
1044 gdcmVRKey vr = valEntry->GetVR();
1045 if( vr == "US" || vr == "SS" )
1047 c = CountSubstring(content, "\\") + 1; // for multivaluated items
1050 else if( vr == "UL" || vr == "SL" )
1052 c = CountSubstring(content, "\\") + 1; // for multivaluated items
1056 valEntry->SetLength(l);
1061 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1062 * through it's (group, element) and modifies it's content with
1064 * @param content new value (void *) to substitute with
1065 * @param lgth new value length
1066 * @param group group number of the Dicom Element to modify
1067 * @param element element number of the Dicom Element to modify
1069 bool gdcmDocument::SetEntryByNumber(void *content,
1074 (void)lgth; //not used
1075 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1076 if ( !TagHT.count(key))
1081 /* Hope Binary field length is *never* wrong
1082 if(lgth%2) // Non even length are padded with a space (020H).
1085 //content = content + '\0'; // fing a trick to enlarge a binary field?
1088 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1089 a->SetVoidArea(content);
1096 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1097 * in the PubDocEntrySet of this instance
1098 * through it's (group, element) and modifies it's length with
1100 * \warning Use with extreme caution.
1101 * @param l new length to substitute with
1102 * @param group group number of the Entry to modify
1103 * @param element element number of the Entry to modify
1104 * @return true on success, false otherwise.
1106 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1110 /// \todo use map methods, instead of multimap JPR
1111 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1112 if ( !TagHT.count(key) )
1118 l++; // length must be even
1120 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1126 * \brief Gets (from Header) the offset of a 'non string' element value
1127 * (LoadElementValues has already be executed)
1128 * @param group group number of the Entry
1129 * @param elem element number of the Entry
1130 * @return File Offset of the Element Value
1132 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1134 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1137 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1140 return entry->GetOffset();
1144 * \brief Gets (from Header) a 'non string' element value
1145 * (LoadElementValues has already be executed)
1146 * @param group group number of the Entry
1147 * @param elem element number of the Entry
1148 * @return Pointer to the 'non string' area
1150 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1152 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1155 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1158 return ((gdcmBinEntry *)entry)->GetVoidArea();
1162 * \brief Loads (from disk) the element content
1163 * when a string is not suitable
1164 * @param group group number of the Entry
1165 * @param elem element number of the Entry
1167 void* gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1169 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1174 size_t o =(size_t)docElement->GetOffset();
1175 fseek(Fp, o, SEEK_SET);
1176 size_t l = docElement->GetLength();
1177 char* a = new char[l];
1180 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1183 size_t l2 = fread(a, 1, l , Fp);
1189 /// \TODO Drop any already existing void area! JPR
1190 if( !SetEntryVoidAreaByNumber( a, group, elem ) );
1192 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea setting failed.");
1198 * \brief Loads (from disk) the element content
1199 * when a string is not suitable
1200 * @param element Entry whose voidArea is going to be loaded
1202 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1204 size_t o =(size_t)element->GetOffset();
1205 fseek(Fp, o, SEEK_SET);
1206 size_t l = element->GetLength();
1207 char* a = new char[l];
1210 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1213 element->SetVoidArea((void *)a);
1214 /// \todo check the result
1215 size_t l2 = fread(a, 1, l , Fp);
1226 * \brief Sets a 'non string' value to a given Dicom Element
1227 * @param area area containing the 'non string' value
1228 * @param group Group number of the searched Dicom Element
1229 * @param element Element number of the searched Dicom Element
1232 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1236 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1237 if ( !currentEntry )
1241 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1243 binEntry->SetVoidArea( area );
1250 * \brief Update the entries with the shadow dictionary.
1251 * Only non even entries are analyzed
1253 void gdcmDocument::UpdateShaEntries()
1255 //gdcmDictEntry *entry;
1258 /// \todo TODO : still any use to explore recursively the whole structure?
1260 for(ListTag::iterator it=listEntries.begin();
1261 it!=listEntries.end();
1264 // Odd group => from public dictionary
1265 if((*it)->GetGroup()%2==0)
1268 // Peer group => search the corresponding dict entry
1270 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1274 if((*it)->IsImplicitVR())
1279 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1281 // Set the new entry and the new value
1282 (*it)->SetDictEntry(entry);
1283 CheckDocEntryVR(*it,vr);
1285 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1290 // Remove precedent value transformation
1291 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1298 * \brief Searches within the Header Entries for a Dicom Element of
1300 * @param tagName name of the searched Dicom Element.
1301 * @return Corresponding Dicom Element when it exists, and NULL
1304 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1306 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1312 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1316 * \brief retrieves a Dicom Element (the first one) using (group, element)
1317 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1318 * if you think it's NOT UNIQUE, check the count number
1319 * and use iterators to retrieve ALL the Dicoms Elements within
1320 * a given couple (group, element)
1321 * @param group Group number of the searched Dicom Element
1322 * @param element Element number of the searched Dicom Element
1325 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1328 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1329 if ( !TagHT.count(key))
1333 return TagHT.find(key)->second;
1337 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1338 * returns a result when the corresponding entry is of type
1340 * @return When present, the corresponding ValEntry.
1342 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1345 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1346 if ( !currentEntry )
1350 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1354 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1360 * \brief Loads the element while preserving the current
1361 * underlying file position indicator as opposed to
1362 * to LoadDocEntry that modifies it.
1363 * @param entry Header Entry whose value shall be loaded.
1366 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1368 long PositionOnEntry = ftell(Fp);
1369 LoadDocEntry(entry);
1370 fseek(Fp, PositionOnEntry, SEEK_SET);
1374 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1376 * @return The properly swaped 32 bits integer.
1378 uint32_t gdcmDocument::SwapLong(uint32_t a)
1385 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1386 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1390 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1394 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1397 //std::cout << "swapCode= " << SwapCode << std::endl;
1398 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1405 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1407 * @return The properly unswaped 32 bits integer.
1409 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1415 * \brief Swaps the bytes so they agree with the processor order
1416 * @return The properly swaped 16 bits integer.
1418 uint16_t gdcmDocument::SwapShort(uint16_t a)
1420 if ( SwapCode == 4321 || SwapCode == 2143 )
1422 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1428 * \brief Unswaps the bytes so they agree with the processor order
1429 * @return The properly unswaped 16 bits integer.
1431 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1433 return SwapShort(a);
1436 //-----------------------------------------------------------------------------
1440 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1441 * @return length of the parsed set.
1444 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1449 gdcmDocEntry *newDocEntry = 0;
1450 unsigned long l = 0;
1452 int depth = set->GetDepthLevel();
1455 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1459 newDocEntry = ReadNextDocEntry( );
1465 gdcmVRKey vr = newDocEntry->GetVR();
1469 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1472 gdcmValEntry* newValEntry =
1473 new gdcmValEntry( newDocEntry->GetDictEntry() );
1474 newValEntry->Copy( newDocEntry );
1475 newValEntry->SetKey( set->GetBaseTagKey() + newValEntry->GetKey() );
1476 set->AddEntry( newValEntry );
1477 LoadDocEntry( newValEntry );
1478 if (newValEntry->IsItemDelimitor())
1482 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1489 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1491 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1492 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1493 "nor BinEntry. Probably unknown VR.");
1496 ////// BinEntry or UNKOWN VR:
1497 gdcmBinEntry* newBinEntry =
1498 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1499 newBinEntry->Copy( newDocEntry );
1500 newBinEntry->SetKey( set->GetBaseTagKey() + newBinEntry->GetKey() );
1501 set->AddEntry( newBinEntry );
1502 LoadDocEntry( newBinEntry );
1505 if (newDocEntry->GetGroup() == 0x7fe0 &&
1506 newDocEntry->GetElement() == 0x0010 )
1508 if (newDocEntry->GetReadLength()==0xffffffff)
1510 // Broken US.3405.1.dcm
1511 Parse7FE0(); // to skip the pixels
1512 // (multipart JPEG/RLE are trouble makers)
1516 SkipToNextDocEntry(newDocEntry);
1517 l = newDocEntry->GetFullLength();
1522 // to be sure we are at the beginning
1523 SkipToNextDocEntry(newDocEntry);
1524 l = newDocEntry->GetFullLength();
1530 l = newDocEntry->GetReadLength();
1531 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1533 if ( l == 0xffffffff )
1542 // no other way to create it ...
1543 gdcmSeqEntry* newSeqEntry =
1544 new gdcmSeqEntry( newDocEntry->GetDictEntry(),
1545 set->GetDepthLevel() );
1546 newSeqEntry->Copy( newDocEntry );
1547 newSeqEntry->SetDelimitorMode( delim_mode );
1548 newSeqEntry->SetDepthLevel( depth );
1549 newSeqEntry->SetKey( set->GetBaseTagKey() + newSeqEntry->GetKey() );
1552 { // Don't try to parse zero-length sequences
1553 (void)ParseSQ( newSeqEntry,
1554 newDocEntry->GetOffset(),
1557 set->AddEntry( newSeqEntry );
1558 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1565 return l; // Probably useless
1569 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1570 * @return parsed length for this level
1572 long gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1573 long offset, long l_max, bool delim_mode)
1575 int SQItemNumber = 0;
1580 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1583 // FIXME Should warn user
1588 if ( newDocEntry->IsSequenceDelimitor() )
1590 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1594 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1599 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1600 std::ostringstream newBase;
1601 newBase << seqEntry->GetKey()
1605 itemSQ->SetBaseTagKey( newBase.str() );
1606 unsigned int l = newDocEntry->GetReadLength();
1608 if ( l == 0xffffffff )
1617 (void)ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1619 seqEntry->AddEntry( itemSQ, SQItemNumber );
1621 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1627 int lgth = ftell(Fp) - offset;
1632 * \brief Loads the element content if its length doesn't exceed
1633 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1634 * @param entry Header Entry (Dicom Element) to be dealt with
1636 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1639 uint16_t group = entry->GetGroup();
1640 std::string vr = entry->GetVR();
1641 uint32_t length = entry->GetLength();
1643 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1645 // A SeQuence "contains" a set of Elements.
1646 // (fffe e000) tells us an Element is beginning
1647 // (fffe e00d) tells us an Element just ended
1648 // (fffe e0dd) tells us the current SeQuence just ended
1649 if( group == 0xfffe )
1651 // NO more value field for SQ !
1655 // When the length is zero things are easy:
1658 ((gdcmValEntry *)entry)->SetValue("");
1662 // The elements whose length is bigger than the specified upper bound
1663 // are not loaded. Instead we leave a short notice of the offset of
1664 // the element content and it's length.
1666 std::ostringstream s;
1667 if (length > MaxSizeLoadEntry)
1669 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1671 //s << "gdcm::NotLoaded (BinEntry)";
1672 s << GDCM_NOTLOADED;
1673 s << " Address:" << (long)entry->GetOffset();
1674 s << " Length:" << entry->GetLength();
1675 s << " x(" << std::hex << entry->GetLength() << ")";
1676 binEntryPtr->SetValue(s.str());
1678 // Be carefull : a BinEntry IS_A ValEntry ...
1679 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1681 // s << "gdcm::NotLoaded. (ValEntry)";
1682 s << GDCM_NOTLOADED;
1683 s << " Address:" << (long)entry->GetOffset();
1684 s << " Length:" << entry->GetLength();
1685 s << " x(" << std::hex << entry->GetLength() << ")";
1686 valEntryPtr->SetValue(s.str());
1691 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1692 << "nor a ValEntry ?! Should never print that !" << std::endl;
1695 // to be sure we are at the end of the value ...
1696 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1700 // When we find a BinEntry not very much can be done :
1701 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1703 s << "gdcm::Loaded (BinEntry)";
1704 binEntryPtr->SetValue(s.str());
1705 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1709 /// \todo Any compacter code suggested (?)
1710 if ( IsDocEntryAnInteger(entry) )
1714 // When short integer(s) are expected, read and convert the following
1715 // n *two characters properly i.e. consider them as short integers as
1716 // opposed to strings.
1717 // Elements with Value Multiplicity > 1
1718 // contain a set of integers (not a single one)
1719 if (vr == "US" || vr == "SS")
1722 NewInt = ReadInt16();
1726 for (int i=1; i < nbInt; i++)
1729 NewInt = ReadInt16();
1734 // See above comment on multiple integers (mutatis mutandis).
1735 else if (vr == "UL" || vr == "SL")
1738 NewInt = ReadInt32();
1742 for (int i=1; i < nbInt; i++)
1745 NewInt = ReadInt32();
1750 #ifdef GDCM_NO_ANSI_STRING_STREAM
1751 s << std::ends; // to avoid oddities on Solaris
1752 #endif //GDCM_NO_ANSI_STRING_STREAM
1754 ((gdcmValEntry *)entry)->SetValue(s.str());
1758 // We need an additional byte for storing \0 that is not on disk
1759 //std::string newValue(length,0);
1760 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1761 //rah !! I can't believe it could work, normally this is a const char* !!!
1762 char *str = new char[length+1];
1763 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1765 std::string newValue = str;
1767 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1769 if ( item_read != 1 )
1771 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1772 "unread element value");
1773 valEntry->SetValue(GDCM_UNREAD);
1779 // Because of correspondance with the VR dic
1780 valEntry->SetValue(newValue);
1784 valEntry->SetValue(newValue);
1789 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1790 "Should have a ValEntry, here !");
1796 * \brief Find the value Length of the passed Header Entry
1797 * @param entry Header Entry whose length of the value shall be loaded.
1799 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1800 throw ( gdcmFormatError )
1802 uint16_t element = entry->GetElement();
1803 std::string vr = entry->GetVR();
1806 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1808 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1810 // The following reserved two bytes (see PS 3.5-2001, section
1811 // 7.1.2 Data element structure with explicit vr p27) must be
1812 // skipped before proceeding on reading the length on 4 bytes.
1813 fseek(Fp, 2L, SEEK_CUR);
1814 uint32_t length32 = ReadInt32();
1816 if ( vr == "OB" && length32 == 0xffffffff )
1821 lengthOB = FindDocEntryLengthOB();
1823 catch ( gdcmFormatUnexpected )
1825 // Computing the length failed (this happens with broken
1826 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1827 // chance to get the pixels by deciding the element goes
1828 // until the end of the file. Hence we artificially fix the
1829 // the length and proceed.
1830 long currentPosition = ftell(Fp);
1831 fseek(Fp,0L,SEEK_END);
1832 long lengthUntilEOF = ftell(Fp) - currentPosition;
1833 fseek(Fp, currentPosition, SEEK_SET);
1834 entry->SetLength(lengthUntilEOF);
1837 entry->SetLength(lengthOB);
1840 FixDocEntryFoundLength(entry, length32);
1844 // Length is encoded on 2 bytes.
1845 length16 = ReadInt16();
1847 // We can tell the current file is encoded in big endian (like
1848 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1849 // and it's value is the one of the encoding of a big endian file.
1850 // In order to deal with such big endian encoded files, we have
1851 // (at least) two strategies:
1852 // * when we load the "Transfer Syntax" tag with value of big endian
1853 // encoding, we raise the proper flags. Then we wait for the end
1854 // of the META group (0x0002) among which is "Transfer Syntax",
1855 // before switching the swap code to big endian. We have to postpone
1856 // the switching of the swap code since the META group is fully encoded
1857 // in little endian, and big endian coding only starts at the next
1858 // group. The corresponding code can be hard to analyse and adds
1859 // many additional unnecessary tests for regular tags.
1860 // * the second strategy consists in waiting for trouble, that shall
1861 // appear when we find the first group with big endian encoding. This
1862 // is easy to detect since the length of a "Group Length" tag (the
1863 // ones with zero as element number) has to be of 4 (0x0004). When we
1864 // encounter 1024 (0x0400) chances are the encoding changed and we
1865 // found a group with big endian encoding.
1866 // We shall use this second strategy. In order to make sure that we
1867 // can interpret the presence of an apparently big endian encoded
1868 // length of a "Group Length" without committing a big mistake, we
1869 // add an additional check: we look in the already parsed elements
1870 // for the presence of a "Transfer Syntax" whose value has to be "big
1871 // endian encoding". When this is the case, chances are we have got our
1872 // hands on a big endian encoded file: we switch the swap code to
1873 // big endian and proceed...
1874 if ( element == 0x0000 && length16 == 0x0400 )
1876 if ( !IsExplicitVRBigEndianTransferSyntax() )
1878 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1879 " not explicit VR." );
1883 SwitchSwapToBigEndian();
1884 // Restore the unproperly loaded values i.e. the group, the element
1885 // and the dictionary entry depending on them.
1886 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1887 uint16_t correctElem = SwapShort( entry->GetElement() );
1888 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1892 // This correct tag is not in the dictionary. Create a new one.
1893 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1895 // FIXME this can create a memory leaks on the old entry that be
1896 // left unreferenced.
1897 entry->SetDictEntry( newTag );
1900 // Heuristic: well, some files are really ill-formed.
1901 if ( length16 == 0xffff)
1903 // 0xffff means that we deal with 'Unknown Length' Sequence
1906 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1911 // Either implicit VR or a non DICOM conformal (see note below) explicit
1912 // VR that ommited the VR of (at least) this element. Farts happen.
1913 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1914 // on Data elements "Implicit and Explicit VR Data Elements shall
1915 // not coexist in a Data Set and Data Sets nested within it".]
1916 // Length is on 4 bytes.
1918 FixDocEntryFoundLength( entry, ReadInt32() );
1924 * \brief Find the Value Representation of the current Dicom Element.
1927 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1929 if ( Filetype != gdcmExplicitVR )
1936 long positionOnEntry = ftell(Fp);
1937 // Warning: we believe this is explicit VR (Value Representation) because
1938 // we used a heuristic that found "UL" in the first tag. Alas this
1939 // doesn't guarantee that all the tags will be in explicit VR. In some
1940 // cases (see e-film filtered files) one finds implicit VR tags mixed
1941 // within an explicit VR file. Hence we make sure the present tag
1942 // is in explicit VR and try to fix things if it happens not to be
1945 fread (vr, (size_t)2,(size_t)1, Fp);
1948 if( !CheckDocEntryVR(entry, vr) )
1950 fseek(Fp, positionOnEntry, SEEK_SET);
1951 // When this element is known in the dictionary we shall use, e.g. for
1952 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1953 // dictionary entry. Still we have to flag the element as implicit since
1954 // we know now our assumption on expliciteness is not furfilled.
1956 if ( entry->IsVRUnknown() )
1958 entry->SetVR("Implicit");
1960 entry->SetImplicitVR();
1965 * \brief Check the correspondance between the VR of the header entry
1966 * and the taken VR. If they are different, the header entry is
1967 * updated with the new VR.
1968 * @param entry Header Entry to check
1969 * @param vr Dicom Value Representation
1970 * @return false if the VR is incorrect of if the VR isn't referenced
1971 * otherwise, it returns true
1973 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1975 char msg[100]; // for sprintf
1976 bool realExplicit = true;
1978 // Assume we are reading a falsely explicit VR file i.e. we reached
1979 // a tag where we expect reading a VR but are in fact we read the
1980 // first to bytes of the length. Then we will interogate (through find)
1981 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1982 // both GCC and VC++ implementations of the STL map. Hence when the
1983 // expected VR read happens to be non-ascii characters we consider
1984 // we hit falsely explicit VR tag.
1986 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1988 realExplicit = false;
1991 // CLEANME searching the dicom_vr at each occurence is expensive.
1992 // PostPone this test in an optional integrity check at the end
1993 // of parsing or only in debug mode.
1994 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1996 realExplicit = false;
1999 if ( !realExplicit )
2001 // We thought this was explicit VR, but we end up with an
2002 // implicit VR tag. Let's backtrack.
2003 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
2004 entry->GetGroup(), entry->GetElement());
2005 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
2007 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2009 // Group length is UL !
2010 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2011 entry->GetGroup(), entry->GetElement(),
2012 "UL", "FIXME", "Group Length");
2013 entry->SetDictEntry( newEntry );
2018 if ( entry->IsVRUnknown() )
2020 // When not a dictionary entry, we can safely overwrite the VR.
2021 if( entry->GetElement() == 0x0000 )
2023 // Group length is UL !
2031 else if ( entry->GetVR() != vr )
2033 // The VR present in the file and the dictionary disagree. We assume
2034 // the file writer knew best and use the VR of the file. Since it would
2035 // be unwise to overwrite the VR of a dictionary (since it would
2036 // compromise it's next user), we need to clone the actual DictEntry
2037 // and change the VR for the read one.
2038 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2039 entry->GetGroup(), entry->GetElement(),
2040 vr, "FIXME", entry->GetName());
2041 entry->SetDictEntry(newEntry);
2048 * \brief Get the transformed value of the header entry. The VR value
2049 * is used to define the transformation to operate on the value
2050 * \warning NOT end user intended method !
2051 * @param entry entry to tranform
2052 * @return Transformed entry value
2054 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2056 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2058 std::string val = ((gdcmValEntry *)entry)->GetValue();
2059 std::string vr = entry->GetVR();
2060 uint32_t length = entry->GetLength();
2061 std::ostringstream s;
2064 // When short integer(s) are expected, read and convert the following
2065 // n * 2 bytes properly i.e. as a multivaluated strings
2066 // (each single value is separated fromthe next one by '\'
2067 // as usual for standard multivaluated filels
2068 // Elements with Value Multiplicity > 1
2069 // contain a set of short integers (not a single one)
2071 if( vr == "US" || vr == "SS" )
2076 for (int i=0; i < nbInt; i++)
2082 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2083 newInt16 = SwapShort( newInt16 );
2088 // When integer(s) are expected, read and convert the following
2089 // n * 4 bytes properly i.e. as a multivaluated strings
2090 // (each single value is separated fromthe next one by '\'
2091 // as usual for standard multivaluated filels
2092 // Elements with Value Multiplicity > 1
2093 // contain a set of integers (not a single one)
2094 else if( vr == "UL" || vr == "SL" )
2099 for (int i=0; i < nbInt; i++)
2105 newInt32 = ( val[4*i+0] & 0xFF )
2106 + (( val[4*i+1] & 0xFF ) << 8 )
2107 + (( val[4*i+2] & 0xFF ) << 16 )
2108 + (( val[4*i+3] & 0xFF ) << 24 );
2109 newInt32 = SwapLong( newInt32 );
2113 #ifdef GDCM_NO_ANSI_STRING_STREAM
2114 s << std::ends; // to avoid oddities on Solaris
2115 #endif //GDCM_NO_ANSI_STRING_STREAM
2119 return ((gdcmValEntry *)entry)->GetValue();
2123 * \brief Get the reverse transformed value of the header entry. The VR
2124 * value is used to define the reverse transformation to operate on
2126 * \warning NOT end user intended method !
2127 * @param entry Entry to reverse transform
2128 * @return Reverse transformed entry value
2130 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2132 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2134 std::string vr = entry->GetVR();
2135 std::vector<std::string> tokens;
2136 std::ostringstream s;
2138 if ( vr == "US" || vr == "SS" )
2142 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2143 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2144 for (unsigned int i=0; i<tokens.size(); i++)
2146 newInt16 = atoi(tokens[i].c_str());
2147 s << ( newInt16 & 0xFF )
2148 << (( newInt16 >> 8 ) & 0xFF );
2152 if ( vr == "UL" || vr == "SL")
2156 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2157 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2158 for (unsigned int i=0; i<tokens.size();i++)
2160 newInt32 = atoi(tokens[i].c_str());
2161 s << (char)( newInt32 & 0xFF )
2162 << (char)(( newInt32 >> 8 ) & 0xFF )
2163 << (char)(( newInt32 >> 16 ) & 0xFF )
2164 << (char)(( newInt32 >> 24 ) & 0xFF );
2169 #ifdef GDCM_NO_ANSI_STRING_STREAM
2170 s << std::ends; // to avoid oddities on Solaris
2171 #endif //GDCM_NO_ANSI_STRING_STREAM
2175 return ((gdcmValEntry *)entry)->GetValue();
2179 * \brief Skip a given Header Entry
2180 * \warning NOT end user intended method !
2181 * @param entry entry to skip
2183 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2185 SkipBytes(entry->GetLength());
2189 * \brief Skips to the begining of the next Header Entry
2190 * \warning NOT end user intended method !
2191 * @param entry entry to skip
2193 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2195 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2196 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2200 * \brief When the length of an element value is obviously wrong (because
2201 * the parser went Jabberwocky) one can hope improving things by
2202 * applying some heuristics.
2203 * @param entry entry to check
2204 * @param foundLength fist assumption about length
2206 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2207 uint32_t foundLength)
2209 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2210 if ( foundLength == 0xffffffff)
2215 uint16_t gr = entry->GetGroup();
2216 uint16_t el = entry->GetElement();
2218 if ( foundLength % 2)
2220 std::ostringstream s;
2221 s << "Warning : Tag with uneven length "
2223 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2224 dbg.Verbose(0, s.str().c_str());
2227 //////// Fix for some naughty General Electric images.
2228 // Allthough not recent many such GE corrupted images are still present
2229 // on Creatis hard disks. Hence this fix shall remain when such images
2230 // are no longer in user (we are talking a few years, here)...
2231 // Note: XMedCom probably uses such a trick since it is able to read
2232 // those pesky GE images ...
2233 if ( foundLength == 13)
2235 // Only happens for this length !
2236 if ( entry->GetGroup() != 0x0008
2237 || ( entry->GetElement() != 0x0070
2238 && entry->GetElement() != 0x0080 ) )
2241 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2245 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2246 // Occurence of such images is quite low (unless one leaves close to a
2247 // 'Leonardo' source. Hence, one might consider commenting out the
2248 // following fix on efficiency reasons.
2249 else if ( entry->GetGroup() == 0x0009
2250 && ( entry->GetElement() == 0x1113
2251 || entry->GetElement() == 0x1114 ) )
2254 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2257 else if ( entry->GetVR() == "SQ" )
2259 foundLength = 0; // ReadLength is unchanged
2262 //////// We encountered a 'delimiter' element i.e. a tag of the form
2263 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2264 // taken into account.
2265 else if( entry->GetGroup() == 0xfffe )
2267 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2268 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2269 // causes extra troubles...
2270 if( entry->GetElement() != 0x0000 )
2276 entry->SetUsableLength(foundLength);
2280 * \brief Apply some heuristics to predict whether the considered
2281 * element value contains/represents an integer or not.
2282 * @param entry The element value on which to apply the predicate.
2283 * @return The result of the heuristical predicate.
2285 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2287 uint16_t element = entry->GetElement();
2288 uint16_t group = entry->GetGroup();
2289 std::string vr = entry->GetVR();
2290 uint32_t length = entry->GetLength();
2292 // When we have some semantics on the element we just read, and if we
2293 // a priori know we are dealing with an integer, then we shall be
2294 // able to swap it's element value properly.
2295 if ( element == 0 ) // This is the group length of the group
2303 // Allthough this should never happen, still some images have a
2304 // corrupted group length [e.g. have a glance at offset x(8336) of
2305 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2306 // Since for dicom compliant and well behaved headers, the present
2307 // test is useless (and might even look a bit paranoid), when we
2308 // encounter such an ill-formed image, we simply display a warning
2309 // message and proceed on parsing (while crossing fingers).
2310 std::ostringstream s;
2311 int filePosition = ftell(Fp);
2312 s << "Erroneous Group Length element length on : (" \
2313 << std::hex << group << " , " << element
2314 << ") -before- position x(" << filePosition << ")"
2315 << "lgt : " << length;
2316 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2320 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2329 * \brief Find the Length till the next sequence delimiter
2330 * \warning NOT end user intended method !
2334 uint32_t gdcmDocument::FindDocEntryLengthOB()
2335 throw( gdcmFormatUnexpected )
2337 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2338 long positionOnEntry = ftell(Fp);
2339 bool foundSequenceDelimiter = false;
2340 uint32_t totalLength = 0;
2342 while ( !foundSequenceDelimiter )
2348 group = ReadInt16();
2351 catch ( gdcmFormatError )
2353 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2354 " group or element not present.");
2357 // We have to decount the group and element we just read
2360 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2362 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2363 "tag nor a Sequence delimiter tag.");
2364 fseek(Fp, positionOnEntry, SEEK_SET);
2365 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2366 "Neither an Item tag nor a Sequence "
2370 if ( elem == 0xe0dd )
2372 foundSequenceDelimiter = true;
2375 uint32_t itemLength = ReadInt32();
2376 // We add 4 bytes since we just read the ItemLength with ReadInt32
2377 totalLength += itemLength + 4;
2378 SkipBytes(itemLength);
2380 if ( foundSequenceDelimiter )
2385 fseek(Fp, positionOnEntry, SEEK_SET);
2390 * \brief Reads a supposed to be 16 Bits integer
2391 * (swaps it depending on processor endianity)
2392 * @return read value
2394 uint16_t gdcmDocument::ReadInt16()
2395 throw( gdcmFormatError )
2398 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2399 if ( item_read != 1 )
2403 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2405 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2412 * \brief Reads a supposed to be 32 Bits integer
2413 * (swaps it depending on processor endianity)
2414 * @return read value
2416 uint32_t gdcmDocument::ReadInt32()
2417 throw( gdcmFormatError )
2420 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2421 if ( item_read != 1 )
2425 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2427 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2434 * \brief skips bytes inside the source file
2435 * \warning NOT end user intended method !
2438 void gdcmDocument::SkipBytes(uint32_t nBytes)
2440 //FIXME don't dump the returned value
2441 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2445 * \brief Loads all the needed Dictionaries
2446 * \warning NOT end user intended method !
2448 void gdcmDocument::Initialise()
2450 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2455 * \brief Discover what the swap code is (among little endian, big endian,
2456 * bad little endian, bad big endian).
2458 * @return false when we are absolutely sure
2459 * it's neither ACR-NEMA nor DICOM
2460 * true when we hope ours assuptions are OK
2462 bool gdcmDocument::CheckSwap()
2464 // The only guaranted way of finding the swap code is to find a
2465 // group tag since we know it's length has to be of four bytes i.e.
2466 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2467 // occurs when we can't find such group...
2469 uint32_t x = 4; // x : for ntohs
2470 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2474 char deb[HEADER_LENGTH_TO_READ];
2476 // First, compare HostByteOrder and NetworkByteOrder in order to
2477 // determine if we shall need to swap bytes (i.e. the Endian type).
2478 if ( x == ntohs(x) )
2487 // The easiest case is the one of a DICOM header, since it possesses a
2488 // file preamble where it suffice to look for the string "DICM".
2489 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2490 (void)lgrLue; //FIXME not used
2492 char *entCur = deb + 128;
2493 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2495 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2497 // Next, determine the value representation (VR). Let's skip to the
2498 // first element (0002, 0000) and check there if we find "UL"
2499 // - or "OB" if the 1st one is (0002,0001) -,
2500 // in which case we (almost) know it is explicit VR.
2501 // WARNING: if it happens to be implicit VR then what we will read
2502 // is the length of the group. If this ascii representation of this
2503 // length happens to be "UL" then we shall believe it is explicit VR.
2504 // FIXME: in order to fix the above warning, we could read the next
2505 // element value (or a couple of elements values) in order to make
2506 // sure we are not commiting a big mistake.
2507 // We need to skip :
2508 // * the 128 bytes of File Preamble (often padded with zeroes),
2509 // * the 4 bytes of "DICM" string,
2510 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2511 // i.e. a total of 136 bytes.
2515 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2516 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2517 // *Implicit* VR. -and it is !-
2519 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2520 memcmp(entCur, "OB", (size_t)2) == 0 ||
2521 memcmp(entCur, "UI", (size_t)2) == 0 ||
2522 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2523 // when Write DCM *adds*
2525 // Use gdcmDocument::dicom_vr to test all the possibilities
2526 // instead of just checking for UL, OB and UI !? group 0000
2528 Filetype = gdcmExplicitVR;
2529 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2530 "explicit Value Representation");
2534 Filetype = gdcmImplicitVR;
2535 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2536 "not an explicit Value Representation");
2542 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2543 "HostByteOrder != NetworkByteOrder");
2548 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2549 "HostByteOrder = NetworkByteOrder");
2552 // Position the file position indicator at first tag (i.e.
2553 // after the file preamble and the "DICM" string).
2555 fseek (Fp, 132L, SEEK_SET);
2559 // Alas, this is not a DicomV3 file and whatever happens there is no file
2560 // preamble. We can reset the file position indicator to where the data
2561 // is (i.e. the beginning of the file).
2562 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2565 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2566 // By clean we mean that the length of the first tag is written down.
2567 // If this is the case and since the length of the first group HAS to be
2568 // four (bytes), then determining the proper swap code is straightforward.
2571 // We assume the array of char we are considering contains the binary
2572 // representation of a 32 bits integer. Hence the following dirty
2574 s32 = *((uint32_t *)(entCur));
2595 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2596 // It is time for despaired wild guesses.
2597 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2598 // i.e. the 'group length' element is not present :
2600 // check the supposed to be 'group number'
2601 // 0x0002 or 0x0004 or 0x0008
2602 // to determine ' SwapCode' value .
2603 // Only 0 or 4321 will be possible
2604 // (no oportunity to check for the formerly well known
2605 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2606 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2607 // the file IS NOT ACR-NEMA nor DICOM V3
2608 // Find a trick to tell it the caller...
2610 s16 = *((uint16_t *)(deb));
2627 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2628 "ACR/NEMA unfound swap info (Really hopeless !)");
2629 Filetype = gdcmUnknown;
2632 // Then the only info we have is the net2host one.
2642 * \brief Restore the unproperly loaded values i.e. the group, the element
2643 * and the dictionary entry depending on them.
2645 void gdcmDocument::SwitchSwapToBigEndian()
2647 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2648 "Switching to BigEndian mode.");
2649 if ( SwapCode == 0 )
2653 else if ( SwapCode == 4321 )
2657 else if ( SwapCode == 3412 )
2661 else if ( SwapCode == 2143 )
2668 * \brief during parsing, Header Elements too long are not loaded in memory
2671 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2677 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2679 MaxSizeLoadEntry = 0xffffffff;
2682 MaxSizeLoadEntry = newSize;
2687 * \brief Header Elements too long will not be printed
2688 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2691 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2693 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2698 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2700 MaxSizePrintEntry = 0xffffffff;
2703 MaxSizePrintEntry = newSize;
2709 * \brief Read the next tag but WITHOUT loading it's value
2710 * (read the 'Group Number', the 'Element Number',
2711 * gets the Dict Entry
2712 * gets the VR, gets the length, gets the offset value)
2713 * @return On succes the newly created DocEntry, NULL on failure.
2715 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2722 group = ReadInt16();
2725 catch ( gdcmFormatError e )
2727 // We reached the EOF (or an error occured) therefore
2728 // header parsing has to be considered as finished.
2733 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2734 FindDocEntryVR(newEntry);
2738 FindDocEntryLength(newEntry);
2740 catch ( gdcmFormatError e )
2748 newEntry->SetOffset(ftell(Fp));
2755 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2756 * in the TagHt dictionary.
2757 * @param group The generated tag must belong to this group.
2758 * @return The element of tag with given group which is fee.
2760 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2762 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2764 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2765 if (TagHT.count(key) == 0)
2774 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2775 * is placed at the beginning of a tag check whether this
2776 * tag is (TestGroup, TestElement).
2777 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2778 * is modified to point after the tag.
2779 * On failure (i.e. when the tag wasn't the expected tag
2780 * (TestGroup, TestElement) the internal file pointer
2781 * \ref gdcmDocument::Fp is restored to it's original position.
2782 * @param testGroup The expected group of the tag.
2783 * @param testElement The expected Element of the tag.
2784 * @return True on success, false otherwise.
2786 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2788 long positionOnEntry = ftell(Fp);
2789 long currentPosition = ftell(Fp); // On debugging purposes
2791 //// Read the Item Tag group and element, and make
2792 // sure they are what we expected:
2793 uint16_t itemTagGroup = ReadInt16();
2794 uint16_t itemTagElement = ReadInt16();
2795 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2797 std::ostringstream s;
2798 s << " We should have found tag (";
2799 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2800 s << " but instead we encountered tag (";
2801 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2803 s << " at address: " << (unsigned)currentPosition << std::endl;
2804 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2805 dbg.Verbose(0, s.str().c_str());
2806 fseek(Fp, positionOnEntry, SEEK_SET);
2814 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2815 * is placed at the beginning of a tag (TestGroup, TestElement),
2816 * read the length associated to the Tag.
2817 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2818 * is modified to point after the tag and it's length.
2819 * On failure (i.e. when the tag wasn't the expected tag
2820 * (TestGroup, TestElement) the internal file pointer
2821 * \ref gdcmDocument::Fp is restored to it's original position.
2822 * @param testGroup The expected group of the tag.
2823 * @param testElement The expected Element of the tag.
2824 * @return On success returns the length associated to the tag. On failure
2827 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2829 long positionOnEntry = ftell(Fp);
2830 (void)positionOnEntry;
2832 if ( !ReadTag(testGroup, testElement) )
2837 //// Then read the associated Item Length
2838 long currentPosition = ftell(Fp);
2839 uint32_t itemLength = ReadInt32();
2841 std::ostringstream s;
2842 s << "Basic Item Length is: "
2843 << itemLength << std::endl;
2844 s << " at address: " << (unsigned)currentPosition << std::endl;
2845 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2851 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2852 * No other way so 'skip' the Data
2855 void gdcmDocument::Parse7FE0 ()
2857 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2860 // Should warn user FIXME
2864 if ( IsImplicitVRLittleEndianTransferSyntax()
2865 || IsExplicitVRLittleEndianTransferSyntax()
2866 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2867 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2872 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2874 //// Read the Basic Offset Table Item Tag length...
2875 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2877 //// ... and then read length[s] itself[themselves]. We don't use
2878 // the values read (BTW what is the purpous of those lengths ?)
2879 if ( itemLength != 0 )
2881 // BTW, what is the purpous of those length anyhow !?
2882 char* basicOffsetTableItemValue = new char[itemLength + 1];
2883 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2885 for (unsigned int i=0; i < itemLength; i += 4 )
2887 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2888 std::ostringstream s;
2889 s << " Read one length: ";
2890 s << std::hex << individualLength << std::endl;
2891 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2893 delete[] basicOffsetTableItemValue;
2896 if ( ! IsRLELossLessTransferSyntax() )
2900 //// We then skip (not reading them) all the fragments of images:
2901 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2903 SkipBytes(itemLength);
2910 long rleSegmentLength[15], fragmentLength;
2912 // While we find some items:
2913 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2915 // Parse fragments of the current Fragment (Frame)
2916 //------------------ scanning (not reading) fragment pixels
2917 uint32_t nbRleSegments = ReadInt32();
2919 //// Reading RLE Segments Offset Table
2920 uint32_t rleSegmentOffsetTable[15];
2921 for(int k=1; k<=15; k++)
2923 ftellRes = ftell(Fp);
2924 rleSegmentOffsetTable[k] = ReadInt32();
2927 // skipping (not reading) RLE Segments
2928 if ( nbRleSegments > 1)
2930 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2932 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2933 - rleSegmentOffsetTable[k];
2934 ftellRes = ftell(Fp);
2935 SkipBytes(rleSegmentLength[k]);
2939 rleSegmentLength[nbRleSegments] = fragmentLength
2940 - rleSegmentOffsetTable[nbRleSegments];
2941 ftellRes = ftell(Fp);
2942 SkipBytes(rleSegmentLength[nbRleSegments]);
2945 // Make sure that at the end of the item we encounter a 'Sequence
2947 if ( !ReadTag(0xfffe, 0xe0dd) )
2949 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2950 dbg.Verbose(0, " at end of RLE item sequence");
2958 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2959 * \warning Does NOT work with ACR-NEMA files
2960 * \todo Find a trick to solve the pb (use RET fields ?)
2962 * @return true if 'smaller'
2964 bool gdcmDocument::operator<(gdcmDocument &document)
2967 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2968 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2980 s1 = GetEntryByNumber(0x0010,0x0020);
2981 s2 = document.GetEntryByNumber(0x0010,0x0020);
2992 // Study Instance UID
2993 s1 = GetEntryByNumber(0x0020,0x000d);
2994 s2 = document.GetEntryByNumber(0x0020,0x000d);
3005 // Serie Instance UID
3006 s1 = GetEntryByNumber(0x0020,0x000e);
3007 s2 = document.GetEntryByNumber(0x0020,0x000e);
3023 //-----------------------------------------------------------------------------