1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/15 03:50:48 $
7 Version: $Revision: 1.78 $
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
602 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
603 std::string const & value,
607 gdcmValEntry* valEntry = 0;
608 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
612 // The entry wasn't present and we simply create the required ValEntry:
613 currentEntry = NewDocEntryByNumber(group, elem);
616 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
617 " NewDocEntryByNumber failed.");
620 valEntry = new gdcmValEntry(currentEntry);
621 if ( !AddEntry(valEntry))
623 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
624 " failed allthough this is a creation.");
629 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
630 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
631 // then we change it to a ValEntry ?
632 // Shouldn't it be considered as an error ?
634 // We need to promote the gdcmDocEntry to a gdcmValEntry:
635 valEntry = new gdcmValEntry(currentEntry);
636 if (!RemoveEntry(currentEntry))
638 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
639 " of previous DocEntry failed.");
642 if ( !AddEntry(valEntry))
644 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
645 " promoted ValEntry failed.");
651 SetEntryByNumber(value, group, elem);
657 * \brief Modifies the value of a given Header Entry (Dicom Element)
658 * when it exists. Create it with the given value when unexistant.
659 * @param value (string) Value to be set
660 * @param group Group number of the Entry
661 * @param elem Element number of the Entry
662 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
663 * \return pointer to the modified/created Header Entry (NULL when creation
667 // TODO : write something clever, using default value for VR
668 // to avoid code duplication
669 // (I don't know how to tell NewDocEntryByNumber
670 // that ReplaceOrCreateByNumber was called with a default value)
672 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
673 std::string const & value,
676 std::string const & VR )
678 gdcmValEntry* valEntry = 0;
679 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
683 // check if (group,element) DictEntry exists
684 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
687 // Find out if the tag we received is in the dictionaries:
688 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
689 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
692 currentEntry = NewDocEntryByNumber(group, elem,VR);
696 currentEntry = NewDocEntryByNumber(group, elem);
701 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
702 " NewDocEntryByNumber failed.");
705 valEntry = new gdcmValEntry(currentEntry);
706 if ( !AddEntry(valEntry))
708 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
709 " failed allthough this is a creation.");
714 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
715 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
716 // then we change it to a ValEntry ?
717 // Shouldn't it be considered as an error ?
719 // We need to promote the gdcmDocEntry to a gdcmValEntry:
720 valEntry = new gdcmValEntry(currentEntry);
721 if (!RemoveEntry(currentEntry))
723 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
724 " of previous DocEntry failed.");
727 if ( !AddEntry(valEntry))
729 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
730 " promoted ValEntry failed.");
736 SetEntryByNumber(value, group, elem);
742 * \brief Modifies the value of a given Header Entry (Dicom Element)
743 * when it exists. Create it with the given value when unexistant.
744 * @param voidArea (binary) value to be set
745 * @param Group Group number of the Entry
746 * @param Elem Element number of the Entry
747 * \return pointer to the modified/created Header Entry (NULL when creation
750 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
757 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
760 a = NewBinEntryByNumber(group, elem);
766 b = new gdcmBinEntry(a);
768 b->SetVoidArea(voidArea);
771 SetEntryByNumber(voidArea, lgth, group, elem);
778 * \brief Modifies the value of a given Header Entry (Dicom Element)
779 * when it exists. Create it when unexistant.
780 * @param Group Group number of the Entry
781 * @param Elem Element number of the Entry
782 * \return pointer to the modified/created SeqEntry (NULL when creation
785 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
790 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
793 a = NewSeqEntryByNumber(group, elem);
799 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
806 * \brief Set a new value if the invoked element exists
807 * Seems to be useless !!!
808 * @param value new element value
809 * @param group group number of the Entry
810 * @param elem element number of the Entry
813 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
814 uint16_t group, uint16_t elem )
816 SetEntryByNumber(value, group, elem);
821 //-----------------------------------------------------------------------------
825 * \brief Checks if a given Dicom Element exists within the H table
826 * @param group Group number of the searched Dicom Element
827 * @param element Element number of the searched Dicom Element
828 * @return true is found
830 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
832 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
833 return TagHT.count(key);
837 * \brief Searches within Header Entries (Dicom Elements) parsed with
838 * the public and private dictionaries
839 * for the element value of a given tag.
840 * \warning Don't use any longer : use GetPubEntryByName
841 * @param tagName name of the searched element.
842 * @return Corresponding element value when it exists,
843 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
845 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
847 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
853 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
857 * \brief Searches within Header Entries (Dicom Elements) parsed with
858 * the public and private dictionaries
859 * for the element value representation of a given tag.
861 * Obtaining the VR (Value Representation) might be needed by caller
862 * to convert the string typed content to caller's native type
863 * (think of C++ vs Python). The VR is actually of a higher level
864 * of semantics than just the native C++ type.
865 * @param tagName name of the searched element.
866 * @return Corresponding element value representation when it exists,
867 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
869 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
871 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
872 if( dictEntry == NULL)
877 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
878 dictEntry->GetElement());
879 return elem->GetVR();
884 * \brief Searches within Header Entries (Dicom Elements) parsed with
885 * the public and private dictionaries
886 * for the element value representation of a given tag.
887 * @param group Group number of the searched tag.
888 * @param element Element number of the searched tag.
889 * @return Corresponding element value representation when it exists,
890 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
892 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
894 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
895 /// \todo use map methods, instead of multimap JPR
896 if ( !TagHT.count(key))
901 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
905 * \brief Searches within Header Entries (Dicom Elements) parsed with
906 * the public and private dictionaries
907 * for the element value representation of a given tag..
909 * Obtaining the VR (Value Representation) might be needed by caller
910 * to convert the string typed content to caller's native type
911 * (think of C++ vs Python). The VR is actually of a higher level
912 * of semantics than just the native C++ type.
913 * @param group Group number of the searched tag.
914 * @param element Element number of the searched tag.
915 * @return Corresponding element value representation when it exists,
916 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
918 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
920 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
925 return elem->GetVR();
929 * \brief Searches within Header Entries (Dicom Elements) parsed with
930 * the public and private dictionaries
931 * for the value length of a given tag..
932 * @param group Group number of the searched tag.
933 * @param element Element number of the searched tag.
934 * @return Corresponding element length; -2 if not found
936 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
938 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
941 return -2; //magic number
943 return elem->GetLength();
946 * \brief Sets the value (string) of the Header Entry (Dicom Element)
947 * @param content string value of the Dicom Element
948 * @param tagName name of the searched Dicom Element.
949 * @return true when found
951 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
953 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
959 return SetEntryByNumber(content,dictEntry->GetGroup(),
960 dictEntry->GetElement());
964 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
965 * through it's (group, element) and modifies it's content with
967 * @param content new value (string) to substitute with
968 * @param group group number of the Dicom Element to modify
969 * @param element element number of the Dicom Element to modify
971 bool gdcmDocument::SetEntryByNumber(std::string const & content,
978 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
981 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
982 " ValEntry (try promotion first).");
985 // Non even content must be padded with a space (020H)...
986 std::string finalContent = content;
987 if( finalContent.length() % 2 )
989 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
991 valEntry->SetValue(finalContent);
993 // Integers have a special treatement for their length:
995 l = finalContent.length();
996 if ( l != 0) // To avoid to be cheated by 'zero length' integers
998 gdcmVRKey vr = valEntry->GetVR();
999 if( vr == "US" || vr == "SS" )
1001 c = CountSubstring(content, "\\") + 1; // for multivaluated items
1004 else if( vr == "UL" || vr == "SL" )
1006 c = CountSubstring(content, "\\") + 1; // for multivaluated items
1010 valEntry->SetLength(l);
1015 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1016 * through it's (group, element) and modifies it's content with
1018 * @param content new value (void *) to substitute with
1019 * @param lgth new value length
1020 * @param group group number of the Dicom Element to modify
1021 * @param element element number of the Dicom Element to modify
1023 bool gdcmDocument::SetEntryByNumber(void *content,
1028 (void)lgth; //not used
1029 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1030 if ( !TagHT.count(key))
1035 /* Hope Binary field length is *never* wrong
1036 if(lgth%2) // Non even length are padded with a space (020H).
1039 //content = content + '\0'; // fing a trick to enlarge a binary field?
1042 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1043 a->SetVoidArea(content);
1050 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1051 * in the PubDocEntrySet of this instance
1052 * through it's (group, element) and modifies it's length with
1054 * \warning Use with extreme caution.
1055 * @param l new length to substitute with
1056 * @param group group number of the Entry to modify
1057 * @param element element number of the Entry to modify
1058 * @return true on success, false otherwise.
1060 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1064 /// \todo use map methods, instead of multimap JPR
1065 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1066 if ( !TagHT.count(key) )
1072 l++; // length must be even
1074 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1080 * \brief Gets (from Header) the offset of a 'non string' element value
1081 * (LoadElementValues has already be executed)
1082 * @param group group number of the Entry
1083 * @param elem element number of the Entry
1084 * @return File Offset of the Element Value
1086 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1088 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1091 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1094 return entry->GetOffset();
1098 * \brief Gets (from Header) a 'non string' element value
1099 * (LoadElementValues has already be executed)
1100 * @param group group number of the Entry
1101 * @param elem element number of the Entry
1102 * @return Pointer to the 'non string' area
1104 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1106 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1109 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1112 return ((gdcmBinEntry *)entry)->GetVoidArea();
1116 * \brief Loads (from disk) the element content
1117 * when a string is not suitable
1118 * @param group group number of the Entry
1119 * @param elem element number of the Entry
1121 void* gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1123 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1128 size_t o =(size_t)docElement->GetOffset();
1129 fseek(Fp, o, SEEK_SET);
1130 size_t l = docElement->GetLength();
1131 char* a = new char[l];
1134 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1137 size_t l2 = fread(a, 1, l , Fp);
1143 /// \TODO Drop any already existing void area! JPR
1144 if( !SetEntryVoidAreaByNumber( a, group, elem ) );
1146 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea setting failed.");
1152 * \brief Loads (from disk) the element content
1153 * when a string is not suitable
1154 * @param element Entry whose voidArea is going to be loaded
1156 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1158 size_t o =(size_t)element->GetOffset();
1159 fseek(Fp, o, SEEK_SET);
1160 size_t l = element->GetLength();
1161 char* a = new char[l];
1164 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1167 element->SetVoidArea((void *)a);
1168 /// \todo check the result
1169 size_t l2 = fread(a, 1, l , Fp);
1180 * \brief Sets a 'non string' value to a given Dicom Element
1181 * @param area area containing the 'non string' value
1182 * @param group Group number of the searched Dicom Element
1183 * @param element Element number of the searched Dicom Element
1186 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1190 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1191 if ( !currentEntry )
1195 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1197 binEntry->SetVoidArea( area );
1204 * \brief Update the entries with the shadow dictionary.
1205 * Only non even entries are analyzed
1207 void gdcmDocument::UpdateShaEntries()
1209 //gdcmDictEntry *entry;
1212 /// \todo TODO : still any use to explore recursively the whole structure?
1214 for(ListTag::iterator it=listEntries.begin();
1215 it!=listEntries.end();
1218 // Odd group => from public dictionary
1219 if((*it)->GetGroup()%2==0)
1222 // Peer group => search the corresponding dict entry
1224 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1228 if((*it)->IsImplicitVR())
1233 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1235 // Set the new entry and the new value
1236 (*it)->SetDictEntry(entry);
1237 CheckDocEntryVR(*it,vr);
1239 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1244 // Remove precedent value transformation
1245 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1252 * \brief Searches within the Header Entries for a Dicom Element of
1254 * @param tagName name of the searched Dicom Element.
1255 * @return Corresponding Dicom Element when it exists, and NULL
1258 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1260 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1266 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1270 * \brief retrieves a Dicom Element (the first one) using (group, element)
1271 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1272 * if you think it's NOT UNIQUE, check the count number
1273 * and use iterators to retrieve ALL the Dicoms Elements within
1274 * a given couple (group, element)
1275 * @param group Group number of the searched Dicom Element
1276 * @param element Element number of the searched Dicom Element
1279 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1282 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1283 if ( !TagHT.count(key))
1287 return TagHT.find(key)->second;
1291 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1292 * returns a result when the corresponding entry is of type
1294 * @return When present, the corresponding ValEntry.
1296 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1299 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1300 if ( !currentEntry )
1304 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1308 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1314 * \brief Loads the element while preserving the current
1315 * underlying file position indicator as opposed to
1316 * to LoadDocEntry that modifies it.
1317 * @param entry Header Entry whose value shall be loaded.
1320 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1322 long PositionOnEntry = ftell(Fp);
1323 LoadDocEntry(entry);
1324 fseek(Fp, PositionOnEntry, SEEK_SET);
1328 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1330 * @return The properly swaped 32 bits integer.
1332 uint32_t gdcmDocument::SwapLong(uint32_t a)
1339 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1340 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1344 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1348 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1351 //std::cout << "swapCode= " << SwapCode << std::endl;
1352 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1359 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1361 * @return The properly unswaped 32 bits integer.
1363 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1369 * \brief Swaps the bytes so they agree with the processor order
1370 * @return The properly swaped 16 bits integer.
1372 uint16_t gdcmDocument::SwapShort(uint16_t a)
1374 if ( SwapCode == 4321 || SwapCode == 2143 )
1376 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1382 * \brief Unswaps the bytes so they agree with the processor order
1383 * @return The properly unswaped 16 bits integer.
1385 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1387 return SwapShort(a);
1390 //-----------------------------------------------------------------------------
1394 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1395 * @return length of the parsed set.
1398 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1403 gdcmDocEntry *newDocEntry = 0;
1404 unsigned long l = 0;
1406 int depth = set->GetDepthLevel();
1409 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1413 newDocEntry = ReadNextDocEntry( );
1419 gdcmVRKey vr = newDocEntry->GetVR();
1423 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1426 gdcmValEntry* newValEntry =
1427 new gdcmValEntry( newDocEntry->GetDictEntry() );
1428 newValEntry->Copy( newDocEntry );
1429 newValEntry->SetKey( set->GetBaseTagKey() + newValEntry->GetKey() );
1430 set->AddEntry( newValEntry );
1431 LoadDocEntry( newValEntry );
1432 if (newValEntry->IsItemDelimitor())
1436 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1443 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1445 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1446 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1447 "nor BinEntry. Probably unknown VR.");
1450 ////// BinEntry or UNKOWN VR:
1451 gdcmBinEntry* newBinEntry =
1452 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1453 newBinEntry->Copy( newDocEntry );
1454 newBinEntry->SetKey( set->GetBaseTagKey() + newBinEntry->GetKey() );
1455 set->AddEntry( newBinEntry );
1456 LoadDocEntry( newBinEntry );
1459 if (newDocEntry->GetGroup() == 0x7fe0 &&
1460 newDocEntry->GetElement() == 0x0010 )
1462 if (newDocEntry->GetReadLength()==0xffffffff)
1464 // Broken US.3405.1.dcm
1465 Parse7FE0(); // to skip the pixels
1466 // (multipart JPEG/RLE are trouble makers)
1470 SkipToNextDocEntry(newDocEntry);
1471 l = newDocEntry->GetFullLength();
1476 // to be sure we are at the beginning
1477 SkipToNextDocEntry(newDocEntry);
1478 l = newDocEntry->GetFullLength();
1484 l = newDocEntry->GetReadLength();
1485 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1487 if ( l == 0xffffffff )
1496 // no other way to create it ...
1497 gdcmSeqEntry* newSeqEntry =
1498 new gdcmSeqEntry( newDocEntry->GetDictEntry(),
1499 set->GetDepthLevel() );
1500 newSeqEntry->Copy( newDocEntry );
1501 newSeqEntry->SetDelimitorMode( delim_mode );
1502 newSeqEntry->SetDepthLevel( depth );
1503 newSeqEntry->SetKey( set->GetBaseTagKey() + newSeqEntry->GetKey() );
1506 { // Don't try to parse zero-length sequences
1507 (void)ParseSQ( newSeqEntry,
1508 newDocEntry->GetOffset(),
1511 set->AddEntry( newSeqEntry );
1512 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1519 return l; // Probably useless
1523 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1524 * @return parsed length for this level
1526 long gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1527 long offset, long l_max, bool delim_mode)
1529 int SQItemNumber = 0;
1534 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1537 // FIXME Should warn user
1542 if ( newDocEntry->IsSequenceDelimitor() )
1544 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1548 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1553 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1554 std::ostringstream newBase;
1555 newBase << seqEntry->GetKey()
1559 itemSQ->SetBaseTagKey( newBase.str() );
1560 unsigned int l = newDocEntry->GetReadLength();
1562 if ( l == 0xffffffff )
1571 (void)ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1573 seqEntry->AddEntry( itemSQ, SQItemNumber );
1575 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1581 int lgth = ftell(Fp) - offset;
1586 * \brief Loads the element content if its length doesn't exceed
1587 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1588 * @param entry Header Entry (Dicom Element) to be dealt with
1590 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1593 uint16_t group = entry->GetGroup();
1594 std::string vr = entry->GetVR();
1595 uint32_t length = entry->GetLength();
1597 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1599 // A SeQuence "contains" a set of Elements.
1600 // (fffe e000) tells us an Element is beginning
1601 // (fffe e00d) tells us an Element just ended
1602 // (fffe e0dd) tells us the current SeQuence just ended
1603 if( group == 0xfffe )
1605 // NO more value field for SQ !
1609 // When the length is zero things are easy:
1612 ((gdcmValEntry *)entry)->SetValue("");
1616 // The elements whose length is bigger than the specified upper bound
1617 // are not loaded. Instead we leave a short notice of the offset of
1618 // the element content and it's length.
1620 std::ostringstream s;
1621 if (length > MaxSizeLoadEntry)
1623 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1625 //s << "gdcm::NotLoaded (BinEntry)";
1626 s << GDCM_NOTLOADED;
1627 s << " Address:" << (long)entry->GetOffset();
1628 s << " Length:" << entry->GetLength();
1629 s << " x(" << std::hex << entry->GetLength() << ")";
1630 binEntryPtr->SetValue(s.str());
1632 // Be carefull : a BinEntry IS_A ValEntry ...
1633 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1635 // s << "gdcm::NotLoaded. (ValEntry)";
1636 s << GDCM_NOTLOADED;
1637 s << " Address:" << (long)entry->GetOffset();
1638 s << " Length:" << entry->GetLength();
1639 s << " x(" << std::hex << entry->GetLength() << ")";
1640 valEntryPtr->SetValue(s.str());
1645 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1646 << "nor a ValEntry ?! Should never print that !" << std::endl;
1649 // to be sure we are at the end of the value ...
1650 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1654 // When we find a BinEntry not very much can be done :
1655 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1657 s << "gdcm::Loaded (BinEntry)";
1658 binEntryPtr->SetValue(s.str());
1659 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1663 /// \todo Any compacter code suggested (?)
1664 if ( IsDocEntryAnInteger(entry) )
1668 // When short integer(s) are expected, read and convert the following
1669 // n *two characters properly i.e. consider them as short integers as
1670 // opposed to strings.
1671 // Elements with Value Multiplicity > 1
1672 // contain a set of integers (not a single one)
1673 if (vr == "US" || vr == "SS")
1676 NewInt = ReadInt16();
1680 for (int i=1; i < nbInt; i++)
1683 NewInt = ReadInt16();
1688 // See above comment on multiple integers (mutatis mutandis).
1689 else if (vr == "UL" || vr == "SL")
1692 NewInt = ReadInt32();
1696 for (int i=1; i < nbInt; i++)
1699 NewInt = ReadInt32();
1704 #ifdef GDCM_NO_ANSI_STRING_STREAM
1705 s << std::ends; // to avoid oddities on Solaris
1706 #endif //GDCM_NO_ANSI_STRING_STREAM
1708 ((gdcmValEntry *)entry)->SetValue(s.str());
1712 // We need an additional byte for storing \0 that is not on disk
1713 //std::string newValue(length,0);
1714 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1715 //rah !! I can't believe it could work, normally this is a const char* !!!
1716 char *str = new char[length+1];
1717 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1719 std::string newValue = str;
1721 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1723 if ( item_read != 1 )
1725 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1726 "unread element value");
1727 valEntry->SetValue(GDCM_UNREAD);
1733 // Because of correspondance with the VR dic
1734 valEntry->SetValue(newValue);
1738 valEntry->SetValue(newValue);
1743 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1744 "Should have a ValEntry, here !");
1750 * \brief Find the value Length of the passed Header Entry
1751 * @param entry Header Entry whose length of the value shall be loaded.
1753 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1754 throw ( gdcmFormatError )
1756 uint16_t element = entry->GetElement();
1757 std::string vr = entry->GetVR();
1760 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1762 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1764 // The following reserved two bytes (see PS 3.5-2001, section
1765 // 7.1.2 Data element structure with explicit vr p27) must be
1766 // skipped before proceeding on reading the length on 4 bytes.
1767 fseek(Fp, 2L, SEEK_CUR);
1768 uint32_t length32 = ReadInt32();
1770 if ( vr == "OB" && length32 == 0xffffffff )
1775 lengthOB = FindDocEntryLengthOB();
1777 catch ( gdcmFormatUnexpected )
1779 // Computing the length failed (this happens with broken
1780 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1781 // chance to get the pixels by deciding the element goes
1782 // until the end of the file. Hence we artificially fix the
1783 // the length and proceed.
1784 long currentPosition = ftell(Fp);
1785 fseek(Fp,0L,SEEK_END);
1786 long lengthUntilEOF = ftell(Fp) - currentPosition;
1787 fseek(Fp, currentPosition, SEEK_SET);
1788 entry->SetLength(lengthUntilEOF);
1791 entry->SetLength(lengthOB);
1794 FixDocEntryFoundLength(entry, length32);
1798 // Length is encoded on 2 bytes.
1799 length16 = ReadInt16();
1801 // We can tell the current file is encoded in big endian (like
1802 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1803 // and it's value is the one of the encoding of a big endian file.
1804 // In order to deal with such big endian encoded files, we have
1805 // (at least) two strategies:
1806 // * when we load the "Transfer Syntax" tag with value of big endian
1807 // encoding, we raise the proper flags. Then we wait for the end
1808 // of the META group (0x0002) among which is "Transfer Syntax",
1809 // before switching the swap code to big endian. We have to postpone
1810 // the switching of the swap code since the META group is fully encoded
1811 // in little endian, and big endian coding only starts at the next
1812 // group. The corresponding code can be hard to analyse and adds
1813 // many additional unnecessary tests for regular tags.
1814 // * the second strategy consists in waiting for trouble, that shall
1815 // appear when we find the first group with big endian encoding. This
1816 // is easy to detect since the length of a "Group Length" tag (the
1817 // ones with zero as element number) has to be of 4 (0x0004). When we
1818 // encounter 1024 (0x0400) chances are the encoding changed and we
1819 // found a group with big endian encoding.
1820 // We shall use this second strategy. In order to make sure that we
1821 // can interpret the presence of an apparently big endian encoded
1822 // length of a "Group Length" without committing a big mistake, we
1823 // add an additional check: we look in the already parsed elements
1824 // for the presence of a "Transfer Syntax" whose value has to be "big
1825 // endian encoding". When this is the case, chances are we have got our
1826 // hands on a big endian encoded file: we switch the swap code to
1827 // big endian and proceed...
1828 if ( element == 0x0000 && length16 == 0x0400 )
1830 if ( !IsExplicitVRBigEndianTransferSyntax() )
1832 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1833 " not explicit VR." );
1837 SwitchSwapToBigEndian();
1838 // Restore the unproperly loaded values i.e. the group, the element
1839 // and the dictionary entry depending on them.
1840 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1841 uint16_t correctElem = SwapShort( entry->GetElement() );
1842 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1846 // This correct tag is not in the dictionary. Create a new one.
1847 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1849 // FIXME this can create a memory leaks on the old entry that be
1850 // left unreferenced.
1851 entry->SetDictEntry( newTag );
1854 // Heuristic: well, some files are really ill-formed.
1855 if ( length16 == 0xffff)
1857 // 0xffff means that we deal with 'Unknown Length' Sequence
1860 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1865 // Either implicit VR or a non DICOM conformal (see note below) explicit
1866 // VR that ommited the VR of (at least) this element. Farts happen.
1867 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1868 // on Data elements "Implicit and Explicit VR Data Elements shall
1869 // not coexist in a Data Set and Data Sets nested within it".]
1870 // Length is on 4 bytes.
1872 FixDocEntryFoundLength( entry, ReadInt32() );
1878 * \brief Find the Value Representation of the current Dicom Element.
1881 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1883 if ( Filetype != gdcmExplicitVR )
1890 long positionOnEntry = ftell(Fp);
1891 // Warning: we believe this is explicit VR (Value Representation) because
1892 // we used a heuristic that found "UL" in the first tag. Alas this
1893 // doesn't guarantee that all the tags will be in explicit VR. In some
1894 // cases (see e-film filtered files) one finds implicit VR tags mixed
1895 // within an explicit VR file. Hence we make sure the present tag
1896 // is in explicit VR and try to fix things if it happens not to be
1899 fread (vr, (size_t)2,(size_t)1, Fp);
1902 if( !CheckDocEntryVR(entry, vr) )
1904 fseek(Fp, positionOnEntry, SEEK_SET);
1905 // When this element is known in the dictionary we shall use, e.g. for
1906 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1907 // dictionary entry. Still we have to flag the element as implicit since
1908 // we know now our assumption on expliciteness is not furfilled.
1910 if ( entry->IsVRUnknown() )
1912 entry->SetVR("Implicit");
1914 entry->SetImplicitVR();
1919 * \brief Check the correspondance between the VR of the header entry
1920 * and the taken VR. If they are different, the header entry is
1921 * updated with the new VR.
1922 * @param entry Header Entry to check
1923 * @param vr Dicom Value Representation
1924 * @return false if the VR is incorrect of if the VR isn't referenced
1925 * otherwise, it returns true
1927 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1929 char msg[100]; // for sprintf
1930 bool realExplicit = true;
1932 // Assume we are reading a falsely explicit VR file i.e. we reached
1933 // a tag where we expect reading a VR but are in fact we read the
1934 // first to bytes of the length. Then we will interogate (through find)
1935 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1936 // both GCC and VC++ implementations of the STL map. Hence when the
1937 // expected VR read happens to be non-ascii characters we consider
1938 // we hit falsely explicit VR tag.
1940 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1942 realExplicit = false;
1945 // CLEANME searching the dicom_vr at each occurence is expensive.
1946 // PostPone this test in an optional integrity check at the end
1947 // of parsing or only in debug mode.
1948 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1950 realExplicit = false;
1953 if ( !realExplicit )
1955 // We thought this was explicit VR, but we end up with an
1956 // implicit VR tag. Let's backtrack.
1957 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1958 entry->GetGroup(), entry->GetElement());
1959 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1961 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1963 // Group length is UL !
1964 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1965 entry->GetGroup(), entry->GetElement(),
1966 "UL", "FIXME", "Group Length");
1967 entry->SetDictEntry( newEntry );
1972 if ( entry->IsVRUnknown() )
1974 // When not a dictionary entry, we can safely overwrite the VR.
1975 if( entry->GetElement() == 0x0000 )
1977 // Group length is UL !
1985 else if ( entry->GetVR() != vr )
1987 // The VR present in the file and the dictionary disagree. We assume
1988 // the file writer knew best and use the VR of the file. Since it would
1989 // be unwise to overwrite the VR of a dictionary (since it would
1990 // compromise it's next user), we need to clone the actual DictEntry
1991 // and change the VR for the read one.
1992 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1993 entry->GetGroup(), entry->GetElement(),
1994 vr, "FIXME", entry->GetName());
1995 entry->SetDictEntry(newEntry);
2002 * \brief Get the transformed value of the header entry. The VR value
2003 * is used to define the transformation to operate on the value
2004 * \warning NOT end user intended method !
2005 * @param entry entry to tranform
2006 * @return Transformed entry value
2008 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2010 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2012 std::string val = ((gdcmValEntry *)entry)->GetValue();
2013 std::string vr = entry->GetVR();
2014 uint32_t length = entry->GetLength();
2015 std::ostringstream s;
2018 // When short integer(s) are expected, read and convert the following
2019 // n * 2 bytes properly i.e. as a multivaluated strings
2020 // (each single value is separated fromthe next one by '\'
2021 // as usual for standard multivaluated filels
2022 // Elements with Value Multiplicity > 1
2023 // contain a set of short integers (not a single one)
2025 if( vr == "US" || vr == "SS" )
2030 for (int i=0; i < nbInt; i++)
2036 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2037 newInt16 = SwapShort( newInt16 );
2042 // When integer(s) are expected, read and convert the following
2043 // n * 4 bytes properly i.e. as a multivaluated strings
2044 // (each single value is separated fromthe next one by '\'
2045 // as usual for standard multivaluated filels
2046 // Elements with Value Multiplicity > 1
2047 // contain a set of integers (not a single one)
2048 else if( vr == "UL" || vr == "SL" )
2053 for (int i=0; i < nbInt; i++)
2059 newInt32 = ( val[4*i+0] & 0xFF )
2060 + (( val[4*i+1] & 0xFF ) << 8 )
2061 + (( val[4*i+2] & 0xFF ) << 16 )
2062 + (( val[4*i+3] & 0xFF ) << 24 );
2063 newInt32 = SwapLong( newInt32 );
2067 #ifdef GDCM_NO_ANSI_STRING_STREAM
2068 s << std::ends; // to avoid oddities on Solaris
2069 #endif //GDCM_NO_ANSI_STRING_STREAM
2073 return ((gdcmValEntry *)entry)->GetValue();
2077 * \brief Get the reverse transformed value of the header entry. The VR
2078 * value is used to define the reverse transformation to operate on
2080 * \warning NOT end user intended method !
2081 * @param entry Entry to reverse transform
2082 * @return Reverse transformed entry value
2084 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2086 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2088 std::string vr = entry->GetVR();
2089 std::vector<std::string> tokens;
2090 std::ostringstream s;
2092 if ( vr == "US" || vr == "SS" )
2096 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2097 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2098 for (unsigned int i=0; i<tokens.size(); i++)
2100 newInt16 = atoi(tokens[i].c_str());
2101 s << ( newInt16 & 0xFF )
2102 << (( newInt16 >> 8 ) & 0xFF );
2106 if ( vr == "UL" || vr == "SL")
2110 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2111 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2112 for (unsigned int i=0; i<tokens.size();i++)
2114 newInt32 = atoi(tokens[i].c_str());
2115 s << (char)( newInt32 & 0xFF )
2116 << (char)(( newInt32 >> 8 ) & 0xFF )
2117 << (char)(( newInt32 >> 16 ) & 0xFF )
2118 << (char)(( newInt32 >> 24 ) & 0xFF );
2123 #ifdef GDCM_NO_ANSI_STRING_STREAM
2124 s << std::ends; // to avoid oddities on Solaris
2125 #endif //GDCM_NO_ANSI_STRING_STREAM
2129 return ((gdcmValEntry *)entry)->GetValue();
2133 * \brief Skip a given Header Entry
2134 * \warning NOT end user intended method !
2135 * @param entry entry to skip
2137 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2139 SkipBytes(entry->GetLength());
2143 * \brief Skips to the begining of the next Header Entry
2144 * \warning NOT end user intended method !
2145 * @param entry entry to skip
2147 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2149 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2150 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2154 * \brief When the length of an element value is obviously wrong (because
2155 * the parser went Jabberwocky) one can hope improving things by
2156 * applying some heuristics.
2157 * @param entry entry to check
2158 * @param foundLength fist assumption about length
2160 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2161 uint32_t foundLength)
2163 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2164 if ( foundLength == 0xffffffff)
2169 uint16_t gr = entry->GetGroup();
2170 uint16_t el = entry->GetElement();
2172 if ( foundLength % 2)
2174 std::ostringstream s;
2175 s << "Warning : Tag with uneven length "
2177 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2178 dbg.Verbose(0, s.str().c_str());
2181 //////// Fix for some naughty General Electric images.
2182 // Allthough not recent many such GE corrupted images are still present
2183 // on Creatis hard disks. Hence this fix shall remain when such images
2184 // are no longer in user (we are talking a few years, here)...
2185 // Note: XMedCom probably uses such a trick since it is able to read
2186 // those pesky GE images ...
2187 if ( foundLength == 13)
2189 // Only happens for this length !
2190 if ( entry->GetGroup() != 0x0008
2191 || ( entry->GetElement() != 0x0070
2192 && entry->GetElement() != 0x0080 ) )
2195 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2199 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2200 // Occurence of such images is quite low (unless one leaves close to a
2201 // 'Leonardo' source. Hence, one might consider commenting out the
2202 // following fix on efficiency reasons.
2203 else if ( entry->GetGroup() == 0x0009
2204 && ( entry->GetElement() == 0x1113
2205 || entry->GetElement() == 0x1114 ) )
2208 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2211 else if ( entry->GetVR() == "SQ" )
2213 foundLength = 0; // ReadLength is unchanged
2216 //////// We encountered a 'delimiter' element i.e. a tag of the form
2217 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2218 // taken into account.
2219 else if( entry->GetGroup() == 0xfffe )
2221 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2222 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2223 // causes extra troubles...
2224 if( entry->GetElement() != 0x0000 )
2230 entry->SetUsableLength(foundLength);
2234 * \brief Apply some heuristics to predict whether the considered
2235 * element value contains/represents an integer or not.
2236 * @param entry The element value on which to apply the predicate.
2237 * @return The result of the heuristical predicate.
2239 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2241 uint16_t element = entry->GetElement();
2242 uint16_t group = entry->GetGroup();
2243 std::string vr = entry->GetVR();
2244 uint32_t length = entry->GetLength();
2246 // When we have some semantics on the element we just read, and if we
2247 // a priori know we are dealing with an integer, then we shall be
2248 // able to swap it's element value properly.
2249 if ( element == 0 ) // This is the group length of the group
2257 // Allthough this should never happen, still some images have a
2258 // corrupted group length [e.g. have a glance at offset x(8336) of
2259 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2260 // Since for dicom compliant and well behaved headers, the present
2261 // test is useless (and might even look a bit paranoid), when we
2262 // encounter such an ill-formed image, we simply display a warning
2263 // message and proceed on parsing (while crossing fingers).
2264 std::ostringstream s;
2265 int filePosition = ftell(Fp);
2266 s << "Erroneous Group Length element length on : (" \
2267 << std::hex << group << " , " << element
2268 << ") -before- position x(" << filePosition << ")"
2269 << "lgt : " << length;
2270 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2274 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2283 * \brief Find the Length till the next sequence delimiter
2284 * \warning NOT end user intended method !
2288 uint32_t gdcmDocument::FindDocEntryLengthOB()
2289 throw( gdcmFormatUnexpected )
2291 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2292 long positionOnEntry = ftell(Fp);
2293 bool foundSequenceDelimiter = false;
2294 uint32_t totalLength = 0;
2296 while ( !foundSequenceDelimiter )
2302 group = ReadInt16();
2305 catch ( gdcmFormatError )
2307 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2308 " group or element not present.");
2311 // We have to decount the group and element we just read
2314 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2316 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2317 "tag nor a Sequence delimiter tag.");
2318 fseek(Fp, positionOnEntry, SEEK_SET);
2319 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2320 "Neither an Item tag nor a Sequence "
2324 if ( elem == 0xe0dd )
2326 foundSequenceDelimiter = true;
2329 uint32_t itemLength = ReadInt32();
2330 // We add 4 bytes since we just read the ItemLength with ReadInt32
2331 totalLength += itemLength + 4;
2332 SkipBytes(itemLength);
2334 if ( foundSequenceDelimiter )
2339 fseek(Fp, positionOnEntry, SEEK_SET);
2344 * \brief Reads a supposed to be 16 Bits integer
2345 * (swaps it depending on processor endianity)
2346 * @return read value
2348 uint16_t gdcmDocument::ReadInt16()
2349 throw( gdcmFormatError )
2352 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2353 if ( item_read != 1 )
2357 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2359 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2366 * \brief Reads a supposed to be 32 Bits integer
2367 * (swaps it depending on processor endianity)
2368 * @return read value
2370 uint32_t gdcmDocument::ReadInt32()
2371 throw( gdcmFormatError )
2374 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2375 if ( item_read != 1 )
2379 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2381 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2388 * \brief skips bytes inside the source file
2389 * \warning NOT end user intended method !
2392 void gdcmDocument::SkipBytes(uint32_t nBytes)
2394 //FIXME don't dump the returned value
2395 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2399 * \brief Loads all the needed Dictionaries
2400 * \warning NOT end user intended method !
2402 void gdcmDocument::Initialise()
2404 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2409 * \brief Discover what the swap code is (among little endian, big endian,
2410 * bad little endian, bad big endian).
2412 * @return false when we are absolutely sure
2413 * it's neither ACR-NEMA nor DICOM
2414 * true when we hope ours assuptions are OK
2416 bool gdcmDocument::CheckSwap()
2418 // The only guaranted way of finding the swap code is to find a
2419 // group tag since we know it's length has to be of four bytes i.e.
2420 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2421 // occurs when we can't find such group...
2423 uint32_t x = 4; // x : for ntohs
2424 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2428 char deb[HEADER_LENGTH_TO_READ];
2430 // First, compare HostByteOrder and NetworkByteOrder in order to
2431 // determine if we shall need to swap bytes (i.e. the Endian type).
2432 if ( x == ntohs(x) )
2441 // The easiest case is the one of a DICOM header, since it possesses a
2442 // file preamble where it suffice to look for the string "DICM".
2443 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2444 (void)lgrLue; //FIXME not used
2446 char *entCur = deb + 128;
2447 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2449 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2451 // Next, determine the value representation (VR). Let's skip to the
2452 // first element (0002, 0000) and check there if we find "UL"
2453 // - or "OB" if the 1st one is (0002,0001) -,
2454 // in which case we (almost) know it is explicit VR.
2455 // WARNING: if it happens to be implicit VR then what we will read
2456 // is the length of the group. If this ascii representation of this
2457 // length happens to be "UL" then we shall believe it is explicit VR.
2458 // FIXME: in order to fix the above warning, we could read the next
2459 // element value (or a couple of elements values) in order to make
2460 // sure we are not commiting a big mistake.
2461 // We need to skip :
2462 // * the 128 bytes of File Preamble (often padded with zeroes),
2463 // * the 4 bytes of "DICM" string,
2464 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2465 // i.e. a total of 136 bytes.
2469 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2470 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2471 // *Implicit* VR. -and it is !-
2473 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2474 memcmp(entCur, "OB", (size_t)2) == 0 ||
2475 memcmp(entCur, "UI", (size_t)2) == 0 ||
2476 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2477 // when Write DCM *adds*
2479 // Use gdcmDocument::dicom_vr to test all the possibilities
2480 // instead of just checking for UL, OB and UI !? group 0000
2482 Filetype = gdcmExplicitVR;
2483 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2484 "explicit Value Representation");
2488 Filetype = gdcmImplicitVR;
2489 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2490 "not an explicit Value Representation");
2496 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2497 "HostByteOrder != NetworkByteOrder");
2502 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2503 "HostByteOrder = NetworkByteOrder");
2506 // Position the file position indicator at first tag (i.e.
2507 // after the file preamble and the "DICM" string).
2509 fseek (Fp, 132L, SEEK_SET);
2513 // Alas, this is not a DicomV3 file and whatever happens there is no file
2514 // preamble. We can reset the file position indicator to where the data
2515 // is (i.e. the beginning of the file).
2516 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2519 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2520 // By clean we mean that the length of the first tag is written down.
2521 // If this is the case and since the length of the first group HAS to be
2522 // four (bytes), then determining the proper swap code is straightforward.
2525 // We assume the array of char we are considering contains the binary
2526 // representation of a 32 bits integer. Hence the following dirty
2528 s32 = *((uint32_t *)(entCur));
2549 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2550 // It is time for despaired wild guesses.
2551 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2552 // i.e. the 'group length' element is not present :
2554 // check the supposed to be 'group number'
2555 // 0x0002 or 0x0004 or 0x0008
2556 // to determine ' SwapCode' value .
2557 // Only 0 or 4321 will be possible
2558 // (no oportunity to check for the formerly well known
2559 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2560 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2561 // the file IS NOT ACR-NEMA nor DICOM V3
2562 // Find a trick to tell it the caller...
2564 s16 = *((uint16_t *)(deb));
2581 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2582 "ACR/NEMA unfound swap info (Really hopeless !)");
2583 Filetype = gdcmUnknown;
2586 // Then the only info we have is the net2host one.
2596 * \brief Restore the unproperly loaded values i.e. the group, the element
2597 * and the dictionary entry depending on them.
2599 void gdcmDocument::SwitchSwapToBigEndian()
2601 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2602 "Switching to BigEndian mode.");
2603 if ( SwapCode == 0 )
2607 else if ( SwapCode == 4321 )
2611 else if ( SwapCode == 3412 )
2615 else if ( SwapCode == 2143 )
2622 * \brief during parsing, Header Elements too long are not loaded in memory
2625 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2631 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2633 MaxSizeLoadEntry = 0xffffffff;
2636 MaxSizeLoadEntry = newSize;
2641 * \brief Header Elements too long will not be printed
2642 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2645 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2647 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2652 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2654 MaxSizePrintEntry = 0xffffffff;
2657 MaxSizePrintEntry = newSize;
2663 * \brief Read the next tag but WITHOUT loading it's value
2664 * (read the 'Group Number', the 'Element Number',
2665 * gets the Dict Entry
2666 * gets the VR, gets the length, gets the offset value)
2667 * @return On succes the newly created DocEntry, NULL on failure.
2669 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2676 group = ReadInt16();
2679 catch ( gdcmFormatError e )
2681 // We reached the EOF (or an error occured) therefore
2682 // header parsing has to be considered as finished.
2687 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2688 FindDocEntryVR(newEntry);
2692 FindDocEntryLength(newEntry);
2694 catch ( gdcmFormatError e )
2702 newEntry->SetOffset(ftell(Fp));
2709 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2710 * in the TagHt dictionary.
2711 * @param group The generated tag must belong to this group.
2712 * @return The element of tag with given group which is fee.
2714 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2716 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2718 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2719 if (TagHT.count(key) == 0)
2728 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2729 * is placed at the beginning of a tag check whether this
2730 * tag is (TestGroup, TestElement).
2731 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2732 * is modified to point after the tag.
2733 * On failure (i.e. when the tag wasn't the expected tag
2734 * (TestGroup, TestElement) the internal file pointer
2735 * \ref gdcmDocument::Fp is restored to it's original position.
2736 * @param testGroup The expected group of the tag.
2737 * @param testElement The expected Element of the tag.
2738 * @return True on success, false otherwise.
2740 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2742 long positionOnEntry = ftell(Fp);
2743 long currentPosition = ftell(Fp); // On debugging purposes
2745 //// Read the Item Tag group and element, and make
2746 // sure they are what we expected:
2747 uint16_t itemTagGroup = ReadInt16();
2748 uint16_t itemTagElement = ReadInt16();
2749 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2751 std::ostringstream s;
2752 s << " We should have found tag (";
2753 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2754 s << " but instead we encountered tag (";
2755 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2757 s << " at address: " << (unsigned)currentPosition << std::endl;
2758 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2759 dbg.Verbose(0, s.str().c_str());
2760 fseek(Fp, positionOnEntry, SEEK_SET);
2768 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2769 * is placed at the beginning of a tag (TestGroup, TestElement),
2770 * read the length associated to the Tag.
2771 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2772 * is modified to point after the tag and it's length.
2773 * On failure (i.e. when the tag wasn't the expected tag
2774 * (TestGroup, TestElement) the internal file pointer
2775 * \ref gdcmDocument::Fp is restored to it's original position.
2776 * @param testGroup The expected group of the tag.
2777 * @param testElement The expected Element of the tag.
2778 * @return On success returns the length associated to the tag. On failure
2781 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2783 long positionOnEntry = ftell(Fp);
2784 (void)positionOnEntry;
2786 if ( !ReadTag(testGroup, testElement) )
2791 //// Then read the associated Item Length
2792 long currentPosition = ftell(Fp);
2793 uint32_t itemLength = ReadInt32();
2795 std::ostringstream s;
2796 s << "Basic Item Length is: "
2797 << itemLength << std::endl;
2798 s << " at address: " << (unsigned)currentPosition << std::endl;
2799 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2805 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2806 * No other way so 'skip' the Data
2809 void gdcmDocument::Parse7FE0 ()
2811 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2814 // Should warn user FIXME
2818 if ( IsImplicitVRLittleEndianTransferSyntax()
2819 || IsExplicitVRLittleEndianTransferSyntax()
2820 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2821 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2826 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2828 //// Read the Basic Offset Table Item Tag length...
2829 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2831 //// ... and then read length[s] itself[themselves]. We don't use
2832 // the values read (BTW what is the purpous of those lengths ?)
2833 if ( itemLength != 0 )
2835 // BTW, what is the purpous of those length anyhow !?
2836 char* basicOffsetTableItemValue = new char[itemLength + 1];
2837 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2839 for (unsigned int i=0; i < itemLength; i += 4 )
2841 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2842 std::ostringstream s;
2843 s << " Read one length: ";
2844 s << std::hex << individualLength << std::endl;
2845 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2847 delete[] basicOffsetTableItemValue;
2850 if ( ! IsRLELossLessTransferSyntax() )
2854 //// We then skip (not reading them) all the fragments of images:
2855 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2857 SkipBytes(itemLength);
2864 long rleSegmentLength[15], fragmentLength;
2866 // While we find some items:
2867 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2869 // Parse fragments of the current Fragment (Frame)
2870 //------------------ scanning (not reading) fragment pixels
2871 uint32_t nbRleSegments = ReadInt32();
2873 //// Reading RLE Segments Offset Table
2874 uint32_t rleSegmentOffsetTable[15];
2875 for(int k=1; k<=15; k++)
2877 ftellRes = ftell(Fp);
2878 rleSegmentOffsetTable[k] = ReadInt32();
2881 // skipping (not reading) RLE Segments
2882 if ( nbRleSegments > 1)
2884 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2886 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2887 - rleSegmentOffsetTable[k];
2888 ftellRes = ftell(Fp);
2889 SkipBytes(rleSegmentLength[k]);
2893 rleSegmentLength[nbRleSegments] = fragmentLength
2894 - rleSegmentOffsetTable[nbRleSegments];
2895 ftellRes = ftell(Fp);
2896 SkipBytes(rleSegmentLength[nbRleSegments]);
2899 // Make sure that at the end of the item we encounter a 'Sequence
2901 if ( !ReadTag(0xfffe, 0xe0dd) )
2903 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2904 dbg.Verbose(0, " at end of RLE item sequence");
2912 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2913 * \warning Does NOT work with ACR-NEMA files
2914 * \todo Find a trick to solve the pb (use RET fields ?)
2916 * @return true if 'smaller'
2918 bool gdcmDocument::operator<(gdcmDocument &document)
2921 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2922 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2934 s1 = GetEntryByNumber(0x0010,0x0020);
2935 s2 = document.GetEntryByNumber(0x0010,0x0020);
2946 // Study Instance UID
2947 s1 = GetEntryByNumber(0x0020,0x000d);
2948 s2 = document.GetEntryByNumber(0x0020,0x000d);
2959 // Serie Instance UID
2960 s1 = GetEntryByNumber(0x0020,0x000e);
2961 s2 = document.GetEntryByNumber(0x0020,0x000e);
2977 //-----------------------------------------------------------------------------