1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/07/16 15:18:05 $
7 Version: $Revision: 1.49 $
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,
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);
108 Filename = inFilename;
111 if ( !OpenFile(exception_on_error))
114 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
118 fseek(fp,0L,SEEK_END);
119 long lgt = ftell(fp);
123 long beg = ftell(fp);
128 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
129 (void)l; //is l used anywhere ?
133 // Load 'non string' values
135 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
136 if( PhotometricInterpretation == "PALETTE COLOR " )
138 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
139 LoadEntryVoidArea(0x0028,0x1201); // R LUT
140 LoadEntryVoidArea(0x0028,0x1202); // G LUT
141 LoadEntryVoidArea(0x0028,0x1203); // B LUT
143 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
144 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
145 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
147 //FIXME later : how to use it?
148 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
152 // --------------------------------------------------------------
153 // Special Patch to allow gdcm to read ACR-LibIDO formated images
155 // if recognition code tells us we deal with a LibIDO image
156 // we switch lineNumber and columnNumber
159 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
160 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
161 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
162 // with "little-endian strings"
164 Filetype = gdcmACR_LIBIDO;
165 std::string rows = GetEntryByNumber(0x0028, 0x0010);
166 std::string columns = GetEntryByNumber(0x0028, 0x0011);
167 SetEntryByNumber(columns, 0x0028, 0x0010);
168 SetEntryByNumber(rows , 0x0028, 0x0011);
170 // ----------------- End of Special Patch ----------------
172 printLevel = 1; // 'Medium' print level by default
177 * @param exception_on_error
179 gdcmDocument::gdcmDocument(bool exception_on_error)
182 (void)exception_on_error;
183 //enableSequences=0; // ?!? JPR
185 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
188 printLevel = 1; // 'Medium' print level by default
192 * \brief Canonical destructor.
194 gdcmDocument::~gdcmDocument ()
199 // Recursive clean up of sequences
200 for (TagDocEntryHT::const_iterator it = tagHT.begin();
201 it != tagHT.end(); ++it )
208 //-----------------------------------------------------------------------------
212 * \brief Prints The Dict Entries of THE public Dicom Dictionary
215 void gdcmDocument::PrintPubDict(std::ostream & os)
217 RefPubDict->Print(os);
221 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
224 void gdcmDocument::PrintShaDict(std::ostream & os)
226 RefShaDict->Print(os);
229 //-----------------------------------------------------------------------------
232 * \brief Get the public dictionary used
234 gdcmDict *gdcmDocument::GetPubDict()
240 * \brief Get the shadow dictionary used
242 gdcmDict *gdcmDocument::GetShaDict()
248 * \brief Set the shadow dictionary used
249 * \param dict dictionary to use in shadow
251 bool gdcmDocument::SetShaDict(gdcmDict *dict)
258 * \brief Set the shadow dictionary used
259 * \param dictName name of the dictionary to use in shadow
261 bool gdcmDocument::SetShaDict(DictKey dictName)
263 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
268 * \brief This predicate, based on hopefully reasonable heuristics,
269 * decides whether or not the current gdcmDocument was properly parsed
270 * and contains the mandatory information for being considered as
271 * a well formed and usable Dicom/Acr File.
272 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
275 bool gdcmDocument::IsReadable()
277 if( Filetype == gdcmUnknown)
279 std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
280 << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
281 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
287 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
297 * \brief Internal function that checks whether the Transfer Syntax given
298 * as argument is the one present in the current document.
299 * @param SyntaxToCheck The transfert syntax we need to check against.
300 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
301 * the current document. False either when the document contains
302 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
304 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
306 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
312 // The entry might be present but not loaded (parsing and loading
313 // happen at differente stages): try loading and proceed with check...
314 LoadDocEntrySafe(entry);
315 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
317 std::string transfer = valEntry->GetValue();
319 // The actual transfer (as read from disk) might be padded. We
320 // first need to remove the potential padding. We can make the
321 // weak assumption that padding was not executed with digits...
322 while ( ! isdigit(transfer[transfer.length()-1]) )
324 transfer.erase(transfer.length()-1, 1);
326 if ( transfer == syntaxToCheck )
335 * \brief Determines if the Transfer Syntax of the present document
336 * corresponds to a Implicit Value Representation of
338 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
339 * @return True when ImplicitVRLittleEndian found. False in all other cases.
341 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
343 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
347 * \brief Determines if the Transfer Syntax was already encountered
348 * and if it corresponds to a ExplicitVRLittleEndian one.
349 * @return True when ExplicitVRLittleEndian found. False in all other cases.
351 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
353 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
357 * \brief Determines if the Transfer Syntax was already encountered
358 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
359 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
361 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
363 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
367 * \brief Determines if the Transfer Syntax was already encountered
368 * and if it corresponds to a Explicit VR Big Endian one.
369 * @return True when big endian found. False in all other cases.
371 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
373 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
377 * \brief Determines if the Transfer Syntax was already encountered
378 * and if it corresponds to a JPEGBaseLineProcess1 one.
379 * @return True when JPEGBaseLineProcess1found. False in all other cases.
381 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
383 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
387 * \brief Determines if the Transfer Syntax was already encountered
388 * and if it corresponds to a JPEGExtendedProcess2-4 one.
389 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
391 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
393 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
397 * \brief Determines if the Transfer Syntax was already encountered
398 * and if it corresponds to a JPEGExtendeProcess3-5 one.
399 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
401 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
403 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
407 * \brief Determines if the Transfer Syntax was already encountered
408 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
409 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
412 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
414 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
418 * \brief Determines if the Transfer Syntax was already encountered
419 * and if it corresponds to a RLE Lossless one.
420 * @return True when RLE Lossless found. False in all
423 bool gdcmDocument::IsRLELossLessTransferSyntax()
425 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
429 * \brief Determines if Transfer Syntax was already encountered
430 * and if it corresponds to a JPEG Lossless one.
431 * @return True when RLE Lossless found. False in all
435 bool gdcmDocument::IsJPEGLossless()
437 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
438 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
439 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
443 * \brief Determines if the Transfer Syntax was already encountered
444 * and if it corresponds to a JPEG2000 one
445 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
448 bool gdcmDocument::IsJPEG2000()
450 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
451 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
455 * \brief Predicate for dicom version 3 file.
456 * @return True when the file is a dicom version 3.
458 bool gdcmDocument::IsDicomV3()
460 // Checking if Transfert Syntax exists is enough
461 // Anyway, it's to late check if the 'Preamble' was found ...
462 // And ... would it be a rich idea to check ?
463 // (some 'no Preamble' DICOM images exist !)
464 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
468 * \brief returns the File Type
469 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
470 * @return the FileType code
472 FileType gdcmDocument::GetFileType()
478 * \brief opens the file
479 * @param exception_on_error
482 FILE *gdcmDocument::OpenFile(bool exception_on_error)
485 fp = fopen(Filename.c_str(),"rb");
489 if(exception_on_error)
491 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
495 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
504 fread(&zero, (size_t)2, (size_t)1, fp);
506 //ACR -- or DICOM with no Preamble --
507 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
513 fseek(fp, 126L, SEEK_CUR);
515 fread(dicm, (size_t)4, (size_t)1, fp);
516 if( memcmp(dicm, "DICM", 4) == 0 )
522 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
526 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
533 * \brief closes the file
534 * @return TRUE if the close was successfull
536 bool gdcmDocument::CloseFile()
538 int closed = fclose(fp);
545 * \brief Writes in a file all the Header Entries (Dicom Elements)
546 * @param fp file pointer on an already open file
547 * @param filetype Type of the File to be written
548 * (ACR-NEMA, ExplicitVR, ImplicitVR)
549 * \return Always true.
551 void gdcmDocument::Write(FILE* fp,FileType filetype)
553 /// \todo move the following lines (and a lot of others, to be written)
554 /// to a future function CheckAndCorrectHeader
556 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
557 /// no way (check : FileType est un champ de gdcmDocument ...)
558 /// a moins de se livrer a un tres complique ajout des champs manquants.
559 /// faire un CheckAndCorrectHeader (?)
561 if (filetype == gdcmImplicitVR)
563 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
564 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
566 /// \todo Refer to standards on page 21, chapter 6.2
567 /// "Value representation": values with a VR of UI shall be
568 /// padded with a single trailing null
569 /// in the following case we have to padd manually with a 0
571 SetEntryLengthByNumber(18, 0x0002, 0x0010);
574 if (filetype == gdcmExplicitVR)
576 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
577 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
579 /// \todo Refer to standards on page 21, chapter 6.2
580 /// "Value representation": values with a VR of UI shall be
581 /// padded with a single trailing null
582 /// Dans le cas suivant on doit pader manuellement avec un 0
584 SetEntryLengthByNumber(20, 0x0002, 0x0010);
588 * \todo rewrite later, if really usefull
589 * - 'Group Length' element is optional in DICOM
590 * - but un-updated odd groups lengthes can causes pb
593 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
594 * UpdateGroupLength(false,filetype);
595 * if ( filetype == ACR)
596 * UpdateGroupLength(true,ACR);
599 gdcmElementSet::Write(fp,filetype); // This one is recursive
604 * \brief Modifies the value of a given Header Entry (Dicom Element)
605 * when it exists. Create it with the given value when unexistant.
606 * @param Value (string) Value to be set
607 * @param Group Group number of the Entry
608 * @param Elem Element number of the Entry
609 * \return pointer to the modified/created Header Entry (NULL when creation
613 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
618 gdcmValEntry* valEntry;
620 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
623 // The entry wasn't present and we simply create the required ValEntry:
624 currentEntry = NewDocEntryByNumber(group, elem);
627 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
628 " NewDocEntryByNumber failed.");
631 valEntry = new gdcmValEntry(currentEntry);
632 if ( !AddEntry(valEntry))
634 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
635 " failed allthough this is a creation.");
640 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
643 // We need to promote the gdcmDocEntry to a gdcmValEntry:
644 valEntry = new gdcmValEntry(currentEntry);
645 if (!RemoveEntry(currentEntry))
647 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
648 " of previous DocEntry failed.");
651 if ( !AddEntry(valEntry))
653 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
654 " promoted ValEntry failed.");
660 SetEntryByNumber(value, group, elem);
666 * \brief Modifies the value of a given Header Entry (Dicom Element)
667 * when it exists. Create it with the given value when unexistant.
668 * @param voidArea (binary) value to be set
669 * @param Group Group number of the Entry
670 * @param Elem Element number of the Entry
671 * \return pointer to the modified/created Header Entry (NULL when creation
674 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
681 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
684 a = NewBinEntryByNumber(group, elem);
690 b = new gdcmBinEntry(a);
692 b->SetVoidArea(voidArea);
694 SetEntryByNumber(voidArea, lgth, group, elem);
695 //b->SetVoidArea(voidArea); //what if b == 0 !!
701 * \brief Set a new value if the invoked element exists
702 * Seems to be useless !!!
703 * @param Value new element value
704 * @param Group group number of the Entry
705 * @param Elem element number of the Entry
708 bool gdcmDocument::ReplaceIfExistByNumber(const char* value, uint16_t group,
711 std::string v = value;
712 SetEntryByNumber(v, group, elem);
716 //-----------------------------------------------------------------------------
720 * \brief Checks if a given Dicom Element exists within the H table
721 * @param group Group number of the searched Dicom Element
722 * @param element Element number of the searched Dicom Element
723 * @return number of occurences
725 int gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
727 std::string key = gdcmDictEntry::TranslateToKey(group, element );
728 return tagHT.count(key);
732 * \brief Searches within Header Entries (Dicom Elements) parsed with
733 * the public and private dictionaries
734 * for the element value of a given tag.
735 * \warning Don't use any longer : use GetPubEntryByName
736 * @param tagName name of the searched element.
737 * @return Corresponding element value when it exists,
738 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
740 std::string gdcmDocument::GetEntryByName(TagName tagName)
742 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
748 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
752 * \brief Searches within Header Entries (Dicom Elements) parsed with
753 * the public and private dictionaries
754 * for the element value representation of a given tag.
756 * Obtaining the VR (Value Representation) might be needed by caller
757 * to convert the string typed content to caller's native type
758 * (think of C++ vs Python). The VR is actually of a higher level
759 * of semantics than just the native C++ type.
760 * @param tagName name of the searched element.
761 * @return Corresponding element value representation when it exists,
762 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
764 std::string gdcmDocument::GetEntryVRByName(TagName tagName)
766 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
767 if( dictEntry == NULL)
770 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
771 dictEntry->GetElement());
772 return elem->GetVR();
777 * \brief Searches within Header Entries (Dicom Elements) parsed with
778 * the public and private dictionaries
779 * for the element value representation of a given tag.
780 * @param group Group number of the searched tag.
781 * @param element Element number of the searched tag.
782 * @return Corresponding element value representation when it exists,
783 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
785 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
787 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
788 /// \todo use map methods, instead of multimap JPR
789 if ( ! tagHT.count(key))
791 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
795 * \brief Searches within Header Entries (Dicom Elements) parsed with
796 * the public and private dictionaries
797 * for the element value representation of a given tag..
799 * Obtaining the VR (Value Representation) might be needed by caller
800 * to convert the string typed content to caller's native type
801 * (think of C++ vs Python). The VR is actually of a higher level
802 * of semantics than just the native C++ type.
803 * @param group Group number of the searched tag.
804 * @param element Element number of the searched tag.
805 * @return Corresponding element value representation when it exists,
806 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
808 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
810 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
813 return elem->GetVR();
817 * \brief Searches within Header Entries (Dicom Elements) parsed with
818 * the public and private dictionaries
819 * for the value length of a given tag..
820 * @param group Group number of the searched tag.
821 * @param element Element number of the searched tag.
822 * @return Corresponding element length; -2 if not found
824 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
826 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
829 return elem->GetLength();
832 * \brief Sets the value (string) of the Header Entry (Dicom Element)
833 * @param content string value of the Dicom Element
834 * @param tagName name of the searched Dicom Element.
835 * @return true when found
837 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName)
839 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
840 if( dictEntry == NULL)
843 return SetEntryByNumber(content,dictEntry->GetGroup(),
844 dictEntry->GetElement());
848 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
849 * through it's (group, element) and modifies it's content with
851 * @param content new value (string) to substitute with
852 * @param group group number of the Dicom Element to modify
853 * @param element element number of the Dicom Element to modify
855 bool gdcmDocument::SetEntryByNumber(std::string content,
859 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
862 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
863 " ValEntry (try promotion first).");
866 // Non even content must be padded with a space (020H).
867 if((content.length())%2) {
868 content = content + '\0';
870 ValEntry->SetValue(content);
872 // Integers have a special treatement for their length:
873 gdcmVRKey vr = ValEntry->GetVR();
874 if( (vr == "US") || (vr == "SS") )
875 ValEntry->SetLength(2);
876 else if( (vr == "UL") || (vr == "SL") )
877 ValEntry->SetLength(4);
879 ValEntry->SetLength(content.length());
885 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
886 * through it's (group, element) and modifies it's content with
888 * @param content new value (void *) to substitute with
889 * @param lgth new value length
890 * @param group group number of the Dicom Element to modify
891 * @param element element number of the Dicom Element to modify
893 bool gdcmDocument::SetEntryByNumber(void *content,
898 (void)lgth; //not used
899 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
900 if ( ! tagHT.count(key))
903 /* Hope Binaray field length is *never* wrong
904 if(lgth%2) // Non even length are padded with a space (020H).
907 //content = content + '\0'; // fing a trick to enlarge a binary field?
911 a = (gdcmBinEntry *)tagHT[key];
912 a->SetVoidArea(content);
913 //a->SetLength(lgth); // ???
918 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
919 * in the PubDocEntrySet of this instance
920 * through it's (group, element) and modifies it's length with
922 * \warning Use with extreme caution.
923 * @param l new length to substitute with
924 * @param group group number of the Entry to modify
925 * @param element element number of the Entry to modify
926 * @return true on success, false otherwise.
928 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
932 /// \todo use map methods, instead of multimap JPR
933 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
934 if ( ! tagHT.count(key))
936 if (l%2) l++; // length must be even
937 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
943 * \brief Gets (from Header) the offset of a 'non string' element value
944 * (LoadElementValues has already be executed)
945 * @param Group group number of the Entry
946 * @param Elem element number of the Entry
947 * @return File Offset of the Element Value
949 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t Group, uint16_t Elem)
951 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
954 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
957 return Entry->GetOffset();
961 * \brief Gets (from Header) a 'non string' element value
962 * (LoadElementValues has already be executed)
963 * @param Group group number of the Entry
964 * @param Elem element number of the Entry
965 * @return Pointer to the 'non string' area
967 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t Group, uint16_t Elem)
969 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
972 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
975 return ((gdcmBinEntry *)Entry)->GetVoidArea();
979 * \brief Loads (from disk) the element content
980 * when a string is not suitable
981 * @param Group group number of the Entry
982 * @param Elem element number of the Entry
984 void *gdcmDocument::LoadEntryVoidArea(uint16_t Group, uint16_t Elem)
986 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
989 size_t o =(size_t)Element->GetOffset();
990 fseek(fp, o, SEEK_SET);
991 size_t l = Element->GetLength();
992 char* a = new char[l];
994 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
997 size_t l2 = fread(a, 1, l ,fp);
1003 /// \todo Drop any allready existing void area! JPR
1004 SetEntryVoidAreaByNumber(a, Group, Elem);
1008 * \brief Loads (from disk) the element content
1009 * when a string is not suitable
1010 * @param Element Entry whose voidArea is going to be loaded
1012 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
1014 size_t o =(size_t)Element->GetOffset();
1015 fseek(fp, o, SEEK_SET);
1016 size_t l = Element->GetLength();
1017 char* a = new char[l];
1019 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1022 Element->SetVoidArea((void *)a);
1023 /// \todo check the result
1024 size_t l2 = fread(a, 1, l ,fp);
1034 * \brief Sets a 'non string' value to a given Dicom Element
1035 * @param area area containing the 'non string' value
1036 * @param group Group number of the searched Dicom Element
1037 * @param element Element number of the searched Dicom Element
1040 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1044 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1045 if ( ! tagHT.count(key))
1047 // This was for multimap ?
1048 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1054 * \brief Update the entries with the shadow dictionary.
1055 * Only non even entries are analyzed
1057 void gdcmDocument::UpdateShaEntries() {
1058 //gdcmDictEntry *entry;
1061 /// \todo TODO : still any use to explore recursively the whole structure?
1063 for(ListTag::iterator it=listEntries.begin();
1064 it!=listEntries.end();
1067 // Odd group => from public dictionary
1068 if((*it)->GetGroup()%2==0)
1071 // Peer group => search the corresponding dict entry
1073 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1077 if((*it)->IsImplicitVR())
1082 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1084 // Set the new entry and the new value
1085 (*it)->SetDictEntry(entry);
1086 CheckDocEntryVR(*it,vr);
1088 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1093 // Remove precedent value transformation
1094 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1101 * \brief Searches within the Header Entries for a Dicom Element of
1103 * @param tagName name of the searched Dicom Element.
1104 * @return Corresponding Dicom Element when it exists, and NULL
1107 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string tagName)
1109 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1110 if( dictEntry == NULL)
1113 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1117 * \brief retrieves a Dicom Element (the first one) using (group, element)
1118 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1119 * if you think it's NOT UNIQUE, check the count number
1120 * and use iterators to retrieve ALL the Dicoms Elements within
1121 * a given couple (group, element)
1122 * @param group Group number of the searched Dicom Element
1123 * @param element Element number of the searched Dicom Element
1126 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1129 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1130 if ( ! tagHT.count(key))
1132 return tagHT.find(key)->second;
1136 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1137 * returns a result when the corresponding entry is of type
1139 * @return When present, the corresponding ValEntry.
1141 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1144 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1146 return (gdcmValEntry*)0;
1147 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1151 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1152 return (gdcmValEntry*)0;
1156 * \brief Loads the element while preserving the current
1157 * underlying file position indicator as opposed to
1158 * to LoadDocEntry that modifies it.
1159 * @param entry Header Entry whose value shall be loaded.
1162 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1164 long PositionOnEntry = ftell(fp);
1165 LoadDocEntry(entry);
1166 fseek(fp, PositionOnEntry, SEEK_SET);
1170 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1172 * @return The properly swaped 32 bits integer.
1174 uint32_t gdcmDocument::SwapLong(uint32_t a)
1180 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1181 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1185 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1189 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1192 std::cout << "swapCode= " << sw << std::endl;
1193 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1200 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1202 * @return The properly unswaped 32 bits integer.
1204 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1210 * \brief Swaps the bytes so they agree with the processor order
1211 * @return The properly swaped 16 bits integer.
1213 uint16_t gdcmDocument::SwapShort(uint16_t a)
1215 if ( (sw==4321) || (sw==2143) )
1216 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1221 * \brief Unswaps the bytes so they agree with the processor order
1222 * @return The properly unswaped 16 bits integer.
1224 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1226 return SwapShort(a);
1229 //-----------------------------------------------------------------------------
1233 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1234 * @return length of the parsed set.
1237 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1242 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1243 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1247 unsigned long l = 0;
1250 depth = set->GetDepthLevel();
1253 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1256 NewDocEntry = ReadNextDocEntry( );
1260 vr = NewDocEntry->GetVR();
1264 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1267 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1268 NewValEntry->Copy(NewDocEntry);
1269 NewValEntry->SetDepthLevel(depth);
1270 set->AddEntry(NewValEntry);
1271 LoadDocEntry(NewValEntry);
1272 if (NewValEntry->isItemDelimitor())
1274 if ( !delim_mode && ftell(fp)-offset >= l_max)
1281 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1283 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1284 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1285 "nor BinEntry. Probably unknown VR.");
1288 ////// BinEntry or UNKOWN VR:
1289 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1290 bn->Copy(NewDocEntry);
1295 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1296 NewDocEntry->GetElement() == 0x0010 )
1298 if (NewDocEntry->GetReadLength()==0xffffffff)
1300 // Broken US.3405.1.dcm
1301 Parse7FE0(); // to skip the pixels
1302 // (multipart JPEG/RLE are trouble makers)
1306 SkipToNextDocEntry(NewDocEntry);
1307 l = NewDocEntry->GetFullLength();
1312 // to be sure we are at the beginning
1313 SkipToNextDocEntry(NewDocEntry);
1314 l = NewDocEntry->GetFullLength();
1320 l=NewDocEntry->GetReadLength();
1321 if (l != 0) // don't mess the delim_mode for zero-length sequence
1322 if (l == 0xffffffff)
1326 // no other way to create it ...
1327 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1328 set->GetDepthLevel());
1329 sq->Copy(NewDocEntry);
1330 sq->SetDelimitorMode(delim_mode);
1331 sq->SetDepthLevel(depth);
1334 { // Don't try to parse zero-length sequences
1335 long lgt = ParseSQ( sq,
1336 NewDocEntry->GetOffset(),
1338 (void)lgt; //not used...
1341 if ( !delim_mode && ftell(fp)-offset >= l_max)
1348 return l; // Probably useless
1352 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1353 * @return parsed length for this level
1355 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1356 long offset, long l_max, bool delim_mode)
1358 int SQItemNumber = 0;
1360 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1365 int depth = set->GetDepthLevel();
1366 (void)depth; //not used
1370 NewDocEntry = ReadNextDocEntry();
1374 if (NewDocEntry->isSequenceDelimitor()) {
1375 set->SetSequenceDelimitationItem(NewDocEntry);
1379 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1383 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1384 itemSQ->AddEntry(NewDocEntry);
1385 l= NewDocEntry->GetReadLength();
1387 if (l == 0xffffffff)
1392 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1394 set->AddEntry(itemSQ,SQItemNumber);
1396 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1400 lgth = ftell(fp) - offset;
1405 * \brief Loads the element content if its length doesn't exceed
1406 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1407 * @param Entry Header Entry (Dicom Element) to be dealt with
1409 void gdcmDocument::LoadDocEntry(gdcmDocEntry* Entry)
1412 uint16_t group = Entry->GetGroup();
1413 std::string vr = Entry->GetVR();
1414 uint32_t length = Entry->GetLength();
1416 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1418 // A SeQuence "contains" a set of Elements.
1419 // (fffe e000) tells us an Element is beginning
1420 // (fffe e00d) tells us an Element just ended
1421 // (fffe e0dd) tells us the current SeQuence just ended
1422 if( group == 0xfffe )
1424 // NO more value field for SQ !
1428 // When the length is zero things are easy:
1431 ((gdcmValEntry *)Entry)->SetValue("");
1435 // The elements whose length is bigger than the specified upper bound
1436 // are not loaded. Instead we leave a short notice of the offset of
1437 // the element content and it's length.
1439 std::ostringstream s;
1440 if (length > MaxSizeLoadEntry)
1442 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1444 s << "gdcm::NotLoaded (BinEntry)";
1445 s << " Address:" << (long)Entry->GetOffset();
1446 s << " Length:" << Entry->GetLength();
1447 s << " x(" << std::hex << Entry->GetLength() << ")";
1448 BinEntryPtr->SetValue(s.str());
1450 // to be sure we are at the end of the value ...
1451 fseek(fp, (long)Entry->GetOffset()+(long)Entry->GetLength(), SEEK_SET);
1453 // Be carefull : a BinEntry IS_A ValEntry ...
1454 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1456 s << "gdcm::NotLoaded. (ValEntry)";
1457 s << " Address:" << (long)Entry->GetOffset();
1458 s << " Length:" << Entry->GetLength();
1459 s << " x(" << std::hex << Entry->GetLength() << ")";
1460 ValEntryPtr->SetValue(s.str());
1462 // to be sure we are at the end of the value ...
1463 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1467 // When we find a BinEntry not very much can be done :
1468 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1471 LoadEntryVoidArea(BinEntryPtr);
1472 s << "gdcm::Loaded (BinEntry)";
1473 BinEntryPtr->SetValue(s.str());
1477 /// \todo Any compacter code suggested (?)
1478 if ( IsDocEntryAnInteger(Entry) )
1481 std::ostringstream s;
1483 // When short integer(s) are expected, read and convert the following
1484 // n *two characters properly i.e. consider them as short integers as
1485 // opposed to strings.
1486 // Elements with Value Multiplicity > 1
1487 // contain a set of integers (not a single one)
1488 if (vr == "US" || vr == "SS")
1491 NewInt = ReadInt16();
1495 for (int i=1; i < nbInt; i++)
1498 NewInt = ReadInt16();
1503 // See above comment on multiple integers (mutatis mutandis).
1504 else if (vr == "UL" || vr == "SL")
1507 NewInt = ReadInt32();
1511 for (int i=1; i < nbInt; i++)
1514 NewInt = ReadInt32();
1519 #ifdef GDCM_NO_ANSI_STRING_STREAM
1520 s << std::ends; // to avoid oddities on Solaris
1521 #endif //GDCM_NO_ANSI_STRING_STREAM
1523 ((gdcmValEntry *)Entry)->SetValue(s.str());
1527 // We need an additional byte for storing \0 that is not on disk
1528 std::string NewValue(length,0);
1529 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1530 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
1532 if ( item_read != 1 )
1534 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1535 "unread element value");
1536 ValEntry->SetValue("gdcm::UnRead");
1540 if( (vr == "UI") ) // Because of correspondance with the VR dic
1541 ValEntry->SetValue(NewValue.c_str());
1543 ValEntry->SetValue(NewValue);
1547 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1548 "Should have a ValEntry, here !");
1554 * \brief Find the value Length of the passed Header Entry
1555 * @param Entry Header Entry whose length of the value shall be loaded.
1557 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry)
1559 uint16_t element = Entry->GetElement();
1560 std::string vr = Entry->GetVR();
1564 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1566 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1568 // The following reserved two bytes (see PS 3.5-2001, section
1569 // 7.1.2 Data element structure with explicit vr p27) must be
1570 // skipped before proceeding on reading the length on 4 bytes.
1571 fseek(fp, 2L, SEEK_CUR);
1572 uint32_t length32 = ReadInt32();
1574 if ( (vr == "OB") && (length32 == 0xffffffff) )
1576 uint32_t LengthOB = FindDocEntryLengthOB();
1579 // Computing the length failed (this happens with broken
1580 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1581 // chance to get the pixels by deciding the element goes
1582 // until the end of the file. Hence we artificially fix the
1583 // the length and proceed.
1584 long CurrentPosition = ftell(fp);
1585 fseek(fp,0L,SEEK_END);
1586 long LengthUntilEOF = ftell(fp) - CurrentPosition;
1587 fseek(fp, CurrentPosition, SEEK_SET);
1588 Entry->SetLength(LengthUntilEOF);
1592 Entry->SetLength(LengthOB);
1595 FixDocEntryFoundLength(Entry, length32);
1599 // Length is encoded on 2 bytes.
1600 length16 = ReadInt16();
1602 // We can tell the current file is encoded in big endian (like
1603 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1604 // and it's value is the one of the encoding of a big endian file.
1605 // In order to deal with such big endian encoded files, we have
1606 // (at least) two strategies:
1607 // * when we load the "Transfer Syntax" tag with value of big endian
1608 // encoding, we raise the proper flags. Then we wait for the end
1609 // of the META group (0x0002) among which is "Transfer Syntax",
1610 // before switching the swap code to big endian. We have to postpone
1611 // the switching of the swap code since the META group is fully encoded
1612 // in little endian, and big endian coding only starts at the next
1613 // group. The corresponding code can be hard to analyse and adds
1614 // many additional unnecessary tests for regular tags.
1615 // * the second strategy consists in waiting for trouble, that shall
1616 // appear when we find the first group with big endian encoding. This
1617 // is easy to detect since the length of a "Group Length" tag (the
1618 // ones with zero as element number) has to be of 4 (0x0004). When we
1619 // encounter 1024 (0x0400) chances are the encoding changed and we
1620 // found a group with big endian encoding.
1621 // We shall use this second strategy. In order to make sure that we
1622 // can interpret the presence of an apparently big endian encoded
1623 // length of a "Group Length" without committing a big mistake, we
1624 // add an additional check: we look in the already parsed elements
1625 // for the presence of a "Transfer Syntax" whose value has to be "big
1626 // endian encoding". When this is the case, chances are we have got our
1627 // hands on a big endian encoded file: we switch the swap code to
1628 // big endian and proceed...
1629 if ( (element == 0x0000) && (length16 == 0x0400) )
1631 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1633 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1638 SwitchSwapToBigEndian();
1639 // Restore the unproperly loaded values i.e. the group, the element
1640 // and the dictionary entry depending on them.
1641 uint16_t CorrectGroup = SwapShort(Entry->GetGroup());
1642 uint16_t CorrectElem = SwapShort(Entry->GetElement());
1643 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1647 // This correct tag is not in the dictionary. Create a new one.
1648 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1650 // FIXME this can create a memory leaks on the old entry that be
1651 // left unreferenced.
1652 Entry->SetDictEntry(NewTag);
1655 // Heuristic: well, some files are really ill-formed.
1656 if ( length16 == 0xffff)
1659 // Length16= 0xffff means that we deal with
1660 // 'Unknown Length' Sequence
1662 FixDocEntryFoundLength(Entry, (uint32_t)length16);
1667 // Either implicit VR or a non DICOM conformal (see note below) explicit
1668 // VR that ommited the VR of (at least) this element. Farts happen.
1669 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1670 // on Data elements "Implicit and Explicit VR Data Elements shall
1671 // not coexist in a Data Set and Data Sets nested within it".]
1672 // Length is on 4 bytes.
1674 FixDocEntryFoundLength(Entry, ReadInt32());
1680 * \brief Find the Value Representation of the current Dicom Element.
1683 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1685 if (Filetype != gdcmExplicitVR)
1690 long PositionOnEntry = ftell(fp);
1691 // Warning: we believe this is explicit VR (Value Representation) because
1692 // we used a heuristic that found "UL" in the first tag. Alas this
1693 // doesn't guarantee that all the tags will be in explicit VR. In some
1694 // cases (see e-film filtered files) one finds implicit VR tags mixed
1695 // within an explicit VR file. Hence we make sure the present tag
1696 // is in explicit VR and try to fix things if it happens not to be
1699 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1701 if(!CheckDocEntryVR(Entry,VR))
1703 fseek(fp, PositionOnEntry, SEEK_SET);
1704 // When this element is known in the dictionary we shall use, e.g. for
1705 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1706 // dictionary entry. Still we have to flag the element as implicit since
1707 // we know now our assumption on expliciteness is not furfilled.
1709 if ( Entry->IsVRUnknown() )
1710 Entry->SetVR("Implicit");
1711 Entry->SetImplicitVR();
1716 * \brief Check the correspondance between the VR of the header entry
1717 * and the taken VR. If they are different, the header entry is
1718 * updated with the new VR.
1719 * @param Entry Header Entry to check
1720 * @param vr Dicom Value Representation
1721 * @return false if the VR is incorrect of if the VR isn't referenced
1722 * otherwise, it returns true
1724 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, gdcmVRKey vr)
1726 char msg[100]; // for sprintf
1727 bool RealExplicit = true;
1729 // Assume we are reading a falsely explicit VR file i.e. we reached
1730 // a tag where we expect reading a VR but are in fact we read the
1731 // first to bytes of the length. Then we will interogate (through find)
1732 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1733 // both GCC and VC++ implementations of the STL map. Hence when the
1734 // expected VR read happens to be non-ascii characters we consider
1735 // we hit falsely explicit VR tag.
1737 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1738 RealExplicit = false;
1740 // CLEANME searching the dicom_vr at each occurence is expensive.
1741 // PostPone this test in an optional integrity check at the end
1742 // of parsing or only in debug mode.
1743 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1744 RealExplicit= false;
1746 if ( !RealExplicit )
1748 // We thought this was explicit VR, but we end up with an
1749 // implicit VR tag. Let's backtrack.
1750 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1751 Entry->GetGroup(),Entry->GetElement());
1752 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1753 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1754 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1755 Entry->GetGroup(),Entry->GetElement(),
1756 "UL","FIXME","Group Length");
1757 Entry->SetDictEntry(NewEntry);
1762 if ( Entry->IsVRUnknown() )
1764 // When not a dictionary entry, we can safely overwrite the VR.
1765 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1771 else if ( Entry->GetVR() != vr )
1773 // The VR present in the file and the dictionary disagree. We assume
1774 // the file writer knew best and use the VR of the file. Since it would
1775 // be unwise to overwrite the VR of a dictionary (since it would
1776 // compromise it's next user), we need to clone the actual DictEntry
1777 // and change the VR for the read one.
1778 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1779 Entry->GetGroup(),Entry->GetElement(),
1780 vr,"FIXME",Entry->GetName());
1781 Entry->SetDictEntry(NewEntry);
1787 * \brief Get the transformed value of the header entry. The VR value
1788 * is used to define the transformation to operate on the value
1789 * \warning NOT end user intended method !
1791 * @return Transformed entry value
1793 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1795 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1797 std::string val=((gdcmValEntry *)Entry)->GetValue();
1798 std::string vr=Entry->GetVR();
1799 uint32_t length = Entry->GetLength();
1800 std::ostringstream s;
1803 // When short integer(s) are expected, read and convert the following
1804 // n * 2 bytes properly i.e. as a multivaluated strings
1805 // (each single value is separated fromthe next one by '\'
1806 // as usual for standard multivaluated filels
1807 // Elements with Value Multiplicity > 1
1808 // contain a set of short integers (not a single one)
1810 if (vr == "US" || vr == "SS")
1815 for (int i=0; i < nbInt; i++)
1819 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1820 NewInt16 = SwapShort(NewInt16);
1825 // When integer(s) are expected, read and convert the following
1826 // n * 4 bytes properly i.e. as a multivaluated strings
1827 // (each single value is separated fromthe next one by '\'
1828 // as usual for standard multivaluated filels
1829 // Elements with Value Multiplicity > 1
1830 // contain a set of integers (not a single one)
1831 else if (vr == "UL" || vr == "SL")
1836 for (int i=0; i < nbInt; i++)
1840 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1841 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1842 NewInt32=SwapLong(NewInt32);
1846 #ifdef GDCM_NO_ANSI_STRING_STREAM
1847 s << std::ends; // to avoid oddities on Solaris
1848 #endif //GDCM_NO_ANSI_STRING_STREAM
1852 return ((gdcmValEntry *)Entry)->GetValue();
1856 * \brief Get the reverse transformed value of the header entry. The VR
1857 * value is used to define the reverse transformation to operate on
1859 * \warning NOT end user intended method !
1861 * @return Reverse transformed entry value
1863 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1865 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1867 std::string vr=Entry->GetVR();
1868 std::ostringstream s;
1869 std::vector<std::string> tokens;
1871 if (vr == "US" || vr == "SS")
1875 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1876 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1877 for (unsigned int i=0; i<tokens.size();i++)
1879 NewInt16 = atoi(tokens[i].c_str());
1880 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1884 if (vr == "UL" || vr == "SL")
1888 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1889 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1890 for (unsigned int i=0; i<tokens.size();i++)
1892 NewInt32 = atoi(tokens[i].c_str());
1893 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1894 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1899 #ifdef GDCM_NO_ANSI_STRING_STREAM
1900 s << std::ends; // to avoid oddities on Solaris
1901 #endif //GDCM_NO_ANSI_STRING_STREAM
1905 return ((gdcmValEntry *)Entry)->GetValue();
1909 * \brief Skip a given Header Entry
1910 * \warning NOT end user intended method !
1913 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1915 SkipBytes(entry->GetLength());
1919 * \brief Skips to the begining of the next Header Entry
1920 * \warning NOT end user intended method !
1923 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1925 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1926 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1930 * \brief When the length of an element value is obviously wrong (because
1931 * the parser went Jabberwocky) one can hope improving things by
1932 * applying some heuristics.
1934 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1935 uint32_t FoundLength)
1937 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1938 if ( FoundLength == 0xffffffff) {
1942 uint16_t gr =Entry->GetGroup();
1943 uint16_t el =Entry->GetElement();
1945 if (FoundLength%2) {
1946 std::ostringstream s;
1947 s << "Warning : Tag with uneven length "
1949 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1950 dbg.Verbose(0, s.str().c_str());
1953 //////// Fix for some naughty General Electric images.
1954 // Allthough not recent many such GE corrupted images are still present
1955 // on Creatis hard disks. Hence this fix shall remain when such images
1956 // are no longer in user (we are talking a few years, here)...
1957 // Note: XMedCom probably uses such a trick since it is able to read
1958 // those pesky GE images ...
1959 if (FoundLength == 13) { // Only happens for this length !
1960 if ( (Entry->GetGroup() != 0x0008)
1961 || ( (Entry->GetElement() != 0x0070)
1962 && (Entry->GetElement() != 0x0080) ) )
1965 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1969 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1970 // Occurence of such images is quite low (unless one leaves close to a
1971 // 'Leonardo' source. Hence, one might consider commenting out the
1972 // following fix on efficiency reasons.
1974 if ( (Entry->GetGroup() == 0x0009)
1975 && ( (Entry->GetElement() == 0x1113)
1976 || (Entry->GetElement() == 0x1114) ) )
1979 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1982 //////// Deal with sequences, but only on users request:
1984 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1986 FoundLength = 0; // ReadLength is unchanged
1989 //////// We encountered a 'delimiter' element i.e. a tag of the form
1990 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1991 // taken into account.
1993 if(Entry->GetGroup() == 0xfffe)
1995 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1996 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1997 // causes extra troubles...
1998 if( Entry->GetElement() != 0x0000 )
2004 Entry->SetUsableLength(FoundLength);
2008 * \brief Apply some heuristics to predict whether the considered
2009 * element value contains/represents an integer or not.
2010 * @param Entry The element value on which to apply the predicate.
2011 * @return The result of the heuristical predicate.
2013 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2014 uint16_t element = Entry->GetElement();
2015 uint16_t group = Entry->GetGroup();
2016 std::string vr = Entry->GetVR();
2017 uint32_t length = Entry->GetLength();
2019 // When we have some semantics on the element we just read, and if we
2020 // a priori know we are dealing with an integer, then we shall be
2021 // able to swap it's element value properly.
2022 if ( element == 0 ) // This is the group length of the group
2028 // Allthough this should never happen, still some images have a
2029 // corrupted group length [e.g. have a glance at offset x(8336) of
2030 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2031 // Since for dicom compliant and well behaved headers, the present
2032 // test is useless (and might even look a bit paranoid), when we
2033 // encounter such an ill-formed image, we simply display a warning
2034 // message and proceed on parsing (while crossing fingers).
2035 std::ostringstream s;
2036 int filePosition = ftell(fp);
2037 s << "Erroneous Group Length element length on : (" \
2038 << std::hex << group << " , " << element
2039 << ") -before- position x(" << filePosition << ")"
2040 << "lgt : " << length;
2041 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2045 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2052 * \brief Find the Length till the next sequence delimiter
2053 * \warning NOT end user intended method !
2057 uint32_t gdcmDocument::FindDocEntryLengthOB() {
2058 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2061 long PositionOnEntry = ftell(fp);
2062 bool FoundSequenceDelimiter = false;
2063 uint32_t TotalLength = 0;
2064 uint32_t ItemLength;
2066 while ( ! FoundSequenceDelimiter)
2073 // We have to decount the group and element we just read
2076 if ( ( g != 0xfffe )
2077 || ( ( n != 0xe0dd ) && ( n != 0xe000 ) ) )
2079 dbg.Verbose(1, "gdcmDocument::FindLengthOB: neither an Item tag "
2080 "nor a Sequence delimiter tag.");
2081 fseek(fp, PositionOnEntry, SEEK_SET);
2087 FoundSequenceDelimiter = true;
2089 ItemLength = ReadInt32();
2090 // We add 4 bytes since we just read the ItemLength with ReadInt32
2091 TotalLength += ItemLength + 4;
2092 SkipBytes(ItemLength);
2094 if ( FoundSequenceDelimiter )
2097 fseek(fp, PositionOnEntry, SEEK_SET);
2102 * \brief Reads a supposed to be 16 Bits integer
2103 * (swaps it depending on processor endianity)
2104 * @return read value
2106 uint16_t gdcmDocument::ReadInt16() {
2109 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2110 if ( item_read != 1 ) {
2112 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2122 * \brief Reads a supposed to be 32 Bits integer
2123 * (swaps it depending on processor endianity)
2124 * @return read value
2126 uint32_t gdcmDocument::ReadInt32() {
2129 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2130 if ( item_read != 1 ) {
2132 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2142 * \brief skips bytes inside the source file
2143 * \warning NOT end user intended method !
2146 void gdcmDocument::SkipBytes(uint32_t NBytes) {
2147 //FIXME don't dump the returned value
2148 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2152 * \brief Loads all the needed Dictionaries
2153 * \warning NOT end user intended method !
2155 void gdcmDocument::Initialise()
2157 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2162 * \brief Discover what the swap code is (among little endian, big endian,
2163 * bad little endian, bad big endian).
2165 * @return false when we are absolutely sure
2166 * it's neither ACR-NEMA nor DICOM
2167 * true when we hope ours assuptions are OK
2169 bool gdcmDocument::CheckSwap() {
2171 // The only guaranted way of finding the swap code is to find a
2172 // group tag since we know it's length has to be of four bytes i.e.
2173 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2174 // occurs when we can't find such group...
2176 uint32_t x=4; // x : for ntohs
2177 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2183 char deb[HEADER_LENGTH_TO_READ];
2185 // First, compare HostByteOrder and NetworkByteOrder in order to
2186 // determine if we shall need to swap bytes (i.e. the Endian type).
2192 // The easiest case is the one of a DICOM header, since it possesses a
2193 // file preamble where it suffice to look for the string "DICM".
2194 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2197 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2198 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2200 // Next, determine the value representation (VR). Let's skip to the
2201 // first element (0002, 0000) and check there if we find "UL"
2202 // - or "OB" if the 1st one is (0002,0001) -,
2203 // in which case we (almost) know it is explicit VR.
2204 // WARNING: if it happens to be implicit VR then what we will read
2205 // is the length of the group. If this ascii representation of this
2206 // length happens to be "UL" then we shall believe it is explicit VR.
2207 // FIXME: in order to fix the above warning, we could read the next
2208 // element value (or a couple of elements values) in order to make
2209 // sure we are not commiting a big mistake.
2210 // We need to skip :
2211 // * the 128 bytes of File Preamble (often padded with zeroes),
2212 // * the 4 bytes of "DICM" string,
2213 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2214 // i.e. a total of 136 bytes.
2218 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2219 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2220 // *Implicit* VR. -and it is !-
2222 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2223 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2224 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2225 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2226 // when Write DCM *adds*
2228 // Use gdcmDocument::dicom_vr to test all the possibilities
2229 // instead of just checking for UL, OB and UI !? group 0000
2231 Filetype = gdcmExplicitVR;
2232 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2233 "explicit Value Representation");
2237 Filetype = gdcmImplicitVR;
2238 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2239 "not an explicit Value Representation");
2245 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2246 "HostByteOrder != NetworkByteOrder");
2251 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2252 "HostByteOrder = NetworkByteOrder");
2255 // Position the file position indicator at first tag (i.e.
2256 // after the file preamble and the "DICM" string).
2258 fseek (fp, 132L, SEEK_SET);
2262 // Alas, this is not a DicomV3 file and whatever happens there is no file
2263 // preamble. We can reset the file position indicator to where the data
2264 // is (i.e. the beginning of the file).
2265 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2268 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2269 // By clean we mean that the length of the first tag is written down.
2270 // If this is the case and since the length of the first group HAS to be
2271 // four (bytes), then determining the proper swap code is straightforward.
2274 // We assume the array of char we are considering contains the binary
2275 // representation of a 32 bits integer. Hence the following dirty
2277 s32 = *((uint32_t *)(entCur));
2298 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2299 // It is time for despaired wild guesses.
2300 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2301 // i.e. the 'group length' element is not present :
2303 // check the supposed to be 'group number'
2304 // 0x0002 or 0x0004 or 0x0008
2305 // to determine ' sw' value .
2306 // Only 0 or 4321 will be possible
2307 // (no oportunity to check for the formerly well known
2308 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2309 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2310 // the file IS NOT ACR-NEMA nor DICOM V3
2311 // Find a trick to tell it the caller...
2313 s16 = *((uint16_t *)(deb));
2329 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2330 "ACR/NEMA unfound swap info (Really hopeless !)");
2331 Filetype = gdcmUnknown;
2335 // Then the only info we have is the net2host one.
2345 * \brief Restore the unproperly loaded values i.e. the group, the element
2346 * and the dictionary entry depending on them.
2348 void gdcmDocument::SwitchSwapToBigEndian()
2350 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2351 "Switching to BigEndian mode.");
2372 * \brief during parsing, Header Elements too long are not loaded in memory
2375 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2379 if ((uint32_t)NewSize >= (uint32_t)0xffffffff)
2381 MaxSizeLoadEntry = 0xffffffff;
2384 MaxSizeLoadEntry = NewSize;
2389 * \brief Header Elements too long will not be printed
2390 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2393 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2397 if ((uint32_t)NewSize >= (uint32_t)0xffffffff)
2399 MaxSizePrintEntry = 0xffffffff;
2402 MaxSizePrintEntry = NewSize;
2408 * \brief Read the next tag but WITHOUT loading it's value
2409 * (read the 'Group Number', the 'Element Number',
2410 * gets the Dict Entry
2411 * gets the VR, gets the length, gets the offset value)
2412 * @return On succes the newly created DocEntry, NULL on failure.
2414 gdcmDocEntry *gdcmDocument::ReadNextDocEntry() {
2415 uint16_t g = ReadInt16();
2416 uint16_t n = ReadInt16();
2417 gdcmDocEntry *NewEntry;
2420 // We reached the EOF (or an error occured) therefore
2421 // header parsing has to be considered as finished.
2422 return (gdcmDocEntry *)0;
2424 NewEntry = NewDocEntryByNumber(g, n);
2425 FindDocEntryVR(NewEntry);
2426 FindDocEntryLength(NewEntry);
2434 NewEntry->SetOffset(ftell(fp));
2440 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2441 * in the TagHt dictionary.
2442 * @param group The generated tag must belong to this group.
2443 * @return The element of tag with given group which is fee.
2445 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2447 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2449 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2450 if (tagHT.count(key) == 0)
2457 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2458 * is placed at the beginning of a tag check whether this
2459 * tag is (TestGroup, TestElement).
2460 * \warning On success the internal file pointer \ref gdcmDocument::fp
2461 * is modified to point after the tag.
2462 * On failure (i.e. when the tag wasn't the expected tag
2463 * (TestGroup, TestElement) the internal file pointer
2464 * \ref gdcmDocument::fp is restored to it's original position.
2465 * @param TestGroup The expected group of the tag.
2466 * @param TestElement The expected Element of the tag.
2467 * @return True on success, false otherwise.
2469 bool gdcmDocument::ReadTag(uint16_t TestGroup, uint16_t TestElement)
2471 uint16_t ItemTagGroup;
2472 uint16_t ItemTagElement;
2473 long PositionOnEntry = ftell(fp);
2474 long CurrentPosition = ftell(fp); // On debugging purposes
2476 //// Read the Item Tag group and element, and make
2477 // sure they are what we expected:
2478 ItemTagGroup = ReadInt16();
2479 ItemTagElement = ReadInt16();
2480 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2482 std::ostringstream s;
2483 s << " We should have found tag (";
2484 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2485 s << " but instead we encountered tag (";
2486 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2488 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2489 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2490 dbg.Verbose(0, s.str().c_str());
2491 fseek(fp, PositionOnEntry, SEEK_SET);
2498 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2499 * is placed at the beginning of a tag (TestGroup, TestElement),
2500 * read the length associated to the Tag.
2501 * \warning On success the internal file pointer \ref gdcmDocument::fp
2502 * is modified to point after the tag and it's length.
2503 * On failure (i.e. when the tag wasn't the expected tag
2504 * (TestGroup, TestElement) the internal file pointer
2505 * \ref gdcmDocument::fp is restored to it's original position.
2506 * @param TestGroup The expected group of the tag.
2507 * @param TestElement The expected Element of the tag.
2508 * @return On success returns the length associated to the tag. On failure
2511 uint32_t gdcmDocument::ReadTagLength(uint16_t TestGroup, uint16_t TestElement)
2513 long PositionOnEntry = ftell(fp);
2514 (void)PositionOnEntry;
2516 if ( !ReadTag(TestGroup, TestElement) )
2521 //// Then read the associated Item Length
2522 long CurrentPosition = ftell(fp);
2523 uint32_t ItemLength;
2524 ItemLength = ReadInt32();
2526 std::ostringstream s;
2527 s << "Basic Item Length is: "
2528 << ItemLength << std::endl;
2529 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2530 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2536 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2537 * No other way so 'skip' the Data
2540 void gdcmDocument::Parse7FE0 ()
2542 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2546 if ( IsImplicitVRLittleEndianTransferSyntax()
2547 || IsExplicitVRLittleEndianTransferSyntax()
2548 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2549 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2552 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2554 //// Read the Basic Offset Table Item Tag length...
2555 uint32_t ItemLength = ReadTagLength(0xfffe, 0xe000);
2557 //// ... and then read length[s] itself[themselves]. We don't use
2558 // the values read (BTW what is the purpous of those lengths ?)
2559 if (ItemLength != 0) {
2560 // BTW, what is the purpous of those length anyhow !?
2561 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2562 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2563 for (unsigned int i=0; i < ItemLength; i += 4){
2564 uint32_t IndividualLength;
2565 IndividualLength = str2num(&BasicOffsetTableItemValue[i],uint32_t);
2566 std::ostringstream s;
2567 s << " Read one length: ";
2568 s << std::hex << IndividualLength << std::endl;
2569 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2573 if ( ! IsRLELossLessTransferSyntax() )
2577 //// We then skip (not reading them) all the fragments of images:
2578 while ( (ItemLength = ReadTagLength(0xfffe, 0xe000)) )
2580 SkipBytes(ItemLength);
2587 long RleSegmentLength[15], fragmentLength;
2589 // While we find some items:
2590 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2592 // Parse fragments of the current Fragment (Frame)
2593 //------------------ scanning (not reading) fragment pixels
2594 uint32_t nbRleSegments = ReadInt32();
2596 //// Reading RLE Segments Offset Table
2597 uint32_t RleSegmentOffsetTable[15];
2598 for(int k=1; k<=15; k++) {
2600 RleSegmentOffsetTable[k] = ReadInt32();
2603 // skipping (not reading) RLE Segments
2604 if (nbRleSegments>1) {
2605 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2606 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2607 - RleSegmentOffsetTable[k];
2609 SkipBytes(RleSegmentLength[k]);
2613 RleSegmentLength[nbRleSegments]= fragmentLength
2614 - RleSegmentOffsetTable[nbRleSegments];
2616 SkipBytes(RleSegmentLength[nbRleSegments]);
2619 // Make sure that at the end of the item we encounter a 'Sequence
2621 if ( ! ReadTag(0xfffe, 0xe0dd) )
2623 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2624 dbg.Verbose(0, " at end of RLE item sequence");
2632 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2633 * \warning Does NOT work with ACR-NEMA files
2634 * \todo Find a trick to solve the pb (use RET fields ?)
2636 * @return true if 'smaller'
2638 bool gdcmDocument::operator<(gdcmDocument &document)
2643 s1=this->GetEntryByNumber(0x0010,0x0010);
2644 s2=document.GetEntryByNumber(0x0010,0x0010);
2652 s1=this->GetEntryByNumber(0x0010,0x0020);
2653 s2=document.GetEntryByNumber(0x0010,0x0020);
2660 // Study Instance UID
2661 s1=this->GetEntryByNumber(0x0020,0x000d);
2662 s2=document.GetEntryByNumber(0x0020,0x000d);
2669 // Serie Instance UID
2670 s1=this->GetEntryByNumber(0x0020,0x000e);
2671 s2=document.GetEntryByNumber(0x0020,0x000e);
2683 //-----------------------------------------------------------------------------