1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/28 16:00:18 $
7 Version: $Revision: 1.40 $
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 enableSequences=true; // JPR // TODO : remove params out of the constructor
105 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
106 Filename = inFilename;
109 if ( !OpenFile(exception_on_error))
112 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
116 fseek(fp,0L,SEEK_END);
117 long lgt = ftell(fp);
121 long beg = ftell(fp);
126 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
127 (void)l; //is l used anywhere ?
131 // Load 'non string' values
133 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
134 if( PhotometricInterpretation == "PALETTE COLOR " ) {
135 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
136 LoadEntryVoidArea(0x0028,0x1201); // R LUT
137 LoadEntryVoidArea(0x0028,0x1202); // G LUT
138 LoadEntryVoidArea(0x0028,0x1203); // B LUT
140 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
141 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
142 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
144 //FIXME later : how to use it?
145 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
149 // --------------------------------------------------------------
150 // Special Patch to allow gdcm to read ACR-LibIDO formated images
152 // if recognition code tells us we deal with a LibIDO image
153 // we switch lineNumber and columnNumber
156 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
157 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
158 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
159 // with "little-endian strings"
161 Filetype = gdcmACR_LIBIDO;
162 std::string rows = GetEntryByNumber(0x0028, 0x0010);
163 std::string columns = GetEntryByNumber(0x0028, 0x0011);
164 SetEntryByNumber(columns, 0x0028, 0x0010);
165 SetEntryByNumber(rows , 0x0028, 0x0011);
167 // ----------------- End of Special Patch ----------------
169 printLevel = 1; // 'Medium' print level by default
174 * @param exception_on_error
176 gdcmDocument::gdcmDocument(bool exception_on_error)
177 :gdcmElementSet(-1) {
178 (void)exception_on_error;
179 //enableSequences=0; // ?!? JPR
181 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
184 printLevel = 1; // 'Medium' print level by default
188 * \brief Canonical destructor.
190 gdcmDocument::~gdcmDocument (void) {
194 // Recursive clean up of sequences
195 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
202 //-----------------------------------------------------------------------------
206 * \brief Prints The Dict Entries of THE public Dicom Dictionary
209 void gdcmDocument::PrintPubDict(std::ostream & os) {
210 RefPubDict->Print(os);
214 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
217 void gdcmDocument::PrintShaDict(std::ostream & os) {
218 RefShaDict->Print(os);
221 //-----------------------------------------------------------------------------
224 * \brief Get the public dictionary used
226 gdcmDict *gdcmDocument::GetPubDict(void) {
231 * \brief Get the shadow dictionary used
233 gdcmDict *gdcmDocument::GetShaDict(void) {
238 * \brief Set the shadow dictionary used
239 * \param dict dictionary to use in shadow
241 bool gdcmDocument::SetShaDict(gdcmDict *dict){
247 * \brief Set the shadow dictionary used
248 * \param dictName name of the dictionary to use in shadow
250 bool gdcmDocument::SetShaDict(DictKey dictName){
251 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
256 * \brief This predicate, based on hopefully reasonable heuristics,
257 * decides whether or not the current gdcmDocument was properly parsed
258 * and contains the mandatory information for being considered as
259 * a well formed and usable Dicom/Acr File.
260 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
263 bool gdcmDocument::IsReadable(void) {
265 if(Filetype==gdcmUnknown) {
266 std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
267 << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
268 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
273 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
283 * \brief Internal function that checks whether the Transfer Syntax given
284 * as argument is the one present in the current document.
285 * @param SyntaxToCheck The transfert syntax we need to check against.
286 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
287 * the current document. False either when the document contains
288 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
290 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
292 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
296 // The entry might be present but not loaded (parsing and loading
297 // happen at differente stages): try loading and proceed with check...
298 LoadDocEntrySafe(Entry);
299 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
301 std::string Transfer = ValEntry->GetValue();
302 // The actual transfer (as read from disk) might be padded. We
303 // first need to remove the potential padding. We can make the
304 // weak assumption that padding was not executed with digits...
305 while ( ! isdigit(Transfer[Transfer.length()-1]) )
307 Transfer.erase(Transfer.length()-1, 1);
309 if ( Transfer == SyntaxToCheck )
316 * \brief Determines if the Transfer Syntax of the present document
317 * corresponds to a Implicit Value Representation of
319 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
320 * @return True when ImplicitVRLittleEndian found. False in all other cases.
322 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
324 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
328 * \brief Determines if the Transfer Syntax was already encountered
329 * and if it corresponds to a ExplicitVRLittleEndian one.
330 * @return True when ExplicitVRLittleEndian found. False in all other cases.
332 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
334 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
338 * \brief Determines if the Transfer Syntax was already encountered
339 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
340 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
342 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
344 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
348 * \brief Determines if the Transfer Syntax was already encountered
349 * and if it corresponds to a Explicit VR Big Endian one.
350 * @return True when big endian found. False in all other cases.
352 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
354 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
358 * \brief Determines if the Transfer Syntax was already encountered
359 * and if it corresponds to a JPEGBaseLineProcess1 one.
360 * @return True when JPEGBaseLineProcess1found. False in all other cases.
362 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
364 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
368 * \brief Determines if the Transfer Syntax was already encountered
369 * and if it corresponds to a JPEGExtendedProcess2-4 one.
370 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
372 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
374 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
378 * \brief Determines if the Transfer Syntax was already encountered
379 * and if it corresponds to a JPEGExtendeProcess3-5 one.
380 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
382 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
384 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
388 * \brief Determines if the Transfer Syntax was already encountered
389 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
390 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
393 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
395 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
399 * \brief Determines if the Transfer Syntax was already encountered
400 * and if it corresponds to a RLE Lossless one.
401 * @return True when RLE Lossless found. False in all
404 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
406 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
410 * \brief Determines if Transfer Syntax was already encountered
411 * and if it corresponds to a JPEG Lossless one.
412 * @return True when RLE Lossless found. False in all
416 bool gdcmDocument::IsJPEGLossless(void)
418 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
419 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
420 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
424 * \brief Determines if the Transfer Syntax was already encountered
425 * and if it corresponds to a JPEG2000 one
426 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
429 bool gdcmDocument::IsJPEG2000(void)
431 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
432 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
436 * \brief Predicate for dicom version 3 file.
437 * @return True when the file is a dicom version 3.
439 bool gdcmDocument::IsDicomV3(void) {
440 // Checking if Transfert Syntax exists is enough
441 // Anyway, it's to late check if the 'Preamble' was found ...
442 // And ... would it be a rich idea to check ?
443 // (some 'no Preamble' DICOM images exist !)
444 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
448 * \brief returns the File Type
449 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
450 * @return the FileType code
452 FileType gdcmDocument::GetFileType(void) {
457 * \brief opens the file
458 * @param exception_on_error
461 FILE *gdcmDocument::OpenFile(bool exception_on_error)
464 fp=fopen(Filename.c_str(),"rb");
468 if(exception_on_error)
469 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
472 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
481 fread(&zero, (size_t)2, (size_t)1, fp);
483 //ACR -- or DICOM with no Preamble --
484 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
488 fseek(fp, 126L, SEEK_CUR);
490 fread(dicm, (size_t)4, (size_t)1, fp);
491 if( memcmp(dicm, "DICM", 4) == 0 )
495 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
498 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
504 * \brief closes the file
505 * @return TRUE if the close was successfull
507 bool gdcmDocument::CloseFile(void) {
508 int closed = fclose(fp);
516 * \brief Writes in a file all the Header Entries (Dicom Elements)
517 * @param fp file pointer on an already open file
518 * @param filetype Type of the File to be written
519 * (ACR-NEMA, ExplicitVR, ImplicitVR)
520 * \return Always true.
522 void gdcmDocument::Write(FILE* fp,FileType filetype) {
524 /// \todo move the following lines (and a lot of others, to be written)
525 /// to a future function CheckAndCorrectHeader
527 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
528 /// no way (check : FileType est un champ de gdcmDocument ...)
529 /// a moins de se livrer a un tres complique ajout des champs manquants.
530 /// faire un CheckAndCorrectHeader (?)
532 if (filetype == gdcmImplicitVR)
534 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
535 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
537 /// \todo Refer to standards on page 21, chapter 6.2
538 /// "Value representation": values with a VR of UI shall be
539 /// padded with a single trailing null
540 /// in the following case we have to padd manually with a 0
542 SetEntryLengthByNumber(18, 0x0002, 0x0010);
545 if (filetype == gdcmExplicitVR)
547 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
548 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
550 /// \todo Refer to standards on page 21, chapter 6.2
551 /// "Value representation": values with a VR of UI shall be
552 /// padded with a single trailing null
553 /// Dans le cas suivant on doit pader manuellement avec un 0
555 SetEntryLengthByNumber(20, 0x0002, 0x0010);
559 * \todo rewrite later, if really usefull
560 * - 'Group Length' element is optional in DICOM
561 * - but un-updated odd groups lengthes can causes pb
564 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
565 * UpdateGroupLength(false,filetype);
566 * if ( filetype == ACR)
567 * UpdateGroupLength(true,ACR);
570 gdcmElementSet::Write(fp,filetype); // This one is recursive
575 * \brief Modifies the value of a given Header Entry (Dicom Element)
576 * when it exists. Create it with the given value when unexistant.
577 * @param Value (string) Value to be set
578 * @param Group Group number of the Entry
579 * @param Elem Element number of the Entry
580 * \return pointer to the modified/created Header Entry (NULL when creation
584 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
589 gdcmDocEntry* CurrentEntry;
590 gdcmValEntry* ValEntry;
592 CurrentEntry = GetDocEntryByNumber( Group, Elem);
595 // The entry wasn't present and we simply create the required ValEntry:
596 CurrentEntry = NewDocEntryByNumber(Group, Elem);
599 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
600 " NewDocEntryByNumber failed.");
603 ValEntry = new gdcmValEntry(CurrentEntry);
604 if ( !AddEntry(ValEntry))
606 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
607 " failed allthough this is a creation.");
612 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
615 // We need to promote the gdcmDocEntry to a gdcmValEntry:
616 ValEntry = new gdcmValEntry(CurrentEntry);
617 if (!RemoveEntry(CurrentEntry))
619 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
620 " of previous DocEntry failed.");
623 if ( !AddEntry(ValEntry))
625 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
626 " promoted ValEntry failed.");
632 SetEntryByNumber(Value, Group, Elem);
638 * \brief Modifies the value of a given Header Entry (Dicom Element)
639 * when it exists. Create it with the given value when unexistant.
640 * @param voidArea (binary) value to be set
641 * @param Group Group number of the Entry
642 * @param Elem Element number of the Entry
643 * \return pointer to the modified/created Header Entry (NULL when creation
646 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
654 a = GetDocEntryByNumber( Group, Elem);
656 a =NewBinEntryByNumber(Group, Elem);
660 b = new gdcmBinEntry(a);
663 SetEntryByNumber(voidArea, lgth, Group, Elem);
664 b->SetVoidArea(voidArea);
672 * \brief Set a new value if the invoked element exists
673 * Seems to be useless !!!
674 * @param Value new element value
675 * @param Group group number of the Entry
676 * @param Elem element number of the Entry
679 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
681 std::string v = Value;
682 SetEntryByNumber(v, Group, Elem);
686 //-----------------------------------------------------------------------------
690 * \brief Checks if a given Dicom Element exists within the H table
691 * @param group Group number of the searched Dicom Element
692 * @param element Element number of the searched Dicom Element
693 * @return number of occurences
695 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
696 std::string key = gdcmDictEntry::TranslateToKey(group, element );
697 return tagHT.count(key);
701 * \brief Searches within Header Entries (Dicom Elements) parsed with
702 * the public and private dictionaries
703 * for the element value of a given tag.
704 * \warning Don't use any longer : use GetPubEntryByName
705 * @param tagName name of the searched element.
706 * @return Corresponding element value when it exists,
707 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
709 std::string gdcmDocument::GetEntryByName(TagName tagName) {
710 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
711 if( dictEntry == NULL)
714 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
718 * \brief Searches within Header Entries (Dicom Elements) parsed with
719 * the public and private dictionaries
720 * for the element value representation of a given tag.
722 * Obtaining the VR (Value Representation) might be needed by caller
723 * to convert the string typed content to caller's native type
724 * (think of C++ vs Python). The VR is actually of a higher level
725 * of semantics than just the native C++ type.
726 * @param tagName name of the searched element.
727 * @return Corresponding element value representation when it exists,
728 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
730 std::string gdcmDocument::GetEntryVRByName(TagName tagName) {
731 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
732 if( dictEntry == NULL)
735 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
736 dictEntry->GetElement());
737 return elem->GetVR();
742 * \brief Searches within Header Entries (Dicom Elements) parsed with
743 * the public and private dictionaries
744 * for the element value representation of a given tag.
745 * @param group Group number of the searched tag.
746 * @param element Element number of the searched tag.
747 * @return Corresponding element value representation when it exists,
748 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
750 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
751 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
752 if ( ! tagHT.count(key))
754 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
758 * \brief Searches within Header Entries (Dicom Elements) parsed with
759 * the public and private dictionaries
760 * for the element value representation of a given tag..
762 * Obtaining the VR (Value Representation) might be needed by caller
763 * to convert the string typed content to caller's native type
764 * (think of C++ vs Python). The VR is actually of a higher level
765 * of semantics than just the native C++ type.
766 * @param group Group number of the searched tag.
767 * @param element Element number of the searched tag.
768 * @return Corresponding element value representation when it exists,
769 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
771 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
772 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
775 return elem->GetVR();
779 * \brief Searches within Header Entries (Dicom Elements) parsed with
780 * the public and private dictionaries
781 * for the value length of a given tag..
782 * @param group Group number of the searched tag.
783 * @param element Element number of the searched tag.
784 * @return Corresponding element length; -2 if not found
786 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
787 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
790 return elem->GetLength();
793 * \brief Sets the value (string) of the Header Entry (Dicom Element)
794 * @param content string value of the Dicom Element
795 * @param tagName name of the searched Dicom Element.
796 * @return true when found
798 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
799 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
800 if( dictEntry == NULL)
803 return SetEntryByNumber(content,dictEntry->GetGroup(),
804 dictEntry->GetElement());
808 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
809 * through it's (group, element) and modifies it's content with
811 * @param content new value (string) to substitute with
812 * @param group group number of the Dicom Element to modify
813 * @param element element number of the Dicom Element to modify
815 bool gdcmDocument::SetEntryByNumber(std::string content,
819 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
822 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
823 " ValEntry (try promotion first).");
826 // Non even content must be padded with a space (020H).
827 if((content.length())%2) {
828 content = content + '\0';
830 ValEntry->SetValue(content);
832 // Integers have a special treatement for their length:
833 VRKey vr = ValEntry->GetVR();
834 if( (vr == "US") || (vr == "SS") )
835 ValEntry->SetLength(2);
836 else if( (vr == "UL") || (vr == "SL") )
837 ValEntry->SetLength(4);
839 ValEntry->SetLength(content.length());
845 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
846 * through it's (group, element) and modifies it's content with
848 * @param content new value (void *) to substitute with
849 * @param lgth new value length
850 * @param group group number of the Dicom Element to modify
851 * @param element element number of the Dicom Element to modify
853 bool gdcmDocument::SetEntryByNumber(void *content,
858 (void)lgth; //not used
859 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
860 if ( ! tagHT.count(key))
863 /* Hope Binray field length is never wrong
864 if(lgth%2) // Non even length are padded with a space (020H).
867 //content = content + '\0'; // fing a trick to enlarge a binary field?
871 a = (gdcmBinEntry *)tagHT[key];
872 a->SetVoidArea(content);
873 //a->SetLength(lgth); // ???
878 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
879 * in the PubDocEntrySet of this instance
880 * through it's (group, element) and modifies it's length with
882 * \warning Use with extreme caution.
883 * @param l new length to substitute with
884 * @param group group number of the Entry to modify
885 * @param element element number of the Entry to modify
886 * @return true on success, false otherwise.
888 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
892 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
893 if ( ! tagHT.count(key))
895 if (l%2) l++; // length must be even
896 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
902 * \brief Gets (from Header) the offset of a 'non string' element value
903 * (LoadElementValues has already be executed)
904 * @param Group group number of the Entry
905 * @param Elem element number of the Entry
906 * @return File Offset of the Element Value
908 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
910 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
913 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
916 return Entry->GetOffset();
920 * \brief Gets (from Header) a 'non string' element value
921 * (LoadElementValues has already be executed)
922 * @param Group group number of the Entry
923 * @param Elem element number of the Entry
924 * @return Pointer to the 'non string' area
926 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
928 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
931 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
934 return ((gdcmBinEntry *)Entry)->GetVoidArea();
938 * \brief Loads (from disk) the element content
939 * when a string is not suitable
940 * @param Group group number of the Entry
941 * @param Elem element number of the Entry
943 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
945 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
948 size_t o =(size_t)Element->GetOffset();
949 fseek(fp, o, SEEK_SET);
950 size_t l = Element->GetLength();
951 char* a = new char[l];
953 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
956 SetEntryVoidAreaByNumber(a, Group, Elem);
957 /// \todo check the result
958 size_t l2 = fread(a, 1, l ,fp);
967 * \brief Loads (from disk) the element content
968 * when a string is not suitable
969 * @param Element Entry whose voidArea is going to be loaded
971 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
973 size_t o =(size_t)Element->GetOffset();
974 fseek(fp, o, SEEK_SET);
975 size_t l = Element->GetLength();
976 char* a = new char[l];
978 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
981 Element->SetVoidArea((void *)a);
982 /// \todo check the result
983 size_t l2 = fread(a, 1, l ,fp);
993 * \brief Sets a 'non string' value to a given Dicom Element
994 * @param area area containing the 'non string' value
995 * @param group Group number of the searched Dicom Element
996 * @param element Element number of the searched Dicom Element
999 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1003 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1004 if ( ! tagHT.count(key))
1006 // This was for multimap ?
1007 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1013 * \brief Update the entries with the shadow dictionary.
1014 * Only non even entries are analyzed
1016 void gdcmDocument::UpdateShaEntries(void) {
1017 //gdcmDictEntry *entry;
1020 /// \todo TODO : still any use to explore recursively the whole structure?
1022 for(ListTag::iterator it=listEntries.begin();
1023 it!=listEntries.end();
1026 // Odd group => from public dictionary
1027 if((*it)->GetGroup()%2==0)
1030 // Peer group => search the corresponding dict entry
1032 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1036 if((*it)->IsImplicitVR())
1041 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1043 // Set the new entry and the new value
1044 (*it)->SetDictEntry(entry);
1045 CheckDocEntryVR(*it,vr);
1047 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1052 // Remove precedent value transformation
1053 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1060 * \brief Searches within the Header Entries for a Dicom Element of
1062 * @param tagName name of the searched Dicom Element.
1063 * @return Corresponding Dicom Element when it exists, and NULL
1066 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1067 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1068 if( dictEntry == NULL)
1071 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1075 * \brief retrieves a Dicom Element (the first one) using (group, element)
1076 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1077 * if you think it's NOT UNIQUE, check the count number
1078 * and use iterators to retrieve ALL the Dicoms Elements within
1079 * a given couple (group, element)
1080 * @param group Group number of the searched Dicom Element
1081 * @param element Element number of the searched Dicom Element
1084 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1086 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1087 if ( ! tagHT.count(key))
1089 return tagHT.find(key)->second;
1093 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1094 * returns a result when the corresponding entry is of type
1096 * @return When present, the corresponding ValEntry.
1098 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1100 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1102 return (gdcmValEntry*)0;
1103 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1107 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1108 return (gdcmValEntry*)0;
1112 * \brief Loads the element while preserving the current
1113 * underlying file position indicator as opposed to
1114 * to LoadDocEntry that modifies it.
1115 * @param entry Header Entry whose value shall be loaded.
1118 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1119 long PositionOnEntry = ftell(fp);
1120 LoadDocEntry(entry);
1121 fseek(fp, PositionOnEntry, SEEK_SET);
1125 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1127 * @return The properly swaped 32 bits integer.
1129 guint32 gdcmDocument::SwapLong(guint32 a) {
1134 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1135 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1139 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1143 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1146 std::cout << "swapCode= " << sw << std::endl;
1147 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1154 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1156 * @return The properly unswaped 32 bits integer.
1158 guint32 gdcmDocument::UnswapLong(guint32 a) {
1163 * \brief Swaps the bytes so they agree with the processor order
1164 * @return The properly swaped 16 bits integer.
1166 guint16 gdcmDocument::SwapShort(guint16 a) {
1167 if ( (sw==4321) || (sw==2143) )
1168 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1173 * \brief Unswaps the bytes so they agree with the processor order
1174 * @return The properly unswaped 16 bits integer.
1176 guint16 gdcmDocument::UnswapShort(guint16 a) {
1177 return SwapShort(a);
1180 //-----------------------------------------------------------------------------
1184 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1185 * @return length of the parsed set.
1188 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1190 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1191 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1195 unsigned long l = 0;
1198 depth = set->GetDepthLevel();
1201 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1204 NewDocEntry = ReadNextDocEntry( );
1207 // NewDocEntry->Print(); cout << endl; //JPR
1208 vr = NewDocEntry->GetVR();
1212 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1215 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1216 NewValEntry->Copy(NewDocEntry);
1217 NewValEntry->SetDepthLevel(depth);
1218 set->AddEntry(NewValEntry);
1219 LoadDocEntry(NewValEntry);
1220 if (NewValEntry->isItemDelimitor())
1222 if ( !delim_mode && ftell(fp)-offset >= l_max)
1229 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1231 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1232 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1233 "nor BinEntry. Probably unknown VR.");
1236 ////// BinEntry or UNKOWN VR:
1237 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1238 bn->Copy(NewDocEntry);
1243 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1244 NewDocEntry->GetElement() == 0x0010 )
1246 if (NewDocEntry->GetReadLength()==0xffffffff)
1248 // Broken US.3405.1.dcm
1249 Parse7FE0(); // to skip the pixels
1250 // (multipart JPEG/RLE are trouble makers)
1254 SkipToNextDocEntry(NewDocEntry);
1255 l = NewDocEntry->GetFullLength();
1260 // to be sure we are at the beginning
1261 SkipToNextDocEntry(NewDocEntry);
1262 l = NewDocEntry->GetFullLength();
1268 l=NewDocEntry->GetReadLength();
1269 if (l != 0) // don't mess the delim_mode for zero-length sequence
1270 if (l == 0xffffffff)
1274 // no other way to create it ...
1275 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1276 set->GetDepthLevel());
1277 sq->Copy(NewDocEntry);
1278 sq->SetDelimitorMode(delim_mode);
1279 sq->SetDepthLevel(depth);
1282 { // Don't try to parse zero-length sequences
1283 long lgt = ParseSQ( sq,
1284 NewDocEntry->GetOffset(),
1286 (void)lgt; //not used...
1289 if ( !delim_mode && ftell(fp)-offset >= l_max)
1296 return l; // Probably useless
1300 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1301 * @return parsed length for this level
1303 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1304 long offset, long l_max, bool delim_mode)
1306 int SQItemNumber = 0;
1308 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1313 int depth = set->GetDepthLevel();
1314 (void)depth; //not used
1318 NewDocEntry = ReadNextDocEntry();
1322 if (NewDocEntry->isSequenceDelimitor()) {
1323 set->SetSequenceDelimitationItem(NewDocEntry);
1327 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1331 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1332 itemSQ->AddEntry(NewDocEntry);
1333 l= NewDocEntry->GetReadLength();
1335 if (l == 0xffffffff)
1340 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1342 set->AddEntry(itemSQ,SQItemNumber);
1344 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1348 lgth = ftell(fp) - offset;
1353 * \brief Loads the element content if its length doesn't exceed
1354 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1355 * @param Entry Header Entry (Dicom Element) to be dealt with
1357 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1360 guint16 group = Entry->GetGroup();
1361 std::string vr= Entry->GetVR();
1362 guint32 length = Entry->GetLength();
1364 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1366 // A SeQuence "contains" a set of Elements.
1367 // (fffe e000) tells us an Element is beginning
1368 // (fffe e00d) tells us an Element just ended
1369 // (fffe e0dd) tells us the current SeQuence just ended
1370 if( group == 0xfffe ) {
1371 // NO more value field for SQ !
1375 // When the length is zero things are easy:
1376 if ( length == 0 ) {
1377 ((gdcmValEntry *)Entry)->SetValue("");
1381 // The elements whose length is bigger than the specified upper bound
1382 // are not loaded. Instead we leave a short notice of the offset of
1383 // the element content and it's length.
1385 std::ostringstream s;
1386 if (length > MaxSizeLoadEntry) {
1387 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1389 s << "gdcm::NotLoaded (BinEntry)";
1390 s << " Address:" << (long)Entry->GetOffset();
1391 s << " Length:" << Entry->GetLength();
1392 s << " x(" << std::hex << Entry->GetLength() << ")";
1393 BinEntryPtr->SetValue(s.str());
1395 // to be sure we are at the end of the value ...
1396 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1398 // Be carefull : a BinEntry IS_A ValEntry ...
1399 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1401 s << "gdcm::NotLoaded. (ValEntry)";
1402 s << " Address:" << (long)Entry->GetOffset();
1403 s << " Length:" << Entry->GetLength();
1404 s << " x(" << std::hex << Entry->GetLength() << ")";
1405 ValEntryPtr->SetValue(s.str());
1407 // to be sure we are at the end of the value ...
1408 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1412 // When we find a BinEntry not very much can be done :
1413 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1415 LoadEntryVoidArea(BinEntryPtr);
1416 s << "gdcm::Loaded (BinEntry)";
1417 BinEntryPtr->SetValue(s.str());
1422 // Any compacter code suggested (?)
1423 if ( IsDocEntryAnInteger(Entry) ) {
1425 std::ostringstream s;
1427 // When short integer(s) are expected, read and convert the following
1428 // n *two characters properly i.e. as short integers as opposed to strings.
1429 // Elements with Value Multiplicity > 1
1430 // contain a set of integers (not a single one)
1431 if (vr == "US" || vr == "SS") {
1433 NewInt = ReadInt16();
1436 for (int i=1; i < nbInt; i++) {
1438 NewInt = ReadInt16();
1443 // When integer(s) are expected, read and convert the following
1444 // n * four characters properly i.e. as integers as opposed to strings.
1445 // Elements with Value Multiplicity > 1
1446 // contain a set of integers (not a single one)
1447 else if (vr == "UL" || vr == "SL") {
1449 NewInt = ReadInt32();
1452 for (int i=1; i < nbInt; i++) {
1454 NewInt = ReadInt32();
1459 #ifdef GDCM_NO_ANSI_STRING_STREAM
1460 s << std::ends; // to avoid oddities on Solaris
1461 #endif //GDCM_NO_ANSI_STRING_STREAM
1463 ((gdcmValEntry *)Entry)->SetValue(s.str());
1467 // We need an additional byte for storing \0 that is not on disk
1468 std::string NewValue(length,0);
1469 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1470 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) ) {
1471 if ( item_read != 1 ) {
1472 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1473 ValEntry->SetValue("gdcm::UnRead");
1477 if( (vr == "UI") ) // Because of correspondance with the VR dic
1478 ValEntry->SetValue(NewValue.c_str());
1480 ValEntry->SetValue(NewValue);
1483 std::cout << "Should have a ValEntry, here !" << std::endl;
1490 * \brief Find the value Length of the passed Header Entry
1491 * @param Entry Header Entry whose length of the value shall be loaded.
1493 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1494 guint16 element = Entry->GetElement();
1495 //guint16 group = Entry->GetGroup(); //FIXME
1496 std::string vr = Entry->GetVR();
1500 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1502 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1504 // The following reserved two bytes (see PS 3.5-2001, section
1505 // 7.1.2 Data element structure with explicit vr p27) must be
1506 // skipped before proceeding on reading the length on 4 bytes.
1507 fseek(fp, 2L, SEEK_CUR);
1508 guint32 length32 = ReadInt32();
1510 if ( (vr == "OB") && (length32 == 0xffffffff) )
1512 Entry->SetLength(FindDocEntryLengthOB());
1515 FixDocEntryFoundLength(Entry, length32);
1519 // Length is encoded on 2 bytes.
1520 length16 = ReadInt16();
1522 // We can tell the current file is encoded in big endian (like
1523 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1524 // and it's value is the one of the encoding of a big endian file.
1525 // In order to deal with such big endian encoded files, we have
1526 // (at least) two strategies:
1527 // * when we load the "Transfer Syntax" tag with value of big endian
1528 // encoding, we raise the proper flags. Then we wait for the end
1529 // of the META group (0x0002) among which is "Transfer Syntax",
1530 // before switching the swap code to big endian. We have to postpone
1531 // the switching of the swap code since the META group is fully encoded
1532 // in little endian, and big endian coding only starts at the next
1533 // group. The corresponding code can be hard to analyse and adds
1534 // many additional unnecessary tests for regular tags.
1535 // * the second strategy consists in waiting for trouble, that shall
1536 // appear when we find the first group with big endian encoding. This
1537 // is easy to detect since the length of a "Group Length" tag (the
1538 // ones with zero as element number) has to be of 4 (0x0004). When we
1539 // encounter 1024 (0x0400) chances are the encoding changed and we
1540 // found a group with big endian encoding.
1541 // We shall use this second strategy. In order to make sure that we
1542 // can interpret the presence of an apparently big endian encoded
1543 // length of a "Group Length" without committing a big mistake, we
1544 // add an additional check: we look in the already parsed elements
1545 // for the presence of a "Transfer Syntax" whose value has to be "big
1546 // endian encoding". When this is the case, chances are we have got our
1547 // hands on a big endian encoded file: we switch the swap code to
1548 // big endian and proceed...
1549 if ( (element == 0x0000) && (length16 == 0x0400) )
1551 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1553 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1558 SwitchSwapToBigEndian();
1559 // Restore the unproperly loaded values i.e. the group, the element
1560 // and the dictionary entry depending on them.
1561 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1562 guint16 CorrectElem = SwapShort(Entry->GetElement());
1563 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1567 // This correct tag is not in the dictionary. Create a new one.
1568 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1570 // FIXME this can create a memory leaks on the old entry that be
1571 // left unreferenced.
1572 Entry->SetDictEntry(NewTag);
1575 // Heuristic: well, some files are really ill-formed.
1576 if ( length16 == 0xffff)
1579 // Length16= 0xffff means that we deal with
1580 // 'Unknown Length' Sequence
1582 FixDocEntryFoundLength(Entry, (guint32)length16);
1587 // Either implicit VR or a non DICOM conformal (see note below) explicit
1588 // VR that ommited the VR of (at least) this element. Farts happen.
1589 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1590 // on Data elements "Implicit and Explicit VR Data Elements shall
1591 // not coexist in a Data Set and Data Sets nested within it".]
1592 // Length is on 4 bytes.
1594 FixDocEntryFoundLength(Entry, ReadInt32());
1600 * \brief Find the Value Representation of the current Dicom Element.
1603 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1605 if (Filetype != gdcmExplicitVR)
1610 long PositionOnEntry = ftell(fp);
1611 // Warning: we believe this is explicit VR (Value Representation) because
1612 // we used a heuristic that found "UL" in the first tag. Alas this
1613 // doesn't guarantee that all the tags will be in explicit VR. In some
1614 // cases (see e-film filtered files) one finds implicit VR tags mixed
1615 // within an explicit VR file. Hence we make sure the present tag
1616 // is in explicit VR and try to fix things if it happens not to be
1619 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1621 if(!CheckDocEntryVR(Entry,VR))
1623 fseek(fp, PositionOnEntry, SEEK_SET);
1624 // When this element is known in the dictionary we shall use, e.g. for
1625 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1626 // dictionary entry. Still we have to flag the element as implicit since
1627 // we know now our assumption on expliciteness is not furfilled.
1629 if ( Entry->IsVRUnknown() )
1630 Entry->SetVR("Implicit");
1631 Entry->SetImplicitVR();
1636 * \brief Check the correspondance between the VR of the header entry
1637 * and the taken VR. If they are different, the header entry is
1638 * updated with the new VR.
1639 * @param Entry Header Entry to check
1640 * @param vr Dicom Value Representation
1641 * @return false if the VR is incorrect of if the VR isn't referenced
1642 * otherwise, it returns true
1644 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1646 char msg[100]; // for sprintf
1647 bool RealExplicit = true;
1649 // Assume we are reading a falsely explicit VR file i.e. we reached
1650 // a tag where we expect reading a VR but are in fact we read the
1651 // first to bytes of the length. Then we will interogate (through find)
1652 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1653 // both GCC and VC++ implementations of the STL map. Hence when the
1654 // expected VR read happens to be non-ascii characters we consider
1655 // we hit falsely explicit VR tag.
1657 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1658 RealExplicit = false;
1660 // CLEANME searching the dicom_vr at each occurence is expensive.
1661 // PostPone this test in an optional integrity check at the end
1662 // of parsing or only in debug mode.
1663 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1664 RealExplicit= false;
1666 if ( !RealExplicit )
1668 // We thought this was explicit VR, but we end up with an
1669 // implicit VR tag. Let's backtrack.
1670 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1671 Entry->GetGroup(),Entry->GetElement());
1672 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1673 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1674 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1675 Entry->GetGroup(),Entry->GetElement(),
1676 "UL","FIXME","Group Length");
1677 Entry->SetDictEntry(NewEntry);
1682 if ( Entry->IsVRUnknown() )
1684 // When not a dictionary entry, we can safely overwrite the VR.
1685 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1691 else if ( Entry->GetVR() != vr )
1693 // The VR present in the file and the dictionary disagree. We assume
1694 // the file writer knew best and use the VR of the file. Since it would
1695 // be unwise to overwrite the VR of a dictionary (since it would
1696 // compromise it's next user), we need to clone the actual DictEntry
1697 // and change the VR for the read one.
1698 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1699 Entry->GetGroup(),Entry->GetElement(),
1700 vr,"FIXME",Entry->GetName());
1701 Entry->SetDictEntry(NewEntry);
1707 * \brief Get the transformed value of the header entry. The VR value
1708 * is used to define the transformation to operate on the value
1709 * \warning NOT end user intended method !
1711 * @return Transformed entry value
1713 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1715 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1717 std::string val=((gdcmValEntry *)Entry)->GetValue();
1718 std::string vr=Entry->GetVR();
1719 guint32 length = Entry->GetLength();
1720 std::ostringstream s;
1723 // When short integer(s) are expected, read and convert the following
1724 // n * 2 bytes properly i.e. as a multivaluated strings
1725 // (each single value is separated fromthe next one by '\'
1726 // as usual for standard multivaluated filels
1727 // Elements with Value Multiplicity > 1
1728 // contain a set of short integers (not a single one)
1730 if (vr == "US" || vr == "SS")
1735 for (int i=0; i < nbInt; i++)
1739 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1740 NewInt16 = SwapShort(NewInt16);
1745 // When integer(s) are expected, read and convert the following
1746 // n * 4 bytes properly i.e. as a multivaluated strings
1747 // (each single value is separated fromthe next one by '\'
1748 // as usual for standard multivaluated filels
1749 // Elements with Value Multiplicity > 1
1750 // contain a set of integers (not a single one)
1751 else if (vr == "UL" || vr == "SL")
1756 for (int i=0; i < nbInt; i++)
1760 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1761 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1762 NewInt32=SwapLong(NewInt32);
1766 #ifdef GDCM_NO_ANSI_STRING_STREAM
1767 s << std::ends; // to avoid oddities on Solaris
1768 #endif //GDCM_NO_ANSI_STRING_STREAM
1772 return ((gdcmValEntry *)Entry)->GetValue();
1776 * \brief Get the reverse transformed value of the header entry. The VR
1777 * value is used to define the reverse transformation to operate on
1779 * \warning NOT end user intended method !
1781 * @return Reverse transformed entry value
1783 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1785 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1787 std::string vr=Entry->GetVR();
1788 std::ostringstream s;
1789 std::vector<std::string> tokens;
1791 if (vr == "US" || vr == "SS")
1795 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1796 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1797 for (unsigned int i=0; i<tokens.size();i++)
1799 NewInt16 = atoi(tokens[i].c_str());
1800 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1804 if (vr == "UL" || vr == "SL")
1808 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1809 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1810 for (unsigned int i=0; i<tokens.size();i++)
1812 NewInt32 = atoi(tokens[i].c_str());
1813 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1814 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1819 #ifdef GDCM_NO_ANSI_STRING_STREAM
1820 s << std::ends; // to avoid oddities on Solaris
1821 #endif //GDCM_NO_ANSI_STRING_STREAM
1825 return ((gdcmValEntry *)Entry)->GetValue();
1829 * \brief Skip a given Header Entry
1830 * \warning NOT end user intended method !
1833 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1835 SkipBytes(entry->GetLength());
1839 * \brief Skips to the begining of the next Header Entry
1840 * \warning NOT end user intended method !
1843 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1845 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1846 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1850 * \brief When the length of an element value is obviously wrong (because
1851 * the parser went Jabberwocky) one can hope improving things by
1852 * applying some heuristics.
1854 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1855 guint32 FoundLength)
1857 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1858 if ( FoundLength == 0xffffffff) {
1862 guint16 gr =Entry->GetGroup();
1863 guint16 el =Entry->GetElement();
1865 if (FoundLength%2) {
1866 std::ostringstream s;
1867 s << "Warning : Tag with uneven length "
1869 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1870 dbg.Verbose(0, s.str().c_str());
1873 //////// Fix for some naughty General Electric images.
1874 // Allthough not recent many such GE corrupted images are still present
1875 // on Creatis hard disks. Hence this fix shall remain when such images
1876 // are no longer in user (we are talking a few years, here)...
1877 // Note: XMedCom probably uses such a trick since it is able to read
1878 // those pesky GE images ...
1879 if (FoundLength == 13) { // Only happens for this length !
1880 if ( (Entry->GetGroup() != 0x0008)
1881 || ( (Entry->GetElement() != 0x0070)
1882 && (Entry->GetElement() != 0x0080) ) )
1885 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1889 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1890 // Occurence of such images is quite low (unless one leaves close to a
1891 // 'Leonardo' source. Hence, one might consider commenting out the
1892 // following fix on efficiency reasons.
1894 if ( (Entry->GetGroup() == 0x0009)
1895 && ( (Entry->GetElement() == 0x1113)
1896 || (Entry->GetElement() == 0x1114) ) )
1899 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1902 //////// Deal with sequences, but only on users request:
1904 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1906 FoundLength = 0; // ReadLength is unchanged
1909 //////// We encountered a 'delimiter' element i.e. a tag of the form
1910 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1911 // taken into account.
1913 if(Entry->GetGroup() == 0xfffe)
1915 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1916 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1917 // causes extra troubles...
1918 if( Entry->GetElement() != 0x0000 )
1924 Entry->SetUsableLength(FoundLength);
1928 * \brief Apply some heuristics to predict whether the considered
1929 * element value contains/represents an integer or not.
1930 * @param Entry The element value on which to apply the predicate.
1931 * @return The result of the heuristical predicate.
1933 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1934 guint16 element = Entry->GetElement();
1935 guint16 group = Entry->GetGroup();
1936 std::string vr = Entry->GetVR();
1937 guint32 length = Entry->GetLength();
1939 // When we have some semantics on the element we just read, and if we
1940 // a priori know we are dealing with an integer, then we shall be
1941 // able to swap it's element value properly.
1942 if ( element == 0 ) // This is the group length of the group
1948 // Allthough this should never happen, still some images have a
1949 // corrupted group length [e.g. have a glance at offset x(8336) of
1950 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1951 // Since for dicom compliant and well behaved headers, the present
1952 // test is useless (and might even look a bit paranoid), when we
1953 // encounter such an ill-formed image, we simply display a warning
1954 // message and proceed on parsing (while crossing fingers).
1955 std::ostringstream s;
1956 int filePosition = ftell(fp);
1957 s << "Erroneous Group Length element length on : (" \
1958 << std::hex << group << " , " << element
1959 << ") -before- position x(" << filePosition << ")"
1960 << "lgt : " << length;
1961 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1965 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1972 * \brief Find the Length till the next sequence delimiter
1973 * \warning NOT end user intended method !
1977 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1978 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1981 long PositionOnEntry = ftell(fp);
1982 bool FoundSequenceDelimiter = false;
1983 guint32 TotalLength = 0;
1986 while ( ! FoundSequenceDelimiter)
1992 TotalLength += 4; // We even have to decount the group and element
1994 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1996 char msg[100]; // for sprintf. Sorry
1997 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1998 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2002 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2003 FoundSequenceDelimiter = true;
2004 else if ( n != 0xe000 )
2006 char msg[100]; // for sprintf. Sorry
2007 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2009 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2013 ItemLength = ReadInt32();
2014 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2015 // the ItemLength with ReadInt32
2016 SkipBytes(ItemLength);
2018 fseek(fp, PositionOnEntry, SEEK_SET);
2023 * \brief Reads a supposed to be 16 Bits integer
2024 * (swaps it depending on processor endianity)
2025 * @return read value
2027 guint16 gdcmDocument::ReadInt16() {
2030 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2031 if ( item_read != 1 ) {
2033 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2043 * \brief Reads a supposed to be 32 Bits integer
2044 * (swaps it depending on processor endianity)
2045 * @return read value
2047 guint32 gdcmDocument::ReadInt32() {
2050 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2051 if ( item_read != 1 ) {
2053 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2063 * \brief skips bytes inside the source file
2064 * \warning NOT end user intended method !
2067 void gdcmDocument::SkipBytes(guint32 NBytes) {
2068 //FIXME don't dump the returned value
2069 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2073 * \brief Loads all the needed Dictionaries
2074 * \warning NOT end user intended method !
2076 void gdcmDocument::Initialise(void)
2078 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2083 * \brief Discover what the swap code is (among little endian, big endian,
2084 * bad little endian, bad big endian).
2086 * @return false when we are absolutely sure
2087 * it's neither ACR-NEMA nor DICOM
2088 * true when we hope ours assuptions are OK
2090 bool gdcmDocument::CheckSwap() {
2092 // The only guaranted way of finding the swap code is to find a
2093 // group tag since we know it's length has to be of four bytes i.e.
2094 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2095 // occurs when we can't find such group...
2097 guint32 x=4; // x : for ntohs
2098 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2104 char deb[HEADER_LENGTH_TO_READ];
2106 // First, compare HostByteOrder and NetworkByteOrder in order to
2107 // determine if we shall need to swap bytes (i.e. the Endian type).
2113 // The easiest case is the one of a DICOM header, since it possesses a
2114 // file preamble where it suffice to look for the string "DICM".
2115 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2118 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2119 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2121 // Next, determine the value representation (VR). Let's skip to the
2122 // first element (0002, 0000) and check there if we find "UL"
2123 // - or "OB" if the 1st one is (0002,0001) -,
2124 // in which case we (almost) know it is explicit VR.
2125 // WARNING: if it happens to be implicit VR then what we will read
2126 // is the length of the group. If this ascii representation of this
2127 // length happens to be "UL" then we shall believe it is explicit VR.
2128 // FIXME: in order to fix the above warning, we could read the next
2129 // element value (or a couple of elements values) in order to make
2130 // sure we are not commiting a big mistake.
2131 // We need to skip :
2132 // * the 128 bytes of File Preamble (often padded with zeroes),
2133 // * the 4 bytes of "DICM" string,
2134 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2135 // i.e. a total of 136 bytes.
2139 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2140 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2141 // *Implicit* VR. -and it is !-
2143 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2144 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2145 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2146 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2147 // when Write DCM *adds*
2149 // Use gdcmDocument::dicom_vr to test all the possibilities
2150 // instead of just checking for UL, OB and UI !? group 0000
2152 Filetype = gdcmExplicitVR;
2153 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2154 "explicit Value Representation");
2158 Filetype = gdcmImplicitVR;
2159 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2160 "not an explicit Value Representation");
2166 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2167 "HostByteOrder != NetworkByteOrder");
2172 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2173 "HostByteOrder = NetworkByteOrder");
2176 // Position the file position indicator at first tag (i.e.
2177 // after the file preamble and the "DICM" string).
2179 fseek (fp, 132L, SEEK_SET);
2183 // Alas, this is not a DicomV3 file and whatever happens there is no file
2184 // preamble. We can reset the file position indicator to where the data
2185 // is (i.e. the beginning of the file).
2186 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2189 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2190 // By clean we mean that the length of the first tag is written down.
2191 // If this is the case and since the length of the first group HAS to be
2192 // four (bytes), then determining the proper swap code is straightforward.
2195 // We assume the array of char we are considering contains the binary
2196 // representation of a 32 bits integer. Hence the following dirty
2198 s32 = *((guint32 *)(entCur));
2219 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2220 // It is time for despaired wild guesses.
2221 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2222 // i.e. the 'group length' element is not present :
2224 // check the supposed to be 'group number'
2225 // 0x0002 or 0x0004 or 0x0008
2226 // to determine ' sw' value .
2227 // Only 0 or 4321 will be possible
2228 // (no oportunity to check for the formerly well known
2229 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2230 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2231 // the file IS NOT ACR-NEMA nor DICOM V3
2232 // Find a trick to tell it the caller...
2234 s16 = *((guint16 *)(deb));
2250 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2251 "ACR/NEMA unfound swap info (Really hopeless !)");
2252 Filetype = gdcmUnknown;
2256 // Then the only info we have is the net2host one.
2266 * \brief Restore the unproperly loaded values i.e. the group, the element
2267 * and the dictionary entry depending on them.
2269 void gdcmDocument::SwitchSwapToBigEndian(void)
2271 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2272 "Switching to BigEndian mode.");
2293 * \brief during parsing, Header Elements too long are not loaded in memory
2296 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2300 if ((guint32)NewSize >= (guint32)0xffffffff)
2302 MaxSizeLoadEntry = 0xffffffff;
2305 MaxSizeLoadEntry = NewSize;
2310 * \brief Header Elements too long will not be printed
2311 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2314 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2318 if ((guint32)NewSize >= (guint32)0xffffffff)
2320 MaxSizePrintEntry = 0xffffffff;
2323 MaxSizePrintEntry = NewSize;
2329 * \brief Read the next tag but WITHOUT loading it's value
2330 * (read the 'Group Number', the 'Element Number',
2331 * gets the Dict Entry
2332 * gets the VR, gets the length, gets the offset value)
2333 * @return On succes the newly created DocEntry, NULL on failure.
2335 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2337 gdcmDocEntry *NewEntry;
2342 // We reached the EOF (or an error occured) therefore
2343 // header parsing has to be considered as finished.
2344 return (gdcmDocEntry *)0;
2346 NewEntry = NewDocEntryByNumber(g, n);
2347 FindDocEntryVR(NewEntry);
2348 FindDocEntryLength(NewEntry);
2355 NewEntry->SetOffset(ftell(fp));
2361 * \brief Generate a free TagKey i.e. a TagKey that is not present
2362 * in the TagHt dictionary.
2363 * @param group The generated tag must belong to this group.
2364 * @return The element of tag with given group which is fee.
2366 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2368 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2370 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2371 if (tagHT.count(key) == 0)
2379 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2380 * is placed at the beginning of a tag (TestGroup, TestElement),
2381 * read the length associated to the Tag.
2382 * \warning On success the internal file pointer \ref gdcmDocument::fp
2383 * is modified to point after the tag and it's length.
2384 * On failure (i.e. when the tag wasn't the expected tag
2385 * (TestGroup, TestElement) the internal file pointer
2386 * \ref gdcmDocument::fp is restored to it's original position.
2387 * @param TestGroup The expected group of the tag.
2388 * @param TestElement The expected Element of the tag.
2389 * @return On success returns the length associated to the tag. On failure
2392 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2394 guint16 ItemTagGroup;
2395 guint16 ItemTagElement;
2396 long PositionOnEntry = ftell(fp);
2397 long CurrentPosition = ftell(fp); // On debugging purposes
2399 //// Read the Item Tag group and element, and make
2400 // sure they are respectively 0xfffe and 0xe000:
2401 ItemTagGroup = ReadInt16();
2402 ItemTagElement = ReadInt16();
2403 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2405 std::ostringstream s;
2406 s << " We should have found tag (";
2407 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2408 s << " but instead we encountered tag (";
2409 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2411 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2412 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2413 dbg.Verbose(0, s.str().c_str());
2414 fseek(fp, PositionOnEntry, SEEK_SET);
2418 //// Then read the associated Item Length
2419 CurrentPosition=ftell(fp);
2421 ItemLength = ReadInt32();
2423 std::ostringstream s;
2424 s << "Basic Item Length is: "
2425 << ItemLength << std::endl;
2426 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2427 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2433 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2434 * \sa \ref gdcmDocument::ReadTagLength
2435 * \warning See warning of \ref gdcmDocument::ReadTagLength
2436 * @return On success returns the length associated to the item tag.
2437 * On failure returns 0.
2439 guint32 gdcmDocument::ReadItemTagLength(void)
2441 return ReadTagLength(0xfffe, 0xe000);
2445 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2447 * \sa \ref gdcmDocument::ReadTagLength
2448 * \warning See warning of \ref gdcmDocument::ReadTagLength
2449 * @return On success returns the length associated to the Sequence
2450 * Delimiter tag. On failure returns 0.
2452 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2454 return ReadTagLength(0xfffe, 0xe0dd);
2459 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2460 * No other way so 'skip' the Data
2464 void gdcmDocument::Parse7FE0 (void)
2466 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2470 if ( IsImplicitVRLittleEndianTransferSyntax()
2471 || IsExplicitVRLittleEndianTransferSyntax()
2472 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2473 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2476 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2478 //// Read the Basic Offset Table Item Tag length...
2479 guint32 ItemLength = ReadItemTagLength();
2481 //// ... and then read length[s] itself[themselves]. We don't use
2482 // the values read (BTW what is the purpous of those lengths ?)
2483 if (ItemLength != 0) {
2484 // BTW, what is the purpous of those length anyhow !?
2485 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2486 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2487 for (unsigned int i=0; i < ItemLength; i += 4){
2488 guint32 IndividualLength;
2489 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2490 std::ostringstream s;
2491 s << " Read one length: ";
2492 s << std::hex << IndividualLength << std::endl;
2493 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2497 if ( ! IsRLELossLessTransferSyntax() )
2501 //// We then skip (not reading them) all the fragments of images:
2502 while ( (ItemLength = ReadItemTagLength()) )
2504 SkipBytes(ItemLength);
2512 long RleSegmentLength[15], fragmentLength;
2514 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2515 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2517 // Parse fragments of the current Fragment (Frame)
2518 //------------------ scanning (not reading) fragment pixels
2519 guint32 nbRleSegments = ReadInt32();
2520 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2522 //// Reading RLE Segments Offset Table
2523 guint32 RleSegmentOffsetTable[15];
2524 for(int k=1; k<=15; k++) {
2526 RleSegmentOffsetTable[k] = ReadInt32();
2527 printf(" at : %x Offset Segment %d : %d (%x)\n",
2528 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2529 RleSegmentOffsetTable[k]);
2532 // skipping (not reading) RLE Segments
2533 if (nbRleSegments>1) {
2534 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2535 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2536 - RleSegmentOffsetTable[k];
2538 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2539 k,(unsigned)RleSegmentLength[k],
2540 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2541 SkipBytes(RleSegmentLength[k]);
2545 RleSegmentLength[nbRleSegments]= fragmentLength
2546 - RleSegmentOffsetTable[nbRleSegments];
2548 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2549 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2550 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2551 SkipBytes(RleSegmentLength[nbRleSegments]);
2559 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2560 * \warning Does NOT work with ACR-NEMA files
2561 * \todo Find a trick to solve the pb (use RET fields ?)
2563 * @return true if 'smaller'
2565 bool gdcmDocument::operator<(gdcmDocument &document)
2570 s1=this->GetEntryByNumber(0x0010,0x0010);
2571 s2=document.GetEntryByNumber(0x0010,0x0010);
2579 s1=this->GetEntryByNumber(0x0010,0x0020);
2580 s2=document.GetEntryByNumber(0x0010,0x0020);
2587 // Study Instance UID
2588 s1=this->GetEntryByNumber(0x0020,0x000d);
2589 s2=document.GetEntryByNumber(0x0020,0x000d);
2596 // Serie Instance UID
2597 s1=this->GetEntryByNumber(0x0020,0x000e);
2598 s2=document.GetEntryByNumber(0x0020,0x000e);
2610 //-----------------------------------------------------------------------------