1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/10 18:54:38 $
7 Version: $Revision: 1.74 $
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) )
1542 s << "gdcm::Loaded (BinEntry)";
1543 binEntryPtr->SetValue(s.str());
1544 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1548 /// \todo Any compacter code suggested (?)
1549 if ( IsDocEntryAnInteger(entry) )
1552 //std::ostringstream s; //shadow previous declaration
1554 // When short integer(s) are expected, read and convert the following
1555 // n *two characters properly i.e. consider them as short integers as
1556 // opposed to strings.
1557 // Elements with Value Multiplicity > 1
1558 // contain a set of integers (not a single one)
1559 if (vr == "US" || vr == "SS")
1562 NewInt = ReadInt16();
1566 for (int i=1; i < nbInt; i++)
1569 NewInt = ReadInt16();
1574 // See above comment on multiple integers (mutatis mutandis).
1575 else if (vr == "UL" || vr == "SL")
1578 NewInt = ReadInt32();
1582 for (int i=1; i < nbInt; i++)
1585 NewInt = ReadInt32();
1590 #ifdef GDCM_NO_ANSI_STRING_STREAM
1591 s << std::ends; // to avoid oddities on Solaris
1592 #endif //GDCM_NO_ANSI_STRING_STREAM
1594 ((gdcmValEntry *)entry)->SetValue(s.str());
1598 // We need an additional byte for storing \0 that is not on disk
1599 //std::string newValue(length,0);
1600 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1601 //rah !! I can't believe it could work, normally this is a const char* !!!
1602 char *str = new char[length+1];
1603 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1605 std::string newValue = str;
1607 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1609 if ( item_read != 1 )
1611 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1612 "unread element value");
1613 valEntry->SetValue(GDCM_UNREAD);
1619 // Because of correspondance with the VR dic
1620 valEntry->SetValue(newValue);
1624 valEntry->SetValue(newValue);
1629 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1630 "Should have a ValEntry, here !");
1636 * \brief Find the value Length of the passed Header Entry
1637 * @param entry Header Entry whose length of the value shall be loaded.
1639 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1640 throw ( gdcmFormatError )
1642 uint16_t element = entry->GetElement();
1643 std::string vr = entry->GetVR();
1646 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1648 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1650 // The following reserved two bytes (see PS 3.5-2001, section
1651 // 7.1.2 Data element structure with explicit vr p27) must be
1652 // skipped before proceeding on reading the length on 4 bytes.
1653 fseek(Fp, 2L, SEEK_CUR);
1654 uint32_t length32 = ReadInt32();
1656 if ( vr == "OB" && length32 == 0xffffffff )
1661 lengthOB = FindDocEntryLengthOB();
1663 catch ( gdcmFormatUnexpected )
1665 // Computing the length failed (this happens with broken
1666 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1667 // chance to get the pixels by deciding the element goes
1668 // until the end of the file. Hence we artificially fix the
1669 // the length and proceed.
1670 long currentPosition = ftell(Fp);
1671 fseek(Fp,0L,SEEK_END);
1672 long lengthUntilEOF = ftell(Fp) - currentPosition;
1673 fseek(Fp, currentPosition, SEEK_SET);
1674 entry->SetLength(lengthUntilEOF);
1677 entry->SetLength(lengthOB);
1680 FixDocEntryFoundLength(entry, length32);
1684 // Length is encoded on 2 bytes.
1685 length16 = ReadInt16();
1687 // We can tell the current file is encoded in big endian (like
1688 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1689 // and it's value is the one of the encoding of a big endian file.
1690 // In order to deal with such big endian encoded files, we have
1691 // (at least) two strategies:
1692 // * when we load the "Transfer Syntax" tag with value of big endian
1693 // encoding, we raise the proper flags. Then we wait for the end
1694 // of the META group (0x0002) among which is "Transfer Syntax",
1695 // before switching the swap code to big endian. We have to postpone
1696 // the switching of the swap code since the META group is fully encoded
1697 // in little endian, and big endian coding only starts at the next
1698 // group. The corresponding code can be hard to analyse and adds
1699 // many additional unnecessary tests for regular tags.
1700 // * the second strategy consists in waiting for trouble, that shall
1701 // appear when we find the first group with big endian encoding. This
1702 // is easy to detect since the length of a "Group Length" tag (the
1703 // ones with zero as element number) has to be of 4 (0x0004). When we
1704 // encounter 1024 (0x0400) chances are the encoding changed and we
1705 // found a group with big endian encoding.
1706 // We shall use this second strategy. In order to make sure that we
1707 // can interpret the presence of an apparently big endian encoded
1708 // length of a "Group Length" without committing a big mistake, we
1709 // add an additional check: we look in the already parsed elements
1710 // for the presence of a "Transfer Syntax" whose value has to be "big
1711 // endian encoding". When this is the case, chances are we have got our
1712 // hands on a big endian encoded file: we switch the swap code to
1713 // big endian and proceed...
1714 if ( element == 0x0000 && length16 == 0x0400 )
1716 if ( !IsExplicitVRBigEndianTransferSyntax() )
1718 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1719 " not explicit VR." );
1723 SwitchSwapToBigEndian();
1724 // Restore the unproperly loaded values i.e. the group, the element
1725 // and the dictionary entry depending on them.
1726 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1727 uint16_t correctElem = SwapShort( entry->GetElement() );
1728 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1732 // This correct tag is not in the dictionary. Create a new one.
1733 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1735 // FIXME this can create a memory leaks on the old entry that be
1736 // left unreferenced.
1737 entry->SetDictEntry( newTag );
1740 // Heuristic: well, some files are really ill-formed.
1741 if ( length16 == 0xffff)
1743 // 0xffff means that we deal with 'Unknown Length' Sequence
1746 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1751 // Either implicit VR or a non DICOM conformal (see note below) explicit
1752 // VR that ommited the VR of (at least) this element. Farts happen.
1753 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1754 // on Data elements "Implicit and Explicit VR Data Elements shall
1755 // not coexist in a Data Set and Data Sets nested within it".]
1756 // Length is on 4 bytes.
1758 FixDocEntryFoundLength( entry, ReadInt32() );
1764 * \brief Find the Value Representation of the current Dicom Element.
1767 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1769 if ( Filetype != gdcmExplicitVR )
1776 long positionOnEntry = ftell(Fp);
1777 // Warning: we believe this is explicit VR (Value Representation) because
1778 // we used a heuristic that found "UL" in the first tag. Alas this
1779 // doesn't guarantee that all the tags will be in explicit VR. In some
1780 // cases (see e-film filtered files) one finds implicit VR tags mixed
1781 // within an explicit VR file. Hence we make sure the present tag
1782 // is in explicit VR and try to fix things if it happens not to be
1785 fread (vr, (size_t)2,(size_t)1, Fp);
1788 if( !CheckDocEntryVR(entry, vr) )
1790 fseek(Fp, positionOnEntry, SEEK_SET);
1791 // When this element is known in the dictionary we shall use, e.g. for
1792 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1793 // dictionary entry. Still we have to flag the element as implicit since
1794 // we know now our assumption on expliciteness is not furfilled.
1796 if ( entry->IsVRUnknown() )
1798 entry->SetVR("Implicit");
1800 entry->SetImplicitVR();
1805 * \brief Check the correspondance between the VR of the header entry
1806 * and the taken VR. If they are different, the header entry is
1807 * updated with the new VR.
1808 * @param entry Header Entry to check
1809 * @param vr Dicom Value Representation
1810 * @return false if the VR is incorrect of if the VR isn't referenced
1811 * otherwise, it returns true
1813 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1815 char msg[100]; // for sprintf
1816 bool realExplicit = true;
1818 // Assume we are reading a falsely explicit VR file i.e. we reached
1819 // a tag where we expect reading a VR but are in fact we read the
1820 // first to bytes of the length. Then we will interogate (through find)
1821 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1822 // both GCC and VC++ implementations of the STL map. Hence when the
1823 // expected VR read happens to be non-ascii characters we consider
1824 // we hit falsely explicit VR tag.
1826 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1828 realExplicit = false;
1831 // CLEANME searching the dicom_vr at each occurence is expensive.
1832 // PostPone this test in an optional integrity check at the end
1833 // of parsing or only in debug mode.
1834 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1836 realExplicit = false;
1839 if ( !realExplicit )
1841 // We thought this was explicit VR, but we end up with an
1842 // implicit VR tag. Let's backtrack.
1843 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1844 entry->GetGroup(), entry->GetElement());
1845 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1847 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1849 // Group length is UL !
1850 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1851 entry->GetGroup(), entry->GetElement(),
1852 "UL", "FIXME", "Group Length");
1853 entry->SetDictEntry( newEntry );
1858 if ( entry->IsVRUnknown() )
1860 // When not a dictionary entry, we can safely overwrite the VR.
1861 if( entry->GetElement() == 0x0000 )
1863 // Group length is UL !
1871 else if ( entry->GetVR() != vr )
1873 // The VR present in the file and the dictionary disagree. We assume
1874 // the file writer knew best and use the VR of the file. Since it would
1875 // be unwise to overwrite the VR of a dictionary (since it would
1876 // compromise it's next user), we need to clone the actual DictEntry
1877 // and change the VR for the read one.
1878 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1879 entry->GetGroup(), entry->GetElement(),
1880 vr, "FIXME", entry->GetName());
1881 entry->SetDictEntry(newEntry);
1888 * \brief Get the transformed value of the header entry. The VR value
1889 * is used to define the transformation to operate on the value
1890 * \warning NOT end user intended method !
1891 * @param entry entry to tranform
1892 * @return Transformed entry value
1894 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1896 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1898 std::string val = ((gdcmValEntry *)entry)->GetValue();
1899 std::string vr = entry->GetVR();
1900 uint32_t length = entry->GetLength();
1901 std::ostringstream s;
1904 // When short integer(s) are expected, read and convert the following
1905 // n * 2 bytes properly i.e. as a multivaluated strings
1906 // (each single value is separated fromthe next one by '\'
1907 // as usual for standard multivaluated filels
1908 // Elements with Value Multiplicity > 1
1909 // contain a set of short integers (not a single one)
1911 if( vr == "US" || vr == "SS" )
1916 for (int i=0; i < nbInt; i++)
1922 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1923 newInt16 = SwapShort( newInt16 );
1928 // When integer(s) are expected, read and convert the following
1929 // n * 4 bytes properly i.e. as a multivaluated strings
1930 // (each single value is separated fromthe next one by '\'
1931 // as usual for standard multivaluated filels
1932 // Elements with Value Multiplicity > 1
1933 // contain a set of integers (not a single one)
1934 else if( vr == "UL" || vr == "SL" )
1939 for (int i=0; i < nbInt; i++)
1945 newInt32 = ( val[4*i+0] & 0xFF )
1946 + (( val[4*i+1] & 0xFF ) << 8 )
1947 + (( val[4*i+2] & 0xFF ) << 16 )
1948 + (( val[4*i+3] & 0xFF ) << 24 );
1949 newInt32 = SwapLong( newInt32 );
1953 #ifdef GDCM_NO_ANSI_STRING_STREAM
1954 s << std::ends; // to avoid oddities on Solaris
1955 #endif //GDCM_NO_ANSI_STRING_STREAM
1959 return ((gdcmValEntry *)entry)->GetValue();
1963 * \brief Get the reverse transformed value of the header entry. The VR
1964 * value is used to define the reverse transformation to operate on
1966 * \warning NOT end user intended method !
1967 * @param entry Entry to reverse transform
1968 * @return Reverse transformed entry value
1970 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1972 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1974 std::string vr = entry->GetVR();
1975 std::vector<std::string> tokens;
1976 std::ostringstream s;
1978 if ( vr == "US" || vr == "SS" )
1982 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1983 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1984 for (unsigned int i=0; i<tokens.size(); i++)
1986 newInt16 = atoi(tokens[i].c_str());
1987 s << ( newInt16 & 0xFF )
1988 << (( newInt16 >> 8 ) & 0xFF );
1992 if ( vr == "UL" || vr == "SL")
1996 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1997 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1998 for (unsigned int i=0; i<tokens.size();i++)
2000 newInt32 = atoi(tokens[i].c_str());
2001 s << (char)( newInt32 & 0xFF )
2002 << (char)(( newInt32 >> 8 ) & 0xFF )
2003 << (char)(( newInt32 >> 16 ) & 0xFF )
2004 << (char)(( newInt32 >> 24 ) & 0xFF );
2009 #ifdef GDCM_NO_ANSI_STRING_STREAM
2010 s << std::ends; // to avoid oddities on Solaris
2011 #endif //GDCM_NO_ANSI_STRING_STREAM
2015 return ((gdcmValEntry *)entry)->GetValue();
2019 * \brief Skip a given Header Entry
2020 * \warning NOT end user intended method !
2021 * @param entry entry to skip
2023 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2025 SkipBytes(entry->GetLength());
2029 * \brief Skips to the begining of the next Header Entry
2030 * \warning NOT end user intended method !
2031 * @param entry entry to skip
2033 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2035 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2036 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2040 * \brief When the length of an element value is obviously wrong (because
2041 * the parser went Jabberwocky) one can hope improving things by
2042 * applying some heuristics.
2043 * @param entry entry to check
2044 * @param foundLength fist assumption about length
2046 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2047 uint32_t foundLength)
2049 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2050 if ( foundLength == 0xffffffff)
2055 uint16_t gr = entry->GetGroup();
2056 uint16_t el = entry->GetElement();
2058 if ( foundLength % 2)
2060 std::ostringstream s;
2061 s << "Warning : Tag with uneven length "
2063 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2064 dbg.Verbose(0, s.str().c_str());
2067 //////// Fix for some naughty General Electric images.
2068 // Allthough not recent many such GE corrupted images are still present
2069 // on Creatis hard disks. Hence this fix shall remain when such images
2070 // are no longer in user (we are talking a few years, here)...
2071 // Note: XMedCom probably uses such a trick since it is able to read
2072 // those pesky GE images ...
2073 if ( foundLength == 13)
2075 // Only happens for this length !
2076 if ( entry->GetGroup() != 0x0008
2077 || ( entry->GetElement() != 0x0070
2078 && entry->GetElement() != 0x0080 ) )
2081 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2085 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2086 // Occurence of such images is quite low (unless one leaves close to a
2087 // 'Leonardo' source. Hence, one might consider commenting out the
2088 // following fix on efficiency reasons.
2089 else if ( entry->GetGroup() == 0x0009
2090 && ( entry->GetElement() == 0x1113
2091 || entry->GetElement() == 0x1114 ) )
2094 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2097 else if ( entry->GetVR() == "SQ" )
2099 foundLength = 0; // ReadLength is unchanged
2102 //////// We encountered a 'delimiter' element i.e. a tag of the form
2103 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2104 // taken into account.
2105 else if( entry->GetGroup() == 0xfffe )
2107 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2108 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2109 // causes extra troubles...
2110 if( entry->GetElement() != 0x0000 )
2116 entry->SetUsableLength(foundLength);
2120 * \brief Apply some heuristics to predict whether the considered
2121 * element value contains/represents an integer or not.
2122 * @param entry The element value on which to apply the predicate.
2123 * @return The result of the heuristical predicate.
2125 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2127 uint16_t element = entry->GetElement();
2128 uint16_t group = entry->GetGroup();
2129 std::string vr = entry->GetVR();
2130 uint32_t length = entry->GetLength();
2132 // When we have some semantics on the element we just read, and if we
2133 // a priori know we are dealing with an integer, then we shall be
2134 // able to swap it's element value properly.
2135 if ( element == 0 ) // This is the group length of the group
2143 // Allthough this should never happen, still some images have a
2144 // corrupted group length [e.g. have a glance at offset x(8336) of
2145 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2146 // Since for dicom compliant and well behaved headers, the present
2147 // test is useless (and might even look a bit paranoid), when we
2148 // encounter such an ill-formed image, we simply display a warning
2149 // message and proceed on parsing (while crossing fingers).
2150 std::ostringstream s;
2151 int filePosition = ftell(Fp);
2152 s << "Erroneous Group Length element length on : (" \
2153 << std::hex << group << " , " << element
2154 << ") -before- position x(" << filePosition << ")"
2155 << "lgt : " << length;
2156 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2160 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2169 * \brief Find the Length till the next sequence delimiter
2170 * \warning NOT end user intended method !
2174 uint32_t gdcmDocument::FindDocEntryLengthOB()
2175 throw( gdcmFormatUnexpected )
2177 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2178 long positionOnEntry = ftell(Fp);
2179 bool foundSequenceDelimiter = false;
2180 uint32_t totalLength = 0;
2182 while ( !foundSequenceDelimiter )
2188 group = ReadInt16();
2191 catch ( gdcmFormatError )
2193 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2194 " group or element not present.");
2197 // We have to decount the group and element we just read
2200 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2202 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2203 "tag nor a Sequence delimiter tag.");
2204 fseek(Fp, positionOnEntry, SEEK_SET);
2205 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2206 "Neither an Item tag nor a Sequence "
2210 if ( elem == 0xe0dd )
2212 foundSequenceDelimiter = true;
2215 uint32_t itemLength = ReadInt32();
2216 // We add 4 bytes since we just read the ItemLength with ReadInt32
2217 totalLength += itemLength + 4;
2218 SkipBytes(itemLength);
2220 if ( foundSequenceDelimiter )
2225 fseek(Fp, positionOnEntry, SEEK_SET);
2230 * \brief Reads a supposed to be 16 Bits integer
2231 * (swaps it depending on processor endianity)
2232 * @return read value
2234 uint16_t gdcmDocument::ReadInt16()
2235 throw( gdcmFormatError )
2238 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2239 if ( item_read != 1 )
2243 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2245 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2252 * \brief Reads a supposed to be 32 Bits integer
2253 * (swaps it depending on processor endianity)
2254 * @return read value
2256 uint32_t gdcmDocument::ReadInt32()
2257 throw( gdcmFormatError )
2260 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2261 if ( item_read != 1 )
2265 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2267 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2274 * \brief skips bytes inside the source file
2275 * \warning NOT end user intended method !
2278 void gdcmDocument::SkipBytes(uint32_t nBytes)
2280 //FIXME don't dump the returned value
2281 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2285 * \brief Loads all the needed Dictionaries
2286 * \warning NOT end user intended method !
2288 void gdcmDocument::Initialise()
2290 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2295 * \brief Discover what the swap code is (among little endian, big endian,
2296 * bad little endian, bad big endian).
2298 * @return false when we are absolutely sure
2299 * it's neither ACR-NEMA nor DICOM
2300 * true when we hope ours assuptions are OK
2302 bool gdcmDocument::CheckSwap()
2304 // The only guaranted way of finding the swap code is to find a
2305 // group tag since we know it's length has to be of four bytes i.e.
2306 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2307 // occurs when we can't find such group...
2309 uint32_t x = 4; // x : for ntohs
2310 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2314 char deb[HEADER_LENGTH_TO_READ];
2316 // First, compare HostByteOrder and NetworkByteOrder in order to
2317 // determine if we shall need to swap bytes (i.e. the Endian type).
2318 if ( x == ntohs(x) )
2327 // The easiest case is the one of a DICOM header, since it possesses a
2328 // file preamble where it suffice to look for the string "DICM".
2329 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2330 (void)lgrLue; //FIXME not used
2332 char *entCur = deb + 128;
2333 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2335 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2337 // Next, determine the value representation (VR). Let's skip to the
2338 // first element (0002, 0000) and check there if we find "UL"
2339 // - or "OB" if the 1st one is (0002,0001) -,
2340 // in which case we (almost) know it is explicit VR.
2341 // WARNING: if it happens to be implicit VR then what we will read
2342 // is the length of the group. If this ascii representation of this
2343 // length happens to be "UL" then we shall believe it is explicit VR.
2344 // FIXME: in order to fix the above warning, we could read the next
2345 // element value (or a couple of elements values) in order to make
2346 // sure we are not commiting a big mistake.
2347 // We need to skip :
2348 // * the 128 bytes of File Preamble (often padded with zeroes),
2349 // * the 4 bytes of "DICM" string,
2350 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2351 // i.e. a total of 136 bytes.
2355 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2356 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2357 // *Implicit* VR. -and it is !-
2359 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2360 memcmp(entCur, "OB", (size_t)2) == 0 ||
2361 memcmp(entCur, "UI", (size_t)2) == 0 ||
2362 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2363 // when Write DCM *adds*
2365 // Use gdcmDocument::dicom_vr to test all the possibilities
2366 // instead of just checking for UL, OB and UI !? group 0000
2368 Filetype = gdcmExplicitVR;
2369 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2370 "explicit Value Representation");
2374 Filetype = gdcmImplicitVR;
2375 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2376 "not an explicit Value Representation");
2382 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2383 "HostByteOrder != NetworkByteOrder");
2388 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2389 "HostByteOrder = NetworkByteOrder");
2392 // Position the file position indicator at first tag (i.e.
2393 // after the file preamble and the "DICM" string).
2395 fseek (Fp, 132L, SEEK_SET);
2399 // Alas, this is not a DicomV3 file and whatever happens there is no file
2400 // preamble. We can reset the file position indicator to where the data
2401 // is (i.e. the beginning of the file).
2402 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2405 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2406 // By clean we mean that the length of the first tag is written down.
2407 // If this is the case and since the length of the first group HAS to be
2408 // four (bytes), then determining the proper swap code is straightforward.
2411 // We assume the array of char we are considering contains the binary
2412 // representation of a 32 bits integer. Hence the following dirty
2414 s32 = *((uint32_t *)(entCur));
2435 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2436 // It is time for despaired wild guesses.
2437 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2438 // i.e. the 'group length' element is not present :
2440 // check the supposed to be 'group number'
2441 // 0x0002 or 0x0004 or 0x0008
2442 // to determine ' SwapCode' value .
2443 // Only 0 or 4321 will be possible
2444 // (no oportunity to check for the formerly well known
2445 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2446 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2447 // the file IS NOT ACR-NEMA nor DICOM V3
2448 // Find a trick to tell it the caller...
2450 s16 = *((uint16_t *)(deb));
2467 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2468 "ACR/NEMA unfound swap info (Really hopeless !)");
2469 Filetype = gdcmUnknown;
2472 // Then the only info we have is the net2host one.
2482 * \brief Restore the unproperly loaded values i.e. the group, the element
2483 * and the dictionary entry depending on them.
2485 void gdcmDocument::SwitchSwapToBigEndian()
2487 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2488 "Switching to BigEndian mode.");
2489 if ( SwapCode == 0 )
2493 else if ( SwapCode == 4321 )
2497 else if ( SwapCode == 3412 )
2501 else if ( SwapCode == 2143 )
2508 * \brief during parsing, Header Elements too long are not loaded in memory
2511 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2517 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2519 MaxSizeLoadEntry = 0xffffffff;
2522 MaxSizeLoadEntry = newSize;
2527 * \brief Header Elements too long will not be printed
2528 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2531 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2533 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2538 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2540 MaxSizePrintEntry = 0xffffffff;
2543 MaxSizePrintEntry = newSize;
2549 * \brief Read the next tag but WITHOUT loading it's value
2550 * (read the 'Group Number', the 'Element Number',
2551 * gets the Dict Entry
2552 * gets the VR, gets the length, gets the offset value)
2553 * @return On succes the newly created DocEntry, NULL on failure.
2555 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2562 group = ReadInt16();
2565 catch ( gdcmFormatError e )
2567 // We reached the EOF (or an error occured) therefore
2568 // header parsing has to be considered as finished.
2573 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2574 FindDocEntryVR(newEntry);
2578 FindDocEntryLength(newEntry);
2580 catch ( gdcmFormatError e )
2588 newEntry->SetOffset(ftell(Fp));
2595 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2596 * in the TagHt dictionary.
2597 * @param group The generated tag must belong to this group.
2598 * @return The element of tag with given group which is fee.
2600 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2602 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2604 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2605 if (TagHT.count(key) == 0)
2614 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2615 * is placed at the beginning of a tag check whether this
2616 * tag is (TestGroup, TestElement).
2617 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2618 * is modified to point after the tag.
2619 * On failure (i.e. when the tag wasn't the expected tag
2620 * (TestGroup, TestElement) the internal file pointer
2621 * \ref gdcmDocument::Fp is restored to it's original position.
2622 * @param testGroup The expected group of the tag.
2623 * @param testElement The expected Element of the tag.
2624 * @return True on success, false otherwise.
2626 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2628 long positionOnEntry = ftell(Fp);
2629 long currentPosition = ftell(Fp); // On debugging purposes
2631 //// Read the Item Tag group and element, and make
2632 // sure they are what we expected:
2633 uint16_t itemTagGroup = ReadInt16();
2634 uint16_t itemTagElement = ReadInt16();
2635 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2637 std::ostringstream s;
2638 s << " We should have found tag (";
2639 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2640 s << " but instead we encountered tag (";
2641 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2643 s << " at address: " << (unsigned)currentPosition << std::endl;
2644 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2645 dbg.Verbose(0, s.str().c_str());
2646 fseek(Fp, positionOnEntry, SEEK_SET);
2654 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2655 * is placed at the beginning of a tag (TestGroup, TestElement),
2656 * read the length associated to the Tag.
2657 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2658 * is modified to point after the tag and it's length.
2659 * On failure (i.e. when the tag wasn't the expected tag
2660 * (TestGroup, TestElement) the internal file pointer
2661 * \ref gdcmDocument::Fp is restored to it's original position.
2662 * @param testGroup The expected group of the tag.
2663 * @param testElement The expected Element of the tag.
2664 * @return On success returns the length associated to the tag. On failure
2667 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2669 long positionOnEntry = ftell(Fp);
2670 (void)positionOnEntry;
2672 if ( !ReadTag(testGroup, testElement) )
2677 //// Then read the associated Item Length
2678 long currentPosition = ftell(Fp);
2679 uint32_t itemLength = ReadInt32();
2681 std::ostringstream s;
2682 s << "Basic Item Length is: "
2683 << itemLength << std::endl;
2684 s << " at address: " << (unsigned)currentPosition << std::endl;
2685 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2691 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2692 * No other way so 'skip' the Data
2695 void gdcmDocument::Parse7FE0 ()
2697 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2700 // Should warn user FIXME
2704 if ( IsImplicitVRLittleEndianTransferSyntax()
2705 || IsExplicitVRLittleEndianTransferSyntax()
2706 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2707 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2712 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2714 //// Read the Basic Offset Table Item Tag length...
2715 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2717 //// ... and then read length[s] itself[themselves]. We don't use
2718 // the values read (BTW what is the purpous of those lengths ?)
2719 if ( itemLength != 0 )
2721 // BTW, what is the purpous of those length anyhow !?
2722 char* basicOffsetTableItemValue = new char[itemLength + 1];
2723 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2725 for (unsigned int i=0; i < itemLength; i += 4 )
2727 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2728 std::ostringstream s;
2729 s << " Read one length: ";
2730 s << std::hex << individualLength << std::endl;
2731 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2733 delete[] basicOffsetTableItemValue;
2736 if ( ! IsRLELossLessTransferSyntax() )
2740 //// We then skip (not reading them) all the fragments of images:
2741 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2743 SkipBytes(itemLength);
2750 long rleSegmentLength[15], fragmentLength;
2752 // While we find some items:
2753 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2755 // Parse fragments of the current Fragment (Frame)
2756 //------------------ scanning (not reading) fragment pixels
2757 uint32_t nbRleSegments = ReadInt32();
2759 //// Reading RLE Segments Offset Table
2760 uint32_t rleSegmentOffsetTable[15];
2761 for(int k=1; k<=15; k++)
2763 ftellRes = ftell(Fp);
2764 rleSegmentOffsetTable[k] = ReadInt32();
2767 // skipping (not reading) RLE Segments
2768 if ( nbRleSegments > 1)
2770 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2772 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2773 - rleSegmentOffsetTable[k];
2774 ftellRes = ftell(Fp);
2775 SkipBytes(rleSegmentLength[k]);
2779 rleSegmentLength[nbRleSegments] = fragmentLength
2780 - rleSegmentOffsetTable[nbRleSegments];
2781 ftellRes = ftell(Fp);
2782 SkipBytes(rleSegmentLength[nbRleSegments]);
2785 // Make sure that at the end of the item we encounter a 'Sequence
2787 if ( !ReadTag(0xfffe, 0xe0dd) )
2789 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2790 dbg.Verbose(0, " at end of RLE item sequence");
2798 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2799 * \warning Does NOT work with ACR-NEMA files
2800 * \todo Find a trick to solve the pb (use RET fields ?)
2802 * @return true if 'smaller'
2804 bool gdcmDocument::operator<(gdcmDocument &document)
2807 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2808 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2820 s1 = GetEntryByNumber(0x0010,0x0020);
2821 s2 = document.GetEntryByNumber(0x0010,0x0020);
2832 // Study Instance UID
2833 s1 = GetEntryByNumber(0x0020,0x000d);
2834 s2 = document.GetEntryByNumber(0x0020,0x000d);
2845 // Serie Instance UID
2846 s1 = GetEntryByNumber(0x0020,0x000e);
2847 s2 = document.GetEntryByNumber(0x0020,0x000e);
2863 //-----------------------------------------------------------------------------