1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/23 13:02:36 $
7 Version: $Revision: 1.27 $
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 = 4096;
79 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
81 //-----------------------------------------------------------------------------
82 // Constructor / Destructor
86 * @param inFilename file to be opened for parsing
87 * @param exception_on_error whether we throw an exception or not
88 * @param enable_sequences = true to allow the header
89 * to be parsed *inside* the SeQuences,
90 * when they have an actual length
91 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
92 * @param ignore_shadow to allow skipping the shadow elements,
93 * to save memory space.
94 * \warning The TRUE value for this param has to be used
95 * with a FALSE value for the 'enable_sequence' param.
96 * ('public elements' may be embedded in 'shadow Sequences')
98 gdcmDocument::gdcmDocument(std::string const & inFilename,
99 bool exception_on_error,
100 bool enable_sequences,
102 : gdcmElementSet(-1) {
103 enableSequences=enable_sequences;
104 IgnoreShadow =ignore_shadow;
106 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
107 Filename = inFilename;
110 if ( !OpenFile(exception_on_error))
113 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
117 fseek(fp,0L,SEEK_END);
118 long lgt = ftell(fp);
122 long beg = ftell(fp);
127 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
128 (void)l; //is l used anywhere ?
132 // Load 'non string' values
134 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
135 if( PhotometricInterpretation == "PALETTE COLOR " ) {
136 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
137 LoadEntryVoidArea(0x0028,0x1201); // R LUT
138 LoadEntryVoidArea(0x0028,0x1202); // G LUT
139 LoadEntryVoidArea(0x0028,0x1203); // B LUT
141 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
142 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
143 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
145 //FIXME later : how to use it?
146 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
150 // --------------------------------------------------------------
151 // Special Patch to allow gdcm to read ACR-LibIDO formated images
153 // if recognition code tells us we deal with a LibIDO image
154 // we switch lineNumber and columnNumber
157 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
158 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
159 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
160 // with "little-endian strings"
162 Filetype = gdcmACR_LIBIDO;
163 std::string rows = GetEntryByNumber(0x0028, 0x0010);
164 std::string columns = GetEntryByNumber(0x0028, 0x0011);
165 SetEntryByNumber(columns, 0x0028, 0x0010);
166 SetEntryByNumber(rows , 0x0028, 0x0011);
168 // ----------------- End of Special Patch ----------------
170 printLevel = 1; // 'Medium' print level by default
175 * @param exception_on_error
177 gdcmDocument::gdcmDocument(bool exception_on_error)
178 :gdcmElementSet(-1) {
179 (void)exception_on_error;
182 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
185 printLevel = 1; // 'Medium' print level by default
189 * \brief Canonical destructor.
191 gdcmDocument::~gdcmDocument (void) {
195 // Recursive clean up of sequences
196 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
203 //-----------------------------------------------------------------------------
207 * \brief Prints The Dict Entries of THE public Dicom Dictionary
210 void gdcmDocument::PrintPubDict(std::ostream & os) {
211 RefPubDict->Print(os);
215 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
218 void gdcmDocument::PrintShaDict(std::ostream & os) {
219 RefShaDict->Print(os);
222 //-----------------------------------------------------------------------------
225 * \brief Get the public dictionary used
227 gdcmDict *gdcmDocument::GetPubDict(void) {
232 * \brief Get the shadow dictionary used
234 gdcmDict *gdcmDocument::GetShaDict(void) {
239 * \brief Set the shadow dictionary used
240 * \param dict dictionary to use in shadow
242 bool gdcmDocument::SetShaDict(gdcmDict *dict){
248 * \brief Set the shadow dictionary used
249 * \param dictName name of the dictionary to use in shadow
251 bool gdcmDocument::SetShaDict(DictKey dictName){
252 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
257 * \brief This predicate, based on hopefully reasonable heuristics,
258 * decides whether or not the current gdcmDocument was properly parsed
259 * and contains the mandatory information for being considered as
260 * a well formed and usable Dicom/Acr File.
261 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
264 bool gdcmDocument::IsReadable(void) {
265 if(Filetype==gdcmUnknown) {
266 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
269 if(!tagHT.empty()<=0) {
270 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
280 * \brief Internal function that checks whether the Transfer Syntax given
281 * as argument is the one present in the current document.
282 * @param SyntaxToCheck The transfert syntax we need to check against.
283 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
284 * the current document. False either when the document contains
285 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
287 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
289 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
293 // The entry might be present but not loaded (parsing and loading
294 // happen at differente stages): try loading and proceed with check...
295 LoadDocEntrySafe(Entry);
296 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
298 std::string Transfer = ValEntry->GetValue();
299 // The actual transfer (as read from disk) might be padded. We
300 // first need to remove the potential padding. We can make the
301 // weak assumption that padding was not executed with digits...
302 while ( ! isdigit(Transfer[Transfer.length()-1]) )
304 Transfer.erase(Transfer.length()-1, 1);
306 if ( Transfer == SyntaxToCheck )
313 * \brief Determines if the Transfer Syntax of the present document
314 * corresponds to a Implicit Value Representation of
316 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
317 * @return True when ImplicitVRLittleEndian found. False in all other cases.
319 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
321 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
325 * \brief Determines if the Transfer Syntax was already encountered
326 * and if it corresponds to a ExplicitVRLittleEndian one.
327 * @return True when ExplicitVRLittleEndian found. False in all other cases.
329 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
331 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
335 * \brief Determines if the Transfer Syntax was already encountered
336 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
337 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
339 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
341 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
345 * \brief Determines if the Transfer Syntax was already encountered
346 * and if it corresponds to a Explicit VR Big Endian one.
347 * @return True when big endian found. False in all other cases.
349 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
351 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
355 * \brief Determines if the Transfer Syntax was already encountered
356 * and if it corresponds to a JPEGBaseLineProcess1 one.
357 * @return True when JPEGBaseLineProcess1found. False in all other cases.
359 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
361 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
365 * \brief Determines if the Transfer Syntax was already encountered
366 * and if it corresponds to a JPEGExtendedProcess2-4 one.
367 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
369 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
371 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
375 * \brief Determines if the Transfer Syntax was already encountered
376 * and if it corresponds to a JPEGExtendeProcess3-5 one.
377 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
379 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
381 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
385 * \brief Determines if the Transfer Syntax was already encountered
386 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
387 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
390 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
392 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
396 * \brief Determines if the Transfer Syntax was already encountered
397 * and if it corresponds to a RLE Lossless one.
398 * @return True when RLE Lossless found. False in all
401 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
403 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
407 * \brief Determines if Transfer Syntax was already encountered
408 * and if it corresponds to a JPEG Lossless one.
409 * @return True when RLE Lossless found. False in all
413 bool gdcmDocument::IsJPEGLossless(void)
415 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
416 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
417 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) ); // was 90
421 * \brief Determines if the Transfer Syntax was already encountered
422 * and if it corresponds to a JPEG2000 one
423 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
426 bool gdcmDocument::IsJPEG2000(void)
428 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
429 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
433 * \brief Predicate for dicom version 3 file.
434 * @return True when the file is a dicom version 3.
436 bool gdcmDocument::IsDicomV3(void) {
437 // Checking if Transfert Syntax exists is enough
438 // Anyway, it's to late check if the 'Preamble' was found ...
439 // And ... would it be a rich idea to check ?
440 // (some 'no Preamble' DICOM images exist !)
441 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
445 * \brief returns the File Type
446 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
447 * @return the FileType code
449 FileType gdcmDocument::GetFileType(void) {
454 * \brief opens the file
455 * @param exception_on_error
458 FILE *gdcmDocument::OpenFile(bool exception_on_error)
461 fp=fopen(Filename.c_str(),"rb");
465 if(exception_on_error)
466 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
469 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
478 fread(&zero, (size_t)2, (size_t)1, fp);
480 //ACR -- or DICOM with no Preamble --
481 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
485 fseek(fp, 126L, SEEK_CUR);
487 fread(dicm, (size_t)4, (size_t)1, fp);
488 if( memcmp(dicm, "DICM", 4) == 0 )
492 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
495 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
501 * \brief closes the file
502 * @return TRUE if the close was successfull
504 bool gdcmDocument::CloseFile(void) {
505 int closed = fclose(fp);
513 * \brief Writes in a file all the Header Entries (Dicom Elements)
514 * @param fp file pointer on an already open file
515 * @param filetype Type of the File to be written
516 * (ACR-NEMA, ExplicitVR, ImplicitVR)
517 * \return Always true.
519 bool gdcmDocument::WriteF(FileType filetype) {
522 /// The stuff is rewritten using the SeQuence based
523 /// tree-like stucture (cf : Print )
527 /// \todo move the following lines (and a lot of others, to be written)
528 /// to a future function CheckAndCorrectHeader
530 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
531 /// no way (check : FileType est un champ de gdcmDocument ...)
532 /// a moins de se livrer a un tres complique ajout des champs manquants.
533 /// faire un CheckAndCorrectHeader (?)
535 if (filetype == gdcmImplicitVR)
537 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
538 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
540 /// \todo Refer to standards on page 21, chapter 6.2
541 /// "Value representation": values with a VR of UI shall be
542 /// padded with a single trailing null
543 /// Dans le cas suivant on doit pader manuellement avec un 0
545 SetEntryLengthByNumber(18, 0x0002, 0x0010);
548 if (filetype == gdcmExplicitVR)
550 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
551 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
553 /// \todo Refer to standards on page 21, chapter 6.2
554 /// "Value representation": values with a VR of UI shall be
555 /// padded with a single trailing null
556 /// Dans le cas suivant on doit pader manuellement avec un 0
558 SetEntryLengthByNumber(20, 0x0002, 0x0010);
562 * \todo rewrite later, if really usefull
563 * ('Group Length' element is optional in DICOM)
565 * --> Warning : un-updated odd groups lengthes can causes pb
566 * --> (xmedcon breaks)
567 * --> to be re- written with future org.
569 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
570 * UpdateGroupLength(false,filetype);
571 * if ( filetype == ACR)
572 * UpdateGroupLength(true,ACR);
575 gdcmElementSet::Write(fp,filetype);
577 /// WriteEntries(fp,type); // old stuff
582 * \brief Modifies the value of a given Header Entry (Dicom Element)
583 * when it exists. Create it with the given value when unexistant.
584 * @param Value (string) Value to be set
585 * @param Group Group number of the Entry
586 * @param Elem Element number of the Entry
587 * \return pointer to the modified/created Header Entry (NULL when creation
591 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
596 gdcmDocEntry* CurrentEntry;
597 gdcmValEntry* ValEntry;
599 CurrentEntry = GetDocEntryByNumber( Group, Elem);
602 // The entry wasn't present and we simply create the required ValEntry:
603 CurrentEntry = NewDocEntryByNumber(Group, Elem);
606 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
607 " NewDocEntryByNumber failed.");
610 ValEntry = new gdcmValEntry(CurrentEntry);
611 if ( !AddEntry(ValEntry))
613 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
614 " failed allthough this is a creation.");
619 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
622 // We need to promote the gdcmDocEntry to a gdcmValEntry:
623 ValEntry = new gdcmValEntry(CurrentEntry);
624 if (!RemoveEntry(CurrentEntry))
626 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
627 " of previous DocEntry failed.");
630 if ( !AddEntry(ValEntry))
632 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
633 " promoted ValEntry failed.");
639 SetEntryByNumber(Value, Group, Elem);
645 * \brief Modifies the value of a given Header Entry (Dicom Element)
646 * when it exists. Create it with the given value when unexistant.
647 * @param voidArea (binary) value to be set
648 * @param Group Group number of the Entry
649 * @param Elem Element number of the Entry
650 * \return pointer to the modified/created Header Entry (NULL when creation
653 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
661 a = GetDocEntryByNumber( Group, Elem);
663 a =NewBinEntryByNumber(Group, Elem);
667 b = new gdcmBinEntry(a);
670 SetEntryByNumber(voidArea, lgth, Group, Elem);
671 b->SetVoidArea(voidArea);
679 * \brief Set a new value if the invoked element exists
680 * Seems to be useless !!!
681 * @param Value new element value
682 * @param Group group number of the Entry
683 * @param Elem element number of the Entry
686 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
688 std::string v = Value;
689 SetEntryByNumber(v, Group, Elem);
693 //-----------------------------------------------------------------------------
697 * \brief Checks if a given Dicom Element exists within the H table
698 * @param group Group number of the searched Dicom Element
699 * @param element Element number of the searched Dicom Element
700 * @return number of occurences
702 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
703 std::string key = gdcmDictEntry::TranslateToKey(group, element );
704 return tagHT.count(key);
708 * \brief Searches within Header Entries (Dicom Elements) parsed with
709 * the public and private dictionaries
710 * for the element value of a given tag.
711 * \warning Don't use any longer : use GetPubEntryByName
712 * @param tagName name of the searched element.
713 * @return Corresponding element value when it exists,
714 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
716 std::string gdcmDocument::GetEntryByName(std::string tagName) {
717 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
718 if( dictEntry == NULL)
721 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
725 * \brief Searches within Header Entries (Dicom Elements) parsed with
726 * the public and private dictionaries
727 * for the element value representation of a given tag.
729 * Obtaining the VR (Value Representation) might be needed by caller
730 * to convert the string typed content to caller's native type
731 * (think of C++ vs Python). The VR is actually of a higher level
732 * of semantics than just the native C++ type.
733 * @param tagName name of the searched element.
734 * @return Corresponding element value representation when it exists,
735 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
737 std::string gdcmDocument::GetEntryVRByName(TagName tagName) {
738 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
739 if( dictEntry == NULL)
742 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
743 dictEntry->GetElement());
744 return elem->GetVR();
749 * \brief Searches within Header Entries (Dicom Elements) parsed with
750 * the public and private dictionaries
751 * for the element value representation of a given tag.
752 * @param group Group number of the searched tag.
753 * @param element Element number of the searched tag.
754 * @return Corresponding element value representation when it exists,
755 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
757 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
758 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
759 if ( ! tagHT.count(key))
761 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
765 * \brief Searches within Header Entries (Dicom Elements) parsed with
766 * the public and private dictionaries
767 * for the element value representation of a given tag..
769 * Obtaining the VR (Value Representation) might be needed by caller
770 * to convert the string typed content to caller's native type
771 * (think of C++ vs Python). The VR is actually of a higher level
772 * of semantics than just the native C++ type.
773 * @param group Group number of the searched tag.
774 * @param element Element number of the searched tag.
775 * @return Corresponding element value representation when it exists,
776 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
778 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
779 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
782 return elem->GetVR();
786 * \brief Searches within Header Entries (Dicom Elements) parsed with
787 * the public and private dictionaries
788 * for the value length of a given tag..
789 * @param group Group number of the searched tag.
790 * @param element Element number of the searched tag.
791 * @return Corresponding element length; -2 if not found
793 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
794 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
797 return elem->GetLength();
800 * \brief Sets the value (string) of the Header Entry (Dicom Element)
801 * @param content string value of the Dicom Element
802 * @param tagName name of the searched Dicom Element.
803 * @return true when found
805 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
806 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
807 if( dictEntry == NULL)
810 return SetEntryByNumber(content,dictEntry->GetGroup(),
811 dictEntry->GetElement());
815 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
816 * through it's (group, element) and modifies it's content with
818 * @param content new value (string) to substitute with
819 * @param group group number of the Dicom Element to modify
820 * @param element element number of the Dicom Element to modify
822 bool gdcmDocument::SetEntryByNumber(std::string content,
826 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
829 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
830 " ValEntry (try promotion first).");
834 // Non even content must be padded with a space (020H).
835 if((content.length())%2)
836 content = content + '\0';
838 ValEntry->SetValue(content);
840 // Integers have a special treatement for their length:
841 VRKey vr = ValEntry->GetVR();
842 if( (vr == "US") || (vr == "SS") )
843 ValEntry->SetLength(2);
844 else if( (vr == "UL") || (vr == "SL") )
845 ValEntry->SetLength(4);
847 ValEntry->SetLength(content.length());
853 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
854 * through it's (group, element) and modifies it's content with
856 * @param content new value (void *) to substitute with
857 * @param group group number of the Dicom Element to modify
858 * @param element element number of the Dicom Element to modify
860 bool gdcmDocument::SetEntryByNumber(void *content,
865 (void)lgth; //not used
866 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
867 if ( ! tagHT.count(key))
870 /* Hope Binray field length is never wrong
871 if(lgth%2) // Non even length are padded with a space (020H).
874 //content = content + '\0'; // fing a trick to enlarge a binary field?
878 a = (gdcmBinEntry *)tagHT[key];
879 a->SetVoidArea(content);
880 //a->SetLength(lgth); // ???
885 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
886 * in the PubDocEntrySet of this instance
887 * through it's (group, element) and modifies it's length with
889 * \warning Use with extreme caution.
890 * @param l new length to substitute with
891 * @param group group number of the Entry to modify
892 * @param element element number of the Entry to modify
893 * @return true on success, false otherwise.
895 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
899 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
900 if ( ! tagHT.count(key))
902 if (l%2) l++; // length must be even
903 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
909 * \brief Gets (from Header) the offset of a 'non string' element value
910 * (LoadElementValues has already be executed)
911 * @param Group group number of the Entry
912 * @param Elem element number of the Entry
913 * @return File Offset of the Element Value
915 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
917 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
920 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
923 return Entry->GetOffset();
927 * \brief Gets (from Header) a 'non string' element value
928 * (LoadElementValues has already be executed)
929 * @param Group group number of the Entry
930 * @param Elem element number of the Entry
931 * @return Pointer to the 'non string' area
933 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
935 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
938 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
941 return ((gdcmBinEntry *)Entry)->GetVoidArea();
945 * \brief Loads (from disk) the element content
946 * when a string is not suitable
947 * @param Group group number of the Entry
948 * @param Elem element number of the Entry
950 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
952 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
955 size_t o =(size_t)Element->GetOffset();
956 fseek(fp, o, SEEK_SET);
957 size_t l = Element->GetLength();
958 char* a = new char[l];
960 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
963 SetEntryVoidAreaByNumber(a, Group, Elem);
964 /// \todo check the result
965 size_t l2 = fread(a, 1, l ,fp);
976 * \brief Sets a 'non string' value to a given Dicom Element
977 * @param area area containing the 'non string' value
978 * @param group Group number of the searched Dicom Element
979 * @param element Element number of the searched Dicom Element
982 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
986 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
987 if ( ! tagHT.count(key))
989 // This was for multimap ?
990 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
996 * \brief Update the entries with the shadow dictionary.
997 * Only non even entries are analyzed
999 void gdcmDocument::UpdateShaEntries(void) {
1000 //gdcmDictEntry *entry;
1003 /// \todo TODO : still any use to explore recursively the whole structure?
1005 for(ListTag::iterator it=listEntries.begin();
1006 it!=listEntries.end();
1009 // Odd group => from public dictionary
1010 if((*it)->GetGroup()%2==0)
1013 // Peer group => search the corresponding dict entry
1015 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1019 if((*it)->IsImplicitVR())
1024 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1026 // Set the new entry and the new value
1027 (*it)->SetDictEntry(entry);
1028 CheckDocEntryVR(*it,vr);
1030 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1035 // Remove precedent value transformation
1036 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1043 * \brief Searches within the Header Entries for a Dicom Element of
1045 * @param tagName name of the searched Dicom Element.
1046 * @return Corresponding Dicom Element when it exists, and NULL
1049 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1050 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1051 if( dictEntry == NULL)
1054 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1058 * \brief retrieves a Dicom Element (the first one) using (group, element)
1059 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1060 * if you think it's NOT UNIQUE, check the count number
1061 * and use iterators to retrieve ALL the Dicoms Elements within
1062 * a given couple (group, element)
1063 * @param group Group number of the searched Dicom Element
1064 * @param element Element number of the searched Dicom Element
1067 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1069 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1070 if ( ! tagHT.count(key))
1072 return tagHT.find(key)->second;
1076 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1077 * returns a result when the corresponding entry is of type
1079 * @return When present, the corresponding ValEntry.
1081 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1083 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1085 return (gdcmValEntry*)0;
1086 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1090 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1091 return (gdcmValEntry*)0;
1095 * \brief Loads the element while preserving the current
1096 * underlying file position indicator as opposed to
1097 * to LoadDocEntry that modifies it.
1098 * @param entry Header Entry whose value shall be loaded.
1101 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1102 long PositionOnEntry = ftell(fp);
1103 LoadDocEntry(entry);
1104 fseek(fp, PositionOnEntry, SEEK_SET);
1108 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1110 * @return The properly swaped 32 bits integer.
1112 guint32 gdcmDocument::SwapLong(guint32 a) {
1117 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1118 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1122 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1126 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1129 std::cout << "swapCode= " << sw << std::endl;
1130 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1137 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1139 * @return The properly unswaped 32 bits integer.
1141 guint32 gdcmDocument::UnswapLong(guint32 a) {
1142 return (SwapLong(a));
1146 * \brief Swaps the bytes so they agree with the processor order
1147 * @return The properly swaped 16 bits integer.
1149 guint16 gdcmDocument::SwapShort(guint16 a) {
1150 if ( (sw==4321) || (sw==2143) )
1151 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1156 * \brief Unswaps the bytes so they agree with the processor order
1157 * @return The properly unswaped 16 bits integer.
1159 guint16 gdcmDocument::UnswapShort(guint16 a) {
1160 return (SwapShort(a));
1163 //-----------------------------------------------------------------------------
1167 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1168 * @return length of the parsed set.
1171 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1173 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1174 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1181 depth = set->GetDepthLevel();
1184 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1187 NewDocEntry = ReadNextDocEntry( );
1191 vr = NewDocEntry->GetVR();
1195 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1198 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1199 NewValEntry->Copy(NewDocEntry);
1200 NewValEntry->SetDepthLevel(depth);
1201 set->AddEntry(NewValEntry);
1202 LoadDocEntry(NewValEntry);
1203 if (NewValEntry->isItemDelimitor())
1205 if ( !delim_mode && ftell(fp)-offset >= l_max)
1212 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1214 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1215 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1216 "nor BinEntry. Probably unknown VR.");
1219 ////// BinEntry or UNKOWN VR:
1220 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1221 bn->Copy(NewDocEntry);
1226 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1227 NewDocEntry->GetElement() == 0x0010 )
1229 if (NewDocEntry->GetLength()==0xffffffff)
1230 // Broken US.3405.1.dcm
1231 Parse7FE0(); // to skip the pixels
1232 // (multipart JPEG/RLE are trouble makers)
1236 // to be sure we are at the beginning
1237 SkipToNextDocEntry(NewDocEntry);
1238 l = NewDocEntry->GetFullLength();
1244 l=NewDocEntry->GetReadLength();
1245 if (l != 0) // don't mess the delim_mode for zero-length sequence
1246 if (l == 0xffffffff)
1250 // no other way to create it ...
1251 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1252 set->GetDepthLevel());
1253 sq->Copy(NewDocEntry);
1254 sq->SetDelimitorMode(delim_mode);
1255 sq->SetDepthLevel(depth);
1258 { // Don't try to parse zero-length sequences
1259 long lgt = ParseSQ( sq,
1260 NewDocEntry->GetOffset(),
1262 (void)lgt; //not used...
1264 // FIXME : on en fait quoi, de lgt ?
1266 if ( !delim_mode && ftell(fp)-offset >= l_max)
1277 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1278 * @return parsed length for this level
1280 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1281 long offset, long l_max, bool delim_mode)
1283 int SQItemNumber = 0;
1285 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1290 int depth = set->GetDepthLevel();
1291 (void)depth; //not used
1294 NewDocEntry = ReadNextDocEntry();
1296 if (NewDocEntry->isSequenceDelimitor()) {
1297 set->SetSequenceDelimitationItem(NewDocEntry);
1301 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1305 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1306 itemSQ->AddEntry(NewDocEntry);
1307 l= NewDocEntry->GetReadLength();
1309 if (l == 0xffffffff)
1314 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1316 set->AddEntry(itemSQ,SQItemNumber);
1318 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1322 lgth = ftell(fp) - offset;
1327 * \brief Loads the element content if its length doesn't exceed
1328 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1329 * @param Entry Header Entry (Dicom Element) to be dealt with
1331 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1334 guint16 group = Entry->GetGroup();
1335 std::string vr= Entry->GetVR();
1336 guint32 length = Entry->GetLength();
1338 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1340 // A SeQuence "contains" a set of Elements.
1341 // (fffe e000) tells us an Element is beginning
1342 // (fffe e00d) tells us an Element just ended
1343 // (fffe e0dd) tells us the current SeQuence just ended
1344 if( group == 0xfffe ) {
1345 // NO more value field for SQ !
1349 // When the length is zero things are easy:
1350 if ( length == 0 ) {
1351 ((gdcmValEntry *)Entry)->SetValue("");
1355 // The elements whose length is bigger than the specified upper bound
1356 // are not loaded. Instead we leave a short notice of the offset of
1357 // the element content and it's length.
1359 if (length > MaxSizeLoadEntry) {
1360 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1362 std::ostringstream s;
1363 s << "gdcm::NotLoaded (BinEntry)";
1364 s << " Address:" << (long)Entry->GetOffset();
1365 s << " Length:" << Entry->GetLength();
1366 s << " x(" << std::hex << Entry->GetLength() << ")";
1367 BinEntryPtr->SetValue(s.str());
1369 // to be sure we are at the end of the value ...
1370 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1372 // Be carefull : a BinEntry IS_A ValEntry ...
1373 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1375 std::ostringstream s;
1376 s << "gdcm::NotLoaded. (ValEntry)";
1377 s << " Address:" << (long)Entry->GetOffset();
1378 s << " Length:" << Entry->GetLength();
1379 s << " x(" << std::hex << Entry->GetLength() << ")";
1380 ValEntryPtr->SetValue(s.str());
1382 // to be sure we are at the end of the value ...
1383 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1387 // When we find a BinEntry not very much can be done :
1388 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1389 LoadEntryVoidArea (BinEntryPtr->GetGroup(),BinEntryPtr->GetElement());
1394 // Any compacter code suggested (?)
1395 if ( IsDocEntryAnInteger(Entry) ) {
1397 std::ostringstream s;
1399 // When short integer(s) are expected, read and convert the following
1400 // n *two characters properly i.e. as short integers as opposed to strings.
1401 // Elements with Value Multiplicity > 1
1402 // contain a set of integers (not a single one)
1403 if (vr == "US" || vr == "SS") {
1405 NewInt = ReadInt16();
1408 for (int i=1; i < nbInt; i++) {
1410 NewInt = ReadInt16();
1415 // When integer(s) are expected, read and convert the following
1416 // n * four characters properly i.e. as integers as opposed to strings.
1417 // Elements with Value Multiplicity > 1
1418 // contain a set of integers (not a single one)
1419 else if (vr == "UL" || vr == "SL") {
1421 NewInt = ReadInt32();
1424 for (int i=1; i < nbInt; i++) {
1426 NewInt = ReadInt32();
1431 #ifdef GDCM_NO_ANSI_STRING_STREAM
1432 s << std::ends; // to avoid oddities on Solaris
1433 #endif //GDCM_NO_ANSI_STRING_STREAM
1435 ((gdcmValEntry *)Entry)->SetValue(s.str());
1439 // We need an additional byte for storing \0 that is not on disk
1440 std::string NewValue(length,0);
1441 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1442 if ( item_read != 1 ) {
1443 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1444 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1448 if( (vr == "UI") ) // Because of correspondance with the VR dic
1449 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1451 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1456 * \brief Find the value Length of the passed Header Entry
1457 * @param Entry Header Entry whose length of the value shall be loaded.
1459 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1460 guint16 element = Entry->GetElement();
1461 //guint16 group = Entry->GetGroup(); //FIXME
1462 std::string vr = Entry->GetVR();
1466 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1468 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1470 // The following reserved two bytes (see PS 3.5-2001, section
1471 // 7.1.2 Data element structure with explicit vr p27) must be
1472 // skipped before proceeding on reading the length on 4 bytes.
1473 fseek(fp, 2L, SEEK_CUR);
1474 guint32 length32 = ReadInt32();
1476 if ( (vr == "OB") && (length32 == 0xffffffff) )
1478 Entry->SetLength(FindDocEntryLengthOB());
1481 FixDocEntryFoundLength(Entry, length32);
1485 // Length is encoded on 2 bytes.
1486 length16 = ReadInt16();
1488 // We can tell the current file is encoded in big endian (like
1489 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1490 // and it's value is the one of the encoding of a big endian file.
1491 // In order to deal with such big endian encoded files, we have
1492 // (at least) two strategies:
1493 // * when we load the "Transfer Syntax" tag with value of big endian
1494 // encoding, we raise the proper flags. Then we wait for the end
1495 // of the META group (0x0002) among which is "Transfer Syntax",
1496 // before switching the swap code to big endian. We have to postpone
1497 // the switching of the swap code since the META group is fully encoded
1498 // in little endian, and big endian coding only starts at the next
1499 // group. The corresponding code can be hard to analyse and adds
1500 // many additional unnecessary tests for regular tags.
1501 // * the second strategy consists in waiting for trouble, that shall
1502 // appear when we find the first group with big endian encoding. This
1503 // is easy to detect since the length of a "Group Length" tag (the
1504 // ones with zero as element number) has to be of 4 (0x0004). When we
1505 // encounter 1024 (0x0400) chances are the encoding changed and we
1506 // found a group with big endian encoding.
1507 // We shall use this second strategy. In order to make sure that we
1508 // can interpret the presence of an apparently big endian encoded
1509 // length of a "Group Length" without committing a big mistake, we
1510 // add an additional check: we look in the already parsed elements
1511 // for the presence of a "Transfer Syntax" whose value has to be "big
1512 // endian encoding". When this is the case, chances are we have got our
1513 // hands on a big endian encoded file: we switch the swap code to
1514 // big endian and proceed...
1515 if ( (element == 0x0000) && (length16 == 0x0400) )
1517 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1519 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1524 SwitchSwapToBigEndian();
1525 // Restore the unproperly loaded values i.e. the group, the element
1526 // and the dictionary entry depending on them.
1527 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1528 guint16 CorrectElem = SwapShort(Entry->GetElement());
1529 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1533 // This correct tag is not in the dictionary. Create a new one.
1534 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1536 // FIXME this can create a memory leaks on the old entry that be
1537 // left unreferenced.
1538 Entry->SetDictEntry(NewTag);
1541 // Heuristic: well some files are really ill-formed.
1542 if ( length16 == 0xffff)
1545 //dbg.Verbose(0, "gdcmDocument::FindLength",
1546 // "Erroneous element length fixed.");
1547 // Actually, length= 0xffff means that we deal with
1548 // Unknown Sequence Length
1550 FixDocEntryFoundLength(Entry, (guint32)length16);
1555 // Either implicit VR or a non DICOM conformal (see note below) explicit
1556 // VR that ommited the VR of (at least) this element. Farts happen.
1557 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1558 // on Data elements "Implicit and Explicit VR Data Elements shall
1559 // not coexist in a Data Set and Data Sets nested within it".]
1560 // Length is on 4 bytes.
1562 FixDocEntryFoundLength(Entry, ReadInt32());
1568 * \brief Find the Value Representation of the current Dicom Element.
1571 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1573 if (Filetype != gdcmExplicitVR)
1578 long PositionOnEntry = ftell(fp);
1579 // Warning: we believe this is explicit VR (Value Representation) because
1580 // we used a heuristic that found "UL" in the first tag. Alas this
1581 // doesn't guarantee that all the tags will be in explicit VR. In some
1582 // cases (see e-film filtered files) one finds implicit VR tags mixed
1583 // within an explicit VR file. Hence we make sure the present tag
1584 // is in explicit VR and try to fix things if it happens not to be
1587 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1589 if(!CheckDocEntryVR(Entry,VR))
1591 fseek(fp, PositionOnEntry, SEEK_SET);
1592 // When this element is known in the dictionary we shall use, e.g. for
1593 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1594 // dictionary entry. Still we have to flag the element as implicit since
1595 // we know now our assumption on expliciteness is not furfilled.
1597 if ( Entry->IsVRUnknown() )
1598 Entry->SetVR("Implicit");
1599 Entry->SetImplicitVR();
1604 * \brief Check the correspondance between the VR of the header entry
1605 * and the taken VR. If they are different, the header entry is
1606 * updated with the new VR.
1607 * @param Entry Header Entry to check
1608 * @param vr Dicom Value Representation
1609 * @return false if the VR is incorrect of if the VR isn't referenced
1610 * otherwise, it returns true
1612 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1614 char msg[100]; // for sprintf
1615 bool RealExplicit = true;
1617 // Assume we are reading a falsely explicit VR file i.e. we reached
1618 // a tag where we expect reading a VR but are in fact we read the
1619 // first to bytes of the length. Then we will interogate (through find)
1620 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1621 // both GCC and VC++ implementations of the STL map. Hence when the
1622 // expected VR read happens to be non-ascii characters we consider
1623 // we hit falsely explicit VR tag.
1625 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1626 RealExplicit = false;
1628 // CLEANME searching the dicom_vr at each occurence is expensive.
1629 // PostPone this test in an optional integrity check at the end
1630 // of parsing or only in debug mode.
1631 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1632 RealExplicit= false;
1634 if ( !RealExplicit )
1636 // We thought this was explicit VR, but we end up with an
1637 // implicit VR tag. Let's backtrack.
1638 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1639 Entry->GetGroup(),Entry->GetElement());
1640 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1641 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1642 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1643 Entry->GetGroup(),Entry->GetElement(),
1644 "UL","FIXME","Group Length");
1645 Entry->SetDictEntry(NewEntry);
1650 if ( Entry->IsVRUnknown() )
1652 // When not a dictionary entry, we can safely overwrite the VR.
1653 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1659 else if ( Entry->GetVR() != vr )
1661 // The VR present in the file and the dictionary disagree. We assume
1662 // the file writer knew best and use the VR of the file. Since it would
1663 // be unwise to overwrite the VR of a dictionary (since it would
1664 // compromise it's next user), we need to clone the actual DictEntry
1665 // and change the VR for the read one.
1666 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1667 Entry->GetGroup(),Entry->GetElement(),
1668 vr,"FIXME",Entry->GetName());
1669 Entry->SetDictEntry(NewEntry);
1675 * \brief Get the transformed value of the header entry. The VR value
1676 * is used to define the transformation to operate on the value
1677 * \warning NOT end user intended method !
1679 * @return Transformed entry value
1681 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1683 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1685 std::string val=((gdcmValEntry *)Entry)->GetValue();
1686 std::string vr=Entry->GetVR();
1687 guint32 length = Entry->GetLength();
1688 std::ostringstream s;
1691 // When short integer(s) are expected, read and convert the following
1692 // n * 2 bytes properly i.e. as a multivaluated strings
1693 // (each single value is separated fromthe next one by '\'
1694 // as usual for standard multivaluated filels
1695 // Elements with Value Multiplicity > 1
1696 // contain a set of short integers (not a single one)
1698 if (vr == "US" || vr == "SS")
1703 for (int i=0; i < nbInt; i++)
1707 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1708 NewInt16 = SwapShort(NewInt16);
1713 // When integer(s) are expected, read and convert the following
1714 // n * 4 bytes properly i.e. as a multivaluated strings
1715 // (each single value is separated fromthe next one by '\'
1716 // as usual for standard multivaluated filels
1717 // Elements with Value Multiplicity > 1
1718 // contain a set of integers (not a single one)
1719 else if (vr == "UL" || vr == "SL")
1724 for (int i=0; i < nbInt; i++)
1728 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1729 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1730 NewInt32=SwapLong(NewInt32);
1734 #ifdef GDCM_NO_ANSI_STRING_STREAM
1735 s << std::ends; // to avoid oddities on Solaris
1736 #endif //GDCM_NO_ANSI_STRING_STREAM
1740 return(((gdcmValEntry *)Entry)->GetValue());
1744 * \brief Get the reverse transformed value of the header entry. The VR
1745 * value is used to define the reverse transformation to operate on
1747 * \warning NOT end user intended method !
1749 * @return Reverse transformed entry value
1751 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1753 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1755 std::string vr=Entry->GetVR();
1756 std::ostringstream s;
1757 std::vector<std::string> tokens;
1759 if (vr == "US" || vr == "SS")
1763 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1764 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1765 for (unsigned int i=0; i<tokens.size();i++)
1767 NewInt16 = atoi(tokens[i].c_str());
1768 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1772 if (vr == "UL" || vr == "SL")
1776 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1777 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1778 for (unsigned int i=0; i<tokens.size();i++)
1780 NewInt32 = atoi(tokens[i].c_str());
1781 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1782 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1787 #ifdef GDCM_NO_ANSI_STRING_STREAM
1788 s << std::ends; // to avoid oddities on Solaris
1789 #endif //GDCM_NO_ANSI_STRING_STREAM
1793 return(((gdcmValEntry *)Entry)->GetValue());
1797 * \brief Skip a given Header Entry
1798 * \warning NOT end user intended method !
1801 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1803 SkipBytes(entry->GetLength());
1807 * \brief Skips to the begining of the next Header Entry
1808 * \warning NOT end user intended method !
1811 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1813 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1814 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1818 * \brief When the length of an element value is obviously wrong (because
1819 * the parser went Jabberwocky) one can hope improving things by
1820 * applying some heuristics.
1822 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1823 guint32 FoundLength)
1825 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1826 if ( FoundLength == 0xffffffff) {
1830 guint16 gr =Entry->GetGroup();
1831 guint16 el =Entry->GetElement();
1833 if (FoundLength%2) {
1834 std::ostringstream s;
1835 s << "Warning : Tag with uneven length "
1837 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1838 dbg.Verbose(0, s.str().c_str());
1841 //////// Fix for some naughty General Electric images.
1842 // Allthough not recent many such GE corrupted images are still present
1843 // on Creatis hard disks. Hence this fix shall remain when such images
1844 // are no longer in user (we are talking a few years, here)...
1845 // Note: XMedCom probably uses such a trick since it is able to read
1846 // those pesky GE images ...
1847 if (FoundLength == 13) { // Only happens for this length !
1848 if ( (Entry->GetGroup() != 0x0008)
1849 || ( (Entry->GetElement() != 0x0070)
1850 && (Entry->GetElement() != 0x0080) ) )
1853 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1857 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1858 // Occurence of such images is quite low (unless one leaves close to a
1859 // 'Leonardo' source. Hence, one might consider commenting out the
1860 // following fix on efficiency reasons.
1862 if ( (Entry->GetGroup() == 0x0009)
1863 && ( (Entry->GetElement() == 0x1113)
1864 || (Entry->GetElement() == 0x1114) ) )
1867 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1870 //////// Deal with sequences, but only on users request:
1872 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1874 FoundLength = 0; // ReadLength is unchanged
1877 //////// We encountered a 'delimiter' element i.e. a tag of the form
1878 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1879 // taken into account.
1881 if(Entry->GetGroup() == 0xfffe)
1883 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1884 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1885 // causes extra troubles...
1886 if( Entry->GetElement() != 0x0000 )
1892 Entry->SetUsableLength(FoundLength);
1896 * \brief Apply some heuristics to predict whether the considered
1897 * element value contains/represents an integer or not.
1898 * @param Entry The element value on which to apply the predicate.
1899 * @return The result of the heuristical predicate.
1901 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1902 guint16 element = Entry->GetElement();
1903 guint16 group = Entry->GetGroup();
1904 std::string vr = Entry->GetVR();
1905 guint32 length = Entry->GetLength();
1907 // When we have some semantics on the element we just read, and if we
1908 // a priori know we are dealing with an integer, then we shall be
1909 // able to swap it's element value properly.
1910 if ( element == 0 ) // This is the group length of the group
1916 // Allthough this should never happen, still some images have a
1917 // corrupted group length [e.g. have a glance at offset x(8336) of
1918 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1919 // Since for dicom compliant and well behaved headers, the present
1920 // test is useless (and might even look a bit paranoid), when we
1921 // encounter such an ill-formed image, we simply display a warning
1922 // message and proceed on parsing (while crossing fingers).
1923 std::ostringstream s;
1924 int filePosition = ftell(fp);
1925 s << "Erroneous Group Length element length on : (" \
1926 << std::hex << group << " , " << element
1927 << ") -before- position x(" << filePosition << ")"
1928 << "lgt : " << length;
1929 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1933 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1940 * \brief Find the Length till the next sequence delimiter
1941 * \warning NOT end user intended method !
1945 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1946 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1949 long PositionOnEntry = ftell(fp);
1950 bool FoundSequenceDelimiter = false;
1951 guint32 TotalLength = 0;
1954 while ( ! FoundSequenceDelimiter)
1960 TotalLength += 4; // We even have to decount the group and element
1962 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1964 char msg[100]; // for sprintf. Sorry
1965 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1966 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1970 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1971 FoundSequenceDelimiter = true;
1972 else if ( n != 0xe000 )
1974 char msg[100]; // for sprintf. Sorry
1975 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1977 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1981 ItemLength = ReadInt32();
1982 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1983 // the ItemLength with ReadInt32
1984 SkipBytes(ItemLength);
1986 fseek(fp, PositionOnEntry, SEEK_SET);
1991 * \brief Reads a supposed to be 16 Bits integer
1992 * (swaps it depending on processor endianity)
1993 * @return read value
1995 guint16 gdcmDocument::ReadInt16() {
1998 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1999 if ( item_read != 1 ) {
2001 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2011 * \brief Reads a supposed to be 32 Bits integer
2012 * (swaps it depending on processor endianity)
2013 * @return read value
2015 guint32 gdcmDocument::ReadInt32() {
2018 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2019 if ( item_read != 1 ) {
2021 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2031 * \brief skips bytes inside the source file
2032 * \warning NOT end user intended method !
2035 void gdcmDocument::SkipBytes(guint32 NBytes) {
2036 //FIXME don't dump the returned value
2037 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2041 * \brief Loads all the needed Dictionaries
2042 * \warning NOT end user intended method !
2044 void gdcmDocument::Initialise(void)
2046 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2051 * \brief Discover what the swap code is (among little endian, big endian,
2052 * bad little endian, bad big endian).
2054 * @return false when we are absolutely sure
2055 * it's neither ACR-NEMA nor DICOM
2056 * true when we hope ours assuptions are OK
2058 bool gdcmDocument::CheckSwap() {
2060 // The only guaranted way of finding the swap code is to find a
2061 // group tag since we know it's length has to be of four bytes i.e.
2062 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2063 // occurs when we can't find such group...
2065 guint32 x=4; // x : for ntohs
2066 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2072 char deb[HEADER_LENGTH_TO_READ];
2074 // First, compare HostByteOrder and NetworkByteOrder in order to
2075 // determine if we shall need to swap bytes (i.e. the Endian type).
2081 // The easiest case is the one of a DICOM header, since it possesses a
2082 // file preamble where it suffice to look for the string "DICM".
2083 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2086 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2087 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2089 // Next, determine the value representation (VR). Let's skip to the
2090 // first element (0002, 0000) and check there if we find "UL"
2091 // - or "OB" if the 1st one is (0002,0001) -,
2092 // in which case we (almost) know it is explicit VR.
2093 // WARNING: if it happens to be implicit VR then what we will read
2094 // is the length of the group. If this ascii representation of this
2095 // length happens to be "UL" then we shall believe it is explicit VR.
2096 // FIXME: in order to fix the above warning, we could read the next
2097 // element value (or a couple of elements values) in order to make
2098 // sure we are not commiting a big mistake.
2099 // We need to skip :
2100 // * the 128 bytes of File Preamble (often padded with zeroes),
2101 // * the 4 bytes of "DICM" string,
2102 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2103 // i.e. a total of 136 bytes.
2107 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2108 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2109 // *Implicit* VR. -and it is !-
2111 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2112 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2113 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2114 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2115 // when Write DCM *adds*
2117 // Use gdcmDocument::dicom_vr to test all the possibilities
2118 // instead of just checking for UL, OB and UI !? group 0000
2120 Filetype = gdcmExplicitVR;
2121 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2122 "explicit Value Representation");
2126 Filetype = gdcmImplicitVR;
2127 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2128 "not an explicit Value Representation");
2134 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2135 "HostByteOrder != NetworkByteOrder");
2140 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2141 "HostByteOrder = NetworkByteOrder");
2144 // Position the file position indicator at first tag (i.e.
2145 // after the file preamble and the "DICM" string).
2147 fseek (fp, 132L, SEEK_SET);
2151 // Alas, this is not a DicomV3 file and whatever happens there is no file
2152 // preamble. We can reset the file position indicator to where the data
2153 // is (i.e. the beginning of the file).
2154 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2157 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2158 // By clean we mean that the length of the first tag is written down.
2159 // If this is the case and since the length of the first group HAS to be
2160 // four (bytes), then determining the proper swap code is straightforward.
2163 // We assume the array of char we are considering contains the binary
2164 // representation of a 32 bits integer. Hence the following dirty
2166 s32 = *((guint32 *)(entCur));
2187 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2188 // It is time for despaired wild guesses.
2189 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2190 // i.e. the 'group length' element is not present :
2192 // check the supposed to be 'group number'
2193 // 0x0002 or 0x0004 or 0x0008
2194 // to determine ' sw' value .
2195 // Only 0 or 4321 will be possible
2196 // (no oportunity to check for the formerly well known
2197 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2198 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2199 // the file IS NOT ACR-NEMA nor DICOM V3
2200 // Find a trick to tell it the caller...
2202 s16 = *((guint16 *)(deb));
2218 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2219 "ACR/NEMA unfound swap info (Really hopeless !)");
2220 Filetype = gdcmUnknown;
2224 // Then the only info we have is the net2host one.
2234 * \brief Restore the unproperly loaded values i.e. the group, the element
2235 * and the dictionary entry depending on them.
2237 void gdcmDocument::SwitchSwapToBigEndian(void)
2239 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2240 "Switching to BigEndian mode.");
2261 * \brief during parsing, Header Elements too long are not loaded in memory
2264 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2268 if ((guint32)NewSize >= (guint32)0xffffffff)
2270 MaxSizeLoadEntry = 0xffffffff;
2273 MaxSizeLoadEntry = NewSize;
2278 * \brief Header Elements too long will not be printed
2279 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2282 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2286 if ((guint32)NewSize >= (guint32)0xffffffff)
2288 MaxSizePrintEntry = 0xffffffff;
2291 MaxSizePrintEntry = NewSize;
2297 * \brief Read the next tag but WITHOUT loading it's value
2298 * (read the 'Group Number', the 'Element Number',
2299 * gets the Dict Entry
2300 * gets the VR, gets the length, gets the offset value)
2301 * @return On succes the newly created DocEntry, NULL on failure.
2303 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2305 gdcmDocEntry *NewEntry;
2310 // We reached the EOF (or an error occured) therefore
2311 // header parsing has to be considered as finished.
2312 return (gdcmDocEntry *)0;
2314 NewEntry = NewDocEntryByNumber(g, n);
2315 FindDocEntryVR(NewEntry);
2316 FindDocEntryLength(NewEntry);
2323 NewEntry->SetOffset(ftell(fp));
2329 * \brief Generate a free TagKey i.e. a TagKey that is not present
2330 * in the TagHt dictionary.
2331 * @param group The generated tag must belong to this group.
2332 * @return The element of tag with given group which is fee.
2334 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2336 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2338 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2339 if (tagHT.count(key) == 0)
2347 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2348 * is placed at the beginning of a tag (TestGroup, TestElement),
2349 * read the length associated to the Tag.
2350 * \warning On success the internal file pointer \ref gdcmDocument::fp
2351 * is modified to point after the tag and it's length.
2352 * On failure (i.e. when the tag wasn't the expected tag
2353 * (TestGroup, TestElement) the internal file pointer
2354 * \ref gdcmDocument::fp is restored to it's original position.
2355 * @param TestGroup The expected group of the tag.
2356 * @param TestElement The expected Element of the tag.
2357 * @return On success returns the length associated to the tag. On failure
2360 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2362 guint16 ItemTagGroup;
2363 guint16 ItemTagElement;
2364 long PositionOnEntry = ftell(fp);
2365 long CurrentPosition = ftell(fp); // On debugging purposes
2367 //// Read the Item Tag group and element, and make
2368 // sure they are respectively 0xfffe and 0xe000:
2369 ItemTagGroup = ReadInt16();
2370 ItemTagElement = ReadInt16();
2371 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2373 std::ostringstream s;
2374 s << " We should have found tag (";
2375 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2376 s << " but instead we encountered tag (";
2377 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2379 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2380 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2381 dbg.Verbose(0, s.str().c_str());
2382 fseek(fp, PositionOnEntry, SEEK_SET);
2386 //// Then read the associated Item Length
2387 CurrentPosition=ftell(fp);
2389 ItemLength = ReadInt32();
2391 std::ostringstream s;
2392 s << "Basic Item Length is: "
2393 << ItemLength << std::endl;
2394 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2395 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2401 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2402 * \sa \ref gdcmDocument::ReadTagLength
2403 * \warning See warning of \ref gdcmDocument::ReadTagLength
2404 * @return On success returns the length associated to the item tag.
2405 * On failure returns 0.
2407 guint32 gdcmDocument::ReadItemTagLength(void)
2409 return ReadTagLength(0xfffe, 0xe000);
2413 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2415 * \sa \ref gdcmDocument::ReadTagLength
2416 * \warning See warning of \ref gdcmDocument::ReadTagLength
2417 * @return On success returns the length associated to the Sequence
2418 * Delimiter tag. On failure returns 0.
2420 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2422 return ReadTagLength(0xfffe, 0xe0dd);
2427 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2428 * No other way so 'skip' the Data
2432 void gdcmDocument::Parse7FE0 (void)
2434 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2438 if ( IsImplicitVRLittleEndianTransferSyntax()
2439 || IsExplicitVRLittleEndianTransferSyntax()
2440 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2441 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2444 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2446 //// Read the Basic Offset Table Item Tag length...
2447 guint32 ItemLength = ReadItemTagLength();
2449 //// ... and then read length[s] itself[themselves]. We don't use
2450 // the values read (BTW what is the purpous of those lengths ?)
2451 if (ItemLength != 0) {
2452 // BTW, what is the purpous of those length anyhow !?
2453 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2454 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2455 for (unsigned int i=0; i < ItemLength; i += 4){
2456 guint32 IndividualLength;
2457 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2458 std::ostringstream s;
2459 s << " Read one length: ";
2460 s << std::hex << IndividualLength << std::endl;
2461 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2465 if ( ! IsRLELossLessTransferSyntax() )
2469 //// We then skip (not reading them) all the fragments of images:
2470 while ( (ItemLength = ReadItemTagLength()) )
2472 SkipBytes(ItemLength);
2480 long RleSegmentLength[15], fragmentLength;
2482 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2483 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2485 // Parse fragments of the current Fragment (Frame)
2486 //------------------ scanning (not reading) fragment pixels
2487 guint32 nbRleSegments = ReadInt32();
2488 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2490 //// Reading RLE Segments Offset Table
2491 guint32 RleSegmentOffsetTable[15];
2492 for(int k=1; k<=15; k++) {
2494 RleSegmentOffsetTable[k] = ReadInt32();
2495 printf(" at : %x Offset Segment %d : %d (%x)\n",
2496 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2497 RleSegmentOffsetTable[k]);
2500 // skipping (not reading) RLE Segments
2501 if (nbRleSegments>1) {
2502 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2503 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2504 - RleSegmentOffsetTable[k];
2506 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2507 k,(unsigned)RleSegmentLength[k],
2508 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2509 SkipBytes(RleSegmentLength[k]);
2513 RleSegmentLength[nbRleSegments]= fragmentLength
2514 - RleSegmentOffsetTable[nbRleSegments];
2516 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2517 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2518 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2519 SkipBytes(RleSegmentLength[nbRleSegments]);
2527 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2528 * \warning Does NOT work with ACR-NEMA files
2529 * \todo Find a trick to solve the pb (use RET fields ?)
2531 * @return true if 'smaller'
2533 bool gdcmDocument::operator<(gdcmDocument &document)
2538 s1=this->GetEntryByNumber(0x0010,0x0010);
2539 s2=document.GetEntryByNumber(0x0010,0x0010);
2547 s1=this->GetEntryByNumber(0x0010,0x0020);
2548 s2=document.GetEntryByNumber(0x0010,0x0020);
2555 // Study Instance UID
2556 s1=this->GetEntryByNumber(0x0020,0x000d);
2557 s2=document.GetEntryByNumber(0x0020,0x000d);
2564 // Serie Instance UID
2565 s1=this->GetEntryByNumber(0x0020,0x000e);
2566 s2=document.GetEntryByNumber(0x0020,0x000e);
2578 //-----------------------------------------------------------------------------