1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/13 12:10:53 $
7 Version: $Revision: 1.76 $
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 )
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 voidArea (binary) value to be set
660 * @param Group Group number of the Entry
661 * @param Elem Element number of the Entry
662 * \return pointer to the modified/created Header Entry (NULL when creation
665 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
672 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
675 a = NewBinEntryByNumber(group, elem);
681 b = new gdcmBinEntry(a);
683 b->SetVoidArea(voidArea);
686 SetEntryByNumber(voidArea, lgth, group, elem);
687 //b->SetVoidArea(voidArea); //what if b == 0 !!
694 * \brief Modifies the value of a given Header Entry (Dicom Element)
695 * when it exists. Create it when unexistant.
696 * @param Group Group number of the Entry
697 * @param Elem Element number of the Entry
698 * \return pointer to the modified/created SeqEntry (NULL when creation
701 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
706 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
709 a = NewSeqEntryByNumber(group, elem);
715 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
722 * \brief Set a new value if the invoked element exists
723 * Seems to be useless !!!
724 * @param value new element value
725 * @param group group number of the Entry
726 * @param elem element number of the Entry
729 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
730 uint16_t group, uint16_t elem )
732 SetEntryByNumber(value, group, elem);
737 //-----------------------------------------------------------------------------
741 * \brief Checks if a given Dicom Element exists within the H table
742 * @param group Group number of the searched Dicom Element
743 * @param element Element number of the searched Dicom Element
744 * @return true is found
746 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
748 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
749 return TagHT.count(key);
753 * \brief Searches within Header Entries (Dicom Elements) parsed with
754 * the public and private dictionaries
755 * for the element value of a given tag.
756 * \warning Don't use any longer : use GetPubEntryByName
757 * @param tagName name of the searched element.
758 * @return Corresponding element value when it exists,
759 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
761 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
763 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
769 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
773 * \brief Searches within Header Entries (Dicom Elements) parsed with
774 * the public and private dictionaries
775 * for the element value representation of a given tag.
777 * Obtaining the VR (Value Representation) might be needed by caller
778 * to convert the string typed content to caller's native type
779 * (think of C++ vs Python). The VR is actually of a higher level
780 * of semantics than just the native C++ type.
781 * @param tagName name of the searched element.
782 * @return Corresponding element value representation when it exists,
783 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
785 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
787 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
788 if( dictEntry == NULL)
793 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
794 dictEntry->GetElement());
795 return elem->GetVR();
800 * \brief Searches within Header Entries (Dicom Elements) parsed with
801 * the public and private dictionaries
802 * for the element value representation of a given tag.
803 * @param group Group number of the searched tag.
804 * @param element Element number of the searched tag.
805 * @return Corresponding element value representation when it exists,
806 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
808 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
810 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
811 /// \todo use map methods, instead of multimap JPR
812 if ( !TagHT.count(key))
817 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
821 * \brief Searches within Header Entries (Dicom Elements) parsed with
822 * the public and private dictionaries
823 * for the element value representation of a given tag..
825 * Obtaining the VR (Value Representation) might be needed by caller
826 * to convert the string typed content to caller's native type
827 * (think of C++ vs Python). The VR is actually of a higher level
828 * of semantics than just the native C++ type.
829 * @param group Group number of the searched tag.
830 * @param element Element number of the searched tag.
831 * @return Corresponding element value representation when it exists,
832 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
834 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
836 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
841 return elem->GetVR();
845 * \brief Searches within Header Entries (Dicom Elements) parsed with
846 * the public and private dictionaries
847 * for the value length of a given tag..
848 * @param group Group number of the searched tag.
849 * @param element Element number of the searched tag.
850 * @return Corresponding element length; -2 if not found
852 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
854 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
857 return -2; //magic number
859 return elem->GetLength();
862 * \brief Sets the value (string) of the Header Entry (Dicom Element)
863 * @param content string value of the Dicom Element
864 * @param tagName name of the searched Dicom Element.
865 * @return true when found
867 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
869 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
875 return SetEntryByNumber(content,dictEntry->GetGroup(),
876 dictEntry->GetElement());
880 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
881 * through it's (group, element) and modifies it's content with
883 * @param content new value (string) to substitute with
884 * @param group group number of the Dicom Element to modify
885 * @param element element number of the Dicom Element to modify
887 bool gdcmDocument::SetEntryByNumber(std::string const & content,
894 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
897 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
898 " ValEntry (try promotion first).");
901 // Non even content must be padded with a space (020H)...
902 std::string finalContent = content;
903 if( finalContent.length() % 2 )
905 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
907 valEntry->SetValue(finalContent);
909 // Integers have a special treatement for their length:
911 l = finalContent.length();
912 if ( l != 0) // To avoid to be cheated by 'zero length' integers
914 gdcmVRKey vr = valEntry->GetVR();
915 if( vr == "US" || vr == "SS" )
917 c = CountSubstring(content, "\\") + 1; // for multivaluated items
920 else if( vr == "UL" || vr == "SL" )
922 c = CountSubstring(content, "\\") + 1; // for multivaluated items
926 valEntry->SetLength(l);
931 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
932 * through it's (group, element) and modifies it's content with
934 * @param content new value (void *) to substitute with
935 * @param lgth new value length
936 * @param group group number of the Dicom Element to modify
937 * @param element element number of the Dicom Element to modify
939 bool gdcmDocument::SetEntryByNumber(void *content,
944 (void)lgth; //not used
945 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
946 if ( !TagHT.count(key))
951 /* Hope Binary field length is *never* wrong
952 if(lgth%2) // Non even length are padded with a space (020H).
955 //content = content + '\0'; // fing a trick to enlarge a binary field?
958 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
959 a->SetVoidArea(content);
966 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
967 * in the PubDocEntrySet of this instance
968 * through it's (group, element) and modifies it's length with
970 * \warning Use with extreme caution.
971 * @param l new length to substitute with
972 * @param group group number of the Entry to modify
973 * @param element element number of the Entry to modify
974 * @return true on success, false otherwise.
976 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
980 /// \todo use map methods, instead of multimap JPR
981 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
982 if ( !TagHT.count(key) )
988 l++; // length must be even
990 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
996 * \brief Gets (from Header) the offset of a 'non string' element value
997 * (LoadElementValues has already be executed)
998 * @param group group number of the Entry
999 * @param elem element number of the Entry
1000 * @return File Offset of the Element Value
1002 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1004 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1007 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1010 return entry->GetOffset();
1014 * \brief Gets (from Header) a 'non string' element value
1015 * (LoadElementValues has already be executed)
1016 * @param group group number of the Entry
1017 * @param elem element number of the Entry
1018 * @return Pointer to the 'non string' area
1020 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1022 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1025 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1028 return ((gdcmBinEntry *)entry)->GetVoidArea();
1032 * \brief Loads (from disk) the element content
1033 * when a string is not suitable
1034 * @param group group number of the Entry
1035 * @param elem element number of the Entry
1037 void* gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1039 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1044 size_t o =(size_t)docElement->GetOffset();
1045 fseek(Fp, o, SEEK_SET);
1046 size_t l = docElement->GetLength();
1047 char* a = new char[l];
1050 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1053 size_t l2 = fread(a, 1, l , Fp);
1059 /// \TODO Drop any already existing void area! JPR
1060 if( !SetEntryVoidAreaByNumber( a, group, elem ) );
1062 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea setting failed.");
1068 * \brief Loads (from disk) the element content
1069 * when a string is not suitable
1070 * @param element Entry whose voidArea is going to be loaded
1072 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1074 size_t o =(size_t)element->GetOffset();
1075 fseek(Fp, o, SEEK_SET);
1076 size_t l = element->GetLength();
1077 char* a = new char[l];
1080 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1083 element->SetVoidArea((void *)a);
1084 /// \todo check the result
1085 size_t l2 = fread(a, 1, l , Fp);
1096 * \brief Sets a 'non string' value to a given Dicom Element
1097 * @param area area containing the 'non string' value
1098 * @param group Group number of the searched Dicom Element
1099 * @param element Element number of the searched Dicom Element
1102 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1106 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1107 if ( !currentEntry )
1111 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1113 binEntry->SetVoidArea( area );
1120 * \brief Update the entries with the shadow dictionary.
1121 * Only non even entries are analyzed
1123 void gdcmDocument::UpdateShaEntries()
1125 //gdcmDictEntry *entry;
1128 /// \todo TODO : still any use to explore recursively the whole structure?
1130 for(ListTag::iterator it=listEntries.begin();
1131 it!=listEntries.end();
1134 // Odd group => from public dictionary
1135 if((*it)->GetGroup()%2==0)
1138 // Peer group => search the corresponding dict entry
1140 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1144 if((*it)->IsImplicitVR())
1149 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1151 // Set the new entry and the new value
1152 (*it)->SetDictEntry(entry);
1153 CheckDocEntryVR(*it,vr);
1155 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1160 // Remove precedent value transformation
1161 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1168 * \brief Searches within the Header Entries for a Dicom Element of
1170 * @param tagName name of the searched Dicom Element.
1171 * @return Corresponding Dicom Element when it exists, and NULL
1174 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1176 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1182 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1186 * \brief retrieves a Dicom Element (the first one) using (group, element)
1187 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1188 * if you think it's NOT UNIQUE, check the count number
1189 * and use iterators to retrieve ALL the Dicoms Elements within
1190 * a given couple (group, element)
1191 * @param group Group number of the searched Dicom Element
1192 * @param element Element number of the searched Dicom Element
1195 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1198 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1199 if ( !TagHT.count(key))
1203 return TagHT.find(key)->second;
1207 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1208 * returns a result when the corresponding entry is of type
1210 * @return When present, the corresponding ValEntry.
1212 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1215 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1216 if ( !currentEntry )
1220 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1224 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1230 * \brief Loads the element while preserving the current
1231 * underlying file position indicator as opposed to
1232 * to LoadDocEntry that modifies it.
1233 * @param entry Header Entry whose value shall be loaded.
1236 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1238 long PositionOnEntry = ftell(Fp);
1239 LoadDocEntry(entry);
1240 fseek(Fp, PositionOnEntry, SEEK_SET);
1244 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1246 * @return The properly swaped 32 bits integer.
1248 uint32_t gdcmDocument::SwapLong(uint32_t a)
1255 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1256 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1260 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1264 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1267 //std::cout << "swapCode= " << SwapCode << std::endl;
1268 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1275 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1277 * @return The properly unswaped 32 bits integer.
1279 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1285 * \brief Swaps the bytes so they agree with the processor order
1286 * @return The properly swaped 16 bits integer.
1288 uint16_t gdcmDocument::SwapShort(uint16_t a)
1290 if ( SwapCode == 4321 || SwapCode == 2143 )
1292 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1298 * \brief Unswaps the bytes so they agree with the processor order
1299 * @return The properly unswaped 16 bits integer.
1301 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1303 return SwapShort(a);
1306 //-----------------------------------------------------------------------------
1310 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1311 * @return length of the parsed set.
1314 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1319 gdcmDocEntry *newDocEntry = 0;
1320 unsigned long l = 0;
1322 int depth = set->GetDepthLevel();
1325 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1329 newDocEntry = ReadNextDocEntry( );
1335 gdcmVRKey vr = newDocEntry->GetVR();
1339 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1342 gdcmValEntry* newValEntry =
1343 new gdcmValEntry( newDocEntry->GetDictEntry() );
1344 newValEntry->Copy( newDocEntry );
1345 newValEntry->SetKey( set->GetBaseTagKey() + newValEntry->GetKey() );
1346 set->AddEntry( newValEntry );
1347 LoadDocEntry( newValEntry );
1348 if (newValEntry->IsItemDelimitor())
1352 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1359 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1361 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1362 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1363 "nor BinEntry. Probably unknown VR.");
1366 ////// BinEntry or UNKOWN VR:
1367 gdcmBinEntry* newBinEntry =
1368 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1369 newBinEntry->Copy( newDocEntry );
1370 newBinEntry->SetKey( set->GetBaseTagKey() + newBinEntry->GetKey() );
1371 set->AddEntry( newBinEntry );
1372 LoadDocEntry( newBinEntry );
1375 if (newDocEntry->GetGroup() == 0x7fe0 &&
1376 newDocEntry->GetElement() == 0x0010 )
1378 if (newDocEntry->GetReadLength()==0xffffffff)
1380 // Broken US.3405.1.dcm
1381 Parse7FE0(); // to skip the pixels
1382 // (multipart JPEG/RLE are trouble makers)
1386 SkipToNextDocEntry(newDocEntry);
1387 l = newDocEntry->GetFullLength();
1392 // to be sure we are at the beginning
1393 SkipToNextDocEntry(newDocEntry);
1394 l = newDocEntry->GetFullLength();
1400 l = newDocEntry->GetReadLength();
1401 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1403 if ( l == 0xffffffff )
1412 // no other way to create it ...
1413 gdcmSeqEntry* newSeqEntry =
1414 new gdcmSeqEntry( newDocEntry->GetDictEntry(),
1415 set->GetDepthLevel() );
1416 newSeqEntry->Copy( newDocEntry );
1417 newSeqEntry->SetDelimitorMode( delim_mode );
1418 newSeqEntry->SetDepthLevel( depth );
1419 newSeqEntry->SetKey( set->GetBaseTagKey() + newSeqEntry->GetKey() );
1422 { // Don't try to parse zero-length sequences
1423 (void)ParseSQ( newSeqEntry,
1424 newDocEntry->GetOffset(),
1427 set->AddEntry( newSeqEntry );
1428 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1435 return l; // Probably useless
1439 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1440 * @return parsed length for this level
1442 long gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1443 long offset, long l_max, bool delim_mode)
1445 int SQItemNumber = 0;
1450 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1453 // FIXME Should warn user
1458 if ( newDocEntry->IsSequenceDelimitor() )
1460 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1464 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1469 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1470 std::ostringstream newBase;
1471 newBase << seqEntry->GetKey()
1475 itemSQ->SetBaseTagKey( newBase.str() );
1476 unsigned int l = newDocEntry->GetReadLength();
1478 if ( l == 0xffffffff )
1487 (void)ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1489 seqEntry->AddEntry( itemSQ, SQItemNumber );
1491 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1497 int lgth = ftell(Fp) - offset;
1502 * \brief Loads the element content if its length doesn't exceed
1503 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1504 * @param entry Header Entry (Dicom Element) to be dealt with
1506 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1509 uint16_t group = entry->GetGroup();
1510 std::string vr = entry->GetVR();
1511 uint32_t length = entry->GetLength();
1513 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1515 // A SeQuence "contains" a set of Elements.
1516 // (fffe e000) tells us an Element is beginning
1517 // (fffe e00d) tells us an Element just ended
1518 // (fffe e0dd) tells us the current SeQuence just ended
1519 if( group == 0xfffe )
1521 // NO more value field for SQ !
1525 // When the length is zero things are easy:
1528 ((gdcmValEntry *)entry)->SetValue("");
1532 // The elements whose length is bigger than the specified upper bound
1533 // are not loaded. Instead we leave a short notice of the offset of
1534 // the element content and it's length.
1536 std::ostringstream s;
1537 if (length > MaxSizeLoadEntry)
1539 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1541 //s << "gdcm::NotLoaded (BinEntry)";
1542 s << GDCM_NOTLOADED;
1543 s << " Address:" << (long)entry->GetOffset();
1544 s << " Length:" << entry->GetLength();
1545 s << " x(" << std::hex << entry->GetLength() << ")";
1546 binEntryPtr->SetValue(s.str());
1548 // Be carefull : a BinEntry IS_A ValEntry ...
1549 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1551 // s << "gdcm::NotLoaded. (ValEntry)";
1552 s << GDCM_NOTLOADED;
1553 s << " Address:" << (long)entry->GetOffset();
1554 s << " Length:" << entry->GetLength();
1555 s << " x(" << std::hex << entry->GetLength() << ")";
1556 valEntryPtr->SetValue(s.str());
1561 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1562 << "nor a ValEntry ?! Should never print that !" << std::endl;
1565 // to be sure we are at the end of the value ...
1566 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1570 // When we find a BinEntry not very much can be done :
1571 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1573 s << "gdcm::Loaded (BinEntry)";
1574 binEntryPtr->SetValue(s.str());
1575 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1579 /// \todo Any compacter code suggested (?)
1580 if ( IsDocEntryAnInteger(entry) )
1584 // When short integer(s) are expected, read and convert the following
1585 // n *two characters properly i.e. consider them as short integers as
1586 // opposed to strings.
1587 // Elements with Value Multiplicity > 1
1588 // contain a set of integers (not a single one)
1589 if (vr == "US" || vr == "SS")
1592 NewInt = ReadInt16();
1596 for (int i=1; i < nbInt; i++)
1599 NewInt = ReadInt16();
1604 // See above comment on multiple integers (mutatis mutandis).
1605 else if (vr == "UL" || vr == "SL")
1608 NewInt = ReadInt32();
1612 for (int i=1; i < nbInt; i++)
1615 NewInt = ReadInt32();
1620 #ifdef GDCM_NO_ANSI_STRING_STREAM
1621 s << std::ends; // to avoid oddities on Solaris
1622 #endif //GDCM_NO_ANSI_STRING_STREAM
1624 ((gdcmValEntry *)entry)->SetValue(s.str());
1628 // We need an additional byte for storing \0 that is not on disk
1629 //std::string newValue(length,0);
1630 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1631 //rah !! I can't believe it could work, normally this is a const char* !!!
1632 char *str = new char[length+1];
1633 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1635 std::string newValue = str;
1637 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1639 if ( item_read != 1 )
1641 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1642 "unread element value");
1643 valEntry->SetValue(GDCM_UNREAD);
1649 // Because of correspondance with the VR dic
1650 valEntry->SetValue(newValue);
1654 valEntry->SetValue(newValue);
1659 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1660 "Should have a ValEntry, here !");
1666 * \brief Find the value Length of the passed Header Entry
1667 * @param entry Header Entry whose length of the value shall be loaded.
1669 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1670 throw ( gdcmFormatError )
1672 uint16_t element = entry->GetElement();
1673 std::string vr = entry->GetVR();
1676 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1678 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1680 // The following reserved two bytes (see PS 3.5-2001, section
1681 // 7.1.2 Data element structure with explicit vr p27) must be
1682 // skipped before proceeding on reading the length on 4 bytes.
1683 fseek(Fp, 2L, SEEK_CUR);
1684 uint32_t length32 = ReadInt32();
1686 if ( vr == "OB" && length32 == 0xffffffff )
1691 lengthOB = FindDocEntryLengthOB();
1693 catch ( gdcmFormatUnexpected )
1695 // Computing the length failed (this happens with broken
1696 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1697 // chance to get the pixels by deciding the element goes
1698 // until the end of the file. Hence we artificially fix the
1699 // the length and proceed.
1700 long currentPosition = ftell(Fp);
1701 fseek(Fp,0L,SEEK_END);
1702 long lengthUntilEOF = ftell(Fp) - currentPosition;
1703 fseek(Fp, currentPosition, SEEK_SET);
1704 entry->SetLength(lengthUntilEOF);
1707 entry->SetLength(lengthOB);
1710 FixDocEntryFoundLength(entry, length32);
1714 // Length is encoded on 2 bytes.
1715 length16 = ReadInt16();
1717 // We can tell the current file is encoded in big endian (like
1718 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1719 // and it's value is the one of the encoding of a big endian file.
1720 // In order to deal with such big endian encoded files, we have
1721 // (at least) two strategies:
1722 // * when we load the "Transfer Syntax" tag with value of big endian
1723 // encoding, we raise the proper flags. Then we wait for the end
1724 // of the META group (0x0002) among which is "Transfer Syntax",
1725 // before switching the swap code to big endian. We have to postpone
1726 // the switching of the swap code since the META group is fully encoded
1727 // in little endian, and big endian coding only starts at the next
1728 // group. The corresponding code can be hard to analyse and adds
1729 // many additional unnecessary tests for regular tags.
1730 // * the second strategy consists in waiting for trouble, that shall
1731 // appear when we find the first group with big endian encoding. This
1732 // is easy to detect since the length of a "Group Length" tag (the
1733 // ones with zero as element number) has to be of 4 (0x0004). When we
1734 // encounter 1024 (0x0400) chances are the encoding changed and we
1735 // found a group with big endian encoding.
1736 // We shall use this second strategy. In order to make sure that we
1737 // can interpret the presence of an apparently big endian encoded
1738 // length of a "Group Length" without committing a big mistake, we
1739 // add an additional check: we look in the already parsed elements
1740 // for the presence of a "Transfer Syntax" whose value has to be "big
1741 // endian encoding". When this is the case, chances are we have got our
1742 // hands on a big endian encoded file: we switch the swap code to
1743 // big endian and proceed...
1744 if ( element == 0x0000 && length16 == 0x0400 )
1746 if ( !IsExplicitVRBigEndianTransferSyntax() )
1748 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1749 " not explicit VR." );
1753 SwitchSwapToBigEndian();
1754 // Restore the unproperly loaded values i.e. the group, the element
1755 // and the dictionary entry depending on them.
1756 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1757 uint16_t correctElem = SwapShort( entry->GetElement() );
1758 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1762 // This correct tag is not in the dictionary. Create a new one.
1763 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1765 // FIXME this can create a memory leaks on the old entry that be
1766 // left unreferenced.
1767 entry->SetDictEntry( newTag );
1770 // Heuristic: well, some files are really ill-formed.
1771 if ( length16 == 0xffff)
1773 // 0xffff means that we deal with 'Unknown Length' Sequence
1776 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1781 // Either implicit VR or a non DICOM conformal (see note below) explicit
1782 // VR that ommited the VR of (at least) this element. Farts happen.
1783 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1784 // on Data elements "Implicit and Explicit VR Data Elements shall
1785 // not coexist in a Data Set and Data Sets nested within it".]
1786 // Length is on 4 bytes.
1788 FixDocEntryFoundLength( entry, ReadInt32() );
1794 * \brief Find the Value Representation of the current Dicom Element.
1797 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1799 if ( Filetype != gdcmExplicitVR )
1806 long positionOnEntry = ftell(Fp);
1807 // Warning: we believe this is explicit VR (Value Representation) because
1808 // we used a heuristic that found "UL" in the first tag. Alas this
1809 // doesn't guarantee that all the tags will be in explicit VR. In some
1810 // cases (see e-film filtered files) one finds implicit VR tags mixed
1811 // within an explicit VR file. Hence we make sure the present tag
1812 // is in explicit VR and try to fix things if it happens not to be
1815 fread (vr, (size_t)2,(size_t)1, Fp);
1818 if( !CheckDocEntryVR(entry, vr) )
1820 fseek(Fp, positionOnEntry, SEEK_SET);
1821 // When this element is known in the dictionary we shall use, e.g. for
1822 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1823 // dictionary entry. Still we have to flag the element as implicit since
1824 // we know now our assumption on expliciteness is not furfilled.
1826 if ( entry->IsVRUnknown() )
1828 entry->SetVR("Implicit");
1830 entry->SetImplicitVR();
1835 * \brief Check the correspondance between the VR of the header entry
1836 * and the taken VR. If they are different, the header entry is
1837 * updated with the new VR.
1838 * @param entry Header Entry to check
1839 * @param vr Dicom Value Representation
1840 * @return false if the VR is incorrect of if the VR isn't referenced
1841 * otherwise, it returns true
1843 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1845 char msg[100]; // for sprintf
1846 bool realExplicit = true;
1848 // Assume we are reading a falsely explicit VR file i.e. we reached
1849 // a tag where we expect reading a VR but are in fact we read the
1850 // first to bytes of the length. Then we will interogate (through find)
1851 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1852 // both GCC and VC++ implementations of the STL map. Hence when the
1853 // expected VR read happens to be non-ascii characters we consider
1854 // we hit falsely explicit VR tag.
1856 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1858 realExplicit = false;
1861 // CLEANME searching the dicom_vr at each occurence is expensive.
1862 // PostPone this test in an optional integrity check at the end
1863 // of parsing or only in debug mode.
1864 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1866 realExplicit = false;
1869 if ( !realExplicit )
1871 // We thought this was explicit VR, but we end up with an
1872 // implicit VR tag. Let's backtrack.
1873 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1874 entry->GetGroup(), entry->GetElement());
1875 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1877 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1879 // Group length is UL !
1880 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1881 entry->GetGroup(), entry->GetElement(),
1882 "UL", "FIXME", "Group Length");
1883 entry->SetDictEntry( newEntry );
1888 if ( entry->IsVRUnknown() )
1890 // When not a dictionary entry, we can safely overwrite the VR.
1891 if( entry->GetElement() == 0x0000 )
1893 // Group length is UL !
1901 else if ( entry->GetVR() != vr )
1903 // The VR present in the file and the dictionary disagree. We assume
1904 // the file writer knew best and use the VR of the file. Since it would
1905 // be unwise to overwrite the VR of a dictionary (since it would
1906 // compromise it's next user), we need to clone the actual DictEntry
1907 // and change the VR for the read one.
1908 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1909 entry->GetGroup(), entry->GetElement(),
1910 vr, "FIXME", entry->GetName());
1911 entry->SetDictEntry(newEntry);
1918 * \brief Get the transformed value of the header entry. The VR value
1919 * is used to define the transformation to operate on the value
1920 * \warning NOT end user intended method !
1921 * @param entry entry to tranform
1922 * @return Transformed entry value
1924 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1926 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1928 std::string val = ((gdcmValEntry *)entry)->GetValue();
1929 std::string vr = entry->GetVR();
1930 uint32_t length = entry->GetLength();
1931 std::ostringstream s;
1934 // When short integer(s) are expected, read and convert the following
1935 // n * 2 bytes properly i.e. as a multivaluated strings
1936 // (each single value is separated fromthe next one by '\'
1937 // as usual for standard multivaluated filels
1938 // Elements with Value Multiplicity > 1
1939 // contain a set of short integers (not a single one)
1941 if( vr == "US" || vr == "SS" )
1946 for (int i=0; i < nbInt; i++)
1952 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1953 newInt16 = SwapShort( newInt16 );
1958 // When integer(s) are expected, read and convert the following
1959 // n * 4 bytes properly i.e. as a multivaluated strings
1960 // (each single value is separated fromthe next one by '\'
1961 // as usual for standard multivaluated filels
1962 // Elements with Value Multiplicity > 1
1963 // contain a set of integers (not a single one)
1964 else if( vr == "UL" || vr == "SL" )
1969 for (int i=0; i < nbInt; i++)
1975 newInt32 = ( val[4*i+0] & 0xFF )
1976 + (( val[4*i+1] & 0xFF ) << 8 )
1977 + (( val[4*i+2] & 0xFF ) << 16 )
1978 + (( val[4*i+3] & 0xFF ) << 24 );
1979 newInt32 = SwapLong( newInt32 );
1983 #ifdef GDCM_NO_ANSI_STRING_STREAM
1984 s << std::ends; // to avoid oddities on Solaris
1985 #endif //GDCM_NO_ANSI_STRING_STREAM
1989 return ((gdcmValEntry *)entry)->GetValue();
1993 * \brief Get the reverse transformed value of the header entry. The VR
1994 * value is used to define the reverse transformation to operate on
1996 * \warning NOT end user intended method !
1997 * @param entry Entry to reverse transform
1998 * @return Reverse transformed entry value
2000 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2002 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2004 std::string vr = entry->GetVR();
2005 std::vector<std::string> tokens;
2006 std::ostringstream s;
2008 if ( vr == "US" || vr == "SS" )
2012 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2013 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2014 for (unsigned int i=0; i<tokens.size(); i++)
2016 newInt16 = atoi(tokens[i].c_str());
2017 s << ( newInt16 & 0xFF )
2018 << (( newInt16 >> 8 ) & 0xFF );
2022 if ( vr == "UL" || vr == "SL")
2026 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2027 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2028 for (unsigned int i=0; i<tokens.size();i++)
2030 newInt32 = atoi(tokens[i].c_str());
2031 s << (char)( newInt32 & 0xFF )
2032 << (char)(( newInt32 >> 8 ) & 0xFF )
2033 << (char)(( newInt32 >> 16 ) & 0xFF )
2034 << (char)(( newInt32 >> 24 ) & 0xFF );
2039 #ifdef GDCM_NO_ANSI_STRING_STREAM
2040 s << std::ends; // to avoid oddities on Solaris
2041 #endif //GDCM_NO_ANSI_STRING_STREAM
2045 return ((gdcmValEntry *)entry)->GetValue();
2049 * \brief Skip a given Header Entry
2050 * \warning NOT end user intended method !
2051 * @param entry entry to skip
2053 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2055 SkipBytes(entry->GetLength());
2059 * \brief Skips to the begining of the next Header Entry
2060 * \warning NOT end user intended method !
2061 * @param entry entry to skip
2063 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2065 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2066 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2070 * \brief When the length of an element value is obviously wrong (because
2071 * the parser went Jabberwocky) one can hope improving things by
2072 * applying some heuristics.
2073 * @param entry entry to check
2074 * @param foundLength fist assumption about length
2076 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2077 uint32_t foundLength)
2079 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2080 if ( foundLength == 0xffffffff)
2085 uint16_t gr = entry->GetGroup();
2086 uint16_t el = entry->GetElement();
2088 if ( foundLength % 2)
2090 std::ostringstream s;
2091 s << "Warning : Tag with uneven length "
2093 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2094 dbg.Verbose(0, s.str().c_str());
2097 //////// Fix for some naughty General Electric images.
2098 // Allthough not recent many such GE corrupted images are still present
2099 // on Creatis hard disks. Hence this fix shall remain when such images
2100 // are no longer in user (we are talking a few years, here)...
2101 // Note: XMedCom probably uses such a trick since it is able to read
2102 // those pesky GE images ...
2103 if ( foundLength == 13)
2105 // Only happens for this length !
2106 if ( entry->GetGroup() != 0x0008
2107 || ( entry->GetElement() != 0x0070
2108 && entry->GetElement() != 0x0080 ) )
2111 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2115 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2116 // Occurence of such images is quite low (unless one leaves close to a
2117 // 'Leonardo' source. Hence, one might consider commenting out the
2118 // following fix on efficiency reasons.
2119 else if ( entry->GetGroup() == 0x0009
2120 && ( entry->GetElement() == 0x1113
2121 || entry->GetElement() == 0x1114 ) )
2124 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2127 else if ( entry->GetVR() == "SQ" )
2129 foundLength = 0; // ReadLength is unchanged
2132 //////// We encountered a 'delimiter' element i.e. a tag of the form
2133 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2134 // taken into account.
2135 else if( entry->GetGroup() == 0xfffe )
2137 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2138 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2139 // causes extra troubles...
2140 if( entry->GetElement() != 0x0000 )
2146 entry->SetUsableLength(foundLength);
2150 * \brief Apply some heuristics to predict whether the considered
2151 * element value contains/represents an integer or not.
2152 * @param entry The element value on which to apply the predicate.
2153 * @return The result of the heuristical predicate.
2155 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2157 uint16_t element = entry->GetElement();
2158 uint16_t group = entry->GetGroup();
2159 std::string vr = entry->GetVR();
2160 uint32_t length = entry->GetLength();
2162 // When we have some semantics on the element we just read, and if we
2163 // a priori know we are dealing with an integer, then we shall be
2164 // able to swap it's element value properly.
2165 if ( element == 0 ) // This is the group length of the group
2173 // Allthough this should never happen, still some images have a
2174 // corrupted group length [e.g. have a glance at offset x(8336) of
2175 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2176 // Since for dicom compliant and well behaved headers, the present
2177 // test is useless (and might even look a bit paranoid), when we
2178 // encounter such an ill-formed image, we simply display a warning
2179 // message and proceed on parsing (while crossing fingers).
2180 std::ostringstream s;
2181 int filePosition = ftell(Fp);
2182 s << "Erroneous Group Length element length on : (" \
2183 << std::hex << group << " , " << element
2184 << ") -before- position x(" << filePosition << ")"
2185 << "lgt : " << length;
2186 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2190 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2199 * \brief Find the Length till the next sequence delimiter
2200 * \warning NOT end user intended method !
2204 uint32_t gdcmDocument::FindDocEntryLengthOB()
2205 throw( gdcmFormatUnexpected )
2207 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2208 long positionOnEntry = ftell(Fp);
2209 bool foundSequenceDelimiter = false;
2210 uint32_t totalLength = 0;
2212 while ( !foundSequenceDelimiter )
2218 group = ReadInt16();
2221 catch ( gdcmFormatError )
2223 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2224 " group or element not present.");
2227 // We have to decount the group and element we just read
2230 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2232 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2233 "tag nor a Sequence delimiter tag.");
2234 fseek(Fp, positionOnEntry, SEEK_SET);
2235 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2236 "Neither an Item tag nor a Sequence "
2240 if ( elem == 0xe0dd )
2242 foundSequenceDelimiter = true;
2245 uint32_t itemLength = ReadInt32();
2246 // We add 4 bytes since we just read the ItemLength with ReadInt32
2247 totalLength += itemLength + 4;
2248 SkipBytes(itemLength);
2250 if ( foundSequenceDelimiter )
2255 fseek(Fp, positionOnEntry, SEEK_SET);
2260 * \brief Reads a supposed to be 16 Bits integer
2261 * (swaps it depending on processor endianity)
2262 * @return read value
2264 uint16_t gdcmDocument::ReadInt16()
2265 throw( gdcmFormatError )
2268 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2269 if ( item_read != 1 )
2273 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2275 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2282 * \brief Reads a supposed to be 32 Bits integer
2283 * (swaps it depending on processor endianity)
2284 * @return read value
2286 uint32_t gdcmDocument::ReadInt32()
2287 throw( gdcmFormatError )
2290 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2291 if ( item_read != 1 )
2295 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2297 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2304 * \brief skips bytes inside the source file
2305 * \warning NOT end user intended method !
2308 void gdcmDocument::SkipBytes(uint32_t nBytes)
2310 //FIXME don't dump the returned value
2311 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2315 * \brief Loads all the needed Dictionaries
2316 * \warning NOT end user intended method !
2318 void gdcmDocument::Initialise()
2320 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2325 * \brief Discover what the swap code is (among little endian, big endian,
2326 * bad little endian, bad big endian).
2328 * @return false when we are absolutely sure
2329 * it's neither ACR-NEMA nor DICOM
2330 * true when we hope ours assuptions are OK
2332 bool gdcmDocument::CheckSwap()
2334 // The only guaranted way of finding the swap code is to find a
2335 // group tag since we know it's length has to be of four bytes i.e.
2336 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2337 // occurs when we can't find such group...
2339 uint32_t x = 4; // x : for ntohs
2340 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2344 char deb[HEADER_LENGTH_TO_READ];
2346 // First, compare HostByteOrder and NetworkByteOrder in order to
2347 // determine if we shall need to swap bytes (i.e. the Endian type).
2348 if ( x == ntohs(x) )
2357 // The easiest case is the one of a DICOM header, since it possesses a
2358 // file preamble where it suffice to look for the string "DICM".
2359 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2360 (void)lgrLue; //FIXME not used
2362 char *entCur = deb + 128;
2363 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2365 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2367 // Next, determine the value representation (VR). Let's skip to the
2368 // first element (0002, 0000) and check there if we find "UL"
2369 // - or "OB" if the 1st one is (0002,0001) -,
2370 // in which case we (almost) know it is explicit VR.
2371 // WARNING: if it happens to be implicit VR then what we will read
2372 // is the length of the group. If this ascii representation of this
2373 // length happens to be "UL" then we shall believe it is explicit VR.
2374 // FIXME: in order to fix the above warning, we could read the next
2375 // element value (or a couple of elements values) in order to make
2376 // sure we are not commiting a big mistake.
2377 // We need to skip :
2378 // * the 128 bytes of File Preamble (often padded with zeroes),
2379 // * the 4 bytes of "DICM" string,
2380 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2381 // i.e. a total of 136 bytes.
2385 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2386 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2387 // *Implicit* VR. -and it is !-
2389 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2390 memcmp(entCur, "OB", (size_t)2) == 0 ||
2391 memcmp(entCur, "UI", (size_t)2) == 0 ||
2392 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2393 // when Write DCM *adds*
2395 // Use gdcmDocument::dicom_vr to test all the possibilities
2396 // instead of just checking for UL, OB and UI !? group 0000
2398 Filetype = gdcmExplicitVR;
2399 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2400 "explicit Value Representation");
2404 Filetype = gdcmImplicitVR;
2405 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2406 "not an explicit Value Representation");
2412 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2413 "HostByteOrder != NetworkByteOrder");
2418 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2419 "HostByteOrder = NetworkByteOrder");
2422 // Position the file position indicator at first tag (i.e.
2423 // after the file preamble and the "DICM" string).
2425 fseek (Fp, 132L, SEEK_SET);
2429 // Alas, this is not a DicomV3 file and whatever happens there is no file
2430 // preamble. We can reset the file position indicator to where the data
2431 // is (i.e. the beginning of the file).
2432 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2435 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2436 // By clean we mean that the length of the first tag is written down.
2437 // If this is the case and since the length of the first group HAS to be
2438 // four (bytes), then determining the proper swap code is straightforward.
2441 // We assume the array of char we are considering contains the binary
2442 // representation of a 32 bits integer. Hence the following dirty
2444 s32 = *((uint32_t *)(entCur));
2465 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2466 // It is time for despaired wild guesses.
2467 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2468 // i.e. the 'group length' element is not present :
2470 // check the supposed to be 'group number'
2471 // 0x0002 or 0x0004 or 0x0008
2472 // to determine ' SwapCode' value .
2473 // Only 0 or 4321 will be possible
2474 // (no oportunity to check for the formerly well known
2475 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2476 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2477 // the file IS NOT ACR-NEMA nor DICOM V3
2478 // Find a trick to tell it the caller...
2480 s16 = *((uint16_t *)(deb));
2497 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2498 "ACR/NEMA unfound swap info (Really hopeless !)");
2499 Filetype = gdcmUnknown;
2502 // Then the only info we have is the net2host one.
2512 * \brief Restore the unproperly loaded values i.e. the group, the element
2513 * and the dictionary entry depending on them.
2515 void gdcmDocument::SwitchSwapToBigEndian()
2517 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2518 "Switching to BigEndian mode.");
2519 if ( SwapCode == 0 )
2523 else if ( SwapCode == 4321 )
2527 else if ( SwapCode == 3412 )
2531 else if ( SwapCode == 2143 )
2538 * \brief during parsing, Header Elements too long are not loaded in memory
2541 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2547 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2549 MaxSizeLoadEntry = 0xffffffff;
2552 MaxSizeLoadEntry = newSize;
2557 * \brief Header Elements too long will not be printed
2558 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2561 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2563 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2568 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2570 MaxSizePrintEntry = 0xffffffff;
2573 MaxSizePrintEntry = newSize;
2579 * \brief Read the next tag but WITHOUT loading it's value
2580 * (read the 'Group Number', the 'Element Number',
2581 * gets the Dict Entry
2582 * gets the VR, gets the length, gets the offset value)
2583 * @return On succes the newly created DocEntry, NULL on failure.
2585 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2592 group = ReadInt16();
2595 catch ( gdcmFormatError e )
2597 // We reached the EOF (or an error occured) therefore
2598 // header parsing has to be considered as finished.
2603 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2604 FindDocEntryVR(newEntry);
2608 FindDocEntryLength(newEntry);
2610 catch ( gdcmFormatError e )
2618 newEntry->SetOffset(ftell(Fp));
2625 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2626 * in the TagHt dictionary.
2627 * @param group The generated tag must belong to this group.
2628 * @return The element of tag with given group which is fee.
2630 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2632 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2634 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2635 if (TagHT.count(key) == 0)
2644 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2645 * is placed at the beginning of a tag check whether this
2646 * tag is (TestGroup, TestElement).
2647 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2648 * is modified to point after the tag.
2649 * On failure (i.e. when the tag wasn't the expected tag
2650 * (TestGroup, TestElement) the internal file pointer
2651 * \ref gdcmDocument::Fp is restored to it's original position.
2652 * @param testGroup The expected group of the tag.
2653 * @param testElement The expected Element of the tag.
2654 * @return True on success, false otherwise.
2656 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2658 long positionOnEntry = ftell(Fp);
2659 long currentPosition = ftell(Fp); // On debugging purposes
2661 //// Read the Item Tag group and element, and make
2662 // sure they are what we expected:
2663 uint16_t itemTagGroup = ReadInt16();
2664 uint16_t itemTagElement = ReadInt16();
2665 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2667 std::ostringstream s;
2668 s << " We should have found tag (";
2669 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2670 s << " but instead we encountered tag (";
2671 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2673 s << " at address: " << (unsigned)currentPosition << std::endl;
2674 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2675 dbg.Verbose(0, s.str().c_str());
2676 fseek(Fp, positionOnEntry, SEEK_SET);
2684 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2685 * is placed at the beginning of a tag (TestGroup, TestElement),
2686 * read the length associated to the Tag.
2687 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2688 * is modified to point after the tag and it's length.
2689 * On failure (i.e. when the tag wasn't the expected tag
2690 * (TestGroup, TestElement) the internal file pointer
2691 * \ref gdcmDocument::Fp is restored to it's original position.
2692 * @param testGroup The expected group of the tag.
2693 * @param testElement The expected Element of the tag.
2694 * @return On success returns the length associated to the tag. On failure
2697 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2699 long positionOnEntry = ftell(Fp);
2700 (void)positionOnEntry;
2702 if ( !ReadTag(testGroup, testElement) )
2707 //// Then read the associated Item Length
2708 long currentPosition = ftell(Fp);
2709 uint32_t itemLength = ReadInt32();
2711 std::ostringstream s;
2712 s << "Basic Item Length is: "
2713 << itemLength << std::endl;
2714 s << " at address: " << (unsigned)currentPosition << std::endl;
2715 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2721 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2722 * No other way so 'skip' the Data
2725 void gdcmDocument::Parse7FE0 ()
2727 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2730 // Should warn user FIXME
2734 if ( IsImplicitVRLittleEndianTransferSyntax()
2735 || IsExplicitVRLittleEndianTransferSyntax()
2736 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2737 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2742 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2744 //// Read the Basic Offset Table Item Tag length...
2745 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2747 //// ... and then read length[s] itself[themselves]. We don't use
2748 // the values read (BTW what is the purpous of those lengths ?)
2749 if ( itemLength != 0 )
2751 // BTW, what is the purpous of those length anyhow !?
2752 char* basicOffsetTableItemValue = new char[itemLength + 1];
2753 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2755 for (unsigned int i=0; i < itemLength; i += 4 )
2757 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2758 std::ostringstream s;
2759 s << " Read one length: ";
2760 s << std::hex << individualLength << std::endl;
2761 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2763 delete[] basicOffsetTableItemValue;
2766 if ( ! IsRLELossLessTransferSyntax() )
2770 //// We then skip (not reading them) all the fragments of images:
2771 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2773 SkipBytes(itemLength);
2780 long rleSegmentLength[15], fragmentLength;
2782 // While we find some items:
2783 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2785 // Parse fragments of the current Fragment (Frame)
2786 //------------------ scanning (not reading) fragment pixels
2787 uint32_t nbRleSegments = ReadInt32();
2789 //// Reading RLE Segments Offset Table
2790 uint32_t rleSegmentOffsetTable[15];
2791 for(int k=1; k<=15; k++)
2793 ftellRes = ftell(Fp);
2794 rleSegmentOffsetTable[k] = ReadInt32();
2797 // skipping (not reading) RLE Segments
2798 if ( nbRleSegments > 1)
2800 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2802 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2803 - rleSegmentOffsetTable[k];
2804 ftellRes = ftell(Fp);
2805 SkipBytes(rleSegmentLength[k]);
2809 rleSegmentLength[nbRleSegments] = fragmentLength
2810 - rleSegmentOffsetTable[nbRleSegments];
2811 ftellRes = ftell(Fp);
2812 SkipBytes(rleSegmentLength[nbRleSegments]);
2815 // Make sure that at the end of the item we encounter a 'Sequence
2817 if ( !ReadTag(0xfffe, 0xe0dd) )
2819 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2820 dbg.Verbose(0, " at end of RLE item sequence");
2828 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2829 * \warning Does NOT work with ACR-NEMA files
2830 * \todo Find a trick to solve the pb (use RET fields ?)
2832 * @return true if 'smaller'
2834 bool gdcmDocument::operator<(gdcmDocument &document)
2837 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2838 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2850 s1 = GetEntryByNumber(0x0010,0x0020);
2851 s2 = document.GetEntryByNumber(0x0010,0x0020);
2862 // Study Instance UID
2863 s1 = GetEntryByNumber(0x0020,0x000d);
2864 s2 = document.GetEntryByNumber(0x0020,0x000d);
2875 // Serie Instance UID
2876 s1 = GetEntryByNumber(0x0020,0x000e);
2877 s2 = document.GetEntryByNumber(0x0020,0x000e);
2893 //-----------------------------------------------------------------------------