1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/24 18:03:14 $
7 Version: $Revision: 1.32 $
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;
79 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;//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) );
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);
581 * \brief Modifies the value of a given Header Entry (Dicom Element)
582 * when it exists. Create it with the given value when unexistant.
583 * @param Value (string) Value to be set
584 * @param Group Group number of the Entry
585 * @param Elem Element number of the Entry
586 * \return pointer to the modified/created Header Entry (NULL when creation
590 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
595 gdcmDocEntry* CurrentEntry;
596 gdcmValEntry* ValEntry;
598 CurrentEntry = GetDocEntryByNumber( Group, Elem);
601 // The entry wasn't present and we simply create the required ValEntry:
602 CurrentEntry = NewDocEntryByNumber(Group, Elem);
605 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
606 " NewDocEntryByNumber failed.");
609 ValEntry = new gdcmValEntry(CurrentEntry);
610 if ( !AddEntry(ValEntry))
612 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
613 " failed allthough this is a creation.");
618 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
621 // We need to promote the gdcmDocEntry to a gdcmValEntry:
622 ValEntry = new gdcmValEntry(CurrentEntry);
623 if (!RemoveEntry(CurrentEntry))
625 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
626 " of previous DocEntry failed.");
629 if ( !AddEntry(ValEntry))
631 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
632 " promoted ValEntry failed.");
638 SetEntryByNumber(Value, Group, Elem);
644 * \brief Modifies the value of a given Header Entry (Dicom Element)
645 * when it exists. Create it with the given value when unexistant.
646 * @param voidArea (binary) value to be set
647 * @param Group Group number of the Entry
648 * @param Elem Element number of the Entry
649 * \return pointer to the modified/created Header Entry (NULL when creation
652 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
660 a = GetDocEntryByNumber( Group, Elem);
662 a =NewBinEntryByNumber(Group, Elem);
666 b = new gdcmBinEntry(a);
669 SetEntryByNumber(voidArea, lgth, Group, Elem);
670 b->SetVoidArea(voidArea);
678 * \brief Set a new value if the invoked element exists
679 * Seems to be useless !!!
680 * @param Value new element value
681 * @param Group group number of the Entry
682 * @param Elem element number of the Entry
685 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
687 std::string v = Value;
688 SetEntryByNumber(v, Group, Elem);
692 //-----------------------------------------------------------------------------
696 * \brief Checks if a given Dicom Element exists within the H table
697 * @param group Group number of the searched Dicom Element
698 * @param element Element number of the searched Dicom Element
699 * @return number of occurences
701 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
702 std::string key = gdcmDictEntry::TranslateToKey(group, element );
703 return tagHT.count(key);
707 * \brief Searches within Header Entries (Dicom Elements) parsed with
708 * the public and private dictionaries
709 * for the element value of a given tag.
710 * \warning Don't use any longer : use GetPubEntryByName
711 * @param tagName name of the searched element.
712 * @return Corresponding element value when it exists,
713 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
715 std::string gdcmDocument::GetEntryByName(std::string tagName) {
716 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
717 if( dictEntry == NULL)
720 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
724 * \brief Searches within Header Entries (Dicom Elements) parsed with
725 * the public and private dictionaries
726 * for the element value representation of a given tag.
728 * Obtaining the VR (Value Representation) might be needed by caller
729 * to convert the string typed content to caller's native type
730 * (think of C++ vs Python). The VR is actually of a higher level
731 * of semantics than just the native C++ type.
732 * @param tagName name of the searched element.
733 * @return Corresponding element value representation when it exists,
734 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
736 std::string gdcmDocument::GetEntryVRByName(TagName tagName) {
737 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
738 if( dictEntry == NULL)
741 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
742 dictEntry->GetElement());
743 return elem->GetVR();
748 * \brief Searches within Header Entries (Dicom Elements) parsed with
749 * the public and private dictionaries
750 * for the element value representation of a given tag.
751 * @param group Group number of the searched tag.
752 * @param element Element number of the searched tag.
753 * @return Corresponding element value representation when it exists,
754 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
756 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
757 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
758 if ( ! tagHT.count(key))
760 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
764 * \brief Searches within Header Entries (Dicom Elements) parsed with
765 * the public and private dictionaries
766 * for the element value representation of a given tag..
768 * Obtaining the VR (Value Representation) might be needed by caller
769 * to convert the string typed content to caller's native type
770 * (think of C++ vs Python). The VR is actually of a higher level
771 * of semantics than just the native C++ type.
772 * @param group Group number of the searched tag.
773 * @param element Element number of the searched tag.
774 * @return Corresponding element value representation when it exists,
775 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
777 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
778 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
781 return elem->GetVR();
785 * \brief Searches within Header Entries (Dicom Elements) parsed with
786 * the public and private dictionaries
787 * for the value length of a given tag..
788 * @param group Group number of the searched tag.
789 * @param element Element number of the searched tag.
790 * @return Corresponding element length; -2 if not found
792 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
793 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
796 return elem->GetLength();
799 * \brief Sets the value (string) of the Header Entry (Dicom Element)
800 * @param content string value of the Dicom Element
801 * @param tagName name of the searched Dicom Element.
802 * @return true when found
804 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
805 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
806 if( dictEntry == NULL)
809 return SetEntryByNumber(content,dictEntry->GetGroup(),
810 dictEntry->GetElement());
814 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
815 * through it's (group, element) and modifies it's content with
817 * @param content new value (string) to substitute with
818 * @param group group number of the Dicom Element to modify
819 * @param element element number of the Dicom Element to modify
821 bool gdcmDocument::SetEntryByNumber(std::string content,
825 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
828 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
829 " ValEntry (try promotion first).");
833 // Non even content must be padded with a space (020H).
834 if((content.length())%2)
835 content = content + '\0';
837 ValEntry->SetValue(content);
839 // Integers have a special treatement for their length:
840 VRKey vr = ValEntry->GetVR();
841 if( (vr == "US") || (vr == "SS") )
842 ValEntry->SetLength(2);
843 else if( (vr == "UL") || (vr == "SL") )
844 ValEntry->SetLength(4);
846 ValEntry->SetLength(content.length());
852 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
853 * through it's (group, element) and modifies it's content with
855 * @param content new value (void *) to substitute with
856 * @param group group number of the Dicom Element to modify
857 * @param element element number of the Dicom Element to modify
859 bool gdcmDocument::SetEntryByNumber(void *content,
864 (void)lgth; //not used
865 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
866 if ( ! tagHT.count(key))
869 /* Hope Binray field length is never wrong
870 if(lgth%2) // Non even length are padded with a space (020H).
873 //content = content + '\0'; // fing a trick to enlarge a binary field?
877 a = (gdcmBinEntry *)tagHT[key];
878 a->SetVoidArea(content);
879 //a->SetLength(lgth); // ???
884 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
885 * in the PubDocEntrySet of this instance
886 * through it's (group, element) and modifies it's length with
888 * \warning Use with extreme caution.
889 * @param l new length to substitute with
890 * @param group group number of the Entry to modify
891 * @param element element number of the Entry to modify
892 * @return true on success, false otherwise.
894 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
898 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
899 if ( ! tagHT.count(key))
901 if (l%2) l++; // length must be even
902 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
908 * \brief Gets (from Header) the offset of a 'non string' element value
909 * (LoadElementValues has already be executed)
910 * @param Group group number of the Entry
911 * @param Elem element number of the Entry
912 * @return File Offset of the Element Value
914 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
916 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
919 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
922 return Entry->GetOffset();
926 * \brief Gets (from Header) a 'non string' element value
927 * (LoadElementValues has already be executed)
928 * @param Group group number of the Entry
929 * @param Elem element number of the Entry
930 * @return Pointer to the 'non string' area
932 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
934 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
937 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
940 return ((gdcmBinEntry *)Entry)->GetVoidArea();
944 * \brief Loads (from disk) the element content
945 * when a string is not suitable
946 * @param Group group number of the Entry
947 * @param Elem element number of the Entry
949 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
951 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
954 size_t o =(size_t)Element->GetOffset();
955 fseek(fp, o, SEEK_SET);
956 size_t l = Element->GetLength();
957 char* a = new char[l];
959 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
962 SetEntryVoidAreaByNumber(a, Group, Elem);
963 /// \todo check the result
964 size_t l2 = fread(a, 1, l ,fp);
973 * \brief Loads (from disk) the element content
974 * when a string is not suitable
975 * @param Element Entry whose voidArea is going to be loaded
977 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
979 size_t o =(size_t)Element->GetOffset();
980 fseek(fp, o, SEEK_SET);
981 size_t l = Element->GetLength();
982 char* a = new char[l];
984 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
987 Element->SetVoidArea((void *)a);
988 /// \todo check the result
989 size_t l2 = fread(a, 1, l ,fp);
999 * \brief Sets a 'non string' value to a given Dicom Element
1000 * @param area area containing the 'non string' value
1001 * @param group Group number of the searched Dicom Element
1002 * @param element Element number of the searched Dicom Element
1005 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1009 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1010 if ( ! tagHT.count(key))
1012 // This was for multimap ?
1013 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1019 * \brief Update the entries with the shadow dictionary.
1020 * Only non even entries are analyzed
1022 void gdcmDocument::UpdateShaEntries(void) {
1023 //gdcmDictEntry *entry;
1026 /// \todo TODO : still any use to explore recursively the whole structure?
1028 for(ListTag::iterator it=listEntries.begin();
1029 it!=listEntries.end();
1032 // Odd group => from public dictionary
1033 if((*it)->GetGroup()%2==0)
1036 // Peer group => search the corresponding dict entry
1038 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1042 if((*it)->IsImplicitVR())
1047 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1049 // Set the new entry and the new value
1050 (*it)->SetDictEntry(entry);
1051 CheckDocEntryVR(*it,vr);
1053 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1058 // Remove precedent value transformation
1059 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1066 * \brief Searches within the Header Entries for a Dicom Element of
1068 * @param tagName name of the searched Dicom Element.
1069 * @return Corresponding Dicom Element when it exists, and NULL
1072 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1073 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1074 if( dictEntry == NULL)
1077 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1081 * \brief retrieves a Dicom Element (the first one) using (group, element)
1082 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1083 * if you think it's NOT UNIQUE, check the count number
1084 * and use iterators to retrieve ALL the Dicoms Elements within
1085 * a given couple (group, element)
1086 * @param group Group number of the searched Dicom Element
1087 * @param element Element number of the searched Dicom Element
1090 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1092 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1093 if ( ! tagHT.count(key))
1095 return tagHT.find(key)->second;
1099 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1100 * returns a result when the corresponding entry is of type
1102 * @return When present, the corresponding ValEntry.
1104 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1106 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1108 return (gdcmValEntry*)0;
1109 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1113 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1114 return (gdcmValEntry*)0;
1118 * \brief Loads the element while preserving the current
1119 * underlying file position indicator as opposed to
1120 * to LoadDocEntry that modifies it.
1121 * @param entry Header Entry whose value shall be loaded.
1124 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1125 long PositionOnEntry = ftell(fp);
1126 LoadDocEntry(entry);
1127 fseek(fp, PositionOnEntry, SEEK_SET);
1131 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1133 * @return The properly swaped 32 bits integer.
1135 guint32 gdcmDocument::SwapLong(guint32 a) {
1140 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1141 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1145 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1149 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1152 std::cout << "swapCode= " << sw << std::endl;
1153 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1160 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1162 * @return The properly unswaped 32 bits integer.
1164 guint32 gdcmDocument::UnswapLong(guint32 a) {
1169 * \brief Swaps the bytes so they agree with the processor order
1170 * @return The properly swaped 16 bits integer.
1172 guint16 gdcmDocument::SwapShort(guint16 a) {
1173 if ( (sw==4321) || (sw==2143) )
1174 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1179 * \brief Unswaps the bytes so they agree with the processor order
1180 * @return The properly unswaped 16 bits integer.
1182 guint16 gdcmDocument::UnswapShort(guint16 a) {
1183 return SwapShort(a);
1186 //-----------------------------------------------------------------------------
1190 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1191 * @return length of the parsed set.
1194 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1196 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1197 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1204 depth = set->GetDepthLevel();
1207 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1210 NewDocEntry = ReadNextDocEntry( );
1214 vr = NewDocEntry->GetVR();
1218 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1221 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1222 NewValEntry->Copy(NewDocEntry);
1223 NewValEntry->SetDepthLevel(depth);
1224 set->AddEntry(NewValEntry);
1225 LoadDocEntry(NewValEntry);
1226 if (NewValEntry->isItemDelimitor())
1228 if ( !delim_mode && ftell(fp)-offset >= l_max)
1235 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1237 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1238 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1239 "nor BinEntry. Probably unknown VR.");
1242 ////// BinEntry or UNKOWN VR:
1243 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1244 bn->Copy(NewDocEntry);
1249 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1250 NewDocEntry->GetElement() == 0x0010 )
1252 if (NewDocEntry->GetLength()==0xffffffff)
1254 // Broken US.3405.1.dcm
1255 Parse7FE0(); // to skip the pixels
1256 // (multipart JPEG/RLE are trouble makers)
1260 SkipToNextDocEntry(NewDocEntry);
1261 l = NewDocEntry->GetFullLength();
1266 // to be sure we are at the beginning
1267 SkipToNextDocEntry(NewDocEntry);
1268 l = NewDocEntry->GetFullLength();
1274 l=NewDocEntry->GetReadLength();
1275 if (l != 0) // don't mess the delim_mode for zero-length sequence
1276 if (l == 0xffffffff)
1280 // no other way to create it ...
1281 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1282 set->GetDepthLevel());
1283 sq->Copy(NewDocEntry);
1284 sq->SetDelimitorMode(delim_mode);
1285 sq->SetDepthLevel(depth);
1288 { // Don't try to parse zero-length sequences
1289 long lgt = ParseSQ( sq,
1290 NewDocEntry->GetOffset(),
1292 (void)lgt; //not used...
1295 if ( !delim_mode && ftell(fp)-offset >= l_max)
1302 return l; // Probably useless
1306 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1307 * @return parsed length for this level
1309 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1310 long offset, long l_max, bool delim_mode)
1312 int SQItemNumber = 0;
1314 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1319 int depth = set->GetDepthLevel();
1320 (void)depth; //not used
1324 NewDocEntry = ReadNextDocEntry();
1328 if (NewDocEntry->isSequenceDelimitor()) {
1329 set->SetSequenceDelimitationItem(NewDocEntry);
1333 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1337 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1338 itemSQ->AddEntry(NewDocEntry);
1339 l= NewDocEntry->GetReadLength();
1341 if (l == 0xffffffff)
1346 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1348 set->AddEntry(itemSQ,SQItemNumber);
1350 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1354 lgth = ftell(fp) - offset;
1359 * \brief Loads the element content if its length doesn't exceed
1360 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1361 * @param Entry Header Entry (Dicom Element) to be dealt with
1363 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1366 guint16 group = Entry->GetGroup();
1367 std::string vr= Entry->GetVR();
1368 guint32 length = Entry->GetLength();
1370 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1372 // A SeQuence "contains" a set of Elements.
1373 // (fffe e000) tells us an Element is beginning
1374 // (fffe e00d) tells us an Element just ended
1375 // (fffe e0dd) tells us the current SeQuence just ended
1376 if( group == 0xfffe ) {
1377 // NO more value field for SQ !
1381 // When the length is zero things are easy:
1382 if ( length == 0 ) {
1383 ((gdcmValEntry *)Entry)->SetValue("");
1387 // The elements whose length is bigger than the specified upper bound
1388 // are not loaded. Instead we leave a short notice of the offset of
1389 // the element content and it's length.
1391 std::ostringstream s;
1392 if (length > MaxSizeLoadEntry) {
1393 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1395 s << "gdcm::NotLoaded (BinEntry)";
1396 s << " Address:" << (long)Entry->GetOffset();
1397 s << " Length:" << Entry->GetLength();
1398 s << " x(" << std::hex << Entry->GetLength() << ")";
1399 BinEntryPtr->SetValue(s.str());
1401 // to be sure we are at the end of the value ...
1402 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1404 // Be carefull : a BinEntry IS_A ValEntry ...
1405 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1407 s << "gdcm::NotLoaded. (ValEntry)";
1408 s << " Address:" << (long)Entry->GetOffset();
1409 s << " Length:" << Entry->GetLength();
1410 s << " x(" << std::hex << Entry->GetLength() << ")";
1411 ValEntryPtr->SetValue(s.str());
1413 // to be sure we are at the end of the value ...
1414 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1418 // When we find a BinEntry not very much can be done :
1419 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1421 LoadEntryVoidArea(BinEntryPtr);
1422 s << "gdcm::Loaded (BinEntry)";
1423 BinEntryPtr->SetValue(s.str());
1428 // Any compacter code suggested (?)
1429 if ( IsDocEntryAnInteger(Entry) ) {
1431 std::ostringstream s;
1433 // When short integer(s) are expected, read and convert the following
1434 // n *two characters properly i.e. as short integers as opposed to strings.
1435 // Elements with Value Multiplicity > 1
1436 // contain a set of integers (not a single one)
1437 if (vr == "US" || vr == "SS") {
1439 NewInt = ReadInt16();
1442 for (int i=1; i < nbInt; i++) {
1444 NewInt = ReadInt16();
1449 // When integer(s) are expected, read and convert the following
1450 // n * four characters properly i.e. as integers as opposed to strings.
1451 // Elements with Value Multiplicity > 1
1452 // contain a set of integers (not a single one)
1453 else if (vr == "UL" || vr == "SL") {
1455 NewInt = ReadInt32();
1458 for (int i=1; i < nbInt; i++) {
1460 NewInt = ReadInt32();
1465 #ifdef GDCM_NO_ANSI_STRING_STREAM
1466 s << std::ends; // to avoid oddities on Solaris
1467 #endif //GDCM_NO_ANSI_STRING_STREAM
1469 ((gdcmValEntry *)Entry)->SetValue(s.str());
1473 // We need an additional byte for storing \0 that is not on disk
1474 std::string NewValue(length,0);
1475 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1476 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) ) {
1477 if ( item_read != 1 ) {
1478 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1479 ValEntry->SetValue("gdcm::UnRead");
1483 if( (vr == "UI") ) // Because of correspondance with the VR dic
1484 ValEntry->SetValue(NewValue.c_str());
1486 ValEntry->SetValue(NewValue);
1489 std::cout << "Should have a ValEntry, here !" << std::endl;
1496 * \brief Find the value Length of the passed Header Entry
1497 * @param Entry Header Entry whose length of the value shall be loaded.
1499 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1500 guint16 element = Entry->GetElement();
1501 //guint16 group = Entry->GetGroup(); //FIXME
1502 std::string vr = Entry->GetVR();
1506 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1508 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1510 // The following reserved two bytes (see PS 3.5-2001, section
1511 // 7.1.2 Data element structure with explicit vr p27) must be
1512 // skipped before proceeding on reading the length on 4 bytes.
1513 fseek(fp, 2L, SEEK_CUR);
1514 guint32 length32 = ReadInt32();
1516 if ( (vr == "OB") && (length32 == 0xffffffff) )
1518 Entry->SetLength(FindDocEntryLengthOB());
1521 FixDocEntryFoundLength(Entry, length32);
1525 // Length is encoded on 2 bytes.
1526 length16 = ReadInt16();
1528 // We can tell the current file is encoded in big endian (like
1529 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1530 // and it's value is the one of the encoding of a big endian file.
1531 // In order to deal with such big endian encoded files, we have
1532 // (at least) two strategies:
1533 // * when we load the "Transfer Syntax" tag with value of big endian
1534 // encoding, we raise the proper flags. Then we wait for the end
1535 // of the META group (0x0002) among which is "Transfer Syntax",
1536 // before switching the swap code to big endian. We have to postpone
1537 // the switching of the swap code since the META group is fully encoded
1538 // in little endian, and big endian coding only starts at the next
1539 // group. The corresponding code can be hard to analyse and adds
1540 // many additional unnecessary tests for regular tags.
1541 // * the second strategy consists in waiting for trouble, that shall
1542 // appear when we find the first group with big endian encoding. This
1543 // is easy to detect since the length of a "Group Length" tag (the
1544 // ones with zero as element number) has to be of 4 (0x0004). When we
1545 // encounter 1024 (0x0400) chances are the encoding changed and we
1546 // found a group with big endian encoding.
1547 // We shall use this second strategy. In order to make sure that we
1548 // can interpret the presence of an apparently big endian encoded
1549 // length of a "Group Length" without committing a big mistake, we
1550 // add an additional check: we look in the already parsed elements
1551 // for the presence of a "Transfer Syntax" whose value has to be "big
1552 // endian encoding". When this is the case, chances are we have got our
1553 // hands on a big endian encoded file: we switch the swap code to
1554 // big endian and proceed...
1555 if ( (element == 0x0000) && (length16 == 0x0400) )
1557 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1559 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1564 SwitchSwapToBigEndian();
1565 // Restore the unproperly loaded values i.e. the group, the element
1566 // and the dictionary entry depending on them.
1567 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1568 guint16 CorrectElem = SwapShort(Entry->GetElement());
1569 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1573 // This correct tag is not in the dictionary. Create a new one.
1574 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1576 // FIXME this can create a memory leaks on the old entry that be
1577 // left unreferenced.
1578 Entry->SetDictEntry(NewTag);
1581 // Heuristic: well, some files are really ill-formed.
1582 if ( length16 == 0xffff)
1585 // Length16= 0xffff means that we deal with
1586 // 'Unknown Length' Sequence
1588 FixDocEntryFoundLength(Entry, (guint32)length16);
1593 // Either implicit VR or a non DICOM conformal (see note below) explicit
1594 // VR that ommited the VR of (at least) this element. Farts happen.
1595 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1596 // on Data elements "Implicit and Explicit VR Data Elements shall
1597 // not coexist in a Data Set and Data Sets nested within it".]
1598 // Length is on 4 bytes.
1600 FixDocEntryFoundLength(Entry, ReadInt32());
1606 * \brief Find the Value Representation of the current Dicom Element.
1609 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1611 if (Filetype != gdcmExplicitVR)
1616 long PositionOnEntry = ftell(fp);
1617 // Warning: we believe this is explicit VR (Value Representation) because
1618 // we used a heuristic that found "UL" in the first tag. Alas this
1619 // doesn't guarantee that all the tags will be in explicit VR. In some
1620 // cases (see e-film filtered files) one finds implicit VR tags mixed
1621 // within an explicit VR file. Hence we make sure the present tag
1622 // is in explicit VR and try to fix things if it happens not to be
1625 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1627 if(!CheckDocEntryVR(Entry,VR))
1629 fseek(fp, PositionOnEntry, SEEK_SET);
1630 // When this element is known in the dictionary we shall use, e.g. for
1631 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1632 // dictionary entry. Still we have to flag the element as implicit since
1633 // we know now our assumption on expliciteness is not furfilled.
1635 if ( Entry->IsVRUnknown() )
1636 Entry->SetVR("Implicit");
1637 Entry->SetImplicitVR();
1642 * \brief Check the correspondance between the VR of the header entry
1643 * and the taken VR. If they are different, the header entry is
1644 * updated with the new VR.
1645 * @param Entry Header Entry to check
1646 * @param vr Dicom Value Representation
1647 * @return false if the VR is incorrect of if the VR isn't referenced
1648 * otherwise, it returns true
1650 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1652 char msg[100]; // for sprintf
1653 bool RealExplicit = true;
1655 // Assume we are reading a falsely explicit VR file i.e. we reached
1656 // a tag where we expect reading a VR but are in fact we read the
1657 // first to bytes of the length. Then we will interogate (through find)
1658 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1659 // both GCC and VC++ implementations of the STL map. Hence when the
1660 // expected VR read happens to be non-ascii characters we consider
1661 // we hit falsely explicit VR tag.
1663 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1664 RealExplicit = false;
1666 // CLEANME searching the dicom_vr at each occurence is expensive.
1667 // PostPone this test in an optional integrity check at the end
1668 // of parsing or only in debug mode.
1669 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1670 RealExplicit= false;
1672 if ( !RealExplicit )
1674 // We thought this was explicit VR, but we end up with an
1675 // implicit VR tag. Let's backtrack.
1676 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1677 Entry->GetGroup(),Entry->GetElement());
1678 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1679 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1680 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1681 Entry->GetGroup(),Entry->GetElement(),
1682 "UL","FIXME","Group Length");
1683 Entry->SetDictEntry(NewEntry);
1688 if ( Entry->IsVRUnknown() )
1690 // When not a dictionary entry, we can safely overwrite the VR.
1691 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1697 else if ( Entry->GetVR() != vr )
1699 // The VR present in the file and the dictionary disagree. We assume
1700 // the file writer knew best and use the VR of the file. Since it would
1701 // be unwise to overwrite the VR of a dictionary (since it would
1702 // compromise it's next user), we need to clone the actual DictEntry
1703 // and change the VR for the read one.
1704 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1705 Entry->GetGroup(),Entry->GetElement(),
1706 vr,"FIXME",Entry->GetName());
1707 Entry->SetDictEntry(NewEntry);
1713 * \brief Get the transformed value of the header entry. The VR value
1714 * is used to define the transformation to operate on the value
1715 * \warning NOT end user intended method !
1717 * @return Transformed entry value
1719 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1721 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1723 std::string val=((gdcmValEntry *)Entry)->GetValue();
1724 std::string vr=Entry->GetVR();
1725 guint32 length = Entry->GetLength();
1726 std::ostringstream s;
1729 // When short integer(s) are expected, read and convert the following
1730 // n * 2 bytes properly i.e. as a multivaluated strings
1731 // (each single value is separated fromthe next one by '\'
1732 // as usual for standard multivaluated filels
1733 // Elements with Value Multiplicity > 1
1734 // contain a set of short integers (not a single one)
1736 if (vr == "US" || vr == "SS")
1741 for (int i=0; i < nbInt; i++)
1745 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1746 NewInt16 = SwapShort(NewInt16);
1751 // When integer(s) are expected, read and convert the following
1752 // n * 4 bytes properly i.e. as a multivaluated strings
1753 // (each single value is separated fromthe next one by '\'
1754 // as usual for standard multivaluated filels
1755 // Elements with Value Multiplicity > 1
1756 // contain a set of integers (not a single one)
1757 else if (vr == "UL" || vr == "SL")
1762 for (int i=0; i < nbInt; i++)
1766 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1767 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1768 NewInt32=SwapLong(NewInt32);
1772 #ifdef GDCM_NO_ANSI_STRING_STREAM
1773 s << std::ends; // to avoid oddities on Solaris
1774 #endif //GDCM_NO_ANSI_STRING_STREAM
1778 return ((gdcmValEntry *)Entry)->GetValue();
1782 * \brief Get the reverse transformed value of the header entry. The VR
1783 * value is used to define the reverse transformation to operate on
1785 * \warning NOT end user intended method !
1787 * @return Reverse transformed entry value
1789 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1791 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1793 std::string vr=Entry->GetVR();
1794 std::ostringstream s;
1795 std::vector<std::string> tokens;
1797 if (vr == "US" || vr == "SS")
1801 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1802 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1803 for (unsigned int i=0; i<tokens.size();i++)
1805 NewInt16 = atoi(tokens[i].c_str());
1806 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1810 if (vr == "UL" || vr == "SL")
1814 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1815 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1816 for (unsigned int i=0; i<tokens.size();i++)
1818 NewInt32 = atoi(tokens[i].c_str());
1819 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1820 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1825 #ifdef GDCM_NO_ANSI_STRING_STREAM
1826 s << std::ends; // to avoid oddities on Solaris
1827 #endif //GDCM_NO_ANSI_STRING_STREAM
1831 return ((gdcmValEntry *)Entry)->GetValue();
1835 * \brief Skip a given Header Entry
1836 * \warning NOT end user intended method !
1839 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1841 SkipBytes(entry->GetLength());
1845 * \brief Skips to the begining of the next Header Entry
1846 * \warning NOT end user intended method !
1849 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1851 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1852 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1856 * \brief When the length of an element value is obviously wrong (because
1857 * the parser went Jabberwocky) one can hope improving things by
1858 * applying some heuristics.
1860 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1861 guint32 FoundLength)
1863 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1864 if ( FoundLength == 0xffffffff) {
1868 guint16 gr =Entry->GetGroup();
1869 guint16 el =Entry->GetElement();
1871 if (FoundLength%2) {
1872 std::ostringstream s;
1873 s << "Warning : Tag with uneven length "
1875 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1876 dbg.Verbose(0, s.str().c_str());
1879 //////// Fix for some naughty General Electric images.
1880 // Allthough not recent many such GE corrupted images are still present
1881 // on Creatis hard disks. Hence this fix shall remain when such images
1882 // are no longer in user (we are talking a few years, here)...
1883 // Note: XMedCom probably uses such a trick since it is able to read
1884 // those pesky GE images ...
1885 if (FoundLength == 13) { // Only happens for this length !
1886 if ( (Entry->GetGroup() != 0x0008)
1887 || ( (Entry->GetElement() != 0x0070)
1888 && (Entry->GetElement() != 0x0080) ) )
1891 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1895 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1896 // Occurence of such images is quite low (unless one leaves close to a
1897 // 'Leonardo' source. Hence, one might consider commenting out the
1898 // following fix on efficiency reasons.
1900 if ( (Entry->GetGroup() == 0x0009)
1901 && ( (Entry->GetElement() == 0x1113)
1902 || (Entry->GetElement() == 0x1114) ) )
1905 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1908 //////// Deal with sequences, but only on users request:
1910 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1912 FoundLength = 0; // ReadLength is unchanged
1915 //////// We encountered a 'delimiter' element i.e. a tag of the form
1916 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1917 // taken into account.
1919 if(Entry->GetGroup() == 0xfffe)
1921 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1922 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1923 // causes extra troubles...
1924 if( Entry->GetElement() != 0x0000 )
1930 Entry->SetUsableLength(FoundLength);
1934 * \brief Apply some heuristics to predict whether the considered
1935 * element value contains/represents an integer or not.
1936 * @param Entry The element value on which to apply the predicate.
1937 * @return The result of the heuristical predicate.
1939 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1940 guint16 element = Entry->GetElement();
1941 guint16 group = Entry->GetGroup();
1942 std::string vr = Entry->GetVR();
1943 guint32 length = Entry->GetLength();
1945 // When we have some semantics on the element we just read, and if we
1946 // a priori know we are dealing with an integer, then we shall be
1947 // able to swap it's element value properly.
1948 if ( element == 0 ) // This is the group length of the group
1954 // Allthough this should never happen, still some images have a
1955 // corrupted group length [e.g. have a glance at offset x(8336) of
1956 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1957 // Since for dicom compliant and well behaved headers, the present
1958 // test is useless (and might even look a bit paranoid), when we
1959 // encounter such an ill-formed image, we simply display a warning
1960 // message and proceed on parsing (while crossing fingers).
1961 std::ostringstream s;
1962 int filePosition = ftell(fp);
1963 s << "Erroneous Group Length element length on : (" \
1964 << std::hex << group << " , " << element
1965 << ") -before- position x(" << filePosition << ")"
1966 << "lgt : " << length;
1967 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1971 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1978 * \brief Find the Length till the next sequence delimiter
1979 * \warning NOT end user intended method !
1983 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1984 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1987 long PositionOnEntry = ftell(fp);
1988 bool FoundSequenceDelimiter = false;
1989 guint32 TotalLength = 0;
1992 while ( ! FoundSequenceDelimiter)
1998 TotalLength += 4; // We even have to decount the group and element
2000 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2002 char msg[100]; // for sprintf. Sorry
2003 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2004 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2008 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2009 FoundSequenceDelimiter = true;
2010 else if ( n != 0xe000 )
2012 char msg[100]; // for sprintf. Sorry
2013 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2015 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2019 ItemLength = ReadInt32();
2020 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2021 // the ItemLength with ReadInt32
2022 SkipBytes(ItemLength);
2024 fseek(fp, PositionOnEntry, SEEK_SET);
2029 * \brief Reads a supposed to be 16 Bits integer
2030 * (swaps it depending on processor endianity)
2031 * @return read value
2033 guint16 gdcmDocument::ReadInt16() {
2036 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2037 if ( item_read != 1 ) {
2039 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2049 * \brief Reads a supposed to be 32 Bits integer
2050 * (swaps it depending on processor endianity)
2051 * @return read value
2053 guint32 gdcmDocument::ReadInt32() {
2056 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2057 if ( item_read != 1 ) {
2059 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2069 * \brief skips bytes inside the source file
2070 * \warning NOT end user intended method !
2073 void gdcmDocument::SkipBytes(guint32 NBytes) {
2074 //FIXME don't dump the returned value
2075 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2079 * \brief Loads all the needed Dictionaries
2080 * \warning NOT end user intended method !
2082 void gdcmDocument::Initialise(void)
2084 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2089 * \brief Discover what the swap code is (among little endian, big endian,
2090 * bad little endian, bad big endian).
2092 * @return false when we are absolutely sure
2093 * it's neither ACR-NEMA nor DICOM
2094 * true when we hope ours assuptions are OK
2096 bool gdcmDocument::CheckSwap() {
2098 // The only guaranted way of finding the swap code is to find a
2099 // group tag since we know it's length has to be of four bytes i.e.
2100 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2101 // occurs when we can't find such group...
2103 guint32 x=4; // x : for ntohs
2104 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2110 char deb[HEADER_LENGTH_TO_READ];
2112 // First, compare HostByteOrder and NetworkByteOrder in order to
2113 // determine if we shall need to swap bytes (i.e. the Endian type).
2119 // The easiest case is the one of a DICOM header, since it possesses a
2120 // file preamble where it suffice to look for the string "DICM".
2121 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2124 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2125 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2127 // Next, determine the value representation (VR). Let's skip to the
2128 // first element (0002, 0000) and check there if we find "UL"
2129 // - or "OB" if the 1st one is (0002,0001) -,
2130 // in which case we (almost) know it is explicit VR.
2131 // WARNING: if it happens to be implicit VR then what we will read
2132 // is the length of the group. If this ascii representation of this
2133 // length happens to be "UL" then we shall believe it is explicit VR.
2134 // FIXME: in order to fix the above warning, we could read the next
2135 // element value (or a couple of elements values) in order to make
2136 // sure we are not commiting a big mistake.
2137 // We need to skip :
2138 // * the 128 bytes of File Preamble (often padded with zeroes),
2139 // * the 4 bytes of "DICM" string,
2140 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2141 // i.e. a total of 136 bytes.
2145 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2146 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2147 // *Implicit* VR. -and it is !-
2149 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2150 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2151 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2152 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2153 // when Write DCM *adds*
2155 // Use gdcmDocument::dicom_vr to test all the possibilities
2156 // instead of just checking for UL, OB and UI !? group 0000
2158 Filetype = gdcmExplicitVR;
2159 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2160 "explicit Value Representation");
2164 Filetype = gdcmImplicitVR;
2165 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2166 "not an explicit Value Representation");
2172 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2173 "HostByteOrder != NetworkByteOrder");
2178 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2179 "HostByteOrder = NetworkByteOrder");
2182 // Position the file position indicator at first tag (i.e.
2183 // after the file preamble and the "DICM" string).
2185 fseek (fp, 132L, SEEK_SET);
2189 // Alas, this is not a DicomV3 file and whatever happens there is no file
2190 // preamble. We can reset the file position indicator to where the data
2191 // is (i.e. the beginning of the file).
2192 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2195 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2196 // By clean we mean that the length of the first tag is written down.
2197 // If this is the case and since the length of the first group HAS to be
2198 // four (bytes), then determining the proper swap code is straightforward.
2201 // We assume the array of char we are considering contains the binary
2202 // representation of a 32 bits integer. Hence the following dirty
2204 s32 = *((guint32 *)(entCur));
2225 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2226 // It is time for despaired wild guesses.
2227 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2228 // i.e. the 'group length' element is not present :
2230 // check the supposed to be 'group number'
2231 // 0x0002 or 0x0004 or 0x0008
2232 // to determine ' sw' value .
2233 // Only 0 or 4321 will be possible
2234 // (no oportunity to check for the formerly well known
2235 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2236 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2237 // the file IS NOT ACR-NEMA nor DICOM V3
2238 // Find a trick to tell it the caller...
2240 s16 = *((guint16 *)(deb));
2256 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2257 "ACR/NEMA unfound swap info (Really hopeless !)");
2258 Filetype = gdcmUnknown;
2262 // Then the only info we have is the net2host one.
2272 * \brief Restore the unproperly loaded values i.e. the group, the element
2273 * and the dictionary entry depending on them.
2275 void gdcmDocument::SwitchSwapToBigEndian(void)
2277 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2278 "Switching to BigEndian mode.");
2299 * \brief during parsing, Header Elements too long are not loaded in memory
2302 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2306 if ((guint32)NewSize >= (guint32)0xffffffff)
2308 MaxSizeLoadEntry = 0xffffffff;
2311 MaxSizeLoadEntry = NewSize;
2316 * \brief Header Elements too long will not be printed
2317 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2320 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2324 if ((guint32)NewSize >= (guint32)0xffffffff)
2326 MaxSizePrintEntry = 0xffffffff;
2329 MaxSizePrintEntry = NewSize;
2335 * \brief Read the next tag but WITHOUT loading it's value
2336 * (read the 'Group Number', the 'Element Number',
2337 * gets the Dict Entry
2338 * gets the VR, gets the length, gets the offset value)
2339 * @return On succes the newly created DocEntry, NULL on failure.
2341 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2343 gdcmDocEntry *NewEntry;
2348 // We reached the EOF (or an error occured) therefore
2349 // header parsing has to be considered as finished.
2350 return (gdcmDocEntry *)0;
2352 NewEntry = NewDocEntryByNumber(g, n);
2353 FindDocEntryVR(NewEntry);
2354 FindDocEntryLength(NewEntry);
2361 NewEntry->SetOffset(ftell(fp));
2367 * \brief Generate a free TagKey i.e. a TagKey that is not present
2368 * in the TagHt dictionary.
2369 * @param group The generated tag must belong to this group.
2370 * @return The element of tag with given group which is fee.
2372 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2374 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2376 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2377 if (tagHT.count(key) == 0)
2385 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2386 * is placed at the beginning of a tag (TestGroup, TestElement),
2387 * read the length associated to the Tag.
2388 * \warning On success the internal file pointer \ref gdcmDocument::fp
2389 * is modified to point after the tag and it's length.
2390 * On failure (i.e. when the tag wasn't the expected tag
2391 * (TestGroup, TestElement) the internal file pointer
2392 * \ref gdcmDocument::fp is restored to it's original position.
2393 * @param TestGroup The expected group of the tag.
2394 * @param TestElement The expected Element of the tag.
2395 * @return On success returns the length associated to the tag. On failure
2398 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2400 guint16 ItemTagGroup;
2401 guint16 ItemTagElement;
2402 long PositionOnEntry = ftell(fp);
2403 long CurrentPosition = ftell(fp); // On debugging purposes
2405 //// Read the Item Tag group and element, and make
2406 // sure they are respectively 0xfffe and 0xe000:
2407 ItemTagGroup = ReadInt16();
2408 ItemTagElement = ReadInt16();
2409 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2411 std::ostringstream s;
2412 s << " We should have found tag (";
2413 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2414 s << " but instead we encountered tag (";
2415 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2417 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2418 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2419 dbg.Verbose(0, s.str().c_str());
2420 fseek(fp, PositionOnEntry, SEEK_SET);
2424 //// Then read the associated Item Length
2425 CurrentPosition=ftell(fp);
2427 ItemLength = ReadInt32();
2429 std::ostringstream s;
2430 s << "Basic Item Length is: "
2431 << ItemLength << std::endl;
2432 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2433 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2439 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2440 * \sa \ref gdcmDocument::ReadTagLength
2441 * \warning See warning of \ref gdcmDocument::ReadTagLength
2442 * @return On success returns the length associated to the item tag.
2443 * On failure returns 0.
2445 guint32 gdcmDocument::ReadItemTagLength(void)
2447 return ReadTagLength(0xfffe, 0xe000);
2451 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2453 * \sa \ref gdcmDocument::ReadTagLength
2454 * \warning See warning of \ref gdcmDocument::ReadTagLength
2455 * @return On success returns the length associated to the Sequence
2456 * Delimiter tag. On failure returns 0.
2458 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2460 return ReadTagLength(0xfffe, 0xe0dd);
2465 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2466 * No other way so 'skip' the Data
2470 void gdcmDocument::Parse7FE0 (void)
2472 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2476 if ( IsImplicitVRLittleEndianTransferSyntax()
2477 || IsExplicitVRLittleEndianTransferSyntax()
2478 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2479 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2482 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2484 //// Read the Basic Offset Table Item Tag length...
2485 guint32 ItemLength = ReadItemTagLength();
2487 //// ... and then read length[s] itself[themselves]. We don't use
2488 // the values read (BTW what is the purpous of those lengths ?)
2489 if (ItemLength != 0) {
2490 // BTW, what is the purpous of those length anyhow !?
2491 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2492 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2493 for (unsigned int i=0; i < ItemLength; i += 4){
2494 guint32 IndividualLength;
2495 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2496 std::ostringstream s;
2497 s << " Read one length: ";
2498 s << std::hex << IndividualLength << std::endl;
2499 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2503 if ( ! IsRLELossLessTransferSyntax() )
2507 //// We then skip (not reading them) all the fragments of images:
2508 while ( (ItemLength = ReadItemTagLength()) )
2510 SkipBytes(ItemLength);
2518 long RleSegmentLength[15], fragmentLength;
2520 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2521 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2523 // Parse fragments of the current Fragment (Frame)
2524 //------------------ scanning (not reading) fragment pixels
2525 guint32 nbRleSegments = ReadInt32();
2526 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2528 //// Reading RLE Segments Offset Table
2529 guint32 RleSegmentOffsetTable[15];
2530 for(int k=1; k<=15; k++) {
2532 RleSegmentOffsetTable[k] = ReadInt32();
2533 printf(" at : %x Offset Segment %d : %d (%x)\n",
2534 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2535 RleSegmentOffsetTable[k]);
2538 // skipping (not reading) RLE Segments
2539 if (nbRleSegments>1) {
2540 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2541 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2542 - RleSegmentOffsetTable[k];
2544 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2545 k,(unsigned)RleSegmentLength[k],
2546 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2547 SkipBytes(RleSegmentLength[k]);
2551 RleSegmentLength[nbRleSegments]= fragmentLength
2552 - RleSegmentOffsetTable[nbRleSegments];
2554 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2555 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2556 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2557 SkipBytes(RleSegmentLength[nbRleSegments]);
2565 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2566 * \warning Does NOT work with ACR-NEMA files
2567 * \todo Find a trick to solve the pb (use RET fields ?)
2569 * @return true if 'smaller'
2571 bool gdcmDocument::operator<(gdcmDocument &document)
2576 s1=this->GetEntryByNumber(0x0010,0x0010);
2577 s2=document.GetEntryByNumber(0x0010,0x0010);
2585 s1=this->GetEntryByNumber(0x0010,0x0020);
2586 s2=document.GetEntryByNumber(0x0010,0x0020);
2593 // Study Instance UID
2594 s1=this->GetEntryByNumber(0x0020,0x000d);
2595 s2=document.GetEntryByNumber(0x0020,0x000d);
2602 // Serie Instance UID
2603 s1=this->GetEntryByNumber(0x0020,0x000e);
2604 s2=document.GetEntryByNumber(0x0020,0x000e);
2616 //-----------------------------------------------------------------------------