1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/29 23:43:19 $
7 Version: $Revision: 1.44 $
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 = 0x7fffffff;// 4096;//
78 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;//64;
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)
178 :gdcmElementSet(-1) {
179 (void)exception_on_error;
180 //enableSequences=0; // ?!? JPR
182 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
185 printLevel = 1; // 'Medium' print level by default
189 * \brief Canonical destructor.
191 gdcmDocument::~gdcmDocument (void) {
195 // Recursive clean up of sequences
196 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
203 //-----------------------------------------------------------------------------
207 * \brief Prints The Dict Entries of THE public Dicom Dictionary
210 void gdcmDocument::PrintPubDict(std::ostream & os) {
211 RefPubDict->Print(os);
215 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
218 void gdcmDocument::PrintShaDict(std::ostream & os) {
219 RefShaDict->Print(os);
222 //-----------------------------------------------------------------------------
225 * \brief Get the public dictionary used
227 gdcmDict *gdcmDocument::GetPubDict(void) {
232 * \brief Get the shadow dictionary used
234 gdcmDict *gdcmDocument::GetShaDict(void) {
239 * \brief Set the shadow dictionary used
240 * \param dict dictionary to use in shadow
242 bool gdcmDocument::SetShaDict(gdcmDict *dict){
248 * \brief Set the shadow dictionary used
249 * \param dictName name of the dictionary to use in shadow
251 bool gdcmDocument::SetShaDict(DictKey dictName){
252 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
257 * \brief This predicate, based on hopefully reasonable heuristics,
258 * decides whether or not the current gdcmDocument was properly parsed
259 * and contains the mandatory information for being considered as
260 * a well formed and usable Dicom/Acr File.
261 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
264 bool gdcmDocument::IsReadable(void) {
266 if(Filetype==gdcmUnknown) {
267 std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
268 << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
269 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
274 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
284 * \brief Internal function that checks whether the Transfer Syntax given
285 * as argument is the one present in the current document.
286 * @param SyntaxToCheck The transfert syntax we need to check against.
287 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
288 * the current document. False either when the document contains
289 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
291 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
293 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
297 // The entry might be present but not loaded (parsing and loading
298 // happen at differente stages): try loading and proceed with check...
299 LoadDocEntrySafe(Entry);
300 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
302 std::string Transfer = ValEntry->GetValue();
303 // The actual transfer (as read from disk) might be padded. We
304 // first need to remove the potential padding. We can make the
305 // weak assumption that padding was not executed with digits...
306 while ( ! isdigit(Transfer[Transfer.length()-1]) )
308 Transfer.erase(Transfer.length()-1, 1);
310 if ( Transfer == SyntaxToCheck )
317 * \brief Determines if the Transfer Syntax of the present document
318 * corresponds to a Implicit Value Representation of
320 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
321 * @return True when ImplicitVRLittleEndian found. False in all other cases.
323 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
325 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
329 * \brief Determines if the Transfer Syntax was already encountered
330 * and if it corresponds to a ExplicitVRLittleEndian one.
331 * @return True when ExplicitVRLittleEndian found. False in all other cases.
333 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
335 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
339 * \brief Determines if the Transfer Syntax was already encountered
340 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
341 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
343 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
345 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
349 * \brief Determines if the Transfer Syntax was already encountered
350 * and if it corresponds to a Explicit VR Big Endian one.
351 * @return True when big endian found. False in all other cases.
353 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
355 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
359 * \brief Determines if the Transfer Syntax was already encountered
360 * and if it corresponds to a JPEGBaseLineProcess1 one.
361 * @return True when JPEGBaseLineProcess1found. False in all other cases.
363 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
365 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
369 * \brief Determines if the Transfer Syntax was already encountered
370 * and if it corresponds to a JPEGExtendedProcess2-4 one.
371 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
373 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
375 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
379 * \brief Determines if the Transfer Syntax was already encountered
380 * and if it corresponds to a JPEGExtendeProcess3-5 one.
381 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
383 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
385 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
389 * \brief Determines if the Transfer Syntax was already encountered
390 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
391 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
394 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
396 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
400 * \brief Determines if the Transfer Syntax was already encountered
401 * and if it corresponds to a RLE Lossless one.
402 * @return True when RLE Lossless found. False in all
405 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
407 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
411 * \brief Determines if Transfer Syntax was already encountered
412 * and if it corresponds to a JPEG Lossless one.
413 * @return True when RLE Lossless found. False in all
417 bool gdcmDocument::IsJPEGLossless(void)
419 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
420 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
421 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
425 * \brief Determines if the Transfer Syntax was already encountered
426 * and if it corresponds to a JPEG2000 one
427 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
430 bool gdcmDocument::IsJPEG2000(void)
432 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
433 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
437 * \brief Predicate for dicom version 3 file.
438 * @return True when the file is a dicom version 3.
440 bool gdcmDocument::IsDicomV3(void) {
441 // Checking if Transfert Syntax exists is enough
442 // Anyway, it's to late check if the 'Preamble' was found ...
443 // And ... would it be a rich idea to check ?
444 // (some 'no Preamble' DICOM images exist !)
445 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
449 * \brief returns the File Type
450 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
451 * @return the FileType code
453 FileType gdcmDocument::GetFileType(void) {
458 * \brief opens the file
459 * @param exception_on_error
462 FILE *gdcmDocument::OpenFile(bool exception_on_error)
465 fp=fopen(Filename.c_str(),"rb");
469 if(exception_on_error)
470 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
473 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
482 fread(&zero, (size_t)2, (size_t)1, fp);
484 //ACR -- or DICOM with no Preamble --
485 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
489 fseek(fp, 126L, SEEK_CUR);
491 fread(dicm, (size_t)4, (size_t)1, fp);
492 if( memcmp(dicm, "DICM", 4) == 0 )
496 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
499 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
505 * \brief closes the file
506 * @return TRUE if the close was successfull
508 bool gdcmDocument::CloseFile(void) {
509 int closed = fclose(fp);
517 * \brief Writes in a file all the Header Entries (Dicom Elements)
518 * @param fp file pointer on an already open file
519 * @param filetype Type of the File to be written
520 * (ACR-NEMA, ExplicitVR, ImplicitVR)
521 * \return Always true.
523 void gdcmDocument::Write(FILE* fp,FileType filetype) {
525 /// \todo move the following lines (and a lot of others, to be written)
526 /// to a future function CheckAndCorrectHeader
528 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
529 /// no way (check : FileType est un champ de gdcmDocument ...)
530 /// a moins de se livrer a un tres complique ajout des champs manquants.
531 /// faire un CheckAndCorrectHeader (?)
533 if (filetype == gdcmImplicitVR)
535 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
536 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
538 /// \todo Refer to standards on page 21, chapter 6.2
539 /// "Value representation": values with a VR of UI shall be
540 /// padded with a single trailing null
541 /// in the following case we have to padd manually with a 0
543 SetEntryLengthByNumber(18, 0x0002, 0x0010);
546 if (filetype == gdcmExplicitVR)
548 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
549 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
551 /// \todo Refer to standards on page 21, chapter 6.2
552 /// "Value representation": values with a VR of UI shall be
553 /// padded with a single trailing null
554 /// Dans le cas suivant on doit pader manuellement avec un 0
556 SetEntryLengthByNumber(20, 0x0002, 0x0010);
560 * \todo rewrite later, if really usefull
561 * - 'Group Length' element is optional in DICOM
562 * - but un-updated odd groups lengthes can causes pb
565 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
566 * UpdateGroupLength(false,filetype);
567 * if ( filetype == ACR)
568 * UpdateGroupLength(true,ACR);
571 gdcmElementSet::Write(fp,filetype); // This one is recursive
576 * \brief Modifies the value of a given Header Entry (Dicom Element)
577 * when it exists. Create it with the given value when unexistant.
578 * @param Value (string) Value to be set
579 * @param Group Group number of the Entry
580 * @param Elem Element number of the Entry
581 * \return pointer to the modified/created Header Entry (NULL when creation
585 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
590 gdcmDocEntry* CurrentEntry;
591 gdcmValEntry* ValEntry;
593 CurrentEntry = GetDocEntryByNumber( Group, Elem);
596 // The entry wasn't present and we simply create the required ValEntry:
597 CurrentEntry = NewDocEntryByNumber(Group, Elem);
600 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
601 " NewDocEntryByNumber failed.");
604 ValEntry = new gdcmValEntry(CurrentEntry);
605 if ( !AddEntry(ValEntry))
607 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
608 " failed allthough this is a creation.");
613 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
616 // We need to promote the gdcmDocEntry to a gdcmValEntry:
617 ValEntry = new gdcmValEntry(CurrentEntry);
618 if (!RemoveEntry(CurrentEntry))
620 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
621 " of previous DocEntry failed.");
624 if ( !AddEntry(ValEntry))
626 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
627 " promoted ValEntry failed.");
633 SetEntryByNumber(Value, Group, Elem);
639 * \brief Modifies the value of a given Header Entry (Dicom Element)
640 * when it exists. Create it with the given value when unexistant.
641 * @param voidArea (binary) value to be set
642 * @param Group Group number of the Entry
643 * @param Elem Element number of the Entry
644 * \return pointer to the modified/created Header Entry (NULL when creation
647 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
655 a = GetDocEntryByNumber( Group, Elem);
657 a =NewBinEntryByNumber(Group, Elem);
661 b = new gdcmBinEntry(a);
664 SetEntryByNumber(voidArea, lgth, Group, Elem);
665 b->SetVoidArea(voidArea);
673 * \brief Set a new value if the invoked element exists
674 * Seems to be useless !!!
675 * @param Value new element value
676 * @param Group group number of the Entry
677 * @param Elem element number of the Entry
680 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
682 std::string v = Value;
683 SetEntryByNumber(v, Group, Elem);
687 //-----------------------------------------------------------------------------
691 * \brief Checks if a given Dicom Element exists within the H table
692 * @param group Group number of the searched Dicom Element
693 * @param element Element number of the searched Dicom Element
694 * @return number of occurences
696 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
697 std::string key = gdcmDictEntry::TranslateToKey(group, element );
698 return tagHT.count(key);
702 * \brief Searches within Header Entries (Dicom Elements) parsed with
703 * the public and private dictionaries
704 * for the element value of a given tag.
705 * \warning Don't use any longer : use GetPubEntryByName
706 * @param tagName name of the searched element.
707 * @return Corresponding element value when it exists,
708 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
710 std::string gdcmDocument::GetEntryByName(TagName tagName) {
711 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
712 if( dictEntry == NULL)
715 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
719 * \brief Searches within Header Entries (Dicom Elements) parsed with
720 * the public and private dictionaries
721 * for the element value representation of a given tag.
723 * Obtaining the VR (Value Representation) might be needed by caller
724 * to convert the string typed content to caller's native type
725 * (think of C++ vs Python). The VR is actually of a higher level
726 * of semantics than just the native C++ type.
727 * @param tagName name of the searched element.
728 * @return Corresponding element value representation when it exists,
729 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
731 std::string gdcmDocument::GetEntryVRByName(TagName tagName) {
732 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
733 if( dictEntry == NULL)
736 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
737 dictEntry->GetElement());
738 return elem->GetVR();
743 * \brief Searches within Header Entries (Dicom Elements) parsed with
744 * the public and private dictionaries
745 * for the element value representation of a given tag.
746 * @param group Group number of the searched tag.
747 * @param element Element number of the searched tag.
748 * @return Corresponding element value representation when it exists,
749 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
751 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
752 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
753 /// \todo use map methods, instead of multimap JPR
754 if ( ! tagHT.count(key))
756 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
760 * \brief Searches within Header Entries (Dicom Elements) parsed with
761 * the public and private dictionaries
762 * for the element value representation of a given tag..
764 * Obtaining the VR (Value Representation) might be needed by caller
765 * to convert the string typed content to caller's native type
766 * (think of C++ vs Python). The VR is actually of a higher level
767 * of semantics than just the native C++ type.
768 * @param group Group number of the searched tag.
769 * @param element Element number of the searched tag.
770 * @return Corresponding element value representation when it exists,
771 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
773 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
774 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
777 return elem->GetVR();
781 * \brief Searches within Header Entries (Dicom Elements) parsed with
782 * the public and private dictionaries
783 * for the value length of a given tag..
784 * @param group Group number of the searched tag.
785 * @param element Element number of the searched tag.
786 * @return Corresponding element length; -2 if not found
788 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
789 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
792 return elem->GetLength();
795 * \brief Sets the value (string) of the Header Entry (Dicom Element)
796 * @param content string value of the Dicom Element
797 * @param tagName name of the searched Dicom Element.
798 * @return true when found
800 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
801 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
802 if( dictEntry == NULL)
805 return SetEntryByNumber(content,dictEntry->GetGroup(),
806 dictEntry->GetElement());
810 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
811 * through it's (group, element) and modifies it's content with
813 * @param content new value (string) to substitute with
814 * @param group group number of the Dicom Element to modify
815 * @param element element number of the Dicom Element to modify
817 bool gdcmDocument::SetEntryByNumber(std::string content,
821 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
824 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
825 " ValEntry (try promotion first).");
828 // Non even content must be padded with a space (020H).
829 if((content.length())%2) {
830 content = content + '\0';
832 ValEntry->SetValue(content);
834 // Integers have a special treatement for their length:
835 VRKey vr = ValEntry->GetVR();
836 if( (vr == "US") || (vr == "SS") )
837 ValEntry->SetLength(2);
838 else if( (vr == "UL") || (vr == "SL") )
839 ValEntry->SetLength(4);
841 ValEntry->SetLength(content.length());
847 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
848 * through it's (group, element) and modifies it's content with
850 * @param content new value (void *) to substitute with
851 * @param lgth new value length
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(void *content,
860 (void)lgth; //not used
861 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
862 if ( ! tagHT.count(key))
865 /* Hope Binaray field length is *never* wrong
866 if(lgth%2) // Non even length are padded with a space (020H).
869 //content = content + '\0'; // fing a trick to enlarge a binary field?
873 a = (gdcmBinEntry *)tagHT[key];
874 a->SetVoidArea(content);
875 //a->SetLength(lgth); // ???
880 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
881 * in the PubDocEntrySet of this instance
882 * through it's (group, element) and modifies it's length with
884 * \warning Use with extreme caution.
885 * @param l new length to substitute with
886 * @param group group number of the Entry to modify
887 * @param element element number of the Entry to modify
888 * @return true on success, false otherwise.
890 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
894 /// \todo use map methods, instead of multimap JPR
895 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
896 if ( ! tagHT.count(key))
898 if (l%2) l++; // length must be even
899 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
905 * \brief Gets (from Header) the offset of a 'non string' element value
906 * (LoadElementValues has already be executed)
907 * @param Group group number of the Entry
908 * @param Elem element number of the Entry
909 * @return File Offset of the Element Value
911 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
913 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
916 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
919 return Entry->GetOffset();
923 * \brief Gets (from Header) 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 Pointer to the 'non string' area
929 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
931 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
934 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
937 return ((gdcmBinEntry *)Entry)->GetVoidArea();
941 * \brief Loads (from disk) the element content
942 * when a string is not suitable
943 * @param Group group number of the Entry
944 * @param Elem element number of the Entry
946 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
948 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
951 size_t o =(size_t)Element->GetOffset();
952 fseek(fp, o, SEEK_SET);
953 size_t l = Element->GetLength();
954 char* a = new char[l];
956 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
959 size_t l2 = fread(a, 1, l ,fp);
965 /// \todo Drop any allready existing void area! JPR
966 SetEntryVoidAreaByNumber(a, Group, Elem);
970 * \brief Loads (from disk) the element content
971 * when a string is not suitable
972 * @param Element Entry whose voidArea is going to be loaded
974 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
976 size_t o =(size_t)Element->GetOffset();
977 fseek(fp, o, SEEK_SET);
978 size_t l = Element->GetLength();
979 char* a = new char[l];
981 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
984 Element->SetVoidArea((void *)a);
985 /// \todo check the result
986 size_t l2 = fread(a, 1, l ,fp);
996 * \brief Sets a 'non string' value to a given Dicom Element
997 * @param area area containing the 'non string' value
998 * @param group Group number of the searched Dicom Element
999 * @param element Element number of the searched Dicom Element
1002 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1006 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1007 if ( ! tagHT.count(key))
1009 // This was for multimap ?
1010 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1016 * \brief Update the entries with the shadow dictionary.
1017 * Only non even entries are analyzed
1019 void gdcmDocument::UpdateShaEntries(void) {
1020 //gdcmDictEntry *entry;
1023 /// \todo TODO : still any use to explore recursively the whole structure?
1025 for(ListTag::iterator it=listEntries.begin();
1026 it!=listEntries.end();
1029 // Odd group => from public dictionary
1030 if((*it)->GetGroup()%2==0)
1033 // Peer group => search the corresponding dict entry
1035 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1039 if((*it)->IsImplicitVR())
1044 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1046 // Set the new entry and the new value
1047 (*it)->SetDictEntry(entry);
1048 CheckDocEntryVR(*it,vr);
1050 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1055 // Remove precedent value transformation
1056 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1063 * \brief Searches within the Header Entries for a Dicom Element of
1065 * @param tagName name of the searched Dicom Element.
1066 * @return Corresponding Dicom Element when it exists, and NULL
1069 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1070 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1071 if( dictEntry == NULL)
1074 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1078 * \brief retrieves a Dicom Element (the first one) using (group, element)
1079 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1080 * if you think it's NOT UNIQUE, check the count number
1081 * and use iterators to retrieve ALL the Dicoms Elements within
1082 * a given couple (group, element)
1083 * @param group Group number of the searched Dicom Element
1084 * @param element Element number of the searched Dicom Element
1087 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1089 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1090 if ( ! tagHT.count(key))
1092 return tagHT.find(key)->second;
1096 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1097 * returns a result when the corresponding entry is of type
1099 * @return When present, the corresponding ValEntry.
1101 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1103 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1105 return (gdcmValEntry*)0;
1106 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1110 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1111 return (gdcmValEntry*)0;
1115 * \brief Loads the element while preserving the current
1116 * underlying file position indicator as opposed to
1117 * to LoadDocEntry that modifies it.
1118 * @param entry Header Entry whose value shall be loaded.
1121 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1122 long PositionOnEntry = ftell(fp);
1123 LoadDocEntry(entry);
1124 fseek(fp, PositionOnEntry, SEEK_SET);
1128 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1130 * @return The properly swaped 32 bits integer.
1132 guint32 gdcmDocument::SwapLong(guint32 a) {
1137 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1138 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1142 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1146 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1149 std::cout << "swapCode= " << sw << std::endl;
1150 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1157 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1159 * @return The properly unswaped 32 bits integer.
1161 guint32 gdcmDocument::UnswapLong(guint32 a) {
1166 * \brief Swaps the bytes so they agree with the processor order
1167 * @return The properly swaped 16 bits integer.
1169 guint16 gdcmDocument::SwapShort(guint16 a) {
1170 if ( (sw==4321) || (sw==2143) )
1171 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1176 * \brief Unswaps the bytes so they agree with the processor order
1177 * @return The properly unswaped 16 bits integer.
1179 guint16 gdcmDocument::UnswapShort(guint16 a) {
1180 return SwapShort(a);
1183 //-----------------------------------------------------------------------------
1187 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1188 * @return length of the parsed set.
1191 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1193 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1194 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1198 unsigned long l = 0;
1201 depth = set->GetDepthLevel();
1204 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1207 NewDocEntry = ReadNextDocEntry( );
1211 vr = NewDocEntry->GetVR();
1215 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1218 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1219 NewValEntry->Copy(NewDocEntry);
1220 NewValEntry->SetDepthLevel(depth);
1221 set->AddEntry(NewValEntry);
1222 LoadDocEntry(NewValEntry);
1223 if (NewValEntry->isItemDelimitor())
1225 if ( !delim_mode && ftell(fp)-offset >= l_max)
1232 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1234 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1235 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1236 "nor BinEntry. Probably unknown VR.");
1239 ////// BinEntry or UNKOWN VR:
1240 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1241 bn->Copy(NewDocEntry);
1246 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1247 NewDocEntry->GetElement() == 0x0010 )
1249 if (NewDocEntry->GetReadLength()==0xffffffff)
1251 // Broken US.3405.1.dcm
1252 Parse7FE0(); // to skip the pixels
1253 // (multipart JPEG/RLE are trouble makers)
1257 SkipToNextDocEntry(NewDocEntry);
1258 l = NewDocEntry->GetFullLength();
1263 // to be sure we are at the beginning
1264 SkipToNextDocEntry(NewDocEntry);
1265 l = NewDocEntry->GetFullLength();
1271 l=NewDocEntry->GetReadLength();
1272 if (l != 0) // don't mess the delim_mode for zero-length sequence
1273 if (l == 0xffffffff)
1277 // no other way to create it ...
1278 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1279 set->GetDepthLevel());
1280 sq->Copy(NewDocEntry);
1281 sq->SetDelimitorMode(delim_mode);
1282 sq->SetDepthLevel(depth);
1285 { // Don't try to parse zero-length sequences
1286 long lgt = ParseSQ( sq,
1287 NewDocEntry->GetOffset(),
1289 (void)lgt; //not used...
1292 if ( !delim_mode && ftell(fp)-offset >= l_max)
1299 return l; // Probably useless
1303 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1304 * @return parsed length for this level
1306 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1307 long offset, long l_max, bool delim_mode)
1309 int SQItemNumber = 0;
1311 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1316 int depth = set->GetDepthLevel();
1317 (void)depth; //not used
1321 NewDocEntry = ReadNextDocEntry();
1325 if (NewDocEntry->isSequenceDelimitor()) {
1326 set->SetSequenceDelimitationItem(NewDocEntry);
1330 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1334 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1335 itemSQ->AddEntry(NewDocEntry);
1336 l= NewDocEntry->GetReadLength();
1338 if (l == 0xffffffff)
1343 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1345 set->AddEntry(itemSQ,SQItemNumber);
1347 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1351 lgth = ftell(fp) - offset;
1356 * \brief Loads the element content if its length doesn't exceed
1357 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1358 * @param Entry Header Entry (Dicom Element) to be dealt with
1360 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1363 guint16 group = Entry->GetGroup();
1364 std::string vr= Entry->GetVR();
1365 guint32 length = Entry->GetLength();
1367 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1369 // A SeQuence "contains" a set of Elements.
1370 // (fffe e000) tells us an Element is beginning
1371 // (fffe e00d) tells us an Element just ended
1372 // (fffe e0dd) tells us the current SeQuence just ended
1373 if( group == 0xfffe ) {
1374 // NO more value field for SQ !
1378 // When the length is zero things are easy:
1379 if ( length == 0 ) {
1380 ((gdcmValEntry *)Entry)->SetValue("");
1384 // The elements whose length is bigger than the specified upper bound
1385 // are not loaded. Instead we leave a short notice of the offset of
1386 // the element content and it's length.
1388 std::ostringstream s;
1389 if (length > MaxSizeLoadEntry) {
1390 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1392 s << "gdcm::NotLoaded (BinEntry)";
1393 s << " Address:" << (long)Entry->GetOffset();
1394 s << " Length:" << Entry->GetLength();
1395 s << " x(" << std::hex << Entry->GetLength() << ")";
1396 BinEntryPtr->SetValue(s.str());
1398 // to be sure we are at the end of the value ...
1399 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1401 // Be carefull : a BinEntry IS_A ValEntry ...
1402 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1404 s << "gdcm::NotLoaded. (ValEntry)";
1405 s << " Address:" << (long)Entry->GetOffset();
1406 s << " Length:" << Entry->GetLength();
1407 s << " x(" << std::hex << Entry->GetLength() << ")";
1408 ValEntryPtr->SetValue(s.str());
1410 // to be sure we are at the end of the value ...
1411 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1415 // When we find a BinEntry not very much can be done :
1416 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1418 LoadEntryVoidArea(BinEntryPtr);
1419 s << "gdcm::Loaded (BinEntry)";
1420 BinEntryPtr->SetValue(s.str());
1425 // Any compacter code suggested (?)
1426 if ( IsDocEntryAnInteger(Entry) ) {
1428 std::ostringstream s;
1430 // When short integer(s) are expected, read and convert the following
1431 // n *two characters properly i.e. as short integers as opposed to strings.
1432 // Elements with Value Multiplicity > 1
1433 // contain a set of integers (not a single one)
1434 if (vr == "US" || vr == "SS") {
1436 NewInt = ReadInt16();
1439 for (int i=1; i < nbInt; i++) {
1441 NewInt = ReadInt16();
1446 // When integer(s) are expected, read and convert the following
1447 // n * four characters properly i.e. as integers as opposed to strings.
1448 // Elements with Value Multiplicity > 1
1449 // contain a set of integers (not a single one)
1450 else if (vr == "UL" || vr == "SL") {
1452 NewInt = ReadInt32();
1455 for (int i=1; i < nbInt; i++) {
1457 NewInt = ReadInt32();
1462 #ifdef GDCM_NO_ANSI_STRING_STREAM
1463 s << std::ends; // to avoid oddities on Solaris
1464 #endif //GDCM_NO_ANSI_STRING_STREAM
1466 ((gdcmValEntry *)Entry)->SetValue(s.str());
1470 // We need an additional byte for storing \0 that is not on disk
1471 std::string NewValue(length,0);
1472 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1473 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) ) {
1474 if ( item_read != 1 ) {
1475 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1476 ValEntry->SetValue("gdcm::UnRead");
1480 if( (vr == "UI") ) // Because of correspondance with the VR dic
1481 ValEntry->SetValue(NewValue.c_str());
1483 ValEntry->SetValue(NewValue);
1486 std::cout << "Should have a ValEntry, here !" << std::endl;
1493 * \brief Find the value Length of the passed Header Entry
1494 * @param Entry Header Entry whose length of the value shall be loaded.
1496 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1497 uint16_t element = Entry->GetElement();
1498 std::string vr = Entry->GetVR();
1502 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1504 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1506 // The following reserved two bytes (see PS 3.5-2001, section
1507 // 7.1.2 Data element structure with explicit vr p27) must be
1508 // skipped before proceeding on reading the length on 4 bytes.
1509 fseek(fp, 2L, SEEK_CUR);
1510 uint32_t length32 = ReadInt32();
1512 if ( (vr == "OB") && (length32 == 0xffffffff) )
1514 uint32_t LengthOB = FindDocEntryLengthOB();
1517 // Computing the length failed (this happens with broken
1518 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1519 // chance to get the pixels by deciding the element goes
1520 // until the end of the file. Hence we artificially fix the
1521 // the length and proceed.
1522 long CurrentPosition = ftell(fp);
1523 fseek(fp,0L,SEEK_END);
1524 long LengthUntilEOF = ftell(fp) - CurrentPosition;
1525 fseek(fp, CurrentPosition, SEEK_SET);
1526 Entry->SetLength(LengthUntilEOF);
1530 Entry->SetLength(LengthOB);
1533 FixDocEntryFoundLength(Entry, length32);
1537 // Length is encoded on 2 bytes.
1538 length16 = ReadInt16();
1540 // We can tell the current file is encoded in big endian (like
1541 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1542 // and it's value is the one of the encoding of a big endian file.
1543 // In order to deal with such big endian encoded files, we have
1544 // (at least) two strategies:
1545 // * when we load the "Transfer Syntax" tag with value of big endian
1546 // encoding, we raise the proper flags. Then we wait for the end
1547 // of the META group (0x0002) among which is "Transfer Syntax",
1548 // before switching the swap code to big endian. We have to postpone
1549 // the switching of the swap code since the META group is fully encoded
1550 // in little endian, and big endian coding only starts at the next
1551 // group. The corresponding code can be hard to analyse and adds
1552 // many additional unnecessary tests for regular tags.
1553 // * the second strategy consists in waiting for trouble, that shall
1554 // appear when we find the first group with big endian encoding. This
1555 // is easy to detect since the length of a "Group Length" tag (the
1556 // ones with zero as element number) has to be of 4 (0x0004). When we
1557 // encounter 1024 (0x0400) chances are the encoding changed and we
1558 // found a group with big endian encoding.
1559 // We shall use this second strategy. In order to make sure that we
1560 // can interpret the presence of an apparently big endian encoded
1561 // length of a "Group Length" without committing a big mistake, we
1562 // add an additional check: we look in the already parsed elements
1563 // for the presence of a "Transfer Syntax" whose value has to be "big
1564 // endian encoding". When this is the case, chances are we have got our
1565 // hands on a big endian encoded file: we switch the swap code to
1566 // big endian and proceed...
1567 if ( (element == 0x0000) && (length16 == 0x0400) )
1569 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1571 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1576 SwitchSwapToBigEndian();
1577 // Restore the unproperly loaded values i.e. the group, the element
1578 // and the dictionary entry depending on them.
1579 uint16_t CorrectGroup = SwapShort(Entry->GetGroup());
1580 uint16_t CorrectElem = SwapShort(Entry->GetElement());
1581 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1585 // This correct tag is not in the dictionary. Create a new one.
1586 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1588 // FIXME this can create a memory leaks on the old entry that be
1589 // left unreferenced.
1590 Entry->SetDictEntry(NewTag);
1593 // Heuristic: well, some files are really ill-formed.
1594 if ( length16 == 0xffff)
1597 // Length16= 0xffff means that we deal with
1598 // 'Unknown Length' Sequence
1600 FixDocEntryFoundLength(Entry, (uint32_t)length16);
1605 // Either implicit VR or a non DICOM conformal (see note below) explicit
1606 // VR that ommited the VR of (at least) this element. Farts happen.
1607 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1608 // on Data elements "Implicit and Explicit VR Data Elements shall
1609 // not coexist in a Data Set and Data Sets nested within it".]
1610 // Length is on 4 bytes.
1612 FixDocEntryFoundLength(Entry, ReadInt32());
1618 * \brief Find the Value Representation of the current Dicom Element.
1621 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1623 if (Filetype != gdcmExplicitVR)
1628 long PositionOnEntry = ftell(fp);
1629 // Warning: we believe this is explicit VR (Value Representation) because
1630 // we used a heuristic that found "UL" in the first tag. Alas this
1631 // doesn't guarantee that all the tags will be in explicit VR. In some
1632 // cases (see e-film filtered files) one finds implicit VR tags mixed
1633 // within an explicit VR file. Hence we make sure the present tag
1634 // is in explicit VR and try to fix things if it happens not to be
1637 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1639 if(!CheckDocEntryVR(Entry,VR))
1641 fseek(fp, PositionOnEntry, SEEK_SET);
1642 // When this element is known in the dictionary we shall use, e.g. for
1643 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1644 // dictionary entry. Still we have to flag the element as implicit since
1645 // we know now our assumption on expliciteness is not furfilled.
1647 if ( Entry->IsVRUnknown() )
1648 Entry->SetVR("Implicit");
1649 Entry->SetImplicitVR();
1654 * \brief Check the correspondance between the VR of the header entry
1655 * and the taken VR. If they are different, the header entry is
1656 * updated with the new VR.
1657 * @param Entry Header Entry to check
1658 * @param vr Dicom Value Representation
1659 * @return false if the VR is incorrect of if the VR isn't referenced
1660 * otherwise, it returns true
1662 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1664 char msg[100]; // for sprintf
1665 bool RealExplicit = true;
1667 // Assume we are reading a falsely explicit VR file i.e. we reached
1668 // a tag where we expect reading a VR but are in fact we read the
1669 // first to bytes of the length. Then we will interogate (through find)
1670 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1671 // both GCC and VC++ implementations of the STL map. Hence when the
1672 // expected VR read happens to be non-ascii characters we consider
1673 // we hit falsely explicit VR tag.
1675 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1676 RealExplicit = false;
1678 // CLEANME searching the dicom_vr at each occurence is expensive.
1679 // PostPone this test in an optional integrity check at the end
1680 // of parsing or only in debug mode.
1681 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1682 RealExplicit= false;
1684 if ( !RealExplicit )
1686 // We thought this was explicit VR, but we end up with an
1687 // implicit VR tag. Let's backtrack.
1688 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1689 Entry->GetGroup(),Entry->GetElement());
1690 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1691 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1692 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1693 Entry->GetGroup(),Entry->GetElement(),
1694 "UL","FIXME","Group Length");
1695 Entry->SetDictEntry(NewEntry);
1700 if ( Entry->IsVRUnknown() )
1702 // When not a dictionary entry, we can safely overwrite the VR.
1703 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1709 else if ( Entry->GetVR() != vr )
1711 // The VR present in the file and the dictionary disagree. We assume
1712 // the file writer knew best and use the VR of the file. Since it would
1713 // be unwise to overwrite the VR of a dictionary (since it would
1714 // compromise it's next user), we need to clone the actual DictEntry
1715 // and change the VR for the read one.
1716 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1717 Entry->GetGroup(),Entry->GetElement(),
1718 vr,"FIXME",Entry->GetName());
1719 Entry->SetDictEntry(NewEntry);
1725 * \brief Get the transformed value of the header entry. The VR value
1726 * is used to define the transformation to operate on the value
1727 * \warning NOT end user intended method !
1729 * @return Transformed entry value
1731 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1733 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1735 std::string val=((gdcmValEntry *)Entry)->GetValue();
1736 std::string vr=Entry->GetVR();
1737 guint32 length = Entry->GetLength();
1738 std::ostringstream s;
1741 // When short integer(s) are expected, read and convert the following
1742 // n * 2 bytes properly i.e. as a multivaluated strings
1743 // (each single value is separated fromthe next one by '\'
1744 // as usual for standard multivaluated filels
1745 // Elements with Value Multiplicity > 1
1746 // contain a set of short integers (not a single one)
1748 if (vr == "US" || vr == "SS")
1753 for (int i=0; i < nbInt; i++)
1757 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1758 NewInt16 = SwapShort(NewInt16);
1763 // When integer(s) are expected, read and convert the following
1764 // n * 4 bytes properly i.e. as a multivaluated strings
1765 // (each single value is separated fromthe next one by '\'
1766 // as usual for standard multivaluated filels
1767 // Elements with Value Multiplicity > 1
1768 // contain a set of integers (not a single one)
1769 else if (vr == "UL" || vr == "SL")
1774 for (int i=0; i < nbInt; i++)
1778 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1779 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1780 NewInt32=SwapLong(NewInt32);
1784 #ifdef GDCM_NO_ANSI_STRING_STREAM
1785 s << std::ends; // to avoid oddities on Solaris
1786 #endif //GDCM_NO_ANSI_STRING_STREAM
1790 return ((gdcmValEntry *)Entry)->GetValue();
1794 * \brief Get the reverse transformed value of the header entry. The VR
1795 * value is used to define the reverse transformation to operate on
1797 * \warning NOT end user intended method !
1799 * @return Reverse transformed entry value
1801 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1803 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1805 std::string vr=Entry->GetVR();
1806 std::ostringstream s;
1807 std::vector<std::string> tokens;
1809 if (vr == "US" || vr == "SS")
1813 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1814 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1815 for (unsigned int i=0; i<tokens.size();i++)
1817 NewInt16 = atoi(tokens[i].c_str());
1818 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1822 if (vr == "UL" || vr == "SL")
1826 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1827 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1828 for (unsigned int i=0; i<tokens.size();i++)
1830 NewInt32 = atoi(tokens[i].c_str());
1831 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1832 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1837 #ifdef GDCM_NO_ANSI_STRING_STREAM
1838 s << std::ends; // to avoid oddities on Solaris
1839 #endif //GDCM_NO_ANSI_STRING_STREAM
1843 return ((gdcmValEntry *)Entry)->GetValue();
1847 * \brief Skip a given Header Entry
1848 * \warning NOT end user intended method !
1851 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1853 SkipBytes(entry->GetLength());
1857 * \brief Skips to the begining of the next Header Entry
1858 * \warning NOT end user intended method !
1861 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1863 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1864 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1868 * \brief When the length of an element value is obviously wrong (because
1869 * the parser went Jabberwocky) one can hope improving things by
1870 * applying some heuristics.
1872 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1873 guint32 FoundLength)
1875 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1876 if ( FoundLength == 0xffffffff) {
1880 guint16 gr =Entry->GetGroup();
1881 guint16 el =Entry->GetElement();
1883 if (FoundLength%2) {
1884 std::ostringstream s;
1885 s << "Warning : Tag with uneven length "
1887 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1888 dbg.Verbose(0, s.str().c_str());
1891 //////// Fix for some naughty General Electric images.
1892 // Allthough not recent many such GE corrupted images are still present
1893 // on Creatis hard disks. Hence this fix shall remain when such images
1894 // are no longer in user (we are talking a few years, here)...
1895 // Note: XMedCom probably uses such a trick since it is able to read
1896 // those pesky GE images ...
1897 if (FoundLength == 13) { // Only happens for this length !
1898 if ( (Entry->GetGroup() != 0x0008)
1899 || ( (Entry->GetElement() != 0x0070)
1900 && (Entry->GetElement() != 0x0080) ) )
1903 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1907 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1908 // Occurence of such images is quite low (unless one leaves close to a
1909 // 'Leonardo' source. Hence, one might consider commenting out the
1910 // following fix on efficiency reasons.
1912 if ( (Entry->GetGroup() == 0x0009)
1913 && ( (Entry->GetElement() == 0x1113)
1914 || (Entry->GetElement() == 0x1114) ) )
1917 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1920 //////// Deal with sequences, but only on users request:
1922 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1924 FoundLength = 0; // ReadLength is unchanged
1927 //////// We encountered a 'delimiter' element i.e. a tag of the form
1928 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1929 // taken into account.
1931 if(Entry->GetGroup() == 0xfffe)
1933 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1934 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1935 // causes extra troubles...
1936 if( Entry->GetElement() != 0x0000 )
1942 Entry->SetUsableLength(FoundLength);
1946 * \brief Apply some heuristics to predict whether the considered
1947 * element value contains/represents an integer or not.
1948 * @param Entry The element value on which to apply the predicate.
1949 * @return The result of the heuristical predicate.
1951 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1952 guint16 element = Entry->GetElement();
1953 guint16 group = Entry->GetGroup();
1954 std::string vr = Entry->GetVR();
1955 guint32 length = Entry->GetLength();
1957 // When we have some semantics on the element we just read, and if we
1958 // a priori know we are dealing with an integer, then we shall be
1959 // able to swap it's element value properly.
1960 if ( element == 0 ) // This is the group length of the group
1966 // Allthough this should never happen, still some images have a
1967 // corrupted group length [e.g. have a glance at offset x(8336) of
1968 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1969 // Since for dicom compliant and well behaved headers, the present
1970 // test is useless (and might even look a bit paranoid), when we
1971 // encounter such an ill-formed image, we simply display a warning
1972 // message and proceed on parsing (while crossing fingers).
1973 std::ostringstream s;
1974 int filePosition = ftell(fp);
1975 s << "Erroneous Group Length element length on : (" \
1976 << std::hex << group << " , " << element
1977 << ") -before- position x(" << filePosition << ")"
1978 << "lgt : " << length;
1979 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1983 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1990 * \brief Find the Length till the next sequence delimiter
1991 * \warning NOT end user intended method !
1995 uint32_t gdcmDocument::FindDocEntryLengthOB(void) {
1996 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1999 long PositionOnEntry = ftell(fp);
2000 bool FoundSequenceDelimiter = false;
2001 uint32_t TotalLength = 0;
2002 uint32_t ItemLength;
2004 while ( ! FoundSequenceDelimiter)
2011 // We have to decount the group and element we just read
2014 if ( ( g != 0xfffe )
2015 || ( ( n != 0xe0dd ) && ( n != 0xe000 ) ) )
2017 dbg.Verbose(1, "gdcmDocument::FindLengthOB: neither an Item tag "
2018 "nor a Sequence delimiter tag.");
2019 fseek(fp, PositionOnEntry, SEEK_SET);
2025 FoundSequenceDelimiter = true;
2027 ItemLength = ReadInt32();
2028 // We add 4 bytes since we just read the ItemLength with ReadInt32
2029 TotalLength += ItemLength + 4;
2030 SkipBytes(ItemLength);
2032 if ( FoundSequenceDelimiter )
2035 fseek(fp, PositionOnEntry, SEEK_SET);
2040 * \brief Reads a supposed to be 16 Bits integer
2041 * (swaps it depending on processor endianity)
2042 * @return read value
2044 guint16 gdcmDocument::ReadInt16() {
2047 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2048 if ( item_read != 1 ) {
2050 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2060 * \brief Reads a supposed to be 32 Bits integer
2061 * (swaps it depending on processor endianity)
2062 * @return read value
2064 guint32 gdcmDocument::ReadInt32() {
2067 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2068 if ( item_read != 1 ) {
2070 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2080 * \brief skips bytes inside the source file
2081 * \warning NOT end user intended method !
2084 void gdcmDocument::SkipBytes(guint32 NBytes) {
2085 //FIXME don't dump the returned value
2086 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2090 * \brief Loads all the needed Dictionaries
2091 * \warning NOT end user intended method !
2093 void gdcmDocument::Initialise(void)
2095 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2100 * \brief Discover what the swap code is (among little endian, big endian,
2101 * bad little endian, bad big endian).
2103 * @return false when we are absolutely sure
2104 * it's neither ACR-NEMA nor DICOM
2105 * true when we hope ours assuptions are OK
2107 bool gdcmDocument::CheckSwap() {
2109 // The only guaranted way of finding the swap code is to find a
2110 // group tag since we know it's length has to be of four bytes i.e.
2111 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2112 // occurs when we can't find such group...
2114 guint32 x=4; // x : for ntohs
2115 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2121 char deb[HEADER_LENGTH_TO_READ];
2123 // First, compare HostByteOrder and NetworkByteOrder in order to
2124 // determine if we shall need to swap bytes (i.e. the Endian type).
2130 // The easiest case is the one of a DICOM header, since it possesses a
2131 // file preamble where it suffice to look for the string "DICM".
2132 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2135 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2136 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2138 // Next, determine the value representation (VR). Let's skip to the
2139 // first element (0002, 0000) and check there if we find "UL"
2140 // - or "OB" if the 1st one is (0002,0001) -,
2141 // in which case we (almost) know it is explicit VR.
2142 // WARNING: if it happens to be implicit VR then what we will read
2143 // is the length of the group. If this ascii representation of this
2144 // length happens to be "UL" then we shall believe it is explicit VR.
2145 // FIXME: in order to fix the above warning, we could read the next
2146 // element value (or a couple of elements values) in order to make
2147 // sure we are not commiting a big mistake.
2148 // We need to skip :
2149 // * the 128 bytes of File Preamble (often padded with zeroes),
2150 // * the 4 bytes of "DICM" string,
2151 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2152 // i.e. a total of 136 bytes.
2156 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2157 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2158 // *Implicit* VR. -and it is !-
2160 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2161 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2162 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2163 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2164 // when Write DCM *adds*
2166 // Use gdcmDocument::dicom_vr to test all the possibilities
2167 // instead of just checking for UL, OB and UI !? group 0000
2169 Filetype = gdcmExplicitVR;
2170 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2171 "explicit Value Representation");
2175 Filetype = gdcmImplicitVR;
2176 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2177 "not an explicit Value Representation");
2183 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2184 "HostByteOrder != NetworkByteOrder");
2189 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2190 "HostByteOrder = NetworkByteOrder");
2193 // Position the file position indicator at first tag (i.e.
2194 // after the file preamble and the "DICM" string).
2196 fseek (fp, 132L, SEEK_SET);
2200 // Alas, this is not a DicomV3 file and whatever happens there is no file
2201 // preamble. We can reset the file position indicator to where the data
2202 // is (i.e. the beginning of the file).
2203 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2206 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2207 // By clean we mean that the length of the first tag is written down.
2208 // If this is the case and since the length of the first group HAS to be
2209 // four (bytes), then determining the proper swap code is straightforward.
2212 // We assume the array of char we are considering contains the binary
2213 // representation of a 32 bits integer. Hence the following dirty
2215 s32 = *((guint32 *)(entCur));
2236 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2237 // It is time for despaired wild guesses.
2238 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2239 // i.e. the 'group length' element is not present :
2241 // check the supposed to be 'group number'
2242 // 0x0002 or 0x0004 or 0x0008
2243 // to determine ' sw' value .
2244 // Only 0 or 4321 will be possible
2245 // (no oportunity to check for the formerly well known
2246 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2247 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2248 // the file IS NOT ACR-NEMA nor DICOM V3
2249 // Find a trick to tell it the caller...
2251 s16 = *((guint16 *)(deb));
2267 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2268 "ACR/NEMA unfound swap info (Really hopeless !)");
2269 Filetype = gdcmUnknown;
2273 // Then the only info we have is the net2host one.
2283 * \brief Restore the unproperly loaded values i.e. the group, the element
2284 * and the dictionary entry depending on them.
2286 void gdcmDocument::SwitchSwapToBigEndian(void)
2288 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2289 "Switching to BigEndian mode.");
2310 * \brief during parsing, Header Elements too long are not loaded in memory
2313 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2317 if ((guint32)NewSize >= (guint32)0xffffffff)
2319 MaxSizeLoadEntry = 0xffffffff;
2322 MaxSizeLoadEntry = NewSize;
2327 * \brief Header Elements too long will not be printed
2328 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2331 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2335 if ((guint32)NewSize >= (guint32)0xffffffff)
2337 MaxSizePrintEntry = 0xffffffff;
2340 MaxSizePrintEntry = NewSize;
2346 * \brief Read the next tag but WITHOUT loading it's value
2347 * (read the 'Group Number', the 'Element Number',
2348 * gets the Dict Entry
2349 * gets the VR, gets the length, gets the offset value)
2350 * @return On succes the newly created DocEntry, NULL on failure.
2352 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2354 gdcmDocEntry *NewEntry;
2359 // We reached the EOF (or an error occured) therefore
2360 // header parsing has to be considered as finished.
2361 return (gdcmDocEntry *)0;
2363 NewEntry = NewDocEntryByNumber(g, n);
2364 FindDocEntryVR(NewEntry);
2365 FindDocEntryLength(NewEntry);
2373 NewEntry->SetOffset(ftell(fp));
2379 * \brief Generate a free TagKey i.e. a TagKey that is not present
2380 * in the TagHt dictionary.
2381 * @param group The generated tag must belong to this group.
2382 * @return The element of tag with given group which is fee.
2384 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2386 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2388 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2389 if (tagHT.count(key) == 0)
2396 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2397 * is placed at the beginning of a tag check whether this
2398 * tag is (TestGroup, TestElement).
2399 * \warning On success the internal file pointer \ref gdcmDocument::fp
2400 * is modified to point after the tag.
2401 * On failure (i.e. when the tag wasn't the expected tag
2402 * (TestGroup, TestElement) the internal file pointer
2403 * \ref gdcmDocument::fp is restored to it's original position.
2404 * @param TestGroup The expected group of the tag.
2405 * @param TestElement The expected Element of the tag.
2406 * @return True on success, false otherwise.
2408 bool gdcmDocument::ReadTag(uint16_t TestGroup, uint16_t TestElement)
2410 uint16_t ItemTagGroup;
2411 uint16_t ItemTagElement;
2412 long PositionOnEntry = ftell(fp);
2413 long CurrentPosition = ftell(fp); // On debugging purposes
2415 //// Read the Item Tag group and element, and make
2416 // sure they are what we expected:
2417 ItemTagGroup = ReadInt16();
2418 ItemTagElement = ReadInt16();
2419 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2421 std::ostringstream s;
2422 s << " We should have found tag (";
2423 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2424 s << " but instead we encountered tag (";
2425 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2427 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2428 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2429 dbg.Verbose(0, s.str().c_str());
2430 fseek(fp, PositionOnEntry, SEEK_SET);
2437 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2438 * is placed at the beginning of a tag (TestGroup, TestElement),
2439 * read the length associated to the Tag.
2440 * \warning On success the internal file pointer \ref gdcmDocument::fp
2441 * is modified to point after the tag and it's length.
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 On success returns the length associated to the tag. On failure
2450 uint32_t gdcmDocument::ReadTagLength(uint16_t TestGroup, uint16_t TestElement)
2452 long PositionOnEntry = ftell(fp);
2454 if ( !ReadTag(TestGroup, TestElement) )
2459 //// Then read the associated Item Length
2460 long CurrentPosition = ftell(fp);
2462 ItemLength = ReadInt32();
2464 std::ostringstream s;
2465 s << "Basic Item Length is: "
2466 << ItemLength << std::endl;
2467 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2468 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2474 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2475 * No other way so 'skip' the Data
2478 void gdcmDocument::Parse7FE0 (void)
2480 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2484 if ( IsImplicitVRLittleEndianTransferSyntax()
2485 || IsExplicitVRLittleEndianTransferSyntax()
2486 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2487 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2490 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2492 //// Read the Basic Offset Table Item Tag length...
2493 guint32 ItemLength = ReadTagLength(0xfffe, 0xe000);
2495 //// ... and then read length[s] itself[themselves]. We don't use
2496 // the values read (BTW what is the purpous of those lengths ?)
2497 if (ItemLength != 0) {
2498 // BTW, what is the purpous of those length anyhow !?
2499 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2500 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2501 for (unsigned int i=0; i < ItemLength; i += 4){
2502 guint32 IndividualLength;
2503 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2504 std::ostringstream s;
2505 s << " Read one length: ";
2506 s << std::hex << IndividualLength << std::endl;
2507 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2511 if ( ! IsRLELossLessTransferSyntax() )
2515 //// We then skip (not reading them) all the fragments of images:
2516 while ( (ItemLength = ReadTagLength(0xfffe, 0xe000)) )
2518 SkipBytes(ItemLength);
2525 long RleSegmentLength[15], fragmentLength;
2527 // While we find some items:
2528 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2530 // Parse fragments of the current Fragment (Frame)
2531 //------------------ scanning (not reading) fragment pixels
2532 guint32 nbRleSegments = ReadInt32();
2533 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2535 //// Reading RLE Segments Offset Table
2536 guint32 RleSegmentOffsetTable[15];
2537 for(int k=1; k<=15; k++) {
2539 RleSegmentOffsetTable[k] = ReadInt32();
2540 printf(" at : %x Offset Segment %d : %d (%x)\n",
2541 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2542 RleSegmentOffsetTable[k]);
2545 // skipping (not reading) RLE Segments
2546 if (nbRleSegments>1) {
2547 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2548 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2549 - RleSegmentOffsetTable[k];
2551 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2552 k,(unsigned)RleSegmentLength[k],
2553 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2554 SkipBytes(RleSegmentLength[k]);
2558 RleSegmentLength[nbRleSegments]= fragmentLength
2559 - RleSegmentOffsetTable[nbRleSegments];
2561 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2562 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2563 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2564 SkipBytes(RleSegmentLength[nbRleSegments]);
2567 // Make sure that at the end of the item we encounter a 'Sequence
2569 if ( ! ReadTag(0xfffe, 0xe0dd) )
2571 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2572 dbg.Verbose(0, " at end of RLE item sequence");
2580 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2581 * \warning Does NOT work with ACR-NEMA files
2582 * \todo Find a trick to solve the pb (use RET fields ?)
2584 * @return true if 'smaller'
2586 bool gdcmDocument::operator<(gdcmDocument &document)
2591 s1=this->GetEntryByNumber(0x0010,0x0010);
2592 s2=document.GetEntryByNumber(0x0010,0x0010);
2600 s1=this->GetEntryByNumber(0x0010,0x0020);
2601 s2=document.GetEntryByNumber(0x0010,0x0020);
2608 // Study Instance UID
2609 s1=this->GetEntryByNumber(0x0020,0x000d);
2610 s2=document.GetEntryByNumber(0x0020,0x000d);
2617 // Serie Instance UID
2618 s1=this->GetEntryByNumber(0x0020,0x000e);
2619 s2=document.GetEntryByNumber(0x0020,0x000e);
2631 //-----------------------------------------------------------------------------