1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/07/20 08:29:13 $
7 Version: $Revision: 1.56 $
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"
35 #include <netinet/in.h>
40 // Implicit VR Little Endian
41 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
42 // Explicit VR Little Endian
43 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
44 // Deflated Explicit VR Little Endian
45 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
46 // Explicit VR Big Endian
47 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
48 // JPEG Baseline (Process 1)
49 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
50 // JPEG Extended (Process 2 & 4)
51 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
52 // JPEG Extended (Process 3 & 5)
53 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
54 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
55 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
56 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
57 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
58 // JPEG Lossless, Non-Hierarchical (Process 14)
59 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
60 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
61 // [Selection Value 1])
62 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
64 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
66 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
68 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
69 // UI1_1_2_840_10008_1_2_5
70 #define str2num(str, typeNum) *((typeNum *)(str))
72 //-----------------------------------------------------------------------------
73 // Refer to gdcmDocument::CheckSwap()
74 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
76 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
77 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
78 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
80 //-----------------------------------------------------------------------------
81 // Constructor / Destructor
85 * @param inFilename file to be opened for parsing
86 * @param exception_on_error whether we throw an exception or not
87 * @param enable_sequences = true to allow the header
88 * to be parsed *inside* the SeQuences,
89 * when they have an actual length
90 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
91 * @param ignore_shadow to allow skipping the shadow elements,
92 * to save memory space.
93 * \warning The TRUE value for this param has to be used
94 * with a FALSE value for the 'enable_sequence' param.
95 * ('public elements' may be embedded in 'shadow Sequences')
97 gdcmDocument::gdcmDocument( std::string const & filename,
98 bool exception_on_error,
99 bool enable_sequences,
103 IgnoreShadow = ignore_shadow;
104 //EnableSequences=enable_sequences;
105 (void)enable_sequences;
106 EnableSequences = true; // JPR // TODO : remove params out of the constructor
107 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
111 if ( !OpenFile(exception_on_error))
116 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
120 fseek(Fp,0L,SEEK_END);
121 long lgt = ftell(Fp);
125 long beg = ftell(Fp);
130 long l = ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
131 (void)l; //is l used anywhere ?
135 // Load 'non string' values
137 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
138 if( PhotometricInterpretation == "PALETTE COLOR " )
140 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
141 LoadEntryVoidArea(0x0028,0x1201); // R LUT
142 LoadEntryVoidArea(0x0028,0x1202); // G LUT
143 LoadEntryVoidArea(0x0028,0x1203); // B LUT
145 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
146 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
147 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
149 //FIXME later : how to use it?
150 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
154 // --------------------------------------------------------------
155 // Special Patch to allow gdcm to read ACR-LibIDO formated images
157 // if recognition code tells us we deal with a LibIDO image
158 // we switch lineNumber and columnNumber
161 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
162 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
163 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
164 // with "little-endian strings"
166 Filetype = gdcmACR_LIBIDO;
167 std::string rows = GetEntryByNumber(0x0028, 0x0010);
168 std::string columns = GetEntryByNumber(0x0028, 0x0011);
169 SetEntryByNumber(columns, 0x0028, 0x0010);
170 SetEntryByNumber(rows , 0x0028, 0x0011);
172 // ----------------- End of Special Patch ----------------
174 PrintLevel = 1; // 'Medium' print level by default
179 * @param exception_on_error
181 gdcmDocument::gdcmDocument(bool exception_on_error)
184 (void)exception_on_error;
185 //EnableSequences=0; // ?!? JPR
187 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
190 PrintLevel = 1; // 'Medium' print level by default
194 * \brief Canonical destructor.
196 gdcmDocument::~gdcmDocument ()
201 // Recursive clean up of sequences
202 for (TagDocEntryHT::const_iterator it = TagHT.begin();
203 it != TagHT.end(); ++it )
210 //-----------------------------------------------------------------------------
214 * \brief Prints The Dict Entries of THE public Dicom Dictionary
217 void gdcmDocument::PrintPubDict(std::ostream & os)
219 RefPubDict->Print(os);
223 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
226 void gdcmDocument::PrintShaDict(std::ostream & os)
228 RefShaDict->Print(os);
231 //-----------------------------------------------------------------------------
234 * \brief Get the public dictionary used
236 gdcmDict *gdcmDocument::GetPubDict()
242 * \brief Get the shadow dictionary used
244 gdcmDict *gdcmDocument::GetShaDict()
250 * \brief Set the shadow dictionary used
251 * \param dict dictionary to use in shadow
253 bool gdcmDocument::SetShaDict(gdcmDict *dict)
260 * \brief Set the shadow dictionary used
261 * \param dictName name of the dictionary to use in shadow
263 bool gdcmDocument::SetShaDict(DictKey dictName)
265 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
270 * \brief This predicate, based on hopefully reasonable heuristics,
271 * decides whether or not the current gdcmDocument was properly parsed
272 * and contains the mandatory information for being considered as
273 * a well formed and usable Dicom/Acr File.
274 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
277 bool gdcmDocument::IsReadable()
279 if( Filetype == gdcmUnknown)
281 std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
282 << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
283 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
289 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
299 * \brief Internal function that checks whether the Transfer Syntax given
300 * as argument is the one present in the current document.
301 * @param SyntaxToCheck The transfert syntax we need to check against.
302 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
303 * the current document. False either when the document contains
304 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
306 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
308 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
314 // The entry might be present but not loaded (parsing and loading
315 // happen at different stages): try loading and proceed with check...
316 LoadDocEntrySafe(entry);
317 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
319 std::string transfer = valEntry->GetValue();
320 // The actual transfer (as read from disk) might be padded. We
321 // first need to remove the potential padding. We can make the
322 // weak assumption that padding was not executed with digits...
323 if ( transfer.length() == 0 ) { // for brain damaged headers
326 while ( ! isdigit(transfer[transfer.length()-1]) )
328 transfer.erase(transfer.length()-1, 1);
330 if ( transfer == syntaxToCheck )
339 * \brief Determines if the Transfer Syntax of the present document
340 * corresponds to a Implicit Value Representation of
342 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
343 * @return True when ImplicitVRLittleEndian found. False in all other cases.
345 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
347 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
351 * \brief Determines if the Transfer Syntax was already encountered
352 * and if it corresponds to a ExplicitVRLittleEndian one.
353 * @return True when ExplicitVRLittleEndian found. False in all other cases.
355 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
357 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
361 * \brief Determines if the Transfer Syntax was already encountered
362 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
363 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
365 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
367 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
371 * \brief Determines if the Transfer Syntax was already encountered
372 * and if it corresponds to a Explicit VR Big Endian one.
373 * @return True when big endian found. False in all other cases.
375 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
377 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
381 * \brief Determines if the Transfer Syntax was already encountered
382 * and if it corresponds to a JPEGBaseLineProcess1 one.
383 * @return True when JPEGBaseLineProcess1found. False in all other cases.
385 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
387 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
391 * \brief Determines if the Transfer Syntax was already encountered
392 * and if it corresponds to a JPEGExtendedProcess2-4 one.
393 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
395 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
397 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
401 * \brief Determines if the Transfer Syntax was already encountered
402 * and if it corresponds to a JPEGExtendeProcess3-5 one.
403 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
405 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
407 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
411 * \brief Determines if the Transfer Syntax was already encountered
412 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
413 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
416 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
418 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
422 * \brief Determines if the Transfer Syntax was already encountered
423 * and if it corresponds to a RLE Lossless one.
424 * @return True when RLE Lossless found. False in all
427 bool gdcmDocument::IsRLELossLessTransferSyntax()
429 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
433 * \brief Determines if Transfer Syntax was already encountered
434 * and if it corresponds to a JPEG Lossless one.
435 * @return True when RLE Lossless found. False in all
439 bool gdcmDocument::IsJPEGLossless()
441 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
442 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
443 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
447 * \brief Determines if the Transfer Syntax was already encountered
448 * and if it corresponds to a JPEG2000 one
449 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
452 bool gdcmDocument::IsJPEG2000()
454 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
455 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
459 * \brief Predicate for dicom version 3 file.
460 * @return True when the file is a dicom version 3.
462 bool gdcmDocument::IsDicomV3()
464 // Checking if Transfert Syntax exists is enough
465 // Anyway, it's to late check if the 'Preamble' was found ...
466 // And ... would it be a rich idea to check ?
467 // (some 'no Preamble' DICOM images exist !)
468 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
472 * \brief returns the File Type
473 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
474 * @return the FileType code
476 FileType gdcmDocument::GetFileType()
482 * \brief opens the file
483 * @param exception_on_error
486 FILE *gdcmDocument::OpenFile(bool exception_on_error)
489 Fp = fopen(Filename.c_str(),"rb");
493 if(exception_on_error)
495 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
499 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
508 fread(&zero, (size_t)2, (size_t)1, Fp);
510 //ACR -- or DICOM with no Preamble --
511 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
517 fseek(Fp, 126L, SEEK_CUR);
519 fread(dicm, (size_t)4, (size_t)1, Fp);
520 if( memcmp(dicm, "DICM", 4) == 0 )
526 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
530 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
537 * \brief closes the file
538 * @return TRUE if the close was successfull
540 bool gdcmDocument::CloseFile()
542 int closed = fclose(Fp);
549 * \brief Writes in a file all the Header Entries (Dicom Elements)
550 * @param fp file pointer on an already open file
551 * @param filetype Type of the File to be written
552 * (ACR-NEMA, ExplicitVR, ImplicitVR)
553 * \return Always true.
555 void gdcmDocument::Write(FILE* fp,FileType filetype)
557 /// \todo move the following lines (and a lot of others, to be written)
558 /// to a future function CheckAndCorrectHeader
560 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
561 /// no way (check : FileType est un champ de gdcmDocument ...)
562 /// a moins de se livrer a un tres complique ajout des champs manquants.
563 /// faire un CheckAndCorrectHeader (?)
565 if (filetype == gdcmImplicitVR)
567 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
568 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
570 /// \todo Refer to standards on page 21, chapter 6.2
571 /// "Value representation": values with a VR of UI shall be
572 /// padded with a single trailing null
573 /// in the following case we have to padd manually with a 0
575 SetEntryLengthByNumber(18, 0x0002, 0x0010);
578 if (filetype == gdcmExplicitVR)
580 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
581 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
583 /// \todo Refer to standards on page 21, chapter 6.2
584 /// "Value representation": values with a VR of UI shall be
585 /// padded with a single trailing null
586 /// Dans le cas suivant on doit pader manuellement avec un 0
588 SetEntryLengthByNumber(20, 0x0002, 0x0010);
592 * \todo rewrite later, if really usefull
593 * - 'Group Length' element is optional in DICOM
594 * - but un-updated odd groups lengthes can causes pb
597 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
598 * UpdateGroupLength(false,filetype);
599 * if ( filetype == ACR)
600 * UpdateGroupLength(true,ACR);
603 gdcmElementSet::Write(fp, filetype); // This one is recursive
608 * \brief Modifies the value of a given Header Entry (Dicom Element)
609 * when it exists. Create it with the given value when unexistant.
610 * @param Value (string) Value to be set
611 * @param Group Group number of the Entry
612 * @param Elem Element number of the Entry
613 * \return pointer to the modified/created Header Entry (NULL when creation
617 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
622 gdcmValEntry* valEntry = 0;
624 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
627 // The entry wasn't present and we simply create the required ValEntry:
628 currentEntry = NewDocEntryByNumber(group, elem);
631 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
632 " NewDocEntryByNumber failed.");
635 valEntry = new gdcmValEntry(currentEntry);
636 if ( !AddEntry(valEntry))
638 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
639 " failed allthough this is a creation.");
644 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
647 // We need to promote the gdcmDocEntry to a gdcmValEntry:
648 valEntry = new gdcmValEntry(currentEntry);
649 if (!RemoveEntry(currentEntry))
651 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
652 " of previous DocEntry failed.");
655 if ( !AddEntry(valEntry))
657 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
658 " promoted ValEntry failed.");
664 SetEntryByNumber(value, group, elem);
670 * \brief Modifies the value of a given Header Entry (Dicom Element)
671 * when it exists. Create it with the given value when unexistant.
672 * @param voidArea (binary) value to be set
673 * @param Group Group number of the Entry
674 * @param Elem Element number of the Entry
675 * \return pointer to the modified/created Header Entry (NULL when creation
678 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
685 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
688 a = NewBinEntryByNumber(group, elem);
694 b = new gdcmBinEntry(a);
696 b->SetVoidArea(voidArea);
698 SetEntryByNumber(voidArea, lgth, group, elem);
699 //b->SetVoidArea(voidArea); //what if b == 0 !!
705 * \brief Set a new value if the invoked element exists
706 * Seems to be useless !!!
707 * @param Value new element value
708 * @param Group group number of the Entry
709 * @param Elem element number of the Entry
712 bool gdcmDocument::ReplaceIfExistByNumber(const char* value, uint16_t group,
715 const std::string v = value;
716 SetEntryByNumber(v, group, elem);
721 //-----------------------------------------------------------------------------
725 * \brief Checks if a given Dicom Element exists within the H table
726 * @param group Group number of the searched Dicom Element
727 * @param element Element number of the searched Dicom Element
728 * @return number of occurences
730 int gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
732 std::string key = gdcmDictEntry::TranslateToKey(group, element );
733 return TagHT.count(key);
737 * \brief Searches within Header Entries (Dicom Elements) parsed with
738 * the public and private dictionaries
739 * for the element value of a given tag.
740 * \warning Don't use any longer : use GetPubEntryByName
741 * @param tagName name of the searched element.
742 * @return Corresponding element value when it exists,
743 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
745 std::string gdcmDocument::GetEntryByName(TagName tagName)
747 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
753 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
757 * \brief Searches within Header Entries (Dicom Elements) parsed with
758 * the public and private dictionaries
759 * for the element value representation of a given tag.
761 * Obtaining the VR (Value Representation) might be needed by caller
762 * to convert the string typed content to caller's native type
763 * (think of C++ vs Python). The VR is actually of a higher level
764 * of semantics than just the native C++ type.
765 * @param tagName name of the searched element.
766 * @return Corresponding element value representation when it exists,
767 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
769 std::string gdcmDocument::GetEntryVRByName(TagName tagName)
771 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
772 if( dictEntry == NULL)
777 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
778 dictEntry->GetElement());
779 return elem->GetVR();
784 * \brief Searches within Header Entries (Dicom Elements) parsed with
785 * the public and private dictionaries
786 * for the element value representation of a given tag.
787 * @param group Group number of the searched tag.
788 * @param element Element number of the searched tag.
789 * @return Corresponding element value representation when it exists,
790 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
792 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
794 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
795 /// \todo use map methods, instead of multimap JPR
796 if ( !TagHT.count(key))
801 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
805 * \brief Searches within Header Entries (Dicom Elements) parsed with
806 * the public and private dictionaries
807 * for the element value representation of a given tag..
809 * Obtaining the VR (Value Representation) might be needed by caller
810 * to convert the string typed content to caller's native type
811 * (think of C++ vs Python). The VR is actually of a higher level
812 * of semantics than just the native C++ type.
813 * @param group Group number of the searched tag.
814 * @param element Element number of the searched tag.
815 * @return Corresponding element value representation when it exists,
816 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
818 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
820 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
825 return elem->GetVR();
829 * \brief Searches within Header Entries (Dicom Elements) parsed with
830 * the public and private dictionaries
831 * for the value length of a given tag..
832 * @param group Group number of the searched tag.
833 * @param element Element number of the searched tag.
834 * @return Corresponding element length; -2 if not found
836 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
838 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
841 return -2; //magic number
843 return elem->GetLength();
846 * \brief Sets the value (string) of the Header Entry (Dicom Element)
847 * @param content string value of the Dicom Element
848 * @param tagName name of the searched Dicom Element.
849 * @return true when found
851 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName)
853 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
859 return SetEntryByNumber(content,dictEntry->GetGroup(),
860 dictEntry->GetElement());
864 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
865 * through it's (group, element) and modifies it's content with
867 * @param content new value (string) to substitute with
868 * @param group group number of the Dicom Element to modify
869 * @param element element number of the Dicom Element to modify
871 bool gdcmDocument::SetEntryByNumber(std::string content,
875 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
878 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
879 " ValEntry (try promotion first).");
882 // Non even content must be padded with a space (020H)...
883 if( content.length() % 2 )
885 content += '\0'; // ... therefore we padd with (000H) .!?!
887 valEntry->SetValue(content);
889 // Integers have a special treatement for their length:
890 gdcmVRKey vr = valEntry->GetVR();
891 if( vr == "US" || vr == "SS" )
893 valEntry->SetLength(2);
895 else if( vr == "UL" || vr == "SL" )
897 valEntry->SetLength(4);
901 valEntry->SetLength(content.length());
908 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
909 * through it's (group, element) and modifies it's content with
911 * @param content new value (void *) to substitute with
912 * @param lgth new value length
913 * @param group group number of the Dicom Element to modify
914 * @param element element number of the Dicom Element to modify
916 bool gdcmDocument::SetEntryByNumber(void *content,
921 (void)lgth; //not used
922 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
923 if ( !TagHT.count(key))
928 /* Hope Binary field length is *never* wrong
929 if(lgth%2) // Non even length are padded with a space (020H).
932 //content = content + '\0'; // fing a trick to enlarge a binary field?
936 a = (gdcmBinEntry *)TagHT[key];
937 a->SetVoidArea(content);
938 //a->SetLength(lgth); // ???
943 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
944 * in the PubDocEntrySet of this instance
945 * through it's (group, element) and modifies it's length with
947 * \warning Use with extreme caution.
948 * @param l new length to substitute with
949 * @param group group number of the Entry to modify
950 * @param element element number of the Entry to modify
951 * @return true on success, false otherwise.
953 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
957 /// \todo use map methods, instead of multimap JPR
958 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
959 if ( !TagHT.count(key) )
965 l++; // length must be even
967 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
973 * \brief Gets (from Header) the offset of a 'non string' element value
974 * (LoadElementValues has already be executed)
975 * @param Group group number of the Entry
976 * @param Elem element number of the Entry
977 * @return File Offset of the Element Value
979 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
981 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
984 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
987 return entry->GetOffset();
991 * \brief Gets (from Header) a 'non string' element value
992 * (LoadElementValues has already be executed)
993 * @param Group group number of the Entry
994 * @param Elem element number of the Entry
995 * @return Pointer to the 'non string' area
997 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
999 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1002 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1005 return ((gdcmBinEntry *)entry)->GetVoidArea();
1009 * \brief Loads (from disk) the element content
1010 * when a string is not suitable
1011 * @param Group group number of the Entry
1012 * @param Elem element number of the Entry
1014 void *gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1016 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1021 size_t o =(size_t)docElement->GetOffset();
1022 fseek(Fp, o, SEEK_SET);
1023 size_t l = docElement->GetLength();
1024 char* a = new char[l];
1027 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1030 size_t l2 = fread(a, 1, l , Fp);
1036 /// \todo Drop any already existing void area! JPR
1037 SetEntryVoidAreaByNumber(a, group, elem);
1042 * \brief Loads (from disk) the element content
1043 * when a string is not suitable
1044 * @param Element Entry whose voidArea is going to be loaded
1046 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1048 size_t o =(size_t)element->GetOffset();
1049 fseek(Fp, o, SEEK_SET);
1050 size_t l = element->GetLength();
1051 char* a = new char[l];
1054 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1057 element->SetVoidArea((void *)a);
1058 /// \todo check the result
1059 size_t l2 = fread(a, 1, l , Fp);
1070 * \brief Sets a 'non string' value to a given Dicom Element
1071 * @param area area containing the 'non string' value
1072 * @param group Group number of the searched Dicom Element
1073 * @param element Element number of the searched Dicom Element
1076 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1080 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1081 if ( !TagHT.count(key))
1085 // This was for multimap ?
1086 (( gdcmBinEntry *)( ((TagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1092 * \brief Update the entries with the shadow dictionary.
1093 * Only non even entries are analyzed
1095 void gdcmDocument::UpdateShaEntries()
1097 //gdcmDictEntry *entry;
1100 /// \todo TODO : still any use to explore recursively the whole structure?
1102 for(ListTag::iterator it=listEntries.begin();
1103 it!=listEntries.end();
1106 // Odd group => from public dictionary
1107 if((*it)->GetGroup()%2==0)
1110 // Peer group => search the corresponding dict entry
1112 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1116 if((*it)->IsImplicitVR())
1121 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1123 // Set the new entry and the new value
1124 (*it)->SetDictEntry(entry);
1125 CheckDocEntryVR(*it,vr);
1127 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1132 // Remove precedent value transformation
1133 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1140 * \brief Searches within the Header Entries for a Dicom Element of
1142 * @param tagName name of the searched Dicom Element.
1143 * @return Corresponding Dicom Element when it exists, and NULL
1146 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1148 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1154 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1158 * \brief retrieves a Dicom Element (the first one) using (group, element)
1159 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1160 * if you think it's NOT UNIQUE, check the count number
1161 * and use iterators to retrieve ALL the Dicoms Elements within
1162 * a given couple (group, element)
1163 * @param group Group number of the searched Dicom Element
1164 * @param element Element number of the searched Dicom Element
1167 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1170 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1171 if ( !TagHT.count(key))
1175 return TagHT.find(key)->second;
1179 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1180 * returns a result when the corresponding entry is of type
1182 * @return When present, the corresponding ValEntry.
1184 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1187 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1188 if ( !currentEntry )
1192 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1196 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1202 * \brief Loads the element while preserving the current
1203 * underlying file position indicator as opposed to
1204 * to LoadDocEntry that modifies it.
1205 * @param entry Header Entry whose value shall be loaded.
1208 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1210 long PositionOnEntry = ftell(Fp);
1211 LoadDocEntry(entry);
1212 fseek(Fp, PositionOnEntry, SEEK_SET);
1216 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1218 * @return The properly swaped 32 bits integer.
1220 uint32_t gdcmDocument::SwapLong(uint32_t a)
1227 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1228 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1232 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1236 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1239 std::cout << "swapCode= " << SwapCode << std::endl;
1240 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1247 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1249 * @return The properly unswaped 32 bits integer.
1251 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1257 * \brief Swaps the bytes so they agree with the processor order
1258 * @return The properly swaped 16 bits integer.
1260 uint16_t gdcmDocument::SwapShort(uint16_t a)
1262 if ( SwapCode == 4321 || SwapCode == 2143 )
1264 a =((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1270 * \brief Unswaps the bytes so they agree with the processor order
1271 * @return The properly unswaped 16 bits integer.
1273 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1275 return SwapShort(a);
1278 //-----------------------------------------------------------------------------
1282 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1283 * @return length of the parsed set.
1286 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1291 gdcmDocEntry *newDocEntry = 0;
1292 gdcmValEntry *newValEntry = 0;
1293 unsigned long l = 0;
1295 int depth = set->GetDepthLevel();
1298 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1302 newDocEntry = ReadNextDocEntry( );
1308 gdcmVRKey vr = newDocEntry->GetVR();
1312 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1315 newValEntry = new gdcmValEntry(newDocEntry->GetDictEntry());
1316 newValEntry->Copy(newDocEntry);
1317 newValEntry->SetDepthLevel(depth);
1318 set->AddEntry(newValEntry);
1319 LoadDocEntry(newValEntry);
1320 if (newValEntry->isItemDelimitor())
1324 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1331 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1333 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1334 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1335 "nor BinEntry. Probably unknown VR.");
1338 ////// BinEntry or UNKOWN VR:
1339 gdcmBinEntry *bn = new gdcmBinEntry(newDocEntry->GetDictEntry());
1340 bn->Copy(newDocEntry);
1345 if (newDocEntry->GetGroup() == 0x7fe0 &&
1346 newDocEntry->GetElement() == 0x0010 )
1348 if (newDocEntry->GetReadLength()==0xffffffff)
1350 // Broken US.3405.1.dcm
1351 Parse7FE0(); // to skip the pixels
1352 // (multipart JPEG/RLE are trouble makers)
1356 SkipToNextDocEntry(newDocEntry);
1357 l = newDocEntry->GetFullLength();
1362 // to be sure we are at the beginning
1363 SkipToNextDocEntry(newDocEntry);
1364 l = newDocEntry->GetFullLength();
1370 l = newDocEntry->GetReadLength();
1371 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1373 if ( l == 0xffffffff )
1382 // no other way to create it ...
1383 gdcmSeqEntry *sq = new gdcmSeqEntry(newDocEntry->GetDictEntry(),
1384 set->GetDepthLevel());
1385 sq->Copy(newDocEntry);
1386 sq->SetDelimitorMode(delim_mode);
1387 sq->SetDepthLevel(depth);
1390 { // Don't try to parse zero-length sequences
1391 long lgt = ParseSQ( sq,
1392 newDocEntry->GetOffset(),
1394 (void)lgt; //not used...
1397 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1405 return l; // Probably useless
1409 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1410 * @return parsed length for this level
1412 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1413 long offset, long l_max, bool delim_mode)
1415 int SQItemNumber = 0;
1417 //int depth = set->GetDepthLevel();
1418 //(void)depth; //not used
1422 gdcmDocEntry *newDocEntry = ReadNextDocEntry();
1425 // FIXME Should warn user
1430 if ( newDocEntry->isSequenceDelimitor() )
1432 set->SetSequenceDelimitationItem( newDocEntry );
1436 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1441 gdcmSQItem *itemSQ = new gdcmSQItem(set->GetDepthLevel());
1442 itemSQ->AddEntry(newDocEntry);
1443 unsigned int l = newDocEntry->GetReadLength();
1445 if ( l == 0xffffffff )
1454 int lgr = ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1455 (void)lgr; //FIXME not used
1457 set->AddEntry(itemSQ, SQItemNumber);
1459 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1465 int lgth = ftell(Fp) - offset;
1470 * \brief Loads the element content if its length doesn't exceed
1471 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1472 * @param Entry Header Entry (Dicom Element) to be dealt with
1474 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1477 uint16_t group = entry->GetGroup();
1478 std::string vr = entry->GetVR();
1479 uint32_t length = entry->GetLength();
1481 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1483 // A SeQuence "contains" a set of Elements.
1484 // (fffe e000) tells us an Element is beginning
1485 // (fffe e00d) tells us an Element just ended
1486 // (fffe e0dd) tells us the current SeQuence just ended
1487 if( group == 0xfffe )
1489 // NO more value field for SQ !
1493 // When the length is zero things are easy:
1496 ((gdcmValEntry *)entry)->SetValue("");
1500 // The elements whose length is bigger than the specified upper bound
1501 // are not loaded. Instead we leave a short notice of the offset of
1502 // the element content and it's length.
1504 std::ostringstream s;
1505 if (length > MaxSizeLoadEntry)
1507 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1509 s << "gdcm::NotLoaded (BinEntry)";
1510 s << " Address:" << (long)entry->GetOffset();
1511 s << " Length:" << entry->GetLength();
1512 s << " x(" << std::hex << entry->GetLength() << ")";
1513 binEntryPtr->SetValue(s.str());
1515 // to be sure we are at the end of the value ...
1516 fseek(Fp, (long)entry->GetOffset()+(long)entry->GetLength(), SEEK_SET);
1518 return; //FIXME FIXME FIXME FIXME ????
1520 // Be carefull : a BinEntry IS_A ValEntry ...
1521 if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1523 s << "gdcm::NotLoaded. (ValEntry)";
1524 s << " Address:" << (long)entry->GetOffset();
1525 s << " Length:" << entry->GetLength();
1526 s << " x(" << std::hex << entry->GetLength() << ")";
1527 valEntryPtr->SetValue(s.str());
1529 // to be sure we are at the end of the value ...
1530 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1535 // When we find a BinEntry not very much can be done :
1536 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1539 LoadEntryVoidArea(binEntryPtr);
1540 s << "gdcm::Loaded (BinEntry)";
1541 binEntryPtr->SetValue(s.str());
1545 /// \todo Any compacter code suggested (?)
1546 if ( IsDocEntryAnInteger(entry) )
1549 std::ostringstream s;
1551 // When short integer(s) are expected, read and convert the following
1552 // n *two characters properly i.e. consider them as short integers as
1553 // opposed to strings.
1554 // Elements with Value Multiplicity > 1
1555 // contain a set of integers (not a single one)
1556 if (vr == "US" || vr == "SS")
1559 NewInt = ReadInt16();
1563 for (int i=1; i < nbInt; i++)
1566 NewInt = ReadInt16();
1571 // See above comment on multiple integers (mutatis mutandis).
1572 else if (vr == "UL" || vr == "SL")
1575 NewInt = ReadInt32();
1579 for (int i=1; i < nbInt; i++)
1582 NewInt = ReadInt32();
1587 #ifdef GDCM_NO_ANSI_STRING_STREAM
1588 s << std::ends; // to avoid oddities on Solaris
1589 #endif //GDCM_NO_ANSI_STRING_STREAM
1591 ((gdcmValEntry *)entry)->SetValue(s.str());
1595 // We need an additional byte for storing \0 that is not on disk
1596 //std::string newValue(length,0);
1597 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1598 //rah !! I can't believe it could work, normally this is a const char* !!!
1599 char *str = new char[length+1];
1600 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1602 std::string newValue = str;
1604 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1606 if ( item_read != 1 )
1608 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1609 "unread element value");
1610 valEntry->SetValue("gdcm::UnRead");
1616 // Because of correspondance with the VR dic
1617 valEntry->SetValue(newValue);
1621 valEntry->SetValue(newValue);
1626 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1627 "Should have a ValEntry, here !");
1633 * \brief Find the value Length of the passed Header Entry
1634 * @param Entry Header Entry whose length of the value shall be loaded.
1636 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *entry)
1638 uint16_t element = entry->GetElement();
1639 std::string vr = entry->GetVR();
1643 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1645 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1647 // The following reserved two bytes (see PS 3.5-2001, section
1648 // 7.1.2 Data element structure with explicit vr p27) must be
1649 // skipped before proceeding on reading the length on 4 bytes.
1650 fseek(Fp, 2L, SEEK_CUR);
1651 uint32_t length32 = ReadInt32();
1653 if ( vr == "OB" && length32 == 0xffffffff )
1655 uint32_t lengthOB = FindDocEntryLengthOB();
1658 // Computing the length failed (this happens with broken
1659 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1660 // chance to get the pixels by deciding the element goes
1661 // until the end of the file. Hence we artificially fix the
1662 // the length and proceed.
1663 long currentPosition = ftell(Fp);
1664 fseek(Fp,0L,SEEK_END);
1665 long lengthUntilEOF = ftell(Fp) - currentPosition;
1666 fseek(Fp, currentPosition, SEEK_SET);
1667 entry->SetLength(lengthUntilEOF);
1671 entry->SetLength(lengthOB);
1674 FixDocEntryFoundLength(entry, length32);
1678 // Length is encoded on 2 bytes.
1679 length16 = ReadInt16();
1681 // We can tell the current file is encoded in big endian (like
1682 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1683 // and it's value is the one of the encoding of a big endian file.
1684 // In order to deal with such big endian encoded files, we have
1685 // (at least) two strategies:
1686 // * when we load the "Transfer Syntax" tag with value of big endian
1687 // encoding, we raise the proper flags. Then we wait for the end
1688 // of the META group (0x0002) among which is "Transfer Syntax",
1689 // before switching the swap code to big endian. We have to postpone
1690 // the switching of the swap code since the META group is fully encoded
1691 // in little endian, and big endian coding only starts at the next
1692 // group. The corresponding code can be hard to analyse and adds
1693 // many additional unnecessary tests for regular tags.
1694 // * the second strategy consists in waiting for trouble, that shall
1695 // appear when we find the first group with big endian encoding. This
1696 // is easy to detect since the length of a "Group Length" tag (the
1697 // ones with zero as element number) has to be of 4 (0x0004). When we
1698 // encounter 1024 (0x0400) chances are the encoding changed and we
1699 // found a group with big endian encoding.
1700 // We shall use this second strategy. In order to make sure that we
1701 // can interpret the presence of an apparently big endian encoded
1702 // length of a "Group Length" without committing a big mistake, we
1703 // add an additional check: we look in the already parsed elements
1704 // for the presence of a "Transfer Syntax" whose value has to be "big
1705 // endian encoding". When this is the case, chances are we have got our
1706 // hands on a big endian encoded file: we switch the swap code to
1707 // big endian and proceed...
1708 if ( (element == 0x0000) && (length16 == 0x0400) )
1710 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1712 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1717 SwitchSwapToBigEndian();
1718 // Restore the unproperly loaded values i.e. the group, the element
1719 // and the dictionary entry depending on them.
1720 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1721 uint16_t correctElem = SwapShort( entry->GetElement() );
1722 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1726 // This correct tag is not in the dictionary. Create a new one.
1727 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1729 // FIXME this can create a memory leaks on the old entry that be
1730 // left unreferenced.
1731 entry->SetDictEntry( newTag );
1734 // Heuristic: well, some files are really ill-formed.
1735 if ( length16 == 0xffff)
1738 // Length16= 0xffff means that we deal with
1739 // 'Unknown Length' Sequence
1741 FixDocEntryFoundLength(entry, (uint32_t)length16);
1746 // Either implicit VR or a non DICOM conformal (see note below) explicit
1747 // VR that ommited the VR of (at least) this element. Farts happen.
1748 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1749 // on Data elements "Implicit and Explicit VR Data Elements shall
1750 // not coexist in a Data Set and Data Sets nested within it".]
1751 // Length is on 4 bytes.
1753 FixDocEntryFoundLength(entry, ReadInt32());
1759 * \brief Find the Value Representation of the current Dicom Element.
1762 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1764 if ( Filetype != gdcmExplicitVR )
1771 long positionOnEntry = ftell(Fp);
1772 // Warning: we believe this is explicit VR (Value Representation) because
1773 // we used a heuristic that found "UL" in the first tag. Alas this
1774 // doesn't guarantee that all the tags will be in explicit VR. In some
1775 // cases (see e-film filtered files) one finds implicit VR tags mixed
1776 // within an explicit VR file. Hence we make sure the present tag
1777 // is in explicit VR and try to fix things if it happens not to be
1780 fread (&vr, (size_t)2,(size_t)1, Fp);
1783 if( !CheckDocEntryVR(entry, vr) )
1785 fseek(Fp, positionOnEntry, SEEK_SET);
1786 // When this element is known in the dictionary we shall use, e.g. for
1787 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1788 // dictionary entry. Still we have to flag the element as implicit since
1789 // we know now our assumption on expliciteness is not furfilled.
1791 if ( entry->IsVRUnknown() )
1793 entry->SetVR("Implicit");
1795 entry->SetImplicitVR();
1800 * \brief Check the correspondance between the VR of the header entry
1801 * and the taken VR. If they are different, the header entry is
1802 * updated with the new VR.
1803 * @param Entry Header Entry to check
1804 * @param vr Dicom Value Representation
1805 * @return false if the VR is incorrect of if the VR isn't referenced
1806 * otherwise, it returns true
1808 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1810 char msg[100]; // for sprintf
1811 bool realExplicit = true;
1813 // Assume we are reading a falsely explicit VR file i.e. we reached
1814 // a tag where we expect reading a VR but are in fact we read the
1815 // first to bytes of the length. Then we will interogate (through find)
1816 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1817 // both GCC and VC++ implementations of the STL map. Hence when the
1818 // expected VR read happens to be non-ascii characters we consider
1819 // we hit falsely explicit VR tag.
1821 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1823 realExplicit = false;
1826 // CLEANME searching the dicom_vr at each occurence is expensive.
1827 // PostPone this test in an optional integrity check at the end
1828 // of parsing or only in debug mode.
1829 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1831 realExplicit = false;
1834 if ( !realExplicit )
1836 // We thought this was explicit VR, but we end up with an
1837 // implicit VR tag. Let's backtrack.
1838 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1839 entry->GetGroup(), entry->GetElement());
1840 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1842 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1844 // Group length is UL !
1845 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1846 entry->GetGroup(), entry->GetElement(),
1847 "UL", "FIXME", "Group Length");
1848 entry->SetDictEntry( newEntry );
1853 if ( entry->IsVRUnknown() )
1855 // When not a dictionary entry, we can safely overwrite the VR.
1856 if( entry->GetElement() == 0x0000 )
1858 // Group length is UL !
1866 else if ( entry->GetVR() != vr )
1868 // The VR present in the file and the dictionary disagree. We assume
1869 // the file writer knew best and use the VR of the file. Since it would
1870 // be unwise to overwrite the VR of a dictionary (since it would
1871 // compromise it's next user), we need to clone the actual DictEntry
1872 // and change the VR for the read one.
1873 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1874 entry->GetGroup(), entry->GetElement(),
1875 vr, "FIXME", entry->GetName());
1876 entry->SetDictEntry(newEntry);
1883 * \brief Get the transformed value of the header entry. The VR value
1884 * is used to define the transformation to operate on the value
1885 * \warning NOT end user intended method !
1887 * @return Transformed entry value
1889 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1891 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1893 std::string val = ((gdcmValEntry *)entry)->GetValue();
1894 std::string vr = entry->GetVR();
1895 uint32_t length = entry->GetLength();
1896 std::ostringstream s;
1899 // When short integer(s) are expected, read and convert the following
1900 // n * 2 bytes properly i.e. as a multivaluated strings
1901 // (each single value is separated fromthe next one by '\'
1902 // as usual for standard multivaluated filels
1903 // Elements with Value Multiplicity > 1
1904 // contain a set of short integers (not a single one)
1906 if( vr == "US" || vr == "SS" )
1911 for (int i=0; i < nbInt; i++)
1917 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1918 newInt16 = SwapShort( newInt16 );
1923 // When integer(s) are expected, read and convert the following
1924 // n * 4 bytes properly i.e. as a multivaluated strings
1925 // (each single value is separated fromthe next one by '\'
1926 // as usual for standard multivaluated filels
1927 // Elements with Value Multiplicity > 1
1928 // contain a set of integers (not a single one)
1929 else if( vr == "UL" || vr == "SL" )
1934 for (int i=0; i < nbInt; i++)
1940 newInt32 = ( val[4*i+0] & 0xFF )
1941 + (( val[4*i+1] & 0xFF ) << 8 )
1942 + (( val[4*i+2] & 0xFF ) << 16 )
1943 + (( val[4*i+3] & 0xFF ) << 24 );
1944 newInt32 = SwapLong( newInt32 );
1948 #ifdef GDCM_NO_ANSI_STRING_STREAM
1949 s << std::ends; // to avoid oddities on Solaris
1950 #endif //GDCM_NO_ANSI_STRING_STREAM
1954 return ((gdcmValEntry *)entry)->GetValue();
1958 * \brief Get the reverse transformed value of the header entry. The VR
1959 * value is used to define the reverse transformation to operate on
1961 * \warning NOT end user intended method !
1963 * @return Reverse transformed entry value
1965 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1967 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1969 std::string vr = entry->GetVR();
1970 std::vector<std::string> tokens;
1971 std::ostringstream s;
1973 if ( vr == "US" || vr == "SS" )
1977 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1978 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1979 for (unsigned int i=0; i<tokens.size(); i++)
1981 newInt16 = atoi(tokens[i].c_str());
1982 s << ( newInt16 & 0xFF )
1983 << (( newInt16 >> 8 ) & 0xFF );
1987 if ( vr == "UL" || vr == "SL")
1991 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1992 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1993 for (unsigned int i=0; i<tokens.size();i++)
1995 newInt32 = atoi(tokens[i].c_str());
1996 s << (char)( newInt32 & 0xFF )
1997 << (char)(( newInt32 >> 8 ) & 0xFF )
1998 << (char)(( newInt32 >> 16 ) & 0xFF )
1999 << (char)(( newInt32 >> 24 ) & 0xFF );
2004 #ifdef GDCM_NO_ANSI_STRING_STREAM
2005 s << std::ends; // to avoid oddities on Solaris
2006 #endif //GDCM_NO_ANSI_STRING_STREAM
2010 return ((gdcmValEntry *)entry)->GetValue();
2014 * \brief Skip a given Header Entry
2015 * \warning NOT end user intended method !
2018 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2020 SkipBytes(entry->GetLength());
2024 * \brief Skips to the begining of the next Header Entry
2025 * \warning NOT end user intended method !
2028 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2030 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2031 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2035 * \brief When the length of an element value is obviously wrong (because
2036 * the parser went Jabberwocky) one can hope improving things by
2037 * applying some heuristics.
2039 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2040 uint32_t foundLength)
2042 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2043 if ( foundLength == 0xffffffff)
2048 uint16_t gr = entry->GetGroup();
2049 uint16_t el = entry->GetElement();
2051 if ( foundLength % 2)
2053 std::ostringstream s;
2054 s << "Warning : Tag with uneven length "
2056 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2057 dbg.Verbose(0, s.str().c_str());
2060 //////// Fix for some naughty General Electric images.
2061 // Allthough not recent many such GE corrupted images are still present
2062 // on Creatis hard disks. Hence this fix shall remain when such images
2063 // are no longer in user (we are talking a few years, here)...
2064 // Note: XMedCom probably uses such a trick since it is able to read
2065 // those pesky GE images ...
2066 if ( foundLength == 13)
2068 // Only happens for this length !
2069 if ( entry->GetGroup() != 0x0008
2070 || ( entry->GetElement() != 0x0070
2071 && entry->GetElement() != 0x0080 ) )
2074 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2078 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2079 // Occurence of such images is quite low (unless one leaves close to a
2080 // 'Leonardo' source. Hence, one might consider commenting out the
2081 // following fix on efficiency reasons.
2082 else if ( entry->GetGroup() == 0x0009
2083 && ( entry->GetElement() == 0x1113
2084 || entry->GetElement() == 0x1114 ) )
2087 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2090 //////// Deal with sequences, but only on users request:
2091 else if ( entry->GetVR() == "SQ" && EnableSequences)
2093 foundLength = 0; // ReadLength is unchanged
2096 //////// We encountered a 'delimiter' element i.e. a tag of the form
2097 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2098 // taken into account.
2099 else if( entry->GetGroup() == 0xfffe )
2101 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2102 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2103 // causes extra troubles...
2104 if( entry->GetElement() != 0x0000 )
2110 entry->SetUsableLength(foundLength);
2114 * \brief Apply some heuristics to predict whether the considered
2115 * element value contains/represents an integer or not.
2116 * @param Entry The element value on which to apply the predicate.
2117 * @return The result of the heuristical predicate.
2119 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2121 uint16_t element = entry->GetElement();
2122 uint16_t group = entry->GetGroup();
2123 std::string vr = entry->GetVR();
2124 uint32_t length = entry->GetLength();
2126 // When we have some semantics on the element we just read, and if we
2127 // a priori know we are dealing with an integer, then we shall be
2128 // able to swap it's element value properly.
2129 if ( element == 0 ) // This is the group length of the group
2137 // Allthough this should never happen, still some images have a
2138 // corrupted group length [e.g. have a glance at offset x(8336) of
2139 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2140 // Since for dicom compliant and well behaved headers, the present
2141 // test is useless (and might even look a bit paranoid), when we
2142 // encounter such an ill-formed image, we simply display a warning
2143 // message and proceed on parsing (while crossing fingers).
2144 std::ostringstream s;
2145 int filePosition = ftell(Fp);
2146 s << "Erroneous Group Length element length on : (" \
2147 << std::hex << group << " , " << element
2148 << ") -before- position x(" << filePosition << ")"
2149 << "lgt : " << length;
2150 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2154 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2163 * \brief Find the Length till the next sequence delimiter
2164 * \warning NOT end user intended method !
2168 uint32_t gdcmDocument::FindDocEntryLengthOB()
2170 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2171 long positionOnEntry = ftell(Fp);
2172 bool foundSequenceDelimiter = false;
2173 uint32_t totalLength = 0;
2175 while ( !foundSequenceDelimiter )
2177 uint16_t g = ReadInt16();
2178 uint16_t n = ReadInt16();
2184 // We have to decount the group and element we just read
2187 if ( g != 0xfffe || ( n != 0xe0dd && n != 0xe000 ) )
2189 dbg.Verbose(1, "gdcmDocument::FindLengthOB: neither an Item tag "
2190 "nor a Sequence delimiter tag.");
2191 fseek(Fp, positionOnEntry, SEEK_SET);
2198 foundSequenceDelimiter = true;
2201 uint32_t itemLength = ReadInt32();
2202 // We add 4 bytes since we just read the ItemLength with ReadInt32
2203 totalLength += itemLength + 4;
2204 SkipBytes(itemLength);
2206 if ( foundSequenceDelimiter )
2211 fseek(Fp, positionOnEntry, SEEK_SET);
2216 * \brief Reads a supposed to be 16 Bits integer
2217 * (swaps it depending on processor endianity)
2218 * @return read value
2220 uint16_t gdcmDocument::ReadInt16()
2223 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2224 if ( item_read != 1 )
2228 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2239 * \brief Reads a supposed to be 32 Bits integer
2240 * (swaps it depending on processor endianity)
2241 * @return read value
2243 uint32_t gdcmDocument::ReadInt32()
2246 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2247 if ( item_read != 1 )
2251 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2262 * \brief skips bytes inside the source file
2263 * \warning NOT end user intended method !
2266 void gdcmDocument::SkipBytes(uint32_t nBytes)
2268 //FIXME don't dump the returned value
2269 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2273 * \brief Loads all the needed Dictionaries
2274 * \warning NOT end user intended method !
2276 void gdcmDocument::Initialise()
2278 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2283 * \brief Discover what the swap code is (among little endian, big endian,
2284 * bad little endian, bad big endian).
2286 * @return false when we are absolutely sure
2287 * it's neither ACR-NEMA nor DICOM
2288 * true when we hope ours assuptions are OK
2290 bool gdcmDocument::CheckSwap()
2292 // The only guaranted way of finding the swap code is to find a
2293 // group tag since we know it's length has to be of four bytes i.e.
2294 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2295 // occurs when we can't find such group...
2297 uint32_t x = 4; // x : for ntohs
2298 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2302 char deb[HEADER_LENGTH_TO_READ];
2304 // First, compare HostByteOrder and NetworkByteOrder in order to
2305 // determine if we shall need to swap bytes (i.e. the Endian type).
2306 if ( x == ntohs(x) )
2315 // The easiest case is the one of a DICOM header, since it possesses a
2316 // file preamble where it suffice to look for the string "DICM".
2317 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2318 (void)lgrLue; //FIXME not used
2320 char *entCur = deb + 128;
2321 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2323 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2325 // Next, determine the value representation (VR). Let's skip to the
2326 // first element (0002, 0000) and check there if we find "UL"
2327 // - or "OB" if the 1st one is (0002,0001) -,
2328 // in which case we (almost) know it is explicit VR.
2329 // WARNING: if it happens to be implicit VR then what we will read
2330 // is the length of the group. If this ascii representation of this
2331 // length happens to be "UL" then we shall believe it is explicit VR.
2332 // FIXME: in order to fix the above warning, we could read the next
2333 // element value (or a couple of elements values) in order to make
2334 // sure we are not commiting a big mistake.
2335 // We need to skip :
2336 // * the 128 bytes of File Preamble (often padded with zeroes),
2337 // * the 4 bytes of "DICM" string,
2338 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2339 // i.e. a total of 136 bytes.
2343 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2344 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2345 // *Implicit* VR. -and it is !-
2347 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2348 memcmp(entCur, "OB", (size_t)2) == 0 ||
2349 memcmp(entCur, "UI", (size_t)2) == 0 ||
2350 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2351 // when Write DCM *adds*
2353 // Use gdcmDocument::dicom_vr to test all the possibilities
2354 // instead of just checking for UL, OB and UI !? group 0000
2356 Filetype = gdcmExplicitVR;
2357 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2358 "explicit Value Representation");
2362 Filetype = gdcmImplicitVR;
2363 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2364 "not an explicit Value Representation");
2370 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2371 "HostByteOrder != NetworkByteOrder");
2376 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2377 "HostByteOrder = NetworkByteOrder");
2380 // Position the file position indicator at first tag (i.e.
2381 // after the file preamble and the "DICM" string).
2383 fseek (Fp, 132L, SEEK_SET);
2387 // Alas, this is not a DicomV3 file and whatever happens there is no file
2388 // preamble. We can reset the file position indicator to where the data
2389 // is (i.e. the beginning of the file).
2390 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2393 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2394 // By clean we mean that the length of the first tag is written down.
2395 // If this is the case and since the length of the first group HAS to be
2396 // four (bytes), then determining the proper swap code is straightforward.
2399 // We assume the array of char we are considering contains the binary
2400 // representation of a 32 bits integer. Hence the following dirty
2402 s32 = *((uint32_t *)(entCur));
2423 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2424 // It is time for despaired wild guesses.
2425 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2426 // i.e. the 'group length' element is not present :
2428 // check the supposed to be 'group number'
2429 // 0x0002 or 0x0004 or 0x0008
2430 // to determine ' SwapCode' value .
2431 // Only 0 or 4321 will be possible
2432 // (no oportunity to check for the formerly well known
2433 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2434 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2435 // the file IS NOT ACR-NEMA nor DICOM V3
2436 // Find a trick to tell it the caller...
2438 s16 = *((uint16_t *)(deb));
2455 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2456 "ACR/NEMA unfound swap info (Really hopeless !)");
2457 Filetype = gdcmUnknown;
2460 // Then the only info we have is the net2host one.
2470 * \brief Restore the unproperly loaded values i.e. the group, the element
2471 * and the dictionary entry depending on them.
2473 void gdcmDocument::SwitchSwapToBigEndian()
2475 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2476 "Switching to BigEndian mode.");
2477 if ( SwapCode == 0 )
2481 else if ( SwapCode == 4321 )
2485 else if ( SwapCode == 3412 )
2489 else if ( SwapCode == 2143 )
2496 * \brief during parsing, Header Elements too long are not loaded in memory
2499 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2505 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2507 MaxSizeLoadEntry = 0xffffffff;
2510 MaxSizeLoadEntry = newSize;
2515 * \brief Header Elements too long will not be printed
2516 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2519 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2521 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2526 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2528 MaxSizePrintEntry = 0xffffffff;
2531 MaxSizePrintEntry = newSize;
2537 * \brief Read the next tag but WITHOUT loading it's value
2538 * (read the 'Group Number', the 'Element Number',
2539 * gets the Dict Entry
2540 * gets the VR, gets the length, gets the offset value)
2541 * @return On succes the newly created DocEntry, NULL on failure.
2543 gdcmDocEntry *gdcmDocument::ReadNextDocEntry()
2545 uint16_t g = ReadInt16();
2546 uint16_t n = ReadInt16();
2550 // We reached the EOF (or an error occured) therefore
2551 // header parsing has to be considered as finished.
2554 gdcmDocEntry *newEntry = NewDocEntryByNumber(g, n);
2556 FindDocEntryVR(newEntry);
2557 FindDocEntryLength(newEntry);
2565 newEntry->SetOffset(ftell(Fp));
2572 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2573 * in the TagHt dictionary.
2574 * @param group The generated tag must belong to this group.
2575 * @return The element of tag with given group which is fee.
2577 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2579 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2581 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2582 if (TagHT.count(key) == 0)
2591 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2592 * is placed at the beginning of a tag check whether this
2593 * tag is (TestGroup, TestElement).
2594 * \warning On success the internal file pointer \ref gdcmDocument::fp
2595 * is modified to point after the tag.
2596 * On failure (i.e. when the tag wasn't the expected tag
2597 * (TestGroup, TestElement) the internal file pointer
2598 * \ref gdcmDocument::fp is restored to it's original position.
2599 * @param TestGroup The expected group of the tag.
2600 * @param TestElement The expected Element of the tag.
2601 * @return True on success, false otherwise.
2603 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2605 long positionOnEntry = ftell(Fp);
2606 long currentPosition = ftell(Fp); // On debugging purposes
2608 //// Read the Item Tag group and element, and make
2609 // sure they are what we expected:
2610 uint16_t itemTagGroup = ReadInt16();
2611 uint16_t itemTagElement = ReadInt16();
2612 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2614 std::ostringstream s;
2615 s << " We should have found tag (";
2616 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2617 s << " but instead we encountered tag (";
2618 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2620 s << " at address: " << (unsigned)currentPosition << std::endl;
2621 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2622 dbg.Verbose(0, s.str().c_str());
2623 fseek(Fp, positionOnEntry, SEEK_SET);
2631 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2632 * is placed at the beginning of a tag (TestGroup, TestElement),
2633 * read the length associated to the Tag.
2634 * \warning On success the internal file pointer \ref gdcmDocument::fp
2635 * is modified to point after the tag and it's length.
2636 * On failure (i.e. when the tag wasn't the expected tag
2637 * (TestGroup, TestElement) the internal file pointer
2638 * \ref gdcmDocument::fp is restored to it's original position.
2639 * @param TestGroup The expected group of the tag.
2640 * @param TestElement The expected Element of the tag.
2641 * @return On success returns the length associated to the tag. On failure
2644 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2646 long PositionOnEntry = ftell(Fp);
2647 (void)PositionOnEntry;
2649 if ( !ReadTag(testGroup, testElement) )
2654 //// Then read the associated Item Length
2655 long currentPosition = ftell(Fp);
2656 uint32_t itemLength = ReadInt32();
2658 std::ostringstream s;
2659 s << "Basic Item Length is: "
2660 << itemLength << std::endl;
2661 s << " at address: " << (unsigned)currentPosition << std::endl;
2662 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2668 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2669 * No other way so 'skip' the Data
2672 void gdcmDocument::Parse7FE0 ()
2674 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2677 // Should warn user FIXME
2681 if ( IsImplicitVRLittleEndianTransferSyntax()
2682 || IsExplicitVRLittleEndianTransferSyntax()
2683 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2684 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2689 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2691 //// Read the Basic Offset Table Item Tag length...
2692 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2694 //// ... and then read length[s] itself[themselves]. We don't use
2695 // the values read (BTW what is the purpous of those lengths ?)
2696 if ( itemLength != 0 )
2698 // BTW, what is the purpous of those length anyhow !?
2699 char* basicOffsetTableItemValue = new char[itemLength + 1];
2700 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2702 for (unsigned int i=0; i < itemLength; i += 4 )
2704 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2705 std::ostringstream s;
2706 s << " Read one length: ";
2707 s << std::hex << individualLength << std::endl;
2708 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2712 if ( ! IsRLELossLessTransferSyntax() )
2716 //// We then skip (not reading them) all the fragments of images:
2717 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2719 SkipBytes(itemLength);
2726 long rleSegmentLength[15], fragmentLength;
2728 // While we find some items:
2729 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2731 // Parse fragments of the current Fragment (Frame)
2732 //------------------ scanning (not reading) fragment pixels
2733 uint32_t nbRleSegments = ReadInt32();
2735 //// Reading RLE Segments Offset Table
2736 uint32_t rleSegmentOffsetTable[15];
2737 for(int k=1; k<=15; k++)
2739 ftellRes = ftell(Fp);
2740 rleSegmentOffsetTable[k] = ReadInt32();
2743 // skipping (not reading) RLE Segments
2744 if ( nbRleSegments > 1)
2746 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2748 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2749 - rleSegmentOffsetTable[k];
2750 ftellRes = ftell(Fp);
2751 SkipBytes(rleSegmentLength[k]);
2755 rleSegmentLength[nbRleSegments] = fragmentLength
2756 - rleSegmentOffsetTable[nbRleSegments];
2757 ftellRes = ftell(Fp);
2758 SkipBytes(rleSegmentLength[nbRleSegments]);
2761 // Make sure that at the end of the item we encounter a 'Sequence
2763 if ( ! ReadTag(0xfffe, 0xe0dd) )
2765 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2766 dbg.Verbose(0, " at end of RLE item sequence");
2774 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2775 * \warning Does NOT work with ACR-NEMA files
2776 * \todo Find a trick to solve the pb (use RET fields ?)
2778 * @return true if 'smaller'
2780 bool gdcmDocument::operator<(gdcmDocument &document)
2783 std::string s1 = this->GetEntryByNumber(0x0010,0x0010);
2784 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2796 s1 = this->GetEntryByNumber(0x0010,0x0020);
2797 s2 = document.GetEntryByNumber(0x0010,0x0020);
2808 // Study Instance UID
2809 s1 = this->GetEntryByNumber(0x0020,0x000d);
2810 s2 = document.GetEntryByNumber(0x0020,0x000d);
2821 // Serie Instance UID
2822 s1 = this->GetEntryByNumber(0x0020,0x000e);
2823 s2 = document.GetEntryByNumber(0x0020,0x000e);
2839 //-----------------------------------------------------------------------------