1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/07/06 09:50:52 $
7 Version: $Revision: 1.47 $
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 & inFilename,
98 bool exception_on_error,
99 bool enable_sequences,
101 : gdcmElementSet(-1) {
102 IgnoreShadow =ignore_shadow;
103 //enableSequences=enable_sequences;
104 (void)enable_sequences;
105 enableSequences=true; // JPR // TODO : remove params out of the constructor
106 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
107 Filename = inFilename;
110 if ( !OpenFile(exception_on_error))
113 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
117 fseek(fp,0L,SEEK_END);
118 long lgt = ftell(fp);
122 long beg = ftell(fp);
127 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
128 (void)l; //is l used anywhere ?
132 // Load 'non string' values
134 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
135 if( PhotometricInterpretation == "PALETTE COLOR " ) {
136 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
137 LoadEntryVoidArea(0x0028,0x1201); // R LUT
138 LoadEntryVoidArea(0x0028,0x1202); // G LUT
139 LoadEntryVoidArea(0x0028,0x1203); // B LUT
141 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
142 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
143 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
145 //FIXME later : how to use it?
146 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
150 // --------------------------------------------------------------
151 // Special Patch to allow gdcm to read ACR-LibIDO formated images
153 // if recognition code tells us we deal with a LibIDO image
154 // we switch lineNumber and columnNumber
157 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
158 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
159 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
160 // with "little-endian strings"
162 Filetype = gdcmACR_LIBIDO;
163 std::string rows = GetEntryByNumber(0x0028, 0x0010);
164 std::string columns = GetEntryByNumber(0x0028, 0x0011);
165 SetEntryByNumber(columns, 0x0028, 0x0010);
166 SetEntryByNumber(rows , 0x0028, 0x0011);
168 // ----------------- End of Special Patch ----------------
170 printLevel = 1; // 'Medium' print level by default
175 * @param exception_on_error
177 gdcmDocument::gdcmDocument(bool exception_on_error)
180 (void)exception_on_error;
181 //enableSequences=0; // ?!? JPR
183 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
186 printLevel = 1; // 'Medium' print level by default
190 * \brief Canonical destructor.
192 gdcmDocument::~gdcmDocument ()
197 // Recursive clean up of sequences
198 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
205 //-----------------------------------------------------------------------------
209 * \brief Prints The Dict Entries of THE public Dicom Dictionary
212 void gdcmDocument::PrintPubDict(std::ostream & os)
214 RefPubDict->Print(os);
218 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
221 void gdcmDocument::PrintShaDict(std::ostream & os)
223 RefShaDict->Print(os);
226 //-----------------------------------------------------------------------------
229 * \brief Get the public dictionary used
231 gdcmDict *gdcmDocument::GetPubDict()
237 * \brief Get the shadow dictionary used
239 gdcmDict *gdcmDocument::GetShaDict()
245 * \brief Set the shadow dictionary used
246 * \param dict dictionary to use in shadow
248 bool gdcmDocument::SetShaDict(gdcmDict *dict)
255 * \brief Set the shadow dictionary used
256 * \param dictName name of the dictionary to use in shadow
258 bool gdcmDocument::SetShaDict(DictKey dictName)
260 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
265 * \brief This predicate, based on hopefully reasonable heuristics,
266 * decides whether or not the current gdcmDocument was properly parsed
267 * and contains the mandatory information for being considered as
268 * a well formed and usable Dicom/Acr File.
269 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
272 bool gdcmDocument::IsReadable() {
274 if(Filetype==gdcmUnknown) {
275 std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
276 << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
277 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
282 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
292 * \brief Internal function that checks whether the Transfer Syntax given
293 * as argument is the one present in the current document.
294 * @param SyntaxToCheck The transfert syntax we need to check against.
295 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
296 * the current document. False either when the document contains
297 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
299 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
301 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
305 // The entry might be present but not loaded (parsing and loading
306 // happen at differente stages): try loading and proceed with check...
307 LoadDocEntrySafe(Entry);
308 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
310 std::string Transfer = ValEntry->GetValue();
311 // The actual transfer (as read from disk) might be padded. We
312 // first need to remove the potential padding. We can make the
313 // weak assumption that padding was not executed with digits...
314 while ( ! isdigit(Transfer[Transfer.length()-1]) )
316 Transfer.erase(Transfer.length()-1, 1);
318 if ( Transfer == SyntaxToCheck )
325 * \brief Determines if the Transfer Syntax of the present document
326 * corresponds to a Implicit Value Representation of
328 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
329 * @return True when ImplicitVRLittleEndian found. False in all other cases.
331 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
333 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
337 * \brief Determines if the Transfer Syntax was already encountered
338 * and if it corresponds to a ExplicitVRLittleEndian one.
339 * @return True when ExplicitVRLittleEndian found. False in all other cases.
341 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
343 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
347 * \brief Determines if the Transfer Syntax was already encountered
348 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
349 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
351 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
353 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
357 * \brief Determines if the Transfer Syntax was already encountered
358 * and if it corresponds to a Explicit VR Big Endian one.
359 * @return True when big endian found. False in all other cases.
361 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
363 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
367 * \brief Determines if the Transfer Syntax was already encountered
368 * and if it corresponds to a JPEGBaseLineProcess1 one.
369 * @return True when JPEGBaseLineProcess1found. False in all other cases.
371 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
373 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
377 * \brief Determines if the Transfer Syntax was already encountered
378 * and if it corresponds to a JPEGExtendedProcess2-4 one.
379 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
381 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
383 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
387 * \brief Determines if the Transfer Syntax was already encountered
388 * and if it corresponds to a JPEGExtendeProcess3-5 one.
389 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
391 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
393 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
397 * \brief Determines if the Transfer Syntax was already encountered
398 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
399 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
402 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
404 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
408 * \brief Determines if the Transfer Syntax was already encountered
409 * and if it corresponds to a RLE Lossless one.
410 * @return True when RLE Lossless found. False in all
413 bool gdcmDocument::IsRLELossLessTransferSyntax()
415 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
419 * \brief Determines if Transfer Syntax was already encountered
420 * and if it corresponds to a JPEG Lossless one.
421 * @return True when RLE Lossless found. False in all
425 bool gdcmDocument::IsJPEGLossless()
427 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
428 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
429 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
433 * \brief Determines if the Transfer Syntax was already encountered
434 * and if it corresponds to a JPEG2000 one
435 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
438 bool gdcmDocument::IsJPEG2000()
440 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
441 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
445 * \brief Predicate for dicom version 3 file.
446 * @return True when the file is a dicom version 3.
448 bool gdcmDocument::IsDicomV3()
450 // Checking if Transfert Syntax exists is enough
451 // Anyway, it's to late check if the 'Preamble' was found ...
452 // And ... would it be a rich idea to check ?
453 // (some 'no Preamble' DICOM images exist !)
454 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
458 * \brief returns the File Type
459 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
460 * @return the FileType code
462 FileType gdcmDocument::GetFileType()
468 * \brief opens the file
469 * @param exception_on_error
472 FILE *gdcmDocument::OpenFile(bool exception_on_error)
475 fp=fopen(Filename.c_str(),"rb");
479 if(exception_on_error)
480 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
483 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
492 fread(&zero, (size_t)2, (size_t)1, fp);
494 //ACR -- or DICOM with no Preamble --
495 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
499 fseek(fp, 126L, SEEK_CUR);
501 fread(dicm, (size_t)4, (size_t)1, fp);
502 if( memcmp(dicm, "DICM", 4) == 0 )
506 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
509 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
515 * \brief closes the file
516 * @return TRUE if the close was successfull
518 bool gdcmDocument::CloseFile()
520 int closed = fclose(fp);
528 * \brief Writes in a file all the Header Entries (Dicom Elements)
529 * @param fp file pointer on an already open file
530 * @param filetype Type of the File to be written
531 * (ACR-NEMA, ExplicitVR, ImplicitVR)
532 * \return Always true.
534 void gdcmDocument::Write(FILE* fp,FileType filetype)
537 /// \todo move the following lines (and a lot of others, to be written)
538 /// to a future function CheckAndCorrectHeader
540 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
541 /// no way (check : FileType est un champ de gdcmDocument ...)
542 /// a moins de se livrer a un tres complique ajout des champs manquants.
543 /// faire un CheckAndCorrectHeader (?)
545 if (filetype == gdcmImplicitVR)
547 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
548 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
550 /// \todo Refer to standards on page 21, chapter 6.2
551 /// "Value representation": values with a VR of UI shall be
552 /// padded with a single trailing null
553 /// in the following case we have to padd manually with a 0
555 SetEntryLengthByNumber(18, 0x0002, 0x0010);
558 if (filetype == gdcmExplicitVR)
560 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
561 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
563 /// \todo Refer to standards on page 21, chapter 6.2
564 /// "Value representation": values with a VR of UI shall be
565 /// padded with a single trailing null
566 /// Dans le cas suivant on doit pader manuellement avec un 0
568 SetEntryLengthByNumber(20, 0x0002, 0x0010);
572 * \todo rewrite later, if really usefull
573 * - 'Group Length' element is optional in DICOM
574 * - but un-updated odd groups lengthes can causes pb
577 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
578 * UpdateGroupLength(false,filetype);
579 * if ( filetype == ACR)
580 * UpdateGroupLength(true,ACR);
583 gdcmElementSet::Write(fp,filetype); // This one is recursive
588 * \brief Modifies the value of a given Header Entry (Dicom Element)
589 * when it exists. Create it with the given value when unexistant.
590 * @param Value (string) Value to be set
591 * @param Group Group number of the Entry
592 * @param Elem Element number of the Entry
593 * \return pointer to the modified/created Header Entry (NULL when creation
597 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
602 gdcmDocEntry* CurrentEntry;
603 gdcmValEntry* ValEntry;
605 CurrentEntry = GetDocEntryByNumber( Group, Elem);
608 // The entry wasn't present and we simply create the required ValEntry:
609 CurrentEntry = NewDocEntryByNumber(Group, Elem);
612 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
613 " NewDocEntryByNumber failed.");
616 ValEntry = new gdcmValEntry(CurrentEntry);
617 if ( !AddEntry(ValEntry))
619 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
620 " failed allthough this is a creation.");
625 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
628 // We need to promote the gdcmDocEntry to a gdcmValEntry:
629 ValEntry = new gdcmValEntry(CurrentEntry);
630 if (!RemoveEntry(CurrentEntry))
632 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
633 " of previous DocEntry failed.");
636 if ( !AddEntry(ValEntry))
638 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
639 " promoted ValEntry failed.");
645 SetEntryByNumber(Value, Group, Elem);
651 * \brief Modifies the value of a given Header Entry (Dicom Element)
652 * when it exists. Create it with the given value when unexistant.
653 * @param voidArea (binary) value to be set
654 * @param Group Group number of the Entry
655 * @param Elem Element number of the Entry
656 * \return pointer to the modified/created Header Entry (NULL when creation
659 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
667 a = GetDocEntryByNumber( Group, Elem);
669 a =NewBinEntryByNumber(Group, Elem);
673 b = new gdcmBinEntry(a);
676 SetEntryByNumber(voidArea, lgth, Group, Elem);
677 b->SetVoidArea(voidArea);
683 * \brief Set a new value if the invoked element exists
684 * Seems to be useless !!!
685 * @param Value new element value
686 * @param Group group number of the Entry
687 * @param Elem element number of the Entry
690 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, uint16_t Group,
693 std::string v = Value;
694 SetEntryByNumber(v, Group, Elem);
698 //-----------------------------------------------------------------------------
702 * \brief Checks if a given Dicom Element exists within the H table
703 * @param group Group number of the searched Dicom Element
704 * @param element Element number of the searched Dicom Element
705 * @return number of occurences
707 int gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
709 std::string key = gdcmDictEntry::TranslateToKey(group, element );
710 return tagHT.count(key);
714 * \brief Searches within Header Entries (Dicom Elements) parsed with
715 * the public and private dictionaries
716 * for the element value of a given tag.
717 * \warning Don't use any longer : use GetPubEntryByName
718 * @param tagName name of the searched element.
719 * @return Corresponding element value when it exists,
720 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
722 std::string gdcmDocument::GetEntryByName(TagName tagName)
724 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
725 if( dictEntry == NULL)
728 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
732 * \brief Searches within Header Entries (Dicom Elements) parsed with
733 * the public and private dictionaries
734 * for the element value representation of a given tag.
736 * Obtaining the VR (Value Representation) might be needed by caller
737 * to convert the string typed content to caller's native type
738 * (think of C++ vs Python). The VR is actually of a higher level
739 * of semantics than just the native C++ type.
740 * @param tagName name of the searched element.
741 * @return Corresponding element value representation when it exists,
742 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
744 std::string gdcmDocument::GetEntryVRByName(TagName tagName)
746 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
747 if( dictEntry == NULL)
750 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
751 dictEntry->GetElement());
752 return elem->GetVR();
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.
760 * @param group Group number of the searched tag.
761 * @param element Element number of the searched tag.
762 * @return Corresponding element value representation when it exists,
763 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
765 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
767 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
768 /// \todo use map methods, instead of multimap JPR
769 if ( ! tagHT.count(key))
771 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
775 * \brief Searches within Header Entries (Dicom Elements) parsed with
776 * the public and private dictionaries
777 * for the element value representation of a given tag..
779 * Obtaining the VR (Value Representation) might be needed by caller
780 * to convert the string typed content to caller's native type
781 * (think of C++ vs Python). The VR is actually of a higher level
782 * of semantics than just the native C++ type.
783 * @param group Group number of the searched tag.
784 * @param element Element number of the searched tag.
785 * @return Corresponding element value representation when it exists,
786 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
788 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
790 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
793 return elem->GetVR();
797 * \brief Searches within Header Entries (Dicom Elements) parsed with
798 * the public and private dictionaries
799 * for the value length of a given tag..
800 * @param group Group number of the searched tag.
801 * @param element Element number of the searched tag.
802 * @return Corresponding element length; -2 if not found
804 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
806 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
809 return elem->GetLength();
812 * \brief Sets the value (string) of the Header Entry (Dicom Element)
813 * @param content string value of the Dicom Element
814 * @param tagName name of the searched Dicom Element.
815 * @return true when found
817 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName)
819 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
820 if( dictEntry == NULL)
823 return SetEntryByNumber(content,dictEntry->GetGroup(),
824 dictEntry->GetElement());
828 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
829 * through it's (group, element) and modifies it's content with
831 * @param content new value (string) to substitute with
832 * @param group group number of the Dicom Element to modify
833 * @param element element number of the Dicom Element to modify
835 bool gdcmDocument::SetEntryByNumber(std::string content,
839 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
842 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
843 " ValEntry (try promotion first).");
846 // Non even content must be padded with a space (020H).
847 if((content.length())%2) {
848 content = content + '\0';
850 ValEntry->SetValue(content);
852 // Integers have a special treatement for their length:
853 gdcmVRKey vr = ValEntry->GetVR();
854 if( (vr == "US") || (vr == "SS") )
855 ValEntry->SetLength(2);
856 else if( (vr == "UL") || (vr == "SL") )
857 ValEntry->SetLength(4);
859 ValEntry->SetLength(content.length());
865 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
866 * through it's (group, element) and modifies it's content with
868 * @param content new value (void *) to substitute with
869 * @param lgth new value length
870 * @param group group number of the Dicom Element to modify
871 * @param element element number of the Dicom Element to modify
873 bool gdcmDocument::SetEntryByNumber(void *content,
878 (void)lgth; //not used
879 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
880 if ( ! tagHT.count(key))
883 /* Hope Binaray field length is *never* wrong
884 if(lgth%2) // Non even length are padded with a space (020H).
887 //content = content + '\0'; // fing a trick to enlarge a binary field?
891 a = (gdcmBinEntry *)tagHT[key];
892 a->SetVoidArea(content);
893 //a->SetLength(lgth); // ???
898 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
899 * in the PubDocEntrySet of this instance
900 * through it's (group, element) and modifies it's length with
902 * \warning Use with extreme caution.
903 * @param l new length to substitute with
904 * @param group group number of the Entry to modify
905 * @param element element number of the Entry to modify
906 * @return true on success, false otherwise.
908 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
912 /// \todo use map methods, instead of multimap JPR
913 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
914 if ( ! tagHT.count(key))
916 if (l%2) l++; // length must be even
917 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
923 * \brief Gets (from Header) the offset of a 'non string' element value
924 * (LoadElementValues has already be executed)
925 * @param Group group number of the Entry
926 * @param Elem element number of the Entry
927 * @return File Offset of the Element Value
929 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t Group, uint16_t Elem)
931 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
934 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
937 return Entry->GetOffset();
941 * \brief Gets (from Header) a 'non string' element value
942 * (LoadElementValues has already be executed)
943 * @param Group group number of the Entry
944 * @param Elem element number of the Entry
945 * @return Pointer to the 'non string' area
947 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t Group, uint16_t Elem)
949 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
952 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
955 return ((gdcmBinEntry *)Entry)->GetVoidArea();
959 * \brief Loads (from disk) the element content
960 * when a string is not suitable
961 * @param Group group number of the Entry
962 * @param Elem element number of the Entry
964 void *gdcmDocument::LoadEntryVoidArea(uint16_t Group, uint16_t Elem)
966 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
969 size_t o =(size_t)Element->GetOffset();
970 fseek(fp, o, SEEK_SET);
971 size_t l = Element->GetLength();
972 char* a = new char[l];
974 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
977 size_t l2 = fread(a, 1, l ,fp);
983 /// \todo Drop any allready existing void area! JPR
984 SetEntryVoidAreaByNumber(a, Group, Elem);
988 * \brief Loads (from disk) the element content
989 * when a string is not suitable
990 * @param Element Entry whose voidArea is going to be loaded
992 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
994 size_t o =(size_t)Element->GetOffset();
995 fseek(fp, o, SEEK_SET);
996 size_t l = Element->GetLength();
997 char* a = new char[l];
999 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1002 Element->SetVoidArea((void *)a);
1003 /// \todo check the result
1004 size_t l2 = fread(a, 1, l ,fp);
1014 * \brief Sets a 'non string' value to a given Dicom Element
1015 * @param area area containing the 'non string' value
1016 * @param group Group number of the searched Dicom Element
1017 * @param element Element number of the searched Dicom Element
1020 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1024 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1025 if ( ! tagHT.count(key))
1027 // This was for multimap ?
1028 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1034 * \brief Update the entries with the shadow dictionary.
1035 * Only non even entries are analyzed
1037 void gdcmDocument::UpdateShaEntries() {
1038 //gdcmDictEntry *entry;
1041 /// \todo TODO : still any use to explore recursively the whole structure?
1043 for(ListTag::iterator it=listEntries.begin();
1044 it!=listEntries.end();
1047 // Odd group => from public dictionary
1048 if((*it)->GetGroup()%2==0)
1051 // Peer group => search the corresponding dict entry
1053 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1057 if((*it)->IsImplicitVR())
1062 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1064 // Set the new entry and the new value
1065 (*it)->SetDictEntry(entry);
1066 CheckDocEntryVR(*it,vr);
1068 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1073 // Remove precedent value transformation
1074 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1081 * \brief Searches within the Header Entries for a Dicom Element of
1083 * @param tagName name of the searched Dicom Element.
1084 * @return Corresponding Dicom Element when it exists, and NULL
1087 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string tagName)
1089 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1090 if( dictEntry == NULL)
1093 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1097 * \brief retrieves a Dicom Element (the first one) using (group, element)
1098 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1099 * if you think it's NOT UNIQUE, check the count number
1100 * and use iterators to retrieve ALL the Dicoms Elements within
1101 * a given couple (group, element)
1102 * @param group Group number of the searched Dicom Element
1103 * @param element Element number of the searched Dicom Element
1106 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1109 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1110 if ( ! tagHT.count(key))
1112 return tagHT.find(key)->second;
1116 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1117 * returns a result when the corresponding entry is of type
1119 * @return When present, the corresponding ValEntry.
1121 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1124 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1126 return (gdcmValEntry*)0;
1127 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1131 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1132 return (gdcmValEntry*)0;
1136 * \brief Loads the element while preserving the current
1137 * underlying file position indicator as opposed to
1138 * to LoadDocEntry that modifies it.
1139 * @param entry Header Entry whose value shall be loaded.
1142 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1144 long PositionOnEntry = ftell(fp);
1145 LoadDocEntry(entry);
1146 fseek(fp, PositionOnEntry, SEEK_SET);
1150 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1152 * @return The properly swaped 32 bits integer.
1154 uint32_t gdcmDocument::SwapLong(uint32_t a)
1160 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1161 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1165 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1169 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1172 std::cout << "swapCode= " << sw << std::endl;
1173 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1180 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1182 * @return The properly unswaped 32 bits integer.
1184 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1190 * \brief Swaps the bytes so they agree with the processor order
1191 * @return The properly swaped 16 bits integer.
1193 uint16_t gdcmDocument::SwapShort(uint16_t a)
1195 if ( (sw==4321) || (sw==2143) )
1196 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1201 * \brief Unswaps the bytes so they agree with the processor order
1202 * @return The properly unswaped 16 bits integer.
1204 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1206 return SwapShort(a);
1209 //-----------------------------------------------------------------------------
1213 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1214 * @return length of the parsed set.
1217 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1222 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1223 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1227 unsigned long l = 0;
1230 depth = set->GetDepthLevel();
1233 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1236 NewDocEntry = ReadNextDocEntry( );
1240 vr = NewDocEntry->GetVR();
1244 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1247 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1248 NewValEntry->Copy(NewDocEntry);
1249 NewValEntry->SetDepthLevel(depth);
1250 set->AddEntry(NewValEntry);
1251 LoadDocEntry(NewValEntry);
1252 if (NewValEntry->isItemDelimitor())
1254 if ( !delim_mode && ftell(fp)-offset >= l_max)
1261 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1263 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1264 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1265 "nor BinEntry. Probably unknown VR.");
1268 ////// BinEntry or UNKOWN VR:
1269 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1270 bn->Copy(NewDocEntry);
1275 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1276 NewDocEntry->GetElement() == 0x0010 )
1278 if (NewDocEntry->GetReadLength()==0xffffffff)
1280 // Broken US.3405.1.dcm
1281 Parse7FE0(); // to skip the pixels
1282 // (multipart JPEG/RLE are trouble makers)
1286 SkipToNextDocEntry(NewDocEntry);
1287 l = NewDocEntry->GetFullLength();
1292 // to be sure we are at the beginning
1293 SkipToNextDocEntry(NewDocEntry);
1294 l = NewDocEntry->GetFullLength();
1300 l=NewDocEntry->GetReadLength();
1301 if (l != 0) // don't mess the delim_mode for zero-length sequence
1302 if (l == 0xffffffff)
1306 // no other way to create it ...
1307 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1308 set->GetDepthLevel());
1309 sq->Copy(NewDocEntry);
1310 sq->SetDelimitorMode(delim_mode);
1311 sq->SetDepthLevel(depth);
1314 { // Don't try to parse zero-length sequences
1315 long lgt = ParseSQ( sq,
1316 NewDocEntry->GetOffset(),
1318 (void)lgt; //not used...
1321 if ( !delim_mode && ftell(fp)-offset >= l_max)
1328 return l; // Probably useless
1332 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1333 * @return parsed length for this level
1335 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1336 long offset, long l_max, bool delim_mode)
1338 int SQItemNumber = 0;
1340 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1345 int depth = set->GetDepthLevel();
1346 (void)depth; //not used
1350 NewDocEntry = ReadNextDocEntry();
1354 if (NewDocEntry->isSequenceDelimitor()) {
1355 set->SetSequenceDelimitationItem(NewDocEntry);
1359 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1363 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1364 itemSQ->AddEntry(NewDocEntry);
1365 l= NewDocEntry->GetReadLength();
1367 if (l == 0xffffffff)
1372 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1374 set->AddEntry(itemSQ,SQItemNumber);
1376 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1380 lgth = ftell(fp) - offset;
1385 * \brief Loads the element content if its length doesn't exceed
1386 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1387 * @param Entry Header Entry (Dicom Element) to be dealt with
1389 void gdcmDocument::LoadDocEntry(gdcmDocEntry* Entry)
1392 uint16_t group = Entry->GetGroup();
1393 std::string vr = Entry->GetVR();
1394 uint32_t length = Entry->GetLength();
1396 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1398 // A SeQuence "contains" a set of Elements.
1399 // (fffe e000) tells us an Element is beginning
1400 // (fffe e00d) tells us an Element just ended
1401 // (fffe e0dd) tells us the current SeQuence just ended
1402 if( group == 0xfffe )
1404 // NO more value field for SQ !
1408 // When the length is zero things are easy:
1411 ((gdcmValEntry *)Entry)->SetValue("");
1415 // The elements whose length is bigger than the specified upper bound
1416 // are not loaded. Instead we leave a short notice of the offset of
1417 // the element content and it's length.
1419 std::ostringstream s;
1420 if (length > MaxSizeLoadEntry)
1422 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1424 s << "gdcm::NotLoaded (BinEntry)";
1425 s << " Address:" << (long)Entry->GetOffset();
1426 s << " Length:" << Entry->GetLength();
1427 s << " x(" << std::hex << Entry->GetLength() << ")";
1428 BinEntryPtr->SetValue(s.str());
1430 // to be sure we are at the end of the value ...
1431 fseek(fp, (long)Entry->GetOffset()+(long)Entry->GetLength(), SEEK_SET);
1433 // Be carefull : a BinEntry IS_A ValEntry ...
1434 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1436 s << "gdcm::NotLoaded. (ValEntry)";
1437 s << " Address:" << (long)Entry->GetOffset();
1438 s << " Length:" << Entry->GetLength();
1439 s << " x(" << std::hex << Entry->GetLength() << ")";
1440 ValEntryPtr->SetValue(s.str());
1442 // to be sure we are at the end of the value ...
1443 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1447 // When we find a BinEntry not very much can be done :
1448 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1451 LoadEntryVoidArea(BinEntryPtr);
1452 s << "gdcm::Loaded (BinEntry)";
1453 BinEntryPtr->SetValue(s.str());
1457 /// \todo Any compacter code suggested (?)
1458 if ( IsDocEntryAnInteger(Entry) )
1461 std::ostringstream s;
1463 // When short integer(s) are expected, read and convert the following
1464 // n *two characters properly i.e. consider them as short integers as
1465 // opposed to strings.
1466 // Elements with Value Multiplicity > 1
1467 // contain a set of integers (not a single one)
1468 if (vr == "US" || vr == "SS")
1471 NewInt = ReadInt16();
1475 for (int i=1; i < nbInt; i++)
1478 NewInt = ReadInt16();
1483 // See above comment on multiple integers (mutatis mutandis).
1484 else if (vr == "UL" || vr == "SL")
1487 NewInt = ReadInt32();
1491 for (int i=1; i < nbInt; i++)
1494 NewInt = ReadInt32();
1499 #ifdef GDCM_NO_ANSI_STRING_STREAM
1500 s << std::ends; // to avoid oddities on Solaris
1501 #endif //GDCM_NO_ANSI_STRING_STREAM
1503 ((gdcmValEntry *)Entry)->SetValue(s.str());
1507 // We need an additional byte for storing \0 that is not on disk
1508 std::string NewValue(length,0);
1509 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1510 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
1512 if ( item_read != 1 )
1514 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1515 "unread element value");
1516 ValEntry->SetValue("gdcm::UnRead");
1520 if( (vr == "UI") ) // Because of correspondance with the VR dic
1521 ValEntry->SetValue(NewValue.c_str());
1523 ValEntry->SetValue(NewValue);
1527 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1528 "Should have a ValEntry, here !");
1534 * \brief Find the value Length of the passed Header Entry
1535 * @param Entry Header Entry whose length of the value shall be loaded.
1537 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry)
1539 uint16_t element = Entry->GetElement();
1540 std::string vr = Entry->GetVR();
1544 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1546 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1548 // The following reserved two bytes (see PS 3.5-2001, section
1549 // 7.1.2 Data element structure with explicit vr p27) must be
1550 // skipped before proceeding on reading the length on 4 bytes.
1551 fseek(fp, 2L, SEEK_CUR);
1552 uint32_t length32 = ReadInt32();
1554 if ( (vr == "OB") && (length32 == 0xffffffff) )
1556 uint32_t LengthOB = FindDocEntryLengthOB();
1559 // Computing the length failed (this happens with broken
1560 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1561 // chance to get the pixels by deciding the element goes
1562 // until the end of the file. Hence we artificially fix the
1563 // the length and proceed.
1564 long CurrentPosition = ftell(fp);
1565 fseek(fp,0L,SEEK_END);
1566 long LengthUntilEOF = ftell(fp) - CurrentPosition;
1567 fseek(fp, CurrentPosition, SEEK_SET);
1568 Entry->SetLength(LengthUntilEOF);
1572 Entry->SetLength(LengthOB);
1575 FixDocEntryFoundLength(Entry, length32);
1579 // Length is encoded on 2 bytes.
1580 length16 = ReadInt16();
1582 // We can tell the current file is encoded in big endian (like
1583 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1584 // and it's value is the one of the encoding of a big endian file.
1585 // In order to deal with such big endian encoded files, we have
1586 // (at least) two strategies:
1587 // * when we load the "Transfer Syntax" tag with value of big endian
1588 // encoding, we raise the proper flags. Then we wait for the end
1589 // of the META group (0x0002) among which is "Transfer Syntax",
1590 // before switching the swap code to big endian. We have to postpone
1591 // the switching of the swap code since the META group is fully encoded
1592 // in little endian, and big endian coding only starts at the next
1593 // group. The corresponding code can be hard to analyse and adds
1594 // many additional unnecessary tests for regular tags.
1595 // * the second strategy consists in waiting for trouble, that shall
1596 // appear when we find the first group with big endian encoding. This
1597 // is easy to detect since the length of a "Group Length" tag (the
1598 // ones with zero as element number) has to be of 4 (0x0004). When we
1599 // encounter 1024 (0x0400) chances are the encoding changed and we
1600 // found a group with big endian encoding.
1601 // We shall use this second strategy. In order to make sure that we
1602 // can interpret the presence of an apparently big endian encoded
1603 // length of a "Group Length" without committing a big mistake, we
1604 // add an additional check: we look in the already parsed elements
1605 // for the presence of a "Transfer Syntax" whose value has to be "big
1606 // endian encoding". When this is the case, chances are we have got our
1607 // hands on a big endian encoded file: we switch the swap code to
1608 // big endian and proceed...
1609 if ( (element == 0x0000) && (length16 == 0x0400) )
1611 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1613 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1618 SwitchSwapToBigEndian();
1619 // Restore the unproperly loaded values i.e. the group, the element
1620 // and the dictionary entry depending on them.
1621 uint16_t CorrectGroup = SwapShort(Entry->GetGroup());
1622 uint16_t CorrectElem = SwapShort(Entry->GetElement());
1623 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1627 // This correct tag is not in the dictionary. Create a new one.
1628 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1630 // FIXME this can create a memory leaks on the old entry that be
1631 // left unreferenced.
1632 Entry->SetDictEntry(NewTag);
1635 // Heuristic: well, some files are really ill-formed.
1636 if ( length16 == 0xffff)
1639 // Length16= 0xffff means that we deal with
1640 // 'Unknown Length' Sequence
1642 FixDocEntryFoundLength(Entry, (uint32_t)length16);
1647 // Either implicit VR or a non DICOM conformal (see note below) explicit
1648 // VR that ommited the VR of (at least) this element. Farts happen.
1649 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1650 // on Data elements "Implicit and Explicit VR Data Elements shall
1651 // not coexist in a Data Set and Data Sets nested within it".]
1652 // Length is on 4 bytes.
1654 FixDocEntryFoundLength(Entry, ReadInt32());
1660 * \brief Find the Value Representation of the current Dicom Element.
1663 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1665 if (Filetype != gdcmExplicitVR)
1670 long PositionOnEntry = ftell(fp);
1671 // Warning: we believe this is explicit VR (Value Representation) because
1672 // we used a heuristic that found "UL" in the first tag. Alas this
1673 // doesn't guarantee that all the tags will be in explicit VR. In some
1674 // cases (see e-film filtered files) one finds implicit VR tags mixed
1675 // within an explicit VR file. Hence we make sure the present tag
1676 // is in explicit VR and try to fix things if it happens not to be
1679 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1681 if(!CheckDocEntryVR(Entry,VR))
1683 fseek(fp, PositionOnEntry, SEEK_SET);
1684 // When this element is known in the dictionary we shall use, e.g. for
1685 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1686 // dictionary entry. Still we have to flag the element as implicit since
1687 // we know now our assumption on expliciteness is not furfilled.
1689 if ( Entry->IsVRUnknown() )
1690 Entry->SetVR("Implicit");
1691 Entry->SetImplicitVR();
1696 * \brief Check the correspondance between the VR of the header entry
1697 * and the taken VR. If they are different, the header entry is
1698 * updated with the new VR.
1699 * @param Entry Header Entry to check
1700 * @param vr Dicom Value Representation
1701 * @return false if the VR is incorrect of if the VR isn't referenced
1702 * otherwise, it returns true
1704 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, gdcmVRKey vr)
1706 char msg[100]; // for sprintf
1707 bool RealExplicit = true;
1709 // Assume we are reading a falsely explicit VR file i.e. we reached
1710 // a tag where we expect reading a VR but are in fact we read the
1711 // first to bytes of the length. Then we will interogate (through find)
1712 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1713 // both GCC and VC++ implementations of the STL map. Hence when the
1714 // expected VR read happens to be non-ascii characters we consider
1715 // we hit falsely explicit VR tag.
1717 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1718 RealExplicit = false;
1720 // CLEANME searching the dicom_vr at each occurence is expensive.
1721 // PostPone this test in an optional integrity check at the end
1722 // of parsing or only in debug mode.
1723 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1724 RealExplicit= false;
1726 if ( !RealExplicit )
1728 // We thought this was explicit VR, but we end up with an
1729 // implicit VR tag. Let's backtrack.
1730 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1731 Entry->GetGroup(),Entry->GetElement());
1732 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1733 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1734 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1735 Entry->GetGroup(),Entry->GetElement(),
1736 "UL","FIXME","Group Length");
1737 Entry->SetDictEntry(NewEntry);
1742 if ( Entry->IsVRUnknown() )
1744 // When not a dictionary entry, we can safely overwrite the VR.
1745 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1751 else if ( Entry->GetVR() != vr )
1753 // The VR present in the file and the dictionary disagree. We assume
1754 // the file writer knew best and use the VR of the file. Since it would
1755 // be unwise to overwrite the VR of a dictionary (since it would
1756 // compromise it's next user), we need to clone the actual DictEntry
1757 // and change the VR for the read one.
1758 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1759 Entry->GetGroup(),Entry->GetElement(),
1760 vr,"FIXME",Entry->GetName());
1761 Entry->SetDictEntry(NewEntry);
1767 * \brief Get the transformed value of the header entry. The VR value
1768 * is used to define the transformation to operate on the value
1769 * \warning NOT end user intended method !
1771 * @return Transformed entry value
1773 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1775 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1777 std::string val=((gdcmValEntry *)Entry)->GetValue();
1778 std::string vr=Entry->GetVR();
1779 uint32_t length = Entry->GetLength();
1780 std::ostringstream s;
1783 // When short integer(s) are expected, read and convert the following
1784 // n * 2 bytes properly i.e. as a multivaluated strings
1785 // (each single value is separated fromthe next one by '\'
1786 // as usual for standard multivaluated filels
1787 // Elements with Value Multiplicity > 1
1788 // contain a set of short integers (not a single one)
1790 if (vr == "US" || vr == "SS")
1795 for (int i=0; i < nbInt; i++)
1799 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1800 NewInt16 = SwapShort(NewInt16);
1805 // When integer(s) are expected, read and convert the following
1806 // n * 4 bytes properly i.e. as a multivaluated strings
1807 // (each single value is separated fromthe next one by '\'
1808 // as usual for standard multivaluated filels
1809 // Elements with Value Multiplicity > 1
1810 // contain a set of integers (not a single one)
1811 else if (vr == "UL" || vr == "SL")
1816 for (int i=0; i < nbInt; i++)
1820 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1821 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1822 NewInt32=SwapLong(NewInt32);
1826 #ifdef GDCM_NO_ANSI_STRING_STREAM
1827 s << std::ends; // to avoid oddities on Solaris
1828 #endif //GDCM_NO_ANSI_STRING_STREAM
1832 return ((gdcmValEntry *)Entry)->GetValue();
1836 * \brief Get the reverse transformed value of the header entry. The VR
1837 * value is used to define the reverse transformation to operate on
1839 * \warning NOT end user intended method !
1841 * @return Reverse transformed entry value
1843 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1845 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1847 std::string vr=Entry->GetVR();
1848 std::ostringstream s;
1849 std::vector<std::string> tokens;
1851 if (vr == "US" || vr == "SS")
1855 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1856 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1857 for (unsigned int i=0; i<tokens.size();i++)
1859 NewInt16 = atoi(tokens[i].c_str());
1860 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1864 if (vr == "UL" || vr == "SL")
1868 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1869 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1870 for (unsigned int i=0; i<tokens.size();i++)
1872 NewInt32 = atoi(tokens[i].c_str());
1873 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1874 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1879 #ifdef GDCM_NO_ANSI_STRING_STREAM
1880 s << std::ends; // to avoid oddities on Solaris
1881 #endif //GDCM_NO_ANSI_STRING_STREAM
1885 return ((gdcmValEntry *)Entry)->GetValue();
1889 * \brief Skip a given Header Entry
1890 * \warning NOT end user intended method !
1893 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1895 SkipBytes(entry->GetLength());
1899 * \brief Skips to the begining of the next Header Entry
1900 * \warning NOT end user intended method !
1903 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1905 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1906 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1910 * \brief When the length of an element value is obviously wrong (because
1911 * the parser went Jabberwocky) one can hope improving things by
1912 * applying some heuristics.
1914 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1915 uint32_t FoundLength)
1917 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1918 if ( FoundLength == 0xffffffff) {
1922 uint16_t gr =Entry->GetGroup();
1923 uint16_t el =Entry->GetElement();
1925 if (FoundLength%2) {
1926 std::ostringstream s;
1927 s << "Warning : Tag with uneven length "
1929 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1930 dbg.Verbose(0, s.str().c_str());
1933 //////// Fix for some naughty General Electric images.
1934 // Allthough not recent many such GE corrupted images are still present
1935 // on Creatis hard disks. Hence this fix shall remain when such images
1936 // are no longer in user (we are talking a few years, here)...
1937 // Note: XMedCom probably uses such a trick since it is able to read
1938 // those pesky GE images ...
1939 if (FoundLength == 13) { // Only happens for this length !
1940 if ( (Entry->GetGroup() != 0x0008)
1941 || ( (Entry->GetElement() != 0x0070)
1942 && (Entry->GetElement() != 0x0080) ) )
1945 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1949 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1950 // Occurence of such images is quite low (unless one leaves close to a
1951 // 'Leonardo' source. Hence, one might consider commenting out the
1952 // following fix on efficiency reasons.
1954 if ( (Entry->GetGroup() == 0x0009)
1955 && ( (Entry->GetElement() == 0x1113)
1956 || (Entry->GetElement() == 0x1114) ) )
1959 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1962 //////// Deal with sequences, but only on users request:
1964 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1966 FoundLength = 0; // ReadLength is unchanged
1969 //////// We encountered a 'delimiter' element i.e. a tag of the form
1970 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1971 // taken into account.
1973 if(Entry->GetGroup() == 0xfffe)
1975 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1976 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1977 // causes extra troubles...
1978 if( Entry->GetElement() != 0x0000 )
1984 Entry->SetUsableLength(FoundLength);
1988 * \brief Apply some heuristics to predict whether the considered
1989 * element value contains/represents an integer or not.
1990 * @param Entry The element value on which to apply the predicate.
1991 * @return The result of the heuristical predicate.
1993 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1994 uint16_t element = Entry->GetElement();
1995 uint16_t group = Entry->GetGroup();
1996 std::string vr = Entry->GetVR();
1997 uint32_t length = Entry->GetLength();
1999 // When we have some semantics on the element we just read, and if we
2000 // a priori know we are dealing with an integer, then we shall be
2001 // able to swap it's element value properly.
2002 if ( element == 0 ) // This is the group length of the group
2008 // Allthough this should never happen, still some images have a
2009 // corrupted group length [e.g. have a glance at offset x(8336) of
2010 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2011 // Since for dicom compliant and well behaved headers, the present
2012 // test is useless (and might even look a bit paranoid), when we
2013 // encounter such an ill-formed image, we simply display a warning
2014 // message and proceed on parsing (while crossing fingers).
2015 std::ostringstream s;
2016 int filePosition = ftell(fp);
2017 s << "Erroneous Group Length element length on : (" \
2018 << std::hex << group << " , " << element
2019 << ") -before- position x(" << filePosition << ")"
2020 << "lgt : " << length;
2021 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2025 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2032 * \brief Find the Length till the next sequence delimiter
2033 * \warning NOT end user intended method !
2037 uint32_t gdcmDocument::FindDocEntryLengthOB() {
2038 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2041 long PositionOnEntry = ftell(fp);
2042 bool FoundSequenceDelimiter = false;
2043 uint32_t TotalLength = 0;
2044 uint32_t ItemLength;
2046 while ( ! FoundSequenceDelimiter)
2053 // We have to decount the group and element we just read
2056 if ( ( g != 0xfffe )
2057 || ( ( n != 0xe0dd ) && ( n != 0xe000 ) ) )
2059 dbg.Verbose(1, "gdcmDocument::FindLengthOB: neither an Item tag "
2060 "nor a Sequence delimiter tag.");
2061 fseek(fp, PositionOnEntry, SEEK_SET);
2067 FoundSequenceDelimiter = true;
2069 ItemLength = ReadInt32();
2070 // We add 4 bytes since we just read the ItemLength with ReadInt32
2071 TotalLength += ItemLength + 4;
2072 SkipBytes(ItemLength);
2074 if ( FoundSequenceDelimiter )
2077 fseek(fp, PositionOnEntry, SEEK_SET);
2082 * \brief Reads a supposed to be 16 Bits integer
2083 * (swaps it depending on processor endianity)
2084 * @return read value
2086 uint16_t gdcmDocument::ReadInt16() {
2089 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2090 if ( item_read != 1 ) {
2092 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2102 * \brief Reads a supposed to be 32 Bits integer
2103 * (swaps it depending on processor endianity)
2104 * @return read value
2106 uint32_t gdcmDocument::ReadInt32() {
2109 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2110 if ( item_read != 1 ) {
2112 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2122 * \brief skips bytes inside the source file
2123 * \warning NOT end user intended method !
2126 void gdcmDocument::SkipBytes(uint32_t NBytes) {
2127 //FIXME don't dump the returned value
2128 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2132 * \brief Loads all the needed Dictionaries
2133 * \warning NOT end user intended method !
2135 void gdcmDocument::Initialise()
2137 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2142 * \brief Discover what the swap code is (among little endian, big endian,
2143 * bad little endian, bad big endian).
2145 * @return false when we are absolutely sure
2146 * it's neither ACR-NEMA nor DICOM
2147 * true when we hope ours assuptions are OK
2149 bool gdcmDocument::CheckSwap() {
2151 // The only guaranted way of finding the swap code is to find a
2152 // group tag since we know it's length has to be of four bytes i.e.
2153 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2154 // occurs when we can't find such group...
2156 uint32_t x=4; // x : for ntohs
2157 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2163 char deb[HEADER_LENGTH_TO_READ];
2165 // First, compare HostByteOrder and NetworkByteOrder in order to
2166 // determine if we shall need to swap bytes (i.e. the Endian type).
2172 // The easiest case is the one of a DICOM header, since it possesses a
2173 // file preamble where it suffice to look for the string "DICM".
2174 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2177 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2178 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2180 // Next, determine the value representation (VR). Let's skip to the
2181 // first element (0002, 0000) and check there if we find "UL"
2182 // - or "OB" if the 1st one is (0002,0001) -,
2183 // in which case we (almost) know it is explicit VR.
2184 // WARNING: if it happens to be implicit VR then what we will read
2185 // is the length of the group. If this ascii representation of this
2186 // length happens to be "UL" then we shall believe it is explicit VR.
2187 // FIXME: in order to fix the above warning, we could read the next
2188 // element value (or a couple of elements values) in order to make
2189 // sure we are not commiting a big mistake.
2190 // We need to skip :
2191 // * the 128 bytes of File Preamble (often padded with zeroes),
2192 // * the 4 bytes of "DICM" string,
2193 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2194 // i.e. a total of 136 bytes.
2198 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2199 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2200 // *Implicit* VR. -and it is !-
2202 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2203 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2204 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2205 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2206 // when Write DCM *adds*
2208 // Use gdcmDocument::dicom_vr to test all the possibilities
2209 // instead of just checking for UL, OB and UI !? group 0000
2211 Filetype = gdcmExplicitVR;
2212 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2213 "explicit Value Representation");
2217 Filetype = gdcmImplicitVR;
2218 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2219 "not an explicit Value Representation");
2225 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2226 "HostByteOrder != NetworkByteOrder");
2231 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2232 "HostByteOrder = NetworkByteOrder");
2235 // Position the file position indicator at first tag (i.e.
2236 // after the file preamble and the "DICM" string).
2238 fseek (fp, 132L, SEEK_SET);
2242 // Alas, this is not a DicomV3 file and whatever happens there is no file
2243 // preamble. We can reset the file position indicator to where the data
2244 // is (i.e. the beginning of the file).
2245 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2248 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2249 // By clean we mean that the length of the first tag is written down.
2250 // If this is the case and since the length of the first group HAS to be
2251 // four (bytes), then determining the proper swap code is straightforward.
2254 // We assume the array of char we are considering contains the binary
2255 // representation of a 32 bits integer. Hence the following dirty
2257 s32 = *((uint32_t *)(entCur));
2278 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2279 // It is time for despaired wild guesses.
2280 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2281 // i.e. the 'group length' element is not present :
2283 // check the supposed to be 'group number'
2284 // 0x0002 or 0x0004 or 0x0008
2285 // to determine ' sw' value .
2286 // Only 0 or 4321 will be possible
2287 // (no oportunity to check for the formerly well known
2288 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2289 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2290 // the file IS NOT ACR-NEMA nor DICOM V3
2291 // Find a trick to tell it the caller...
2293 s16 = *((uint16_t *)(deb));
2309 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2310 "ACR/NEMA unfound swap info (Really hopeless !)");
2311 Filetype = gdcmUnknown;
2315 // Then the only info we have is the net2host one.
2325 * \brief Restore the unproperly loaded values i.e. the group, the element
2326 * and the dictionary entry depending on them.
2328 void gdcmDocument::SwitchSwapToBigEndian()
2330 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2331 "Switching to BigEndian mode.");
2352 * \brief during parsing, Header Elements too long are not loaded in memory
2355 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2359 if ((uint32_t)NewSize >= (uint32_t)0xffffffff)
2361 MaxSizeLoadEntry = 0xffffffff;
2364 MaxSizeLoadEntry = NewSize;
2369 * \brief Header Elements too long will not be printed
2370 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2373 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2377 if ((uint32_t)NewSize >= (uint32_t)0xffffffff)
2379 MaxSizePrintEntry = 0xffffffff;
2382 MaxSizePrintEntry = NewSize;
2388 * \brief Read the next tag but WITHOUT loading it's value
2389 * (read the 'Group Number', the 'Element Number',
2390 * gets the Dict Entry
2391 * gets the VR, gets the length, gets the offset value)
2392 * @return On succes the newly created DocEntry, NULL on failure.
2394 gdcmDocEntry *gdcmDocument::ReadNextDocEntry() {
2395 uint16_t g = ReadInt16();
2396 uint16_t n = ReadInt16();
2397 gdcmDocEntry *NewEntry;
2400 // We reached the EOF (or an error occured) therefore
2401 // header parsing has to be considered as finished.
2402 return (gdcmDocEntry *)0;
2404 NewEntry = NewDocEntryByNumber(g, n);
2405 FindDocEntryVR(NewEntry);
2406 FindDocEntryLength(NewEntry);
2414 NewEntry->SetOffset(ftell(fp));
2420 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2421 * in the TagHt dictionary.
2422 * @param group The generated tag must belong to this group.
2423 * @return The element of tag with given group which is fee.
2425 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2427 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2429 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2430 if (tagHT.count(key) == 0)
2437 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2438 * is placed at the beginning of a tag check whether this
2439 * tag is (TestGroup, TestElement).
2440 * \warning On success the internal file pointer \ref gdcmDocument::fp
2441 * is modified to point after the tag.
2442 * On failure (i.e. when the tag wasn't the expected tag
2443 * (TestGroup, TestElement) the internal file pointer
2444 * \ref gdcmDocument::fp is restored to it's original position.
2445 * @param TestGroup The expected group of the tag.
2446 * @param TestElement The expected Element of the tag.
2447 * @return True on success, false otherwise.
2449 bool gdcmDocument::ReadTag(uint16_t TestGroup, uint16_t TestElement)
2451 uint16_t ItemTagGroup;
2452 uint16_t ItemTagElement;
2453 long PositionOnEntry = ftell(fp);
2454 long CurrentPosition = ftell(fp); // On debugging purposes
2456 //// Read the Item Tag group and element, and make
2457 // sure they are what we expected:
2458 ItemTagGroup = ReadInt16();
2459 ItemTagElement = ReadInt16();
2460 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2462 std::ostringstream s;
2463 s << " We should have found tag (";
2464 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2465 s << " but instead we encountered tag (";
2466 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2468 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2469 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2470 dbg.Verbose(0, s.str().c_str());
2471 fseek(fp, PositionOnEntry, SEEK_SET);
2478 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2479 * is placed at the beginning of a tag (TestGroup, TestElement),
2480 * read the length associated to the Tag.
2481 * \warning On success the internal file pointer \ref gdcmDocument::fp
2482 * is modified to point after the tag and it's length.
2483 * On failure (i.e. when the tag wasn't the expected tag
2484 * (TestGroup, TestElement) the internal file pointer
2485 * \ref gdcmDocument::fp is restored to it's original position.
2486 * @param TestGroup The expected group of the tag.
2487 * @param TestElement The expected Element of the tag.
2488 * @return On success returns the length associated to the tag. On failure
2491 uint32_t gdcmDocument::ReadTagLength(uint16_t TestGroup, uint16_t TestElement)
2493 long PositionOnEntry = ftell(fp);
2495 if ( !ReadTag(TestGroup, TestElement) )
2500 //// Then read the associated Item Length
2501 long CurrentPosition = ftell(fp);
2502 uint32_t ItemLength;
2503 ItemLength = ReadInt32();
2505 std::ostringstream s;
2506 s << "Basic Item Length is: "
2507 << ItemLength << std::endl;
2508 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2509 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2515 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2516 * No other way so 'skip' the Data
2519 void gdcmDocument::Parse7FE0 ()
2521 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2525 if ( IsImplicitVRLittleEndianTransferSyntax()
2526 || IsExplicitVRLittleEndianTransferSyntax()
2527 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2528 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2531 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2533 //// Read the Basic Offset Table Item Tag length...
2534 uint32_t ItemLength = ReadTagLength(0xfffe, 0xe000);
2536 //// ... and then read length[s] itself[themselves]. We don't use
2537 // the values read (BTW what is the purpous of those lengths ?)
2538 if (ItemLength != 0) {
2539 // BTW, what is the purpous of those length anyhow !?
2540 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2541 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2542 for (unsigned int i=0; i < ItemLength; i += 4){
2543 uint32_t IndividualLength;
2544 IndividualLength = str2num(&BasicOffsetTableItemValue[i],uint32_t);
2545 std::ostringstream s;
2546 s << " Read one length: ";
2547 s << std::hex << IndividualLength << std::endl;
2548 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2552 if ( ! IsRLELossLessTransferSyntax() )
2556 //// We then skip (not reading them) all the fragments of images:
2557 while ( (ItemLength = ReadTagLength(0xfffe, 0xe000)) )
2559 SkipBytes(ItemLength);
2566 long RleSegmentLength[15], fragmentLength;
2568 // While we find some items:
2569 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2571 // Parse fragments of the current Fragment (Frame)
2572 //------------------ scanning (not reading) fragment pixels
2573 uint32_t nbRleSegments = ReadInt32();
2575 //// Reading RLE Segments Offset Table
2576 uint32_t RleSegmentOffsetTable[15];
2577 for(int k=1; k<=15; k++) {
2579 RleSegmentOffsetTable[k] = ReadInt32();
2582 // skipping (not reading) RLE Segments
2583 if (nbRleSegments>1) {
2584 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2585 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2586 - RleSegmentOffsetTable[k];
2588 SkipBytes(RleSegmentLength[k]);
2592 RleSegmentLength[nbRleSegments]= fragmentLength
2593 - RleSegmentOffsetTable[nbRleSegments];
2595 SkipBytes(RleSegmentLength[nbRleSegments]);
2598 // Make sure that at the end of the item we encounter a 'Sequence
2600 if ( ! ReadTag(0xfffe, 0xe0dd) )
2602 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2603 dbg.Verbose(0, " at end of RLE item sequence");
2611 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2612 * \warning Does NOT work with ACR-NEMA files
2613 * \todo Find a trick to solve the pb (use RET fields ?)
2615 * @return true if 'smaller'
2617 bool gdcmDocument::operator<(gdcmDocument &document)
2622 s1=this->GetEntryByNumber(0x0010,0x0010);
2623 s2=document.GetEntryByNumber(0x0010,0x0010);
2631 s1=this->GetEntryByNumber(0x0010,0x0020);
2632 s2=document.GetEntryByNumber(0x0010,0x0020);
2639 // Study Instance UID
2640 s1=this->GetEntryByNumber(0x0020,0x000d);
2641 s2=document.GetEntryByNumber(0x0020,0x000d);
2648 // Serie Instance UID
2649 s1=this->GetEntryByNumber(0x0020,0x000e);
2650 s2=document.GetEntryByNumber(0x0020,0x000e);
2662 //-----------------------------------------------------------------------------