1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/28 14:29:52 $
7 Version: $Revision: 1.39 $
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(std::string 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 group group number of the Dicom Element to modify
850 * @param element element number of the Dicom Element to modify
852 bool gdcmDocument::SetEntryByNumber(void *content,
857 (void)lgth; //not used
858 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
859 if ( ! tagHT.count(key))
862 /* Hope Binray field length is never wrong
863 if(lgth%2) // Non even length are padded with a space (020H).
866 //content = content + '\0'; // fing a trick to enlarge a binary field?
870 a = (gdcmBinEntry *)tagHT[key];
871 a->SetVoidArea(content);
872 //a->SetLength(lgth); // ???
877 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
878 * in the PubDocEntrySet of this instance
879 * through it's (group, element) and modifies it's length with
881 * \warning Use with extreme caution.
882 * @param l new length to substitute with
883 * @param group group number of the Entry to modify
884 * @param element element number of the Entry to modify
885 * @return true on success, false otherwise.
887 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
891 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
892 if ( ! tagHT.count(key))
894 if (l%2) l++; // length must be even
895 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
901 * \brief Gets (from Header) the offset of a 'non string' element value
902 * (LoadElementValues has already be executed)
903 * @param Group group number of the Entry
904 * @param Elem element number of the Entry
905 * @return File Offset of the Element Value
907 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
909 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
912 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
915 return Entry->GetOffset();
919 * \brief Gets (from Header) a 'non string' element value
920 * (LoadElementValues has already be executed)
921 * @param Group group number of the Entry
922 * @param Elem element number of the Entry
923 * @return Pointer to the 'non string' area
925 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
927 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
930 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
933 return ((gdcmBinEntry *)Entry)->GetVoidArea();
937 * \brief Loads (from disk) the element content
938 * when a string is not suitable
939 * @param Group group number of the Entry
940 * @param Elem element number of the Entry
942 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
944 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
947 size_t o =(size_t)Element->GetOffset();
948 fseek(fp, o, SEEK_SET);
949 size_t l = Element->GetLength();
950 char* a = new char[l];
952 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
955 SetEntryVoidAreaByNumber(a, Group, Elem);
956 /// \todo check the result
957 size_t l2 = fread(a, 1, l ,fp);
966 * \brief Loads (from disk) the element content
967 * when a string is not suitable
968 * @param Element Entry whose voidArea is going to be loaded
970 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
972 size_t o =(size_t)Element->GetOffset();
973 fseek(fp, o, SEEK_SET);
974 size_t l = Element->GetLength();
975 char* a = new char[l];
977 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
980 Element->SetVoidArea((void *)a);
981 /// \todo check the result
982 size_t l2 = fread(a, 1, l ,fp);
992 * \brief Sets a 'non string' value to a given Dicom Element
993 * @param area area containing the 'non string' value
994 * @param group Group number of the searched Dicom Element
995 * @param element Element number of the searched Dicom Element
998 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1002 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1003 if ( ! tagHT.count(key))
1005 // This was for multimap ?
1006 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1012 * \brief Update the entries with the shadow dictionary.
1013 * Only non even entries are analyzed
1015 void gdcmDocument::UpdateShaEntries(void) {
1016 //gdcmDictEntry *entry;
1019 /// \todo TODO : still any use to explore recursively the whole structure?
1021 for(ListTag::iterator it=listEntries.begin();
1022 it!=listEntries.end();
1025 // Odd group => from public dictionary
1026 if((*it)->GetGroup()%2==0)
1029 // Peer group => search the corresponding dict entry
1031 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1035 if((*it)->IsImplicitVR())
1040 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1042 // Set the new entry and the new value
1043 (*it)->SetDictEntry(entry);
1044 CheckDocEntryVR(*it,vr);
1046 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1051 // Remove precedent value transformation
1052 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1059 * \brief Searches within the Header Entries for a Dicom Element of
1061 * @param tagName name of the searched Dicom Element.
1062 * @return Corresponding Dicom Element when it exists, and NULL
1065 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1066 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1067 if( dictEntry == NULL)
1070 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1074 * \brief retrieves a Dicom Element (the first one) using (group, element)
1075 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1076 * if you think it's NOT UNIQUE, check the count number
1077 * and use iterators to retrieve ALL the Dicoms Elements within
1078 * a given couple (group, element)
1079 * @param group Group number of the searched Dicom Element
1080 * @param element Element number of the searched Dicom Element
1083 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1085 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1086 if ( ! tagHT.count(key))
1088 return tagHT.find(key)->second;
1092 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1093 * returns a result when the corresponding entry is of type
1095 * @return When present, the corresponding ValEntry.
1097 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1099 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1101 return (gdcmValEntry*)0;
1102 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1106 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1107 return (gdcmValEntry*)0;
1111 * \brief Loads the element while preserving the current
1112 * underlying file position indicator as opposed to
1113 * to LoadDocEntry that modifies it.
1114 * @param entry Header Entry whose value shall be loaded.
1117 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1118 long PositionOnEntry = ftell(fp);
1119 LoadDocEntry(entry);
1120 fseek(fp, PositionOnEntry, SEEK_SET);
1124 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1126 * @return The properly swaped 32 bits integer.
1128 guint32 gdcmDocument::SwapLong(guint32 a) {
1133 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1134 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1138 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1142 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1145 std::cout << "swapCode= " << sw << std::endl;
1146 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1153 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1155 * @return The properly unswaped 32 bits integer.
1157 guint32 gdcmDocument::UnswapLong(guint32 a) {
1162 * \brief Swaps the bytes so they agree with the processor order
1163 * @return The properly swaped 16 bits integer.
1165 guint16 gdcmDocument::SwapShort(guint16 a) {
1166 if ( (sw==4321) || (sw==2143) )
1167 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1172 * \brief Unswaps the bytes so they agree with the processor order
1173 * @return The properly unswaped 16 bits integer.
1175 guint16 gdcmDocument::UnswapShort(guint16 a) {
1176 return SwapShort(a);
1179 //-----------------------------------------------------------------------------
1183 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1184 * @return length of the parsed set.
1187 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1189 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1190 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1194 unsigned long l = 0;
1197 depth = set->GetDepthLevel();
1200 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1203 NewDocEntry = ReadNextDocEntry( );
1206 // NewDocEntry->Print(); cout << endl; //JPR
1207 vr = NewDocEntry->GetVR();
1211 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1214 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1215 NewValEntry->Copy(NewDocEntry);
1216 NewValEntry->SetDepthLevel(depth);
1217 set->AddEntry(NewValEntry);
1218 LoadDocEntry(NewValEntry);
1219 if (NewValEntry->isItemDelimitor())
1221 if ( !delim_mode && ftell(fp)-offset >= l_max)
1228 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1230 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1231 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1232 "nor BinEntry. Probably unknown VR.");
1235 ////// BinEntry or UNKOWN VR:
1236 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1237 bn->Copy(NewDocEntry);
1242 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1243 NewDocEntry->GetElement() == 0x0010 )
1245 if (NewDocEntry->GetReadLength()==0xffffffff)
1247 // Broken US.3405.1.dcm
1248 Parse7FE0(); // to skip the pixels
1249 // (multipart JPEG/RLE are trouble makers)
1253 SkipToNextDocEntry(NewDocEntry);
1254 l = NewDocEntry->GetFullLength();
1259 // to be sure we are at the beginning
1260 SkipToNextDocEntry(NewDocEntry);
1261 l = NewDocEntry->GetFullLength();
1267 l=NewDocEntry->GetReadLength();
1268 if (l != 0) // don't mess the delim_mode for zero-length sequence
1269 if (l == 0xffffffff)
1273 // no other way to create it ...
1274 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1275 set->GetDepthLevel());
1276 sq->Copy(NewDocEntry);
1277 sq->SetDelimitorMode(delim_mode);
1278 sq->SetDepthLevel(depth);
1281 { // Don't try to parse zero-length sequences
1282 long lgt = ParseSQ( sq,
1283 NewDocEntry->GetOffset(),
1285 (void)lgt; //not used...
1288 if ( !delim_mode && ftell(fp)-offset >= l_max)
1295 return l; // Probably useless
1299 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1300 * @return parsed length for this level
1302 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1303 long offset, long l_max, bool delim_mode)
1305 int SQItemNumber = 0;
1307 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1312 int depth = set->GetDepthLevel();
1313 (void)depth; //not used
1317 NewDocEntry = ReadNextDocEntry();
1321 if (NewDocEntry->isSequenceDelimitor()) {
1322 set->SetSequenceDelimitationItem(NewDocEntry);
1326 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1330 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1331 itemSQ->AddEntry(NewDocEntry);
1332 l= NewDocEntry->GetReadLength();
1334 if (l == 0xffffffff)
1339 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1341 set->AddEntry(itemSQ,SQItemNumber);
1343 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1347 lgth = ftell(fp) - offset;
1352 * \brief Loads the element content if its length doesn't exceed
1353 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1354 * @param Entry Header Entry (Dicom Element) to be dealt with
1356 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1359 guint16 group = Entry->GetGroup();
1360 std::string vr= Entry->GetVR();
1361 guint32 length = Entry->GetLength();
1363 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1365 // A SeQuence "contains" a set of Elements.
1366 // (fffe e000) tells us an Element is beginning
1367 // (fffe e00d) tells us an Element just ended
1368 // (fffe e0dd) tells us the current SeQuence just ended
1369 if( group == 0xfffe ) {
1370 // NO more value field for SQ !
1374 // When the length is zero things are easy:
1375 if ( length == 0 ) {
1376 ((gdcmValEntry *)Entry)->SetValue("");
1380 // The elements whose length is bigger than the specified upper bound
1381 // are not loaded. Instead we leave a short notice of the offset of
1382 // the element content and it's length.
1384 std::ostringstream s;
1385 if (length > MaxSizeLoadEntry) {
1386 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1388 s << "gdcm::NotLoaded (BinEntry)";
1389 s << " Address:" << (long)Entry->GetOffset();
1390 s << " Length:" << Entry->GetLength();
1391 s << " x(" << std::hex << Entry->GetLength() << ")";
1392 BinEntryPtr->SetValue(s.str());
1394 // to be sure we are at the end of the value ...
1395 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1397 // Be carefull : a BinEntry IS_A ValEntry ...
1398 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1400 s << "gdcm::NotLoaded. (ValEntry)";
1401 s << " Address:" << (long)Entry->GetOffset();
1402 s << " Length:" << Entry->GetLength();
1403 s << " x(" << std::hex << Entry->GetLength() << ")";
1404 ValEntryPtr->SetValue(s.str());
1406 // to be sure we are at the end of the value ...
1407 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1411 // When we find a BinEntry not very much can be done :
1412 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1414 LoadEntryVoidArea(BinEntryPtr);
1415 s << "gdcm::Loaded (BinEntry)";
1416 BinEntryPtr->SetValue(s.str());
1421 // Any compacter code suggested (?)
1422 if ( IsDocEntryAnInteger(Entry) ) {
1424 std::ostringstream s;
1426 // When short integer(s) are expected, read and convert the following
1427 // n *two characters properly i.e. as short integers as opposed to strings.
1428 // Elements with Value Multiplicity > 1
1429 // contain a set of integers (not a single one)
1430 if (vr == "US" || vr == "SS") {
1432 NewInt = ReadInt16();
1435 for (int i=1; i < nbInt; i++) {
1437 NewInt = ReadInt16();
1442 // When integer(s) are expected, read and convert the following
1443 // n * four characters properly i.e. as integers as opposed to strings.
1444 // Elements with Value Multiplicity > 1
1445 // contain a set of integers (not a single one)
1446 else if (vr == "UL" || vr == "SL") {
1448 NewInt = ReadInt32();
1451 for (int i=1; i < nbInt; i++) {
1453 NewInt = ReadInt32();
1458 #ifdef GDCM_NO_ANSI_STRING_STREAM
1459 s << std::ends; // to avoid oddities on Solaris
1460 #endif //GDCM_NO_ANSI_STRING_STREAM
1462 ((gdcmValEntry *)Entry)->SetValue(s.str());
1466 // We need an additional byte for storing \0 that is not on disk
1467 std::string NewValue(length,0);
1468 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1469 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) ) {
1470 if ( item_read != 1 ) {
1471 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1472 ValEntry->SetValue("gdcm::UnRead");
1476 if( (vr == "UI") ) // Because of correspondance with the VR dic
1477 ValEntry->SetValue(NewValue.c_str());
1479 ValEntry->SetValue(NewValue);
1482 std::cout << "Should have a ValEntry, here !" << std::endl;
1489 * \brief Find the value Length of the passed Header Entry
1490 * @param Entry Header Entry whose length of the value shall be loaded.
1492 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1493 guint16 element = Entry->GetElement();
1494 //guint16 group = Entry->GetGroup(); //FIXME
1495 std::string vr = Entry->GetVR();
1499 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1501 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1503 // The following reserved two bytes (see PS 3.5-2001, section
1504 // 7.1.2 Data element structure with explicit vr p27) must be
1505 // skipped before proceeding on reading the length on 4 bytes.
1506 fseek(fp, 2L, SEEK_CUR);
1507 guint32 length32 = ReadInt32();
1509 if ( (vr == "OB") && (length32 == 0xffffffff) )
1511 Entry->SetLength(FindDocEntryLengthOB());
1514 FixDocEntryFoundLength(Entry, length32);
1518 // Length is encoded on 2 bytes.
1519 length16 = ReadInt16();
1521 // We can tell the current file is encoded in big endian (like
1522 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1523 // and it's value is the one of the encoding of a big endian file.
1524 // In order to deal with such big endian encoded files, we have
1525 // (at least) two strategies:
1526 // * when we load the "Transfer Syntax" tag with value of big endian
1527 // encoding, we raise the proper flags. Then we wait for the end
1528 // of the META group (0x0002) among which is "Transfer Syntax",
1529 // before switching the swap code to big endian. We have to postpone
1530 // the switching of the swap code since the META group is fully encoded
1531 // in little endian, and big endian coding only starts at the next
1532 // group. The corresponding code can be hard to analyse and adds
1533 // many additional unnecessary tests for regular tags.
1534 // * the second strategy consists in waiting for trouble, that shall
1535 // appear when we find the first group with big endian encoding. This
1536 // is easy to detect since the length of a "Group Length" tag (the
1537 // ones with zero as element number) has to be of 4 (0x0004). When we
1538 // encounter 1024 (0x0400) chances are the encoding changed and we
1539 // found a group with big endian encoding.
1540 // We shall use this second strategy. In order to make sure that we
1541 // can interpret the presence of an apparently big endian encoded
1542 // length of a "Group Length" without committing a big mistake, we
1543 // add an additional check: we look in the already parsed elements
1544 // for the presence of a "Transfer Syntax" whose value has to be "big
1545 // endian encoding". When this is the case, chances are we have got our
1546 // hands on a big endian encoded file: we switch the swap code to
1547 // big endian and proceed...
1548 if ( (element == 0x0000) && (length16 == 0x0400) )
1550 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1552 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1557 SwitchSwapToBigEndian();
1558 // Restore the unproperly loaded values i.e. the group, the element
1559 // and the dictionary entry depending on them.
1560 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1561 guint16 CorrectElem = SwapShort(Entry->GetElement());
1562 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1566 // This correct tag is not in the dictionary. Create a new one.
1567 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1569 // FIXME this can create a memory leaks on the old entry that be
1570 // left unreferenced.
1571 Entry->SetDictEntry(NewTag);
1574 // Heuristic: well, some files are really ill-formed.
1575 if ( length16 == 0xffff)
1578 // Length16= 0xffff means that we deal with
1579 // 'Unknown Length' Sequence
1581 FixDocEntryFoundLength(Entry, (guint32)length16);
1586 // Either implicit VR or a non DICOM conformal (see note below) explicit
1587 // VR that ommited the VR of (at least) this element. Farts happen.
1588 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1589 // on Data elements "Implicit and Explicit VR Data Elements shall
1590 // not coexist in a Data Set and Data Sets nested within it".]
1591 // Length is on 4 bytes.
1593 FixDocEntryFoundLength(Entry, ReadInt32());
1599 * \brief Find the Value Representation of the current Dicom Element.
1602 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1604 if (Filetype != gdcmExplicitVR)
1609 long PositionOnEntry = ftell(fp);
1610 // Warning: we believe this is explicit VR (Value Representation) because
1611 // we used a heuristic that found "UL" in the first tag. Alas this
1612 // doesn't guarantee that all the tags will be in explicit VR. In some
1613 // cases (see e-film filtered files) one finds implicit VR tags mixed
1614 // within an explicit VR file. Hence we make sure the present tag
1615 // is in explicit VR and try to fix things if it happens not to be
1618 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1620 if(!CheckDocEntryVR(Entry,VR))
1622 fseek(fp, PositionOnEntry, SEEK_SET);
1623 // When this element is known in the dictionary we shall use, e.g. for
1624 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1625 // dictionary entry. Still we have to flag the element as implicit since
1626 // we know now our assumption on expliciteness is not furfilled.
1628 if ( Entry->IsVRUnknown() )
1629 Entry->SetVR("Implicit");
1630 Entry->SetImplicitVR();
1635 * \brief Check the correspondance between the VR of the header entry
1636 * and the taken VR. If they are different, the header entry is
1637 * updated with the new VR.
1638 * @param Entry Header Entry to check
1639 * @param vr Dicom Value Representation
1640 * @return false if the VR is incorrect of if the VR isn't referenced
1641 * otherwise, it returns true
1643 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1645 char msg[100]; // for sprintf
1646 bool RealExplicit = true;
1648 // Assume we are reading a falsely explicit VR file i.e. we reached
1649 // a tag where we expect reading a VR but are in fact we read the
1650 // first to bytes of the length. Then we will interogate (through find)
1651 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1652 // both GCC and VC++ implementations of the STL map. Hence when the
1653 // expected VR read happens to be non-ascii characters we consider
1654 // we hit falsely explicit VR tag.
1656 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1657 RealExplicit = false;
1659 // CLEANME searching the dicom_vr at each occurence is expensive.
1660 // PostPone this test in an optional integrity check at the end
1661 // of parsing or only in debug mode.
1662 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1663 RealExplicit= false;
1665 if ( !RealExplicit )
1667 // We thought this was explicit VR, but we end up with an
1668 // implicit VR tag. Let's backtrack.
1669 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1670 Entry->GetGroup(),Entry->GetElement());
1671 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1672 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1673 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1674 Entry->GetGroup(),Entry->GetElement(),
1675 "UL","FIXME","Group Length");
1676 Entry->SetDictEntry(NewEntry);
1681 if ( Entry->IsVRUnknown() )
1683 // When not a dictionary entry, we can safely overwrite the VR.
1684 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1690 else if ( Entry->GetVR() != vr )
1692 // The VR present in the file and the dictionary disagree. We assume
1693 // the file writer knew best and use the VR of the file. Since it would
1694 // be unwise to overwrite the VR of a dictionary (since it would
1695 // compromise it's next user), we need to clone the actual DictEntry
1696 // and change the VR for the read one.
1697 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1698 Entry->GetGroup(),Entry->GetElement(),
1699 vr,"FIXME",Entry->GetName());
1700 Entry->SetDictEntry(NewEntry);
1706 * \brief Get the transformed value of the header entry. The VR value
1707 * is used to define the transformation to operate on the value
1708 * \warning NOT end user intended method !
1710 * @return Transformed entry value
1712 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1714 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1716 std::string val=((gdcmValEntry *)Entry)->GetValue();
1717 std::string vr=Entry->GetVR();
1718 guint32 length = Entry->GetLength();
1719 std::ostringstream s;
1722 // When short integer(s) are expected, read and convert the following
1723 // n * 2 bytes properly i.e. as a multivaluated strings
1724 // (each single value is separated fromthe next one by '\'
1725 // as usual for standard multivaluated filels
1726 // Elements with Value Multiplicity > 1
1727 // contain a set of short integers (not a single one)
1729 if (vr == "US" || vr == "SS")
1734 for (int i=0; i < nbInt; i++)
1738 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1739 NewInt16 = SwapShort(NewInt16);
1744 // When integer(s) are expected, read and convert the following
1745 // n * 4 bytes properly i.e. as a multivaluated strings
1746 // (each single value is separated fromthe next one by '\'
1747 // as usual for standard multivaluated filels
1748 // Elements with Value Multiplicity > 1
1749 // contain a set of integers (not a single one)
1750 else if (vr == "UL" || vr == "SL")
1755 for (int i=0; i < nbInt; i++)
1759 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1760 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1761 NewInt32=SwapLong(NewInt32);
1765 #ifdef GDCM_NO_ANSI_STRING_STREAM
1766 s << std::ends; // to avoid oddities on Solaris
1767 #endif //GDCM_NO_ANSI_STRING_STREAM
1771 return ((gdcmValEntry *)Entry)->GetValue();
1775 * \brief Get the reverse transformed value of the header entry. The VR
1776 * value is used to define the reverse transformation to operate on
1778 * \warning NOT end user intended method !
1780 * @return Reverse transformed entry value
1782 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1784 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1786 std::string vr=Entry->GetVR();
1787 std::ostringstream s;
1788 std::vector<std::string> tokens;
1790 if (vr == "US" || vr == "SS")
1794 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1795 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1796 for (unsigned int i=0; i<tokens.size();i++)
1798 NewInt16 = atoi(tokens[i].c_str());
1799 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1803 if (vr == "UL" || vr == "SL")
1807 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1808 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1809 for (unsigned int i=0; i<tokens.size();i++)
1811 NewInt32 = atoi(tokens[i].c_str());
1812 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1813 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1818 #ifdef GDCM_NO_ANSI_STRING_STREAM
1819 s << std::ends; // to avoid oddities on Solaris
1820 #endif //GDCM_NO_ANSI_STRING_STREAM
1824 return ((gdcmValEntry *)Entry)->GetValue();
1828 * \brief Skip a given Header Entry
1829 * \warning NOT end user intended method !
1832 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1834 SkipBytes(entry->GetLength());
1838 * \brief Skips to the begining of the next Header Entry
1839 * \warning NOT end user intended method !
1842 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1844 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1845 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1849 * \brief When the length of an element value is obviously wrong (because
1850 * the parser went Jabberwocky) one can hope improving things by
1851 * applying some heuristics.
1853 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1854 guint32 FoundLength)
1856 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1857 if ( FoundLength == 0xffffffff) {
1861 guint16 gr =Entry->GetGroup();
1862 guint16 el =Entry->GetElement();
1864 if (FoundLength%2) {
1865 std::ostringstream s;
1866 s << "Warning : Tag with uneven length "
1868 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1869 dbg.Verbose(0, s.str().c_str());
1872 //////// Fix for some naughty General Electric images.
1873 // Allthough not recent many such GE corrupted images are still present
1874 // on Creatis hard disks. Hence this fix shall remain when such images
1875 // are no longer in user (we are talking a few years, here)...
1876 // Note: XMedCom probably uses such a trick since it is able to read
1877 // those pesky GE images ...
1878 if (FoundLength == 13) { // Only happens for this length !
1879 if ( (Entry->GetGroup() != 0x0008)
1880 || ( (Entry->GetElement() != 0x0070)
1881 && (Entry->GetElement() != 0x0080) ) )
1884 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1888 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1889 // Occurence of such images is quite low (unless one leaves close to a
1890 // 'Leonardo' source. Hence, one might consider commenting out the
1891 // following fix on efficiency reasons.
1893 if ( (Entry->GetGroup() == 0x0009)
1894 && ( (Entry->GetElement() == 0x1113)
1895 || (Entry->GetElement() == 0x1114) ) )
1898 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1901 //////// Deal with sequences, but only on users request:
1903 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1905 FoundLength = 0; // ReadLength is unchanged
1908 //////// We encountered a 'delimiter' element i.e. a tag of the form
1909 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1910 // taken into account.
1912 if(Entry->GetGroup() == 0xfffe)
1914 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1915 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1916 // causes extra troubles...
1917 if( Entry->GetElement() != 0x0000 )
1923 Entry->SetUsableLength(FoundLength);
1927 * \brief Apply some heuristics to predict whether the considered
1928 * element value contains/represents an integer or not.
1929 * @param Entry The element value on which to apply the predicate.
1930 * @return The result of the heuristical predicate.
1932 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1933 guint16 element = Entry->GetElement();
1934 guint16 group = Entry->GetGroup();
1935 std::string vr = Entry->GetVR();
1936 guint32 length = Entry->GetLength();
1938 // When we have some semantics on the element we just read, and if we
1939 // a priori know we are dealing with an integer, then we shall be
1940 // able to swap it's element value properly.
1941 if ( element == 0 ) // This is the group length of the group
1947 // Allthough this should never happen, still some images have a
1948 // corrupted group length [e.g. have a glance at offset x(8336) of
1949 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1950 // Since for dicom compliant and well behaved headers, the present
1951 // test is useless (and might even look a bit paranoid), when we
1952 // encounter such an ill-formed image, we simply display a warning
1953 // message and proceed on parsing (while crossing fingers).
1954 std::ostringstream s;
1955 int filePosition = ftell(fp);
1956 s << "Erroneous Group Length element length on : (" \
1957 << std::hex << group << " , " << element
1958 << ") -before- position x(" << filePosition << ")"
1959 << "lgt : " << length;
1960 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1964 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1971 * \brief Find the Length till the next sequence delimiter
1972 * \warning NOT end user intended method !
1976 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1977 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1980 long PositionOnEntry = ftell(fp);
1981 bool FoundSequenceDelimiter = false;
1982 guint32 TotalLength = 0;
1985 while ( ! FoundSequenceDelimiter)
1991 TotalLength += 4; // We even have to decount the group and element
1993 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1995 char msg[100]; // for sprintf. Sorry
1996 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1997 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2001 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2002 FoundSequenceDelimiter = true;
2003 else if ( n != 0xe000 )
2005 char msg[100]; // for sprintf. Sorry
2006 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2008 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2012 ItemLength = ReadInt32();
2013 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2014 // the ItemLength with ReadInt32
2015 SkipBytes(ItemLength);
2017 fseek(fp, PositionOnEntry, SEEK_SET);
2022 * \brief Reads a supposed to be 16 Bits integer
2023 * (swaps it depending on processor endianity)
2024 * @return read value
2026 guint16 gdcmDocument::ReadInt16() {
2029 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2030 if ( item_read != 1 ) {
2032 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2042 * \brief Reads a supposed to be 32 Bits integer
2043 * (swaps it depending on processor endianity)
2044 * @return read value
2046 guint32 gdcmDocument::ReadInt32() {
2049 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2050 if ( item_read != 1 ) {
2052 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2062 * \brief skips bytes inside the source file
2063 * \warning NOT end user intended method !
2066 void gdcmDocument::SkipBytes(guint32 NBytes) {
2067 //FIXME don't dump the returned value
2068 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2072 * \brief Loads all the needed Dictionaries
2073 * \warning NOT end user intended method !
2075 void gdcmDocument::Initialise(void)
2077 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2082 * \brief Discover what the swap code is (among little endian, big endian,
2083 * bad little endian, bad big endian).
2085 * @return false when we are absolutely sure
2086 * it's neither ACR-NEMA nor DICOM
2087 * true when we hope ours assuptions are OK
2089 bool gdcmDocument::CheckSwap() {
2091 // The only guaranted way of finding the swap code is to find a
2092 // group tag since we know it's length has to be of four bytes i.e.
2093 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2094 // occurs when we can't find such group...
2096 guint32 x=4; // x : for ntohs
2097 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2103 char deb[HEADER_LENGTH_TO_READ];
2105 // First, compare HostByteOrder and NetworkByteOrder in order to
2106 // determine if we shall need to swap bytes (i.e. the Endian type).
2112 // The easiest case is the one of a DICOM header, since it possesses a
2113 // file preamble where it suffice to look for the string "DICM".
2114 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2117 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2118 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2120 // Next, determine the value representation (VR). Let's skip to the
2121 // first element (0002, 0000) and check there if we find "UL"
2122 // - or "OB" if the 1st one is (0002,0001) -,
2123 // in which case we (almost) know it is explicit VR.
2124 // WARNING: if it happens to be implicit VR then what we will read
2125 // is the length of the group. If this ascii representation of this
2126 // length happens to be "UL" then we shall believe it is explicit VR.
2127 // FIXME: in order to fix the above warning, we could read the next
2128 // element value (or a couple of elements values) in order to make
2129 // sure we are not commiting a big mistake.
2130 // We need to skip :
2131 // * the 128 bytes of File Preamble (often padded with zeroes),
2132 // * the 4 bytes of "DICM" string,
2133 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2134 // i.e. a total of 136 bytes.
2138 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2139 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2140 // *Implicit* VR. -and it is !-
2142 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2143 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2144 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2145 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2146 // when Write DCM *adds*
2148 // Use gdcmDocument::dicom_vr to test all the possibilities
2149 // instead of just checking for UL, OB and UI !? group 0000
2151 Filetype = gdcmExplicitVR;
2152 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2153 "explicit Value Representation");
2157 Filetype = gdcmImplicitVR;
2158 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2159 "not an explicit Value Representation");
2165 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2166 "HostByteOrder != NetworkByteOrder");
2171 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2172 "HostByteOrder = NetworkByteOrder");
2175 // Position the file position indicator at first tag (i.e.
2176 // after the file preamble and the "DICM" string).
2178 fseek (fp, 132L, SEEK_SET);
2182 // Alas, this is not a DicomV3 file and whatever happens there is no file
2183 // preamble. We can reset the file position indicator to where the data
2184 // is (i.e. the beginning of the file).
2185 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2188 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2189 // By clean we mean that the length of the first tag is written down.
2190 // If this is the case and since the length of the first group HAS to be
2191 // four (bytes), then determining the proper swap code is straightforward.
2194 // We assume the array of char we are considering contains the binary
2195 // representation of a 32 bits integer. Hence the following dirty
2197 s32 = *((guint32 *)(entCur));
2218 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2219 // It is time for despaired wild guesses.
2220 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2221 // i.e. the 'group length' element is not present :
2223 // check the supposed to be 'group number'
2224 // 0x0002 or 0x0004 or 0x0008
2225 // to determine ' sw' value .
2226 // Only 0 or 4321 will be possible
2227 // (no oportunity to check for the formerly well known
2228 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2229 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2230 // the file IS NOT ACR-NEMA nor DICOM V3
2231 // Find a trick to tell it the caller...
2233 s16 = *((guint16 *)(deb));
2249 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2250 "ACR/NEMA unfound swap info (Really hopeless !)");
2251 Filetype = gdcmUnknown;
2255 // Then the only info we have is the net2host one.
2265 * \brief Restore the unproperly loaded values i.e. the group, the element
2266 * and the dictionary entry depending on them.
2268 void gdcmDocument::SwitchSwapToBigEndian(void)
2270 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2271 "Switching to BigEndian mode.");
2292 * \brief during parsing, Header Elements too long are not loaded in memory
2295 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2299 if ((guint32)NewSize >= (guint32)0xffffffff)
2301 MaxSizeLoadEntry = 0xffffffff;
2304 MaxSizeLoadEntry = NewSize;
2309 * \brief Header Elements too long will not be printed
2310 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2313 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2317 if ((guint32)NewSize >= (guint32)0xffffffff)
2319 MaxSizePrintEntry = 0xffffffff;
2322 MaxSizePrintEntry = NewSize;
2328 * \brief Read the next tag but WITHOUT loading it's value
2329 * (read the 'Group Number', the 'Element Number',
2330 * gets the Dict Entry
2331 * gets the VR, gets the length, gets the offset value)
2332 * @return On succes the newly created DocEntry, NULL on failure.
2334 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2336 gdcmDocEntry *NewEntry;
2341 // We reached the EOF (or an error occured) therefore
2342 // header parsing has to be considered as finished.
2343 return (gdcmDocEntry *)0;
2345 NewEntry = NewDocEntryByNumber(g, n);
2346 FindDocEntryVR(NewEntry);
2347 FindDocEntryLength(NewEntry);
2354 NewEntry->SetOffset(ftell(fp));
2360 * \brief Generate a free TagKey i.e. a TagKey that is not present
2361 * in the TagHt dictionary.
2362 * @param group The generated tag must belong to this group.
2363 * @return The element of tag with given group which is fee.
2365 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2367 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2369 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2370 if (tagHT.count(key) == 0)
2378 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2379 * is placed at the beginning of a tag (TestGroup, TestElement),
2380 * read the length associated to the Tag.
2381 * \warning On success the internal file pointer \ref gdcmDocument::fp
2382 * is modified to point after the tag and it's length.
2383 * On failure (i.e. when the tag wasn't the expected tag
2384 * (TestGroup, TestElement) the internal file pointer
2385 * \ref gdcmDocument::fp is restored to it's original position.
2386 * @param TestGroup The expected group of the tag.
2387 * @param TestElement The expected Element of the tag.
2388 * @return On success returns the length associated to the tag. On failure
2391 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2393 guint16 ItemTagGroup;
2394 guint16 ItemTagElement;
2395 long PositionOnEntry = ftell(fp);
2396 long CurrentPosition = ftell(fp); // On debugging purposes
2398 //// Read the Item Tag group and element, and make
2399 // sure they are respectively 0xfffe and 0xe000:
2400 ItemTagGroup = ReadInt16();
2401 ItemTagElement = ReadInt16();
2402 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2404 std::ostringstream s;
2405 s << " We should have found tag (";
2406 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2407 s << " but instead we encountered tag (";
2408 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2410 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2411 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2412 dbg.Verbose(0, s.str().c_str());
2413 fseek(fp, PositionOnEntry, SEEK_SET);
2417 //// Then read the associated Item Length
2418 CurrentPosition=ftell(fp);
2420 ItemLength = ReadInt32();
2422 std::ostringstream s;
2423 s << "Basic Item Length is: "
2424 << ItemLength << std::endl;
2425 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2426 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2432 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2433 * \sa \ref gdcmDocument::ReadTagLength
2434 * \warning See warning of \ref gdcmDocument::ReadTagLength
2435 * @return On success returns the length associated to the item tag.
2436 * On failure returns 0.
2438 guint32 gdcmDocument::ReadItemTagLength(void)
2440 return ReadTagLength(0xfffe, 0xe000);
2444 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2446 * \sa \ref gdcmDocument::ReadTagLength
2447 * \warning See warning of \ref gdcmDocument::ReadTagLength
2448 * @return On success returns the length associated to the Sequence
2449 * Delimiter tag. On failure returns 0.
2451 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2453 return ReadTagLength(0xfffe, 0xe0dd);
2458 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2459 * No other way so 'skip' the Data
2463 void gdcmDocument::Parse7FE0 (void)
2465 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2469 if ( IsImplicitVRLittleEndianTransferSyntax()
2470 || IsExplicitVRLittleEndianTransferSyntax()
2471 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2472 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2475 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2477 //// Read the Basic Offset Table Item Tag length...
2478 guint32 ItemLength = ReadItemTagLength();
2480 //// ... and then read length[s] itself[themselves]. We don't use
2481 // the values read (BTW what is the purpous of those lengths ?)
2482 if (ItemLength != 0) {
2483 // BTW, what is the purpous of those length anyhow !?
2484 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2485 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2486 for (unsigned int i=0; i < ItemLength; i += 4){
2487 guint32 IndividualLength;
2488 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2489 std::ostringstream s;
2490 s << " Read one length: ";
2491 s << std::hex << IndividualLength << std::endl;
2492 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2496 if ( ! IsRLELossLessTransferSyntax() )
2500 //// We then skip (not reading them) all the fragments of images:
2501 while ( (ItemLength = ReadItemTagLength()) )
2503 SkipBytes(ItemLength);
2511 long RleSegmentLength[15], fragmentLength;
2513 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2514 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2516 // Parse fragments of the current Fragment (Frame)
2517 //------------------ scanning (not reading) fragment pixels
2518 guint32 nbRleSegments = ReadInt32();
2519 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2521 //// Reading RLE Segments Offset Table
2522 guint32 RleSegmentOffsetTable[15];
2523 for(int k=1; k<=15; k++) {
2525 RleSegmentOffsetTable[k] = ReadInt32();
2526 printf(" at : %x Offset Segment %d : %d (%x)\n",
2527 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2528 RleSegmentOffsetTable[k]);
2531 // skipping (not reading) RLE Segments
2532 if (nbRleSegments>1) {
2533 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2534 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2535 - RleSegmentOffsetTable[k];
2537 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2538 k,(unsigned)RleSegmentLength[k],
2539 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2540 SkipBytes(RleSegmentLength[k]);
2544 RleSegmentLength[nbRleSegments]= fragmentLength
2545 - RleSegmentOffsetTable[nbRleSegments];
2547 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2548 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2549 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2550 SkipBytes(RleSegmentLength[nbRleSegments]);
2558 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2559 * \warning Does NOT work with ACR-NEMA files
2560 * \todo Find a trick to solve the pb (use RET fields ?)
2562 * @return true if 'smaller'
2564 bool gdcmDocument::operator<(gdcmDocument &document)
2569 s1=this->GetEntryByNumber(0x0010,0x0010);
2570 s2=document.GetEntryByNumber(0x0010,0x0010);
2578 s1=this->GetEntryByNumber(0x0010,0x0020);
2579 s2=document.GetEntryByNumber(0x0010,0x0020);
2586 // Study Instance UID
2587 s1=this->GetEntryByNumber(0x0020,0x000d);
2588 s2=document.GetEntryByNumber(0x0020,0x000d);
2595 // Serie Instance UID
2596 s1=this->GetEntryByNumber(0x0020,0x000e);
2597 s2=document.GetEntryByNumber(0x0020,0x000e);
2609 //-----------------------------------------------------------------------------