1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/10 14:32:04 $
7 Version: $Revision: 1.73 $
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"
34 #include <netinet/in.h>
39 // Implicit VR Little Endian
40 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
41 // Explicit VR Little Endian
42 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
43 // Deflated Explicit VR Little Endian
44 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
45 // Explicit VR Big Endian
46 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
47 // JPEG Baseline (Process 1)
48 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
49 // JPEG Extended (Process 2 & 4)
50 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
51 // JPEG Extended (Process 3 & 5)
52 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
53 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
54 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
55 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
56 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
57 // JPEG Lossless, Non-Hierarchical (Process 14)
58 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
59 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
60 // [Selection Value 1])
61 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
63 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
65 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
67 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
68 // UI1_1_2_840_10008_1_2_5
69 #define str2num(str, typeNum) *((typeNum *)(str))
71 //-----------------------------------------------------------------------------
72 // Refer to gdcmDocument::CheckSwap()
73 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
75 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
76 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
77 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
79 //-----------------------------------------------------------------------------
80 // Constructor / Destructor
84 * @param filename file to be opened for parsing
86 gdcmDocument::gdcmDocument( std::string const & filename )
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
102 fseek(Fp,0L,SEEK_END);
103 long lgt = ftell(Fp);
107 long beg = ftell(Fp);
112 long l = ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
113 (void)l; //is l used anywhere ?
117 // Load 'non string' values
119 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
120 if( PhotometricInterpretation == "PALETTE COLOR " )
122 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
123 LoadEntryVoidArea(0x0028,0x1201); // R LUT
124 LoadEntryVoidArea(0x0028,0x1202); // G LUT
125 LoadEntryVoidArea(0x0028,0x1203); // B LUT
127 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
128 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
129 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
131 //FIXME later : how to use it?
132 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
136 // --------------------------------------------------------------
137 // Specific code to allow gdcm to read ACR-LibIDO formated images
138 // Note: ACR-LibIDO is an extension of the ACR standard that was
139 // used at CREATIS. For the time being (say a couple years)
140 // we keep this kludge to allow a smooth move to gdcm for
141 // CREATIS developpers (sorry folks).
143 // if recognition code tells us we deal with a LibIDO image
144 // we switch lineNumber and columnNumber
147 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
148 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
149 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
150 // with "little-endian strings"
152 Filetype = gdcmACR_LIBIDO;
153 std::string rows = GetEntryByNumber(0x0028, 0x0010);
154 std::string columns = GetEntryByNumber(0x0028, 0x0011);
155 SetEntryByNumber(columns, 0x0028, 0x0010);
156 SetEntryByNumber(rows , 0x0028, 0x0011);
158 // ----------------- End of ACR-LibIDO kludge ------------------
160 PrintLevel = 1; // 'Medium' print level by default
164 * \brief This default constructor doesn't parse the file. You should
165 * then invoke \ref gdcmDocument::SetFileName and then the parsing.
167 gdcmDocument::gdcmDocument()
170 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
172 PrintLevel = 1; // 'Medium' print level by default
176 * \brief Canonical destructor.
178 gdcmDocument::~gdcmDocument ()
183 // Recursive clean up of sequences
184 for (TagDocEntryHT::const_iterator it = TagHT.begin();
185 it != TagHT.end(); ++it )
192 //-----------------------------------------------------------------------------
196 * \brief Prints The Dict Entries of THE public Dicom Dictionary
199 void gdcmDocument::PrintPubDict(std::ostream & os)
201 RefPubDict->Print(os);
205 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
208 void gdcmDocument::PrintShaDict(std::ostream & os)
210 RefShaDict->Print(os);
213 //-----------------------------------------------------------------------------
216 * \brief Get the public dictionary used
218 gdcmDict *gdcmDocument::GetPubDict()
224 * \brief Get the shadow dictionary used
226 gdcmDict *gdcmDocument::GetShaDict()
232 * \brief Set the shadow dictionary used
233 * \param dict dictionary to use in shadow
235 bool gdcmDocument::SetShaDict(gdcmDict *dict)
242 * \brief Set the shadow dictionary used
243 * \param dictName name of the dictionary to use in shadow
245 bool gdcmDocument::SetShaDict(DictKey const & dictName)
247 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
252 * \brief This predicate, based on hopefully reasonable heuristics,
253 * decides whether or not the current gdcmDocument was properly parsed
254 * and contains the mandatory information for being considered as
255 * a well formed and usable Dicom/Acr File.
256 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
259 bool gdcmDocument::IsReadable()
261 if( Filetype == gdcmUnknown)
263 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
269 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
279 * \brief Internal function that checks whether the Transfer Syntax given
280 * as argument is the one present in the current document.
281 * @param syntaxToCheck The transfert syntax we need to check against.
282 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
283 * the current document. False either when the document contains
284 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
286 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
288 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
294 // The entry might be present but not loaded (parsing and loading
295 // happen at different stages): try loading and proceed with check...
296 LoadDocEntrySafe(entry);
297 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
299 std::string transfer = valEntry->GetValue();
300 // The actual transfer (as read from disk) might be padded. We
301 // first need to remove the potential padding. We can make the
302 // weak assumption that padding was not executed with digits...
303 if ( transfer.length() == 0 ) { // for brain damaged headers
306 while ( ! isdigit(transfer[transfer.length()-1]) )
308 transfer.erase(transfer.length()-1, 1);
310 if ( transfer == syntaxToCheck )
319 * \brief Determines if the Transfer Syntax of the present document
320 * corresponds to a Implicit Value Representation of
322 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
323 * @return True when ImplicitVRLittleEndian found. False in all other cases.
325 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
327 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
331 * \brief Determines if the Transfer Syntax was already encountered
332 * and if it corresponds to a ExplicitVRLittleEndian one.
333 * @return True when ExplicitVRLittleEndian found. False in all other cases.
335 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
337 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
341 * \brief Determines if the Transfer Syntax was already encountered
342 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
343 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
345 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
347 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
351 * \brief Determines if the Transfer Syntax was already encountered
352 * and if it corresponds to a Explicit VR Big Endian one.
353 * @return True when big endian found. False in all other cases.
355 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
357 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
361 * \brief Determines if the Transfer Syntax was already encountered
362 * and if it corresponds to a JPEGBaseLineProcess1 one.
363 * @return True when JPEGBaseLineProcess1found. False in all other cases.
365 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
367 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
371 * \brief Determines if the Transfer Syntax was already encountered
372 * and if it corresponds to a JPEGExtendedProcess2-4 one.
373 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
375 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
377 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
381 * \brief Determines if the Transfer Syntax was already encountered
382 * and if it corresponds to a JPEGExtendeProcess3-5 one.
383 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
385 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
387 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
391 * \brief Determines if the Transfer Syntax was already encountered
392 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
393 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
396 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
398 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
402 * \brief Determines if the Transfer Syntax was already encountered
403 * and if it corresponds to a RLE Lossless one.
404 * @return True when RLE Lossless found. False in all
407 bool gdcmDocument::IsRLELossLessTransferSyntax()
409 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
413 * \brief Determines if Transfer Syntax was already encountered
414 * and if it corresponds to a JPEG Lossless one.
415 * @return True when RLE Lossless found. False in all
419 bool gdcmDocument::IsJPEGLossless()
421 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
422 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
423 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
427 * \brief Determines if the Transfer Syntax was already encountered
428 * and if it corresponds to a JPEG2000 one
429 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
432 bool gdcmDocument::IsJPEG2000()
434 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
435 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
439 * \brief Predicate for dicom version 3 file.
440 * @return True when the file is a dicom version 3.
442 bool gdcmDocument::IsDicomV3()
444 // Checking if Transfert Syntax exists is enough
445 // Anyway, it's to late check if the 'Preamble' was found ...
446 // And ... would it be a rich idea to check ?
447 // (some 'no Preamble' DICOM images exist !)
448 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
452 * \brief returns the File Type
453 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
454 * @return the FileType code
456 FileType gdcmDocument::GetFileType()
462 * \brief Tries to open the file \ref gdcmDocument::Filename and
463 * checks the preamble when existing.
464 * @return The FILE pointer on success.
466 FILE* gdcmDocument::OpenFile()
468 Fp = fopen(Filename.c_str(),"rb");
473 "gdcmDocument::OpenFile cannot open file: ",
479 fread(&zero, (size_t)2, (size_t)1, Fp);
481 //ACR -- or DICOM with no Preamble --
482 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
488 fseek(Fp, 126L, SEEK_CUR);
490 fread(dicm, (size_t)4, (size_t)1, Fp);
491 if( memcmp(dicm, "DICM", 4) == 0 )
498 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
505 * \brief closes the file
506 * @return TRUE if the close was successfull
508 bool gdcmDocument::CloseFile()
510 int closed = fclose(Fp);
517 * \brief Writes in a file all the Header Entries (Dicom Elements)
518 * @param fp file pointer on an already open file
519 * @param filetype Type of the File to be written
520 * (ACR-NEMA, ExplicitVR, ImplicitVR)
521 * \return Always true.
523 void gdcmDocument::Write(FILE* fp,FileType filetype)
525 /// \todo move the following lines (and a lot of others, to be written)
526 /// to a future function CheckAndCorrectHeader
528 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
529 /// no way (check : FileType est un champ de gdcmDocument ...)
530 /// a moins de se livrer a un tres complique ajout des champs manquants.
531 /// faire un CheckAndCorrectHeader (?)
533 if (filetype == gdcmImplicitVR)
535 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
536 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
538 /// \todo Refer to standards on page 21, chapter 6.2
539 /// "Value representation": values with a VR of UI shall be
540 /// padded with a single trailing null
541 /// in the following case we have to padd manually with a 0
543 SetEntryLengthByNumber(18, 0x0002, 0x0010);
546 if (filetype == gdcmExplicitVR)
548 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
549 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
551 /// \todo Refer to standards on page 21, chapter 6.2
552 /// "Value representation": values with a VR of UI shall be
553 /// padded with a single trailing null
554 /// Dans le cas suivant on doit pader manuellement avec un 0
556 SetEntryLengthByNumber(20, 0x0002, 0x0010);
560 * \todo rewrite later, if really usefull
561 * - 'Group Length' element is optional in DICOM
562 * - but un-updated odd groups lengthes can causes pb
565 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
566 * UpdateGroupLength(false,filetype);
567 * if ( filetype == ACR)
568 * UpdateGroupLength(true,ACR);
571 gdcmElementSet::Write(fp, filetype); // This one is recursive
576 * \brief Modifies the value of a given Header Entry (Dicom Element)
577 * when it exists. Create it with the given value when unexistant.
578 * @param value (string) Value to be set
579 * @param group Group number of the Entry
580 * @param elem Element number of the Entry
581 * \return pointer to the modified/created Header Entry (NULL when creation
585 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
586 std::string const & value,
590 gdcmValEntry* valEntry = 0;
591 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
595 // The entry wasn't present and we simply create the required ValEntry:
596 currentEntry = NewDocEntryByNumber(group, elem);
599 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
600 " NewDocEntryByNumber failed.");
603 valEntry = new gdcmValEntry(currentEntry);
604 if ( !AddEntry(valEntry))
606 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
607 " failed allthough this is a creation.");
612 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
613 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
614 // then we change it to a ValEntry ?
615 // Shouldn't it be considered as an error ?
617 // We need to promote the gdcmDocEntry to a gdcmValEntry:
618 valEntry = new gdcmValEntry(currentEntry);
619 if (!RemoveEntry(currentEntry))
621 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
622 " of previous DocEntry failed.");
625 if ( !AddEntry(valEntry))
627 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
628 " promoted ValEntry failed.");
634 SetEntryByNumber(value, group, elem);
640 * \brief Modifies the value of a given Header Entry (Dicom Element)
641 * when it exists. Create it with the given value when unexistant.
642 * @param voidArea (binary) value to be set
643 * @param Group Group number of the Entry
644 * @param Elem Element number of the Entry
645 * \return pointer to the modified/created Header Entry (NULL when creation
648 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
655 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
658 a = NewBinEntryByNumber(group, elem);
664 b = new gdcmBinEntry(a);
666 b->SetVoidArea(voidArea);
668 SetEntryByNumber(voidArea, lgth, group, elem);
669 //b->SetVoidArea(voidArea); //what if b == 0 !!
676 * \brief Modifies the value of a given Header Entry (Dicom Element)
677 * when it exists. Create it when unexistant.
678 * @param Group Group number of the Entry
679 * @param Elem Element number of the Entry
680 * \return pointer to the modified/created SeqEntry (NULL when creation
683 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
688 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
691 a = NewSeqEntryByNumber(group, elem);
697 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
704 * \brief Set a new value if the invoked element exists
705 * Seems to be useless !!!
706 * @param value new element value
707 * @param group group number of the Entry
708 * @param elem element number of the Entry
711 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
712 uint16_t group, uint16_t elem )
714 SetEntryByNumber(value, group, elem);
719 //-----------------------------------------------------------------------------
723 * \brief Checks if a given Dicom Element exists within the H table
724 * @param group Group number of the searched Dicom Element
725 * @param element Element number of the searched Dicom Element
726 * @return true is found
728 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
730 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
731 return TagHT.count(key);
735 * \brief Searches within Header Entries (Dicom Elements) parsed with
736 * the public and private dictionaries
737 * for the element value of a given tag.
738 * \warning Don't use any longer : use GetPubEntryByName
739 * @param tagName name of the searched element.
740 * @return Corresponding element value when it exists,
741 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
743 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
745 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
751 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
755 * \brief Searches within Header Entries (Dicom Elements) parsed with
756 * the public and private dictionaries
757 * for the element value representation of a given tag.
759 * Obtaining the VR (Value Representation) might be needed by caller
760 * to convert the string typed content to caller's native type
761 * (think of C++ vs Python). The VR is actually of a higher level
762 * of semantics than just the native C++ type.
763 * @param tagName name of the searched element.
764 * @return Corresponding element value representation when it exists,
765 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
767 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
769 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
770 if( dictEntry == NULL)
775 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
776 dictEntry->GetElement());
777 return elem->GetVR();
782 * \brief Searches within Header Entries (Dicom Elements) parsed with
783 * the public and private dictionaries
784 * for the element value representation of a given tag.
785 * @param group Group number of the searched tag.
786 * @param element Element number of the searched tag.
787 * @return Corresponding element value representation when it exists,
788 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
790 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
792 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
793 /// \todo use map methods, instead of multimap JPR
794 if ( !TagHT.count(key))
799 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
803 * \brief Searches within Header Entries (Dicom Elements) parsed with
804 * the public and private dictionaries
805 * for the element value representation of a given tag..
807 * Obtaining the VR (Value Representation) might be needed by caller
808 * to convert the string typed content to caller's native type
809 * (think of C++ vs Python). The VR is actually of a higher level
810 * of semantics than just the native C++ type.
811 * @param group Group number of the searched tag.
812 * @param element Element number of the searched tag.
813 * @return Corresponding element value representation when it exists,
814 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
816 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
818 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
823 return elem->GetVR();
827 * \brief Searches within Header Entries (Dicom Elements) parsed with
828 * the public and private dictionaries
829 * for the value length of a given tag..
830 * @param group Group number of the searched tag.
831 * @param element Element number of the searched tag.
832 * @return Corresponding element length; -2 if not found
834 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
836 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
839 return -2; //magic number
841 return elem->GetLength();
844 * \brief Sets the value (string) of the Header Entry (Dicom Element)
845 * @param content string value of the Dicom Element
846 * @param tagName name of the searched Dicom Element.
847 * @return true when found
849 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
851 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
857 return SetEntryByNumber(content,dictEntry->GetGroup(),
858 dictEntry->GetElement());
862 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
863 * through it's (group, element) and modifies it's content with
865 * @param content new value (string) to substitute with
866 * @param group group number of the Dicom Element to modify
867 * @param element element number of the Dicom Element to modify
869 bool gdcmDocument::SetEntryByNumber(std::string const & content,
873 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
876 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
877 " ValEntry (try promotion first).");
880 // Non even content must be padded with a space (020H)...
881 std::string evenContent = content;
882 if( evenContent.length() % 2 )
884 evenContent += '\0'; // ... therefore we padd with (000H) .!?!
886 valEntry->SetValue(evenContent);
888 // Integers have a special treatement for their length:
889 gdcmVRKey vr = valEntry->GetVR();
890 if( vr == "US" || vr == "SS" )
892 int c = CountSubstring(content, "\\"); // for multivaluated items
893 valEntry->SetLength((c+1)*2);
895 else if( vr == "UL" || vr == "SL" )
897 int c = CountSubstring(content, "\\"); // for multivaluated items
898 valEntry->SetLength((c+1)*4);
902 valEntry->SetLength(evenContent.length());
909 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
910 * through it's (group, element) and modifies it's content with
912 * @param content new value (void *) to substitute with
913 * @param lgth new value length
914 * @param group group number of the Dicom Element to modify
915 * @param element element number of the Dicom Element to modify
917 bool gdcmDocument::SetEntryByNumber(void *content,
922 (void)lgth; //not used
923 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
924 if ( !TagHT.count(key))
929 /* Hope Binary field length is *never* wrong
930 if(lgth%2) // Non even length are padded with a space (020H).
933 //content = content + '\0'; // fing a trick to enlarge a binary field?
936 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
937 a->SetVoidArea(content);
938 //a->SetLength(lgth); // ???
944 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
945 * in the PubDocEntrySet of this instance
946 * through it's (group, element) and modifies it's length with
948 * \warning Use with extreme caution.
949 * @param l new length to substitute with
950 * @param group group number of the Entry to modify
951 * @param element element number of the Entry to modify
952 * @return true on success, false otherwise.
954 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
958 /// \todo use map methods, instead of multimap JPR
959 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
960 if ( !TagHT.count(key) )
966 l++; // length must be even
968 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
974 * \brief Gets (from Header) the offset of a 'non string' element value
975 * (LoadElementValues has already be executed)
976 * @param group group number of the Entry
977 * @param elem element number of the Entry
978 * @return File Offset of the Element Value
980 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
982 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
985 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
988 return entry->GetOffset();
992 * \brief Gets (from Header) a 'non string' element value
993 * (LoadElementValues has already be executed)
994 * @param group group number of the Entry
995 * @param elem element number of the Entry
996 * @return Pointer to the 'non string' area
998 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1000 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1003 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1006 return ((gdcmBinEntry *)entry)->GetVoidArea();
1010 * \brief Loads (from disk) the element content
1011 * when a string is not suitable
1012 * @param group group number of the Entry
1013 * @param elem element number of the Entry
1015 void *gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1017 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1022 size_t o =(size_t)docElement->GetOffset();
1023 fseek(Fp, o, SEEK_SET);
1024 size_t l = docElement->GetLength();
1025 char* a = new char[l];
1028 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1031 size_t l2 = fread(a, 1, l , Fp);
1037 /// \todo Drop any already existing void area! JPR
1038 SetEntryVoidAreaByNumber(a, group, elem);
1043 * \brief Loads (from disk) the element content
1044 * when a string is not suitable
1045 * @param element Entry whose voidArea is going to be loaded
1047 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1049 size_t o =(size_t)element->GetOffset();
1050 fseek(Fp, o, SEEK_SET);
1051 size_t l = element->GetLength();
1052 char* a = new char[l];
1055 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1058 element->SetVoidArea((void *)a);
1059 /// \todo check the result
1060 size_t l2 = fread(a, 1, l , Fp);
1071 * \brief Sets a 'non string' value to a given Dicom Element
1072 * @param area area containing the 'non string' value
1073 * @param group Group number of the searched Dicom Element
1074 * @param element Element number of the searched Dicom Element
1077 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1081 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1082 if ( !TagHT.count(key))
1087 // This was for multimap ?
1088 (( gdcmBinEntry *)( ((TagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1094 * \brief Update the entries with the shadow dictionary.
1095 * Only non even entries are analyzed
1097 void gdcmDocument::UpdateShaEntries()
1099 //gdcmDictEntry *entry;
1102 /// \todo TODO : still any use to explore recursively the whole structure?
1104 for(ListTag::iterator it=listEntries.begin();
1105 it!=listEntries.end();
1108 // Odd group => from public dictionary
1109 if((*it)->GetGroup()%2==0)
1112 // Peer group => search the corresponding dict entry
1114 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1118 if((*it)->IsImplicitVR())
1123 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1125 // Set the new entry and the new value
1126 (*it)->SetDictEntry(entry);
1127 CheckDocEntryVR(*it,vr);
1129 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1134 // Remove precedent value transformation
1135 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1142 * \brief Searches within the Header Entries for a Dicom Element of
1144 * @param tagName name of the searched Dicom Element.
1145 * @return Corresponding Dicom Element when it exists, and NULL
1148 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1150 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1156 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1160 * \brief retrieves a Dicom Element (the first one) using (group, element)
1161 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1162 * if you think it's NOT UNIQUE, check the count number
1163 * and use iterators to retrieve ALL the Dicoms Elements within
1164 * a given couple (group, element)
1165 * @param group Group number of the searched Dicom Element
1166 * @param element Element number of the searched Dicom Element
1169 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1172 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1173 if ( !TagHT.count(key))
1177 return TagHT.find(key)->second;
1181 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1182 * returns a result when the corresponding entry is of type
1184 * @return When present, the corresponding ValEntry.
1186 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1189 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1190 if ( !currentEntry )
1194 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1198 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1204 * \brief Loads the element while preserving the current
1205 * underlying file position indicator as opposed to
1206 * to LoadDocEntry that modifies it.
1207 * @param entry Header Entry whose value shall be loaded.
1210 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1212 long PositionOnEntry = ftell(Fp);
1213 LoadDocEntry(entry);
1214 fseek(Fp, PositionOnEntry, SEEK_SET);
1218 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1220 * @return The properly swaped 32 bits integer.
1222 uint32_t gdcmDocument::SwapLong(uint32_t a)
1229 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1230 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1234 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1238 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1241 //std::cout << "swapCode= " << SwapCode << std::endl;
1242 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1249 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1251 * @return The properly unswaped 32 bits integer.
1253 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1259 * \brief Swaps the bytes so they agree with the processor order
1260 * @return The properly swaped 16 bits integer.
1262 uint16_t gdcmDocument::SwapShort(uint16_t a)
1264 if ( SwapCode == 4321 || SwapCode == 2143 )
1266 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1272 * \brief Unswaps the bytes so they agree with the processor order
1273 * @return The properly unswaped 16 bits integer.
1275 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1277 return SwapShort(a);
1280 //-----------------------------------------------------------------------------
1284 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1285 * @return length of the parsed set.
1288 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1293 gdcmDocEntry *newDocEntry = 0;
1294 gdcmValEntry *newValEntry = 0;
1295 unsigned long l = 0;
1297 int depth = set->GetDepthLevel();
1300 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1304 newDocEntry = ReadNextDocEntry( );
1310 gdcmVRKey vr = newDocEntry->GetVR();
1314 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1317 newValEntry = new gdcmValEntry(newDocEntry->GetDictEntry());
1318 newValEntry->Copy(newDocEntry);
1319 newValEntry->SetDepthLevel(depth);
1320 set->AddEntry(newValEntry);
1321 LoadDocEntry(newValEntry);
1322 if (newValEntry->IsItemDelimitor())
1326 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1333 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1335 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1336 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1337 "nor BinEntry. Probably unknown VR.");
1340 ////// BinEntry or UNKOWN VR:
1341 gdcmBinEntry *bn = new gdcmBinEntry(newDocEntry->GetDictEntry());
1342 bn->Copy(newDocEntry);
1347 if (newDocEntry->GetGroup() == 0x7fe0 &&
1348 newDocEntry->GetElement() == 0x0010 )
1350 if (newDocEntry->GetReadLength()==0xffffffff)
1352 // Broken US.3405.1.dcm
1353 Parse7FE0(); // to skip the pixels
1354 // (multipart JPEG/RLE are trouble makers)
1358 SkipToNextDocEntry(newDocEntry);
1359 l = newDocEntry->GetFullLength();
1364 // to be sure we are at the beginning
1365 SkipToNextDocEntry(newDocEntry);
1366 l = newDocEntry->GetFullLength();
1372 l = newDocEntry->GetReadLength();
1373 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1375 if ( l == 0xffffffff )
1384 // no other way to create it ...
1385 gdcmSeqEntry *sq = new gdcmSeqEntry(newDocEntry->GetDictEntry(),
1386 set->GetDepthLevel());
1387 sq->Copy(newDocEntry);
1388 sq->SetDelimitorMode(delim_mode);
1389 sq->SetDepthLevel(depth);
1392 { // Don't try to parse zero-length sequences
1393 long lgt = ParseSQ( sq,
1394 newDocEntry->GetOffset(),
1396 (void)lgt; //not used...
1399 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1406 return l; // Probably useless
1410 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1411 * @return parsed length for this level
1413 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1414 long offset, long l_max, bool delim_mode)
1416 int SQItemNumber = 0;
1418 //int depth = set->GetDepthLevel();
1419 //(void)depth; //not used
1423 gdcmDocEntry *newDocEntry = ReadNextDocEntry();
1426 // FIXME Should warn user
1431 if ( newDocEntry->IsSequenceDelimitor() )
1433 set->SetSequenceDelimitationItem( newDocEntry );
1437 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1442 gdcmSQItem *itemSQ = new gdcmSQItem(set->GetDepthLevel());
1443 itemSQ->AddEntry(newDocEntry);
1444 unsigned int l = newDocEntry->GetReadLength();
1446 if ( l == 0xffffffff )
1455 int lgr = ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1456 (void)lgr; //FIXME not used
1458 set->AddEntry(itemSQ, SQItemNumber);
1460 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1466 int lgth = ftell(Fp) - offset;
1471 * \brief Loads the element content if its length doesn't exceed
1472 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1473 * @param entry Header Entry (Dicom Element) to be dealt with
1475 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1478 uint16_t group = entry->GetGroup();
1479 std::string vr = entry->GetVR();
1480 uint32_t length = entry->GetLength();
1482 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1484 // A SeQuence "contains" a set of Elements.
1485 // (fffe e000) tells us an Element is beginning
1486 // (fffe e00d) tells us an Element just ended
1487 // (fffe e0dd) tells us the current SeQuence just ended
1488 if( group == 0xfffe )
1490 // NO more value field for SQ !
1494 // When the length is zero things are easy:
1497 ((gdcmValEntry *)entry)->SetValue("");
1501 // The elements whose length is bigger than the specified upper bound
1502 // are not loaded. Instead we leave a short notice of the offset of
1503 // the element content and it's length.
1505 std::ostringstream s;
1506 if (length > MaxSizeLoadEntry)
1508 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1510 //s << "gdcm::NotLoaded (BinEntry)";
1511 s << GDCM_NOTLOADED;
1512 s << " Address:" << (long)entry->GetOffset();
1513 s << " Length:" << entry->GetLength();
1514 s << " x(" << std::hex << entry->GetLength() << ")";
1515 binEntryPtr->SetValue(s.str());
1517 // Be carefull : a BinEntry IS_A ValEntry ...
1518 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1520 // s << "gdcm::NotLoaded. (ValEntry)";
1521 s << GDCM_NOTLOADED;
1522 s << " Address:" << (long)entry->GetOffset();
1523 s << " Length:" << entry->GetLength();
1524 s << " x(" << std::hex << entry->GetLength() << ")";
1525 valEntryPtr->SetValue(s.str());
1530 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1531 << "nor a ValEntry ?! Should never print that !" << std::endl;
1534 // to be sure we are at the end of the value ...
1535 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1539 // When we find a BinEntry not very much can be done :
1540 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1543 LoadEntryVoidArea(binEntryPtr);
1544 s << "gdcm::Loaded (BinEntry)";
1545 binEntryPtr->SetValue(s.str());
1549 /// \todo Any compacter code suggested (?)
1550 if ( IsDocEntryAnInteger(entry) )
1553 //std::ostringstream s; //shadow previous declaration
1555 // When short integer(s) are expected, read and convert the following
1556 // n *two characters properly i.e. consider them as short integers as
1557 // opposed to strings.
1558 // Elements with Value Multiplicity > 1
1559 // contain a set of integers (not a single one)
1560 if (vr == "US" || vr == "SS")
1563 NewInt = ReadInt16();
1567 for (int i=1; i < nbInt; i++)
1570 NewInt = ReadInt16();
1575 // See above comment on multiple integers (mutatis mutandis).
1576 else if (vr == "UL" || vr == "SL")
1579 NewInt = ReadInt32();
1583 for (int i=1; i < nbInt; i++)
1586 NewInt = ReadInt32();
1591 #ifdef GDCM_NO_ANSI_STRING_STREAM
1592 s << std::ends; // to avoid oddities on Solaris
1593 #endif //GDCM_NO_ANSI_STRING_STREAM
1595 ((gdcmValEntry *)entry)->SetValue(s.str());
1599 // We need an additional byte for storing \0 that is not on disk
1600 //std::string newValue(length,0);
1601 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1602 //rah !! I can't believe it could work, normally this is a const char* !!!
1603 char *str = new char[length+1];
1604 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1606 std::string newValue = str;
1608 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1610 if ( item_read != 1 )
1612 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1613 "unread element value");
1614 valEntry->SetValue(GDCM_UNREAD);
1620 // Because of correspondance with the VR dic
1621 valEntry->SetValue(newValue);
1625 valEntry->SetValue(newValue);
1630 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1631 "Should have a ValEntry, here !");
1637 * \brief Find the value Length of the passed Header Entry
1638 * @param entry Header Entry whose length of the value shall be loaded.
1640 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1641 throw ( gdcmFormatError )
1643 uint16_t element = entry->GetElement();
1644 std::string vr = entry->GetVR();
1647 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1649 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1651 // The following reserved two bytes (see PS 3.5-2001, section
1652 // 7.1.2 Data element structure with explicit vr p27) must be
1653 // skipped before proceeding on reading the length on 4 bytes.
1654 fseek(Fp, 2L, SEEK_CUR);
1655 uint32_t length32 = ReadInt32();
1657 if ( vr == "OB" && length32 == 0xffffffff )
1662 lengthOB = FindDocEntryLengthOB();
1664 catch ( gdcmFormatUnexpected )
1666 // Computing the length failed (this happens with broken
1667 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1668 // chance to get the pixels by deciding the element goes
1669 // until the end of the file. Hence we artificially fix the
1670 // the length and proceed.
1671 long currentPosition = ftell(Fp);
1672 fseek(Fp,0L,SEEK_END);
1673 long lengthUntilEOF = ftell(Fp) - currentPosition;
1674 fseek(Fp, currentPosition, SEEK_SET);
1675 entry->SetLength(lengthUntilEOF);
1678 entry->SetLength(lengthOB);
1681 FixDocEntryFoundLength(entry, length32);
1685 // Length is encoded on 2 bytes.
1686 length16 = ReadInt16();
1688 // We can tell the current file is encoded in big endian (like
1689 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1690 // and it's value is the one of the encoding of a big endian file.
1691 // In order to deal with such big endian encoded files, we have
1692 // (at least) two strategies:
1693 // * when we load the "Transfer Syntax" tag with value of big endian
1694 // encoding, we raise the proper flags. Then we wait for the end
1695 // of the META group (0x0002) among which is "Transfer Syntax",
1696 // before switching the swap code to big endian. We have to postpone
1697 // the switching of the swap code since the META group is fully encoded
1698 // in little endian, and big endian coding only starts at the next
1699 // group. The corresponding code can be hard to analyse and adds
1700 // many additional unnecessary tests for regular tags.
1701 // * the second strategy consists in waiting for trouble, that shall
1702 // appear when we find the first group with big endian encoding. This
1703 // is easy to detect since the length of a "Group Length" tag (the
1704 // ones with zero as element number) has to be of 4 (0x0004). When we
1705 // encounter 1024 (0x0400) chances are the encoding changed and we
1706 // found a group with big endian encoding.
1707 // We shall use this second strategy. In order to make sure that we
1708 // can interpret the presence of an apparently big endian encoded
1709 // length of a "Group Length" without committing a big mistake, we
1710 // add an additional check: we look in the already parsed elements
1711 // for the presence of a "Transfer Syntax" whose value has to be "big
1712 // endian encoding". When this is the case, chances are we have got our
1713 // hands on a big endian encoded file: we switch the swap code to
1714 // big endian and proceed...
1715 if ( element == 0x0000 && length16 == 0x0400 )
1717 if ( !IsExplicitVRBigEndianTransferSyntax() )
1719 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1720 " not explicit VR." );
1724 SwitchSwapToBigEndian();
1725 // Restore the unproperly loaded values i.e. the group, the element
1726 // and the dictionary entry depending on them.
1727 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1728 uint16_t correctElem = SwapShort( entry->GetElement() );
1729 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1733 // This correct tag is not in the dictionary. Create a new one.
1734 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1736 // FIXME this can create a memory leaks on the old entry that be
1737 // left unreferenced.
1738 entry->SetDictEntry( newTag );
1741 // Heuristic: well, some files are really ill-formed.
1742 if ( length16 == 0xffff)
1744 // 0xffff means that we deal with 'Unknown Length' Sequence
1747 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1752 // Either implicit VR or a non DICOM conformal (see note below) explicit
1753 // VR that ommited the VR of (at least) this element. Farts happen.
1754 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1755 // on Data elements "Implicit and Explicit VR Data Elements shall
1756 // not coexist in a Data Set and Data Sets nested within it".]
1757 // Length is on 4 bytes.
1759 FixDocEntryFoundLength( entry, ReadInt32() );
1765 * \brief Find the Value Representation of the current Dicom Element.
1768 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1770 if ( Filetype != gdcmExplicitVR )
1777 long positionOnEntry = ftell(Fp);
1778 // Warning: we believe this is explicit VR (Value Representation) because
1779 // we used a heuristic that found "UL" in the first tag. Alas this
1780 // doesn't guarantee that all the tags will be in explicit VR. In some
1781 // cases (see e-film filtered files) one finds implicit VR tags mixed
1782 // within an explicit VR file. Hence we make sure the present tag
1783 // is in explicit VR and try to fix things if it happens not to be
1786 fread (vr, (size_t)2,(size_t)1, Fp);
1789 if( !CheckDocEntryVR(entry, vr) )
1791 fseek(Fp, positionOnEntry, SEEK_SET);
1792 // When this element is known in the dictionary we shall use, e.g. for
1793 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1794 // dictionary entry. Still we have to flag the element as implicit since
1795 // we know now our assumption on expliciteness is not furfilled.
1797 if ( entry->IsVRUnknown() )
1799 entry->SetVR("Implicit");
1801 entry->SetImplicitVR();
1806 * \brief Check the correspondance between the VR of the header entry
1807 * and the taken VR. If they are different, the header entry is
1808 * updated with the new VR.
1809 * @param entry Header Entry to check
1810 * @param vr Dicom Value Representation
1811 * @return false if the VR is incorrect of if the VR isn't referenced
1812 * otherwise, it returns true
1814 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1816 char msg[100]; // for sprintf
1817 bool realExplicit = true;
1819 // Assume we are reading a falsely explicit VR file i.e. we reached
1820 // a tag where we expect reading a VR but are in fact we read the
1821 // first to bytes of the length. Then we will interogate (through find)
1822 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1823 // both GCC and VC++ implementations of the STL map. Hence when the
1824 // expected VR read happens to be non-ascii characters we consider
1825 // we hit falsely explicit VR tag.
1827 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1829 realExplicit = false;
1832 // CLEANME searching the dicom_vr at each occurence is expensive.
1833 // PostPone this test in an optional integrity check at the end
1834 // of parsing or only in debug mode.
1835 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1837 realExplicit = false;
1840 if ( !realExplicit )
1842 // We thought this was explicit VR, but we end up with an
1843 // implicit VR tag. Let's backtrack.
1844 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1845 entry->GetGroup(), entry->GetElement());
1846 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1848 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1850 // Group length is UL !
1851 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1852 entry->GetGroup(), entry->GetElement(),
1853 "UL", "FIXME", "Group Length");
1854 entry->SetDictEntry( newEntry );
1859 if ( entry->IsVRUnknown() )
1861 // When not a dictionary entry, we can safely overwrite the VR.
1862 if( entry->GetElement() == 0x0000 )
1864 // Group length is UL !
1872 else if ( entry->GetVR() != vr )
1874 // The VR present in the file and the dictionary disagree. We assume
1875 // the file writer knew best and use the VR of the file. Since it would
1876 // be unwise to overwrite the VR of a dictionary (since it would
1877 // compromise it's next user), we need to clone the actual DictEntry
1878 // and change the VR for the read one.
1879 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1880 entry->GetGroup(), entry->GetElement(),
1881 vr, "FIXME", entry->GetName());
1882 entry->SetDictEntry(newEntry);
1889 * \brief Get the transformed value of the header entry. The VR value
1890 * is used to define the transformation to operate on the value
1891 * \warning NOT end user intended method !
1892 * @param entry entry to tranform
1893 * @return Transformed entry value
1895 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1897 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1899 std::string val = ((gdcmValEntry *)entry)->GetValue();
1900 std::string vr = entry->GetVR();
1901 uint32_t length = entry->GetLength();
1902 std::ostringstream s;
1905 // When short integer(s) are expected, read and convert the following
1906 // n * 2 bytes properly i.e. as a multivaluated strings
1907 // (each single value is separated fromthe next one by '\'
1908 // as usual for standard multivaluated filels
1909 // Elements with Value Multiplicity > 1
1910 // contain a set of short integers (not a single one)
1912 if( vr == "US" || vr == "SS" )
1917 for (int i=0; i < nbInt; i++)
1923 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1924 newInt16 = SwapShort( newInt16 );
1929 // When integer(s) are expected, read and convert the following
1930 // n * 4 bytes properly i.e. as a multivaluated strings
1931 // (each single value is separated fromthe next one by '\'
1932 // as usual for standard multivaluated filels
1933 // Elements with Value Multiplicity > 1
1934 // contain a set of integers (not a single one)
1935 else if( vr == "UL" || vr == "SL" )
1940 for (int i=0; i < nbInt; i++)
1946 newInt32 = ( val[4*i+0] & 0xFF )
1947 + (( val[4*i+1] & 0xFF ) << 8 )
1948 + (( val[4*i+2] & 0xFF ) << 16 )
1949 + (( val[4*i+3] & 0xFF ) << 24 );
1950 newInt32 = SwapLong( newInt32 );
1954 #ifdef GDCM_NO_ANSI_STRING_STREAM
1955 s << std::ends; // to avoid oddities on Solaris
1956 #endif //GDCM_NO_ANSI_STRING_STREAM
1960 return ((gdcmValEntry *)entry)->GetValue();
1964 * \brief Get the reverse transformed value of the header entry. The VR
1965 * value is used to define the reverse transformation to operate on
1967 * \warning NOT end user intended method !
1968 * @param entry Entry to reverse transform
1969 * @return Reverse transformed entry value
1971 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1973 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1975 std::string vr = entry->GetVR();
1976 std::vector<std::string> tokens;
1977 std::ostringstream s;
1979 if ( vr == "US" || vr == "SS" )
1983 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1984 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1985 for (unsigned int i=0; i<tokens.size(); i++)
1987 newInt16 = atoi(tokens[i].c_str());
1988 s << ( newInt16 & 0xFF )
1989 << (( newInt16 >> 8 ) & 0xFF );
1993 if ( vr == "UL" || vr == "SL")
1997 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1998 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1999 for (unsigned int i=0; i<tokens.size();i++)
2001 newInt32 = atoi(tokens[i].c_str());
2002 s << (char)( newInt32 & 0xFF )
2003 << (char)(( newInt32 >> 8 ) & 0xFF )
2004 << (char)(( newInt32 >> 16 ) & 0xFF )
2005 << (char)(( newInt32 >> 24 ) & 0xFF );
2010 #ifdef GDCM_NO_ANSI_STRING_STREAM
2011 s << std::ends; // to avoid oddities on Solaris
2012 #endif //GDCM_NO_ANSI_STRING_STREAM
2016 return ((gdcmValEntry *)entry)->GetValue();
2020 * \brief Skip a given Header Entry
2021 * \warning NOT end user intended method !
2022 * @param entry entry to skip
2024 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2026 SkipBytes(entry->GetLength());
2030 * \brief Skips to the begining of the next Header Entry
2031 * \warning NOT end user intended method !
2032 * @param entry entry to skip
2034 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2036 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2037 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2041 * \brief When the length of an element value is obviously wrong (because
2042 * the parser went Jabberwocky) one can hope improving things by
2043 * applying some heuristics.
2044 * @param entry entry to check
2045 * @param foundLength fist assumption about length
2047 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2048 uint32_t foundLength)
2050 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2051 if ( foundLength == 0xffffffff)
2056 uint16_t gr = entry->GetGroup();
2057 uint16_t el = entry->GetElement();
2059 if ( foundLength % 2)
2061 std::ostringstream s;
2062 s << "Warning : Tag with uneven length "
2064 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2065 dbg.Verbose(0, s.str().c_str());
2068 //////// Fix for some naughty General Electric images.
2069 // Allthough not recent many such GE corrupted images are still present
2070 // on Creatis hard disks. Hence this fix shall remain when such images
2071 // are no longer in user (we are talking a few years, here)...
2072 // Note: XMedCom probably uses such a trick since it is able to read
2073 // those pesky GE images ...
2074 if ( foundLength == 13)
2076 // Only happens for this length !
2077 if ( entry->GetGroup() != 0x0008
2078 || ( entry->GetElement() != 0x0070
2079 && entry->GetElement() != 0x0080 ) )
2082 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2086 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2087 // Occurence of such images is quite low (unless one leaves close to a
2088 // 'Leonardo' source. Hence, one might consider commenting out the
2089 // following fix on efficiency reasons.
2090 else if ( entry->GetGroup() == 0x0009
2091 && ( entry->GetElement() == 0x1113
2092 || entry->GetElement() == 0x1114 ) )
2095 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2098 else if ( entry->GetVR() == "SQ" )
2100 foundLength = 0; // ReadLength is unchanged
2103 //////// We encountered a 'delimiter' element i.e. a tag of the form
2104 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2105 // taken into account.
2106 else if( entry->GetGroup() == 0xfffe )
2108 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2109 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2110 // causes extra troubles...
2111 if( entry->GetElement() != 0x0000 )
2117 entry->SetUsableLength(foundLength);
2121 * \brief Apply some heuristics to predict whether the considered
2122 * element value contains/represents an integer or not.
2123 * @param entry The element value on which to apply the predicate.
2124 * @return The result of the heuristical predicate.
2126 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2128 uint16_t element = entry->GetElement();
2129 uint16_t group = entry->GetGroup();
2130 std::string vr = entry->GetVR();
2131 uint32_t length = entry->GetLength();
2133 // When we have some semantics on the element we just read, and if we
2134 // a priori know we are dealing with an integer, then we shall be
2135 // able to swap it's element value properly.
2136 if ( element == 0 ) // This is the group length of the group
2144 // Allthough this should never happen, still some images have a
2145 // corrupted group length [e.g. have a glance at offset x(8336) of
2146 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2147 // Since for dicom compliant and well behaved headers, the present
2148 // test is useless (and might even look a bit paranoid), when we
2149 // encounter such an ill-formed image, we simply display a warning
2150 // message and proceed on parsing (while crossing fingers).
2151 std::ostringstream s;
2152 int filePosition = ftell(Fp);
2153 s << "Erroneous Group Length element length on : (" \
2154 << std::hex << group << " , " << element
2155 << ") -before- position x(" << filePosition << ")"
2156 << "lgt : " << length;
2157 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2161 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2170 * \brief Find the Length till the next sequence delimiter
2171 * \warning NOT end user intended method !
2175 uint32_t gdcmDocument::FindDocEntryLengthOB()
2176 throw( gdcmFormatUnexpected )
2178 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2179 long positionOnEntry = ftell(Fp);
2180 bool foundSequenceDelimiter = false;
2181 uint32_t totalLength = 0;
2183 while ( !foundSequenceDelimiter )
2189 group = ReadInt16();
2192 catch ( gdcmFormatError )
2194 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2195 " group or element not present.");
2198 // We have to decount the group and element we just read
2201 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2203 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2204 "tag nor a Sequence delimiter tag.");
2205 fseek(Fp, positionOnEntry, SEEK_SET);
2206 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2207 "Neither an Item tag nor a Sequence "
2211 if ( elem == 0xe0dd )
2213 foundSequenceDelimiter = true;
2216 uint32_t itemLength = ReadInt32();
2217 // We add 4 bytes since we just read the ItemLength with ReadInt32
2218 totalLength += itemLength + 4;
2219 SkipBytes(itemLength);
2221 if ( foundSequenceDelimiter )
2226 fseek(Fp, positionOnEntry, SEEK_SET);
2231 * \brief Reads a supposed to be 16 Bits integer
2232 * (swaps it depending on processor endianity)
2233 * @return read value
2235 uint16_t gdcmDocument::ReadInt16()
2236 throw( gdcmFormatError )
2239 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2240 if ( item_read != 1 )
2244 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2246 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2253 * \brief Reads a supposed to be 32 Bits integer
2254 * (swaps it depending on processor endianity)
2255 * @return read value
2257 uint32_t gdcmDocument::ReadInt32()
2258 throw( gdcmFormatError )
2261 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2262 if ( item_read != 1 )
2266 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2268 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2275 * \brief skips bytes inside the source file
2276 * \warning NOT end user intended method !
2279 void gdcmDocument::SkipBytes(uint32_t nBytes)
2281 //FIXME don't dump the returned value
2282 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2286 * \brief Loads all the needed Dictionaries
2287 * \warning NOT end user intended method !
2289 void gdcmDocument::Initialise()
2291 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2296 * \brief Discover what the swap code is (among little endian, big endian,
2297 * bad little endian, bad big endian).
2299 * @return false when we are absolutely sure
2300 * it's neither ACR-NEMA nor DICOM
2301 * true when we hope ours assuptions are OK
2303 bool gdcmDocument::CheckSwap()
2305 // The only guaranted way of finding the swap code is to find a
2306 // group tag since we know it's length has to be of four bytes i.e.
2307 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2308 // occurs when we can't find such group...
2310 uint32_t x = 4; // x : for ntohs
2311 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2315 char deb[HEADER_LENGTH_TO_READ];
2317 // First, compare HostByteOrder and NetworkByteOrder in order to
2318 // determine if we shall need to swap bytes (i.e. the Endian type).
2319 if ( x == ntohs(x) )
2328 // The easiest case is the one of a DICOM header, since it possesses a
2329 // file preamble where it suffice to look for the string "DICM".
2330 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2331 (void)lgrLue; //FIXME not used
2333 char *entCur = deb + 128;
2334 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2336 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2338 // Next, determine the value representation (VR). Let's skip to the
2339 // first element (0002, 0000) and check there if we find "UL"
2340 // - or "OB" if the 1st one is (0002,0001) -,
2341 // in which case we (almost) know it is explicit VR.
2342 // WARNING: if it happens to be implicit VR then what we will read
2343 // is the length of the group. If this ascii representation of this
2344 // length happens to be "UL" then we shall believe it is explicit VR.
2345 // FIXME: in order to fix the above warning, we could read the next
2346 // element value (or a couple of elements values) in order to make
2347 // sure we are not commiting a big mistake.
2348 // We need to skip :
2349 // * the 128 bytes of File Preamble (often padded with zeroes),
2350 // * the 4 bytes of "DICM" string,
2351 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2352 // i.e. a total of 136 bytes.
2356 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2357 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2358 // *Implicit* VR. -and it is !-
2360 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2361 memcmp(entCur, "OB", (size_t)2) == 0 ||
2362 memcmp(entCur, "UI", (size_t)2) == 0 ||
2363 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2364 // when Write DCM *adds*
2366 // Use gdcmDocument::dicom_vr to test all the possibilities
2367 // instead of just checking for UL, OB and UI !? group 0000
2369 Filetype = gdcmExplicitVR;
2370 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2371 "explicit Value Representation");
2375 Filetype = gdcmImplicitVR;
2376 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2377 "not an explicit Value Representation");
2383 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2384 "HostByteOrder != NetworkByteOrder");
2389 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2390 "HostByteOrder = NetworkByteOrder");
2393 // Position the file position indicator at first tag (i.e.
2394 // after the file preamble and the "DICM" string).
2396 fseek (Fp, 132L, SEEK_SET);
2400 // Alas, this is not a DicomV3 file and whatever happens there is no file
2401 // preamble. We can reset the file position indicator to where the data
2402 // is (i.e. the beginning of the file).
2403 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2406 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2407 // By clean we mean that the length of the first tag is written down.
2408 // If this is the case and since the length of the first group HAS to be
2409 // four (bytes), then determining the proper swap code is straightforward.
2412 // We assume the array of char we are considering contains the binary
2413 // representation of a 32 bits integer. Hence the following dirty
2415 s32 = *((uint32_t *)(entCur));
2436 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2437 // It is time for despaired wild guesses.
2438 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2439 // i.e. the 'group length' element is not present :
2441 // check the supposed to be 'group number'
2442 // 0x0002 or 0x0004 or 0x0008
2443 // to determine ' SwapCode' value .
2444 // Only 0 or 4321 will be possible
2445 // (no oportunity to check for the formerly well known
2446 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2447 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2448 // the file IS NOT ACR-NEMA nor DICOM V3
2449 // Find a trick to tell it the caller...
2451 s16 = *((uint16_t *)(deb));
2468 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2469 "ACR/NEMA unfound swap info (Really hopeless !)");
2470 Filetype = gdcmUnknown;
2473 // Then the only info we have is the net2host one.
2483 * \brief Restore the unproperly loaded values i.e. the group, the element
2484 * and the dictionary entry depending on them.
2486 void gdcmDocument::SwitchSwapToBigEndian()
2488 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2489 "Switching to BigEndian mode.");
2490 if ( SwapCode == 0 )
2494 else if ( SwapCode == 4321 )
2498 else if ( SwapCode == 3412 )
2502 else if ( SwapCode == 2143 )
2509 * \brief during parsing, Header Elements too long are not loaded in memory
2512 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2518 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2520 MaxSizeLoadEntry = 0xffffffff;
2523 MaxSizeLoadEntry = newSize;
2528 * \brief Header Elements too long will not be printed
2529 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2532 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2534 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2539 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2541 MaxSizePrintEntry = 0xffffffff;
2544 MaxSizePrintEntry = newSize;
2550 * \brief Read the next tag but WITHOUT loading it's value
2551 * (read the 'Group Number', the 'Element Number',
2552 * gets the Dict Entry
2553 * gets the VR, gets the length, gets the offset value)
2554 * @return On succes the newly created DocEntry, NULL on failure.
2556 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2563 group = ReadInt16();
2566 catch ( gdcmFormatError e )
2568 // We reached the EOF (or an error occured) therefore
2569 // header parsing has to be considered as finished.
2574 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2575 FindDocEntryVR(newEntry);
2579 FindDocEntryLength(newEntry);
2581 catch ( gdcmFormatError e )
2589 newEntry->SetOffset(ftell(Fp));
2596 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2597 * in the TagHt dictionary.
2598 * @param group The generated tag must belong to this group.
2599 * @return The element of tag with given group which is fee.
2601 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2603 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2605 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2606 if (TagHT.count(key) == 0)
2615 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2616 * is placed at the beginning of a tag check whether this
2617 * tag is (TestGroup, TestElement).
2618 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2619 * is modified to point after the tag.
2620 * On failure (i.e. when the tag wasn't the expected tag
2621 * (TestGroup, TestElement) the internal file pointer
2622 * \ref gdcmDocument::Fp is restored to it's original position.
2623 * @param testGroup The expected group of the tag.
2624 * @param testElement The expected Element of the tag.
2625 * @return True on success, false otherwise.
2627 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2629 long positionOnEntry = ftell(Fp);
2630 long currentPosition = ftell(Fp); // On debugging purposes
2632 //// Read the Item Tag group and element, and make
2633 // sure they are what we expected:
2634 uint16_t itemTagGroup = ReadInt16();
2635 uint16_t itemTagElement = ReadInt16();
2636 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2638 std::ostringstream s;
2639 s << " We should have found tag (";
2640 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2641 s << " but instead we encountered tag (";
2642 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2644 s << " at address: " << (unsigned)currentPosition << std::endl;
2645 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2646 dbg.Verbose(0, s.str().c_str());
2647 fseek(Fp, positionOnEntry, SEEK_SET);
2655 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2656 * is placed at the beginning of a tag (TestGroup, TestElement),
2657 * read the length associated to the Tag.
2658 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2659 * is modified to point after the tag and it's length.
2660 * On failure (i.e. when the tag wasn't the expected tag
2661 * (TestGroup, TestElement) the internal file pointer
2662 * \ref gdcmDocument::Fp is restored to it's original position.
2663 * @param testGroup The expected group of the tag.
2664 * @param testElement The expected Element of the tag.
2665 * @return On success returns the length associated to the tag. On failure
2668 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2670 long positionOnEntry = ftell(Fp);
2671 (void)positionOnEntry;
2673 if ( !ReadTag(testGroup, testElement) )
2678 //// Then read the associated Item Length
2679 long currentPosition = ftell(Fp);
2680 uint32_t itemLength = ReadInt32();
2682 std::ostringstream s;
2683 s << "Basic Item Length is: "
2684 << itemLength << std::endl;
2685 s << " at address: " << (unsigned)currentPosition << std::endl;
2686 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2692 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2693 * No other way so 'skip' the Data
2696 void gdcmDocument::Parse7FE0 ()
2698 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2701 // Should warn user FIXME
2705 if ( IsImplicitVRLittleEndianTransferSyntax()
2706 || IsExplicitVRLittleEndianTransferSyntax()
2707 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2708 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2713 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2715 //// Read the Basic Offset Table Item Tag length...
2716 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2718 //// ... and then read length[s] itself[themselves]. We don't use
2719 // the values read (BTW what is the purpous of those lengths ?)
2720 if ( itemLength != 0 )
2722 // BTW, what is the purpous of those length anyhow !?
2723 char* basicOffsetTableItemValue = new char[itemLength + 1];
2724 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2726 for (unsigned int i=0; i < itemLength; i += 4 )
2728 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2729 std::ostringstream s;
2730 s << " Read one length: ";
2731 s << std::hex << individualLength << std::endl;
2732 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2734 delete[] basicOffsetTableItemValue;
2737 if ( ! IsRLELossLessTransferSyntax() )
2741 //// We then skip (not reading them) all the fragments of images:
2742 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2744 SkipBytes(itemLength);
2751 long rleSegmentLength[15], fragmentLength;
2753 // While we find some items:
2754 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2756 // Parse fragments of the current Fragment (Frame)
2757 //------------------ scanning (not reading) fragment pixels
2758 uint32_t nbRleSegments = ReadInt32();
2760 //// Reading RLE Segments Offset Table
2761 uint32_t rleSegmentOffsetTable[15];
2762 for(int k=1; k<=15; k++)
2764 ftellRes = ftell(Fp);
2765 rleSegmentOffsetTable[k] = ReadInt32();
2768 // skipping (not reading) RLE Segments
2769 if ( nbRleSegments > 1)
2771 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2773 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2774 - rleSegmentOffsetTable[k];
2775 ftellRes = ftell(Fp);
2776 SkipBytes(rleSegmentLength[k]);
2780 rleSegmentLength[nbRleSegments] = fragmentLength
2781 - rleSegmentOffsetTable[nbRleSegments];
2782 ftellRes = ftell(Fp);
2783 SkipBytes(rleSegmentLength[nbRleSegments]);
2786 // Make sure that at the end of the item we encounter a 'Sequence
2788 if ( !ReadTag(0xfffe, 0xe0dd) )
2790 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2791 dbg.Verbose(0, " at end of RLE item sequence");
2799 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2800 * \warning Does NOT work with ACR-NEMA files
2801 * \todo Find a trick to solve the pb (use RET fields ?)
2803 * @return true if 'smaller'
2805 bool gdcmDocument::operator<(gdcmDocument &document)
2808 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2809 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2821 s1 = GetEntryByNumber(0x0010,0x0020);
2822 s2 = document.GetEntryByNumber(0x0010,0x0020);
2833 // Study Instance UID
2834 s1 = GetEntryByNumber(0x0020,0x000d);
2835 s2 = document.GetEntryByNumber(0x0020,0x000d);
2846 // Serie Instance UID
2847 s1 = GetEntryByNumber(0x0020,0x000e);
2848 s2 = document.GetEntryByNumber(0x0020,0x000e);
2864 //-----------------------------------------------------------------------------