1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/08/31 14:24:47 $
7 Version: $Revision: 1.69 $
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;
592 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);
615 // We need to promote the gdcmDocEntry to a gdcmValEntry:
616 valEntry = new gdcmValEntry(currentEntry);
617 if (!RemoveEntry(currentEntry))
619 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
620 " of previous DocEntry failed.");
623 if ( !AddEntry(valEntry))
625 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
626 " promoted ValEntry failed.");
632 SetEntryByNumber(value, group, elem);
638 * \brief Modifies the value of a given Header Entry (Dicom Element)
639 * when it exists. Create it with the given value when unexistant.
640 * @param voidArea (binary) value to be set
641 * @param Group Group number of the Entry
642 * @param Elem Element number of the Entry
643 * \return pointer to the modified/created Header Entry (NULL when creation
646 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
653 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
656 a = NewBinEntryByNumber(group, elem);
662 b = new gdcmBinEntry(a);
664 b->SetVoidArea(voidArea);
666 SetEntryByNumber(voidArea, lgth, group, elem);
667 //b->SetVoidArea(voidArea); //what if b == 0 !!
674 * \brief Modifies the value of a given Header Entry (Dicom Element)
675 * when it exists. Create it when unexistant.
676 * @param Group Group number of the Entry
677 * @param Elem Element number of the Entry
678 * \return pointer to the modified/created SeqEntry (NULL when creation
681 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
686 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
689 a = NewSeqEntryByNumber(group, elem);
695 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
702 * \brief Set a new value if the invoked element exists
703 * Seems to be useless !!!
704 * @param value new element value
705 * @param group group number of the Entry
706 * @param elem element number of the Entry
709 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
710 uint16_t group, uint16_t elem )
712 SetEntryByNumber(value, group, elem);
717 //-----------------------------------------------------------------------------
721 * \brief Checks if a given Dicom Element exists within the H table
722 * @param group Group number of the searched Dicom Element
723 * @param element Element number of the searched Dicom Element
724 * @return number of occurences
726 int gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
728 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
729 return TagHT.count(key);
733 * \brief Searches within Header Entries (Dicom Elements) parsed with
734 * the public and private dictionaries
735 * for the element value of a given tag.
736 * \warning Don't use any longer : use GetPubEntryByName
737 * @param tagName name of the searched element.
738 * @return Corresponding element value when it exists,
739 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
741 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
743 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
749 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
753 * \brief Searches within Header Entries (Dicom Elements) parsed with
754 * the public and private dictionaries
755 * for the element value representation of a given tag.
757 * Obtaining the VR (Value Representation) might be needed by caller
758 * to convert the string typed content to caller's native type
759 * (think of C++ vs Python). The VR is actually of a higher level
760 * of semantics than just the native C++ type.
761 * @param tagName name of the searched element.
762 * @return Corresponding element value representation when it exists,
763 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
765 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
767 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
768 if( dictEntry == NULL)
773 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
774 dictEntry->GetElement());
775 return elem->GetVR();
780 * \brief Searches within Header Entries (Dicom Elements) parsed with
781 * the public and private dictionaries
782 * for the element value representation of a given tag.
783 * @param group Group number of the searched tag.
784 * @param element Element number of the searched tag.
785 * @return Corresponding element value representation when it exists,
786 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
788 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
790 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
791 /// \todo use map methods, instead of multimap JPR
792 if ( !TagHT.count(key))
797 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
801 * \brief Searches within Header Entries (Dicom Elements) parsed with
802 * the public and private dictionaries
803 * for the element value representation of a given tag..
805 * Obtaining the VR (Value Representation) might be needed by caller
806 * to convert the string typed content to caller's native type
807 * (think of C++ vs Python). The VR is actually of a higher level
808 * of semantics than just the native C++ type.
809 * @param group Group number of the searched tag.
810 * @param element Element number of the searched tag.
811 * @return Corresponding element value representation when it exists,
812 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
814 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
816 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
821 return elem->GetVR();
825 * \brief Searches within Header Entries (Dicom Elements) parsed with
826 * the public and private dictionaries
827 * for the value length of a given tag..
828 * @param group Group number of the searched tag.
829 * @param element Element number of the searched tag.
830 * @return Corresponding element length; -2 if not found
832 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
834 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
837 return -2; //magic number
839 return elem->GetLength();
842 * \brief Sets the value (string) of the Header Entry (Dicom Element)
843 * @param content string value of the Dicom Element
844 * @param tagName name of the searched Dicom Element.
845 * @return true when found
847 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
849 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
855 return SetEntryByNumber(content,dictEntry->GetGroup(),
856 dictEntry->GetElement());
860 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
861 * through it's (group, element) and modifies it's content with
863 * @param content new value (string) to substitute with
864 * @param group group number of the Dicom Element to modify
865 * @param element element number of the Dicom Element to modify
867 bool gdcmDocument::SetEntryByNumber(std::string const & content,
871 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
874 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
875 " ValEntry (try promotion first).");
878 // Non even content must be padded with a space (020H)...
879 std::string evenContent = content;
880 if( evenContent.length() % 2 )
882 evenContent += '\0'; // ... therefore we padd with (000H) .!?!
884 valEntry->SetValue(evenContent);
886 // Integers have a special treatement for their length:
887 gdcmVRKey vr = valEntry->GetVR();
888 if( vr == "US" || vr == "SS" )
890 valEntry->SetLength(2);
892 else if( vr == "UL" || vr == "SL" )
894 valEntry->SetLength(4);
898 valEntry->SetLength(evenContent.length());
905 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
906 * through it's (group, element) and modifies it's content with
908 * @param content new value (void *) to substitute with
909 * @param lgth new value length
910 * @param group group number of the Dicom Element to modify
911 * @param element element number of the Dicom Element to modify
913 bool gdcmDocument::SetEntryByNumber(void *content,
918 (void)lgth; //not used
919 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
920 if ( !TagHT.count(key))
925 /* Hope Binary field length is *never* wrong
926 if(lgth%2) // Non even length are padded with a space (020H).
929 //content = content + '\0'; // fing a trick to enlarge a binary field?
932 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
933 a->SetVoidArea(content);
934 //a->SetLength(lgth); // ???
940 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
941 * in the PubDocEntrySet of this instance
942 * through it's (group, element) and modifies it's length with
944 * \warning Use with extreme caution.
945 * @param l new length to substitute with
946 * @param group group number of the Entry to modify
947 * @param element element number of the Entry to modify
948 * @return true on success, false otherwise.
950 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
954 /// \todo use map methods, instead of multimap JPR
955 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
956 if ( !TagHT.count(key) )
962 l++; // length must be even
964 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
970 * \brief Gets (from Header) the offset of a 'non string' element value
971 * (LoadElementValues has already be executed)
972 * @param group group number of the Entry
973 * @param elem element number of the Entry
974 * @return File Offset of the Element Value
976 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
978 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
981 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
984 return entry->GetOffset();
988 * \brief Gets (from Header) a 'non string' element value
989 * (LoadElementValues has already be executed)
990 * @param group group number of the Entry
991 * @param elem element number of the Entry
992 * @return Pointer to the 'non string' area
994 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
996 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
999 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1002 return ((gdcmBinEntry *)entry)->GetVoidArea();
1006 * \brief Loads (from disk) the element content
1007 * when a string is not suitable
1008 * @param group group number of the Entry
1009 * @param elem element number of the Entry
1011 void *gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1013 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1018 size_t o =(size_t)docElement->GetOffset();
1019 fseek(Fp, o, SEEK_SET);
1020 size_t l = docElement->GetLength();
1021 char* a = new char[l];
1024 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1027 size_t l2 = fread(a, 1, l , Fp);
1033 /// \todo Drop any already existing void area! JPR
1034 SetEntryVoidAreaByNumber(a, group, elem);
1039 * \brief Loads (from disk) the element content
1040 * when a string is not suitable
1041 * @param element Entry whose voidArea is going to be loaded
1043 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1045 size_t o =(size_t)element->GetOffset();
1046 fseek(Fp, o, SEEK_SET);
1047 size_t l = element->GetLength();
1048 char* a = new char[l];
1051 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1054 element->SetVoidArea((void *)a);
1055 /// \todo check the result
1056 size_t l2 = fread(a, 1, l , Fp);
1067 * \brief Sets a 'non string' value to a given Dicom Element
1068 * @param area area containing the 'non string' value
1069 * @param group Group number of the searched Dicom Element
1070 * @param element Element number of the searched Dicom Element
1073 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1077 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1078 if ( !TagHT.count(key))
1083 // This was for multimap ?
1084 (( gdcmBinEntry *)( ((TagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1090 * \brief Update the entries with the shadow dictionary.
1091 * Only non even entries are analyzed
1093 void gdcmDocument::UpdateShaEntries()
1095 //gdcmDictEntry *entry;
1098 /// \todo TODO : still any use to explore recursively the whole structure?
1100 for(ListTag::iterator it=listEntries.begin();
1101 it!=listEntries.end();
1104 // Odd group => from public dictionary
1105 if((*it)->GetGroup()%2==0)
1108 // Peer group => search the corresponding dict entry
1110 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1114 if((*it)->IsImplicitVR())
1119 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1121 // Set the new entry and the new value
1122 (*it)->SetDictEntry(entry);
1123 CheckDocEntryVR(*it,vr);
1125 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1130 // Remove precedent value transformation
1131 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1138 * \brief Searches within the Header Entries for a Dicom Element of
1140 * @param tagName name of the searched Dicom Element.
1141 * @return Corresponding Dicom Element when it exists, and NULL
1144 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1146 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1152 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1156 * \brief retrieves a Dicom Element (the first one) using (group, element)
1157 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1158 * if you think it's NOT UNIQUE, check the count number
1159 * and use iterators to retrieve ALL the Dicoms Elements within
1160 * a given couple (group, element)
1161 * @param group Group number of the searched Dicom Element
1162 * @param element Element number of the searched Dicom Element
1165 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1168 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1169 if ( !TagHT.count(key))
1173 return TagHT.find(key)->second;
1177 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1178 * returns a result when the corresponding entry is of type
1180 * @return When present, the corresponding ValEntry.
1182 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1185 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1186 if ( !currentEntry )
1190 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1194 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1200 * \brief Loads the element while preserving the current
1201 * underlying file position indicator as opposed to
1202 * to LoadDocEntry that modifies it.
1203 * @param entry Header Entry whose value shall be loaded.
1206 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1208 long PositionOnEntry = ftell(Fp);
1209 LoadDocEntry(entry);
1210 fseek(Fp, PositionOnEntry, SEEK_SET);
1214 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1216 * @return The properly swaped 32 bits integer.
1218 uint32_t gdcmDocument::SwapLong(uint32_t a)
1225 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1226 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1230 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1234 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1237 //std::cout << "swapCode= " << SwapCode << std::endl;
1238 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1245 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1247 * @return The properly unswaped 32 bits integer.
1249 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1255 * \brief Swaps the bytes so they agree with the processor order
1256 * @return The properly swaped 16 bits integer.
1258 uint16_t gdcmDocument::SwapShort(uint16_t a)
1260 if ( SwapCode == 4321 || SwapCode == 2143 )
1262 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1268 * \brief Unswaps the bytes so they agree with the processor order
1269 * @return The properly unswaped 16 bits integer.
1271 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1273 return SwapShort(a);
1276 //-----------------------------------------------------------------------------
1280 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1281 * @return length of the parsed set.
1284 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1289 gdcmDocEntry *newDocEntry = 0;
1290 gdcmValEntry *newValEntry = 0;
1291 unsigned long l = 0;
1293 int depth = set->GetDepthLevel();
1296 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1300 newDocEntry = ReadNextDocEntry( );
1306 gdcmVRKey vr = newDocEntry->GetVR();
1310 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1313 newValEntry = new gdcmValEntry(newDocEntry->GetDictEntry());
1314 newValEntry->Copy(newDocEntry);
1315 newValEntry->SetDepthLevel(depth);
1316 set->AddEntry(newValEntry);
1317 LoadDocEntry(newValEntry);
1318 if (newValEntry->IsItemDelimitor())
1322 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1329 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1331 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1332 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1333 "nor BinEntry. Probably unknown VR.");
1336 ////// BinEntry or UNKOWN VR:
1337 gdcmBinEntry *bn = new gdcmBinEntry(newDocEntry->GetDictEntry());
1338 bn->Copy(newDocEntry);
1343 if (newDocEntry->GetGroup() == 0x7fe0 &&
1344 newDocEntry->GetElement() == 0x0010 )
1346 if (newDocEntry->GetReadLength()==0xffffffff)
1348 // Broken US.3405.1.dcm
1349 Parse7FE0(); // to skip the pixels
1350 // (multipart JPEG/RLE are trouble makers)
1354 SkipToNextDocEntry(newDocEntry);
1355 l = newDocEntry->GetFullLength();
1360 // to be sure we are at the beginning
1361 SkipToNextDocEntry(newDocEntry);
1362 l = newDocEntry->GetFullLength();
1368 l = newDocEntry->GetReadLength();
1369 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1371 if ( l == 0xffffffff )
1380 // no other way to create it ...
1381 gdcmSeqEntry *sq = new gdcmSeqEntry(newDocEntry->GetDictEntry(),
1382 set->GetDepthLevel());
1383 sq->Copy(newDocEntry);
1384 sq->SetDelimitorMode(delim_mode);
1385 sq->SetDepthLevel(depth);
1388 { // Don't try to parse zero-length sequences
1389 long lgt = ParseSQ( sq,
1390 newDocEntry->GetOffset(),
1392 (void)lgt; //not used...
1395 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1402 return l; // Probably useless
1406 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1407 * @return parsed length for this level
1409 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1410 long offset, long l_max, bool delim_mode)
1412 int SQItemNumber = 0;
1414 //int depth = set->GetDepthLevel();
1415 //(void)depth; //not used
1419 gdcmDocEntry *newDocEntry = ReadNextDocEntry();
1422 // FIXME Should warn user
1427 if ( newDocEntry->IsSequenceDelimitor() )
1429 set->SetSequenceDelimitationItem( newDocEntry );
1433 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1438 gdcmSQItem *itemSQ = new gdcmSQItem(set->GetDepthLevel());
1439 itemSQ->AddEntry(newDocEntry);
1440 unsigned int l = newDocEntry->GetReadLength();
1442 if ( l == 0xffffffff )
1451 int lgr = ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1452 (void)lgr; //FIXME not used
1454 set->AddEntry(itemSQ, SQItemNumber);
1456 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1462 int lgth = ftell(Fp) - offset;
1467 * \brief Loads the element content if its length doesn't exceed
1468 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1469 * @param entry Header Entry (Dicom Element) to be dealt with
1471 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1474 uint16_t group = entry->GetGroup();
1475 std::string vr = entry->GetVR();
1476 uint32_t length = entry->GetLength();
1478 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1480 // A SeQuence "contains" a set of Elements.
1481 // (fffe e000) tells us an Element is beginning
1482 // (fffe e00d) tells us an Element just ended
1483 // (fffe e0dd) tells us the current SeQuence just ended
1484 if( group == 0xfffe )
1486 // NO more value field for SQ !
1490 // When the length is zero things are easy:
1493 ((gdcmValEntry *)entry)->SetValue("");
1497 // The elements whose length is bigger than the specified upper bound
1498 // are not loaded. Instead we leave a short notice of the offset of
1499 // the element content and it's length.
1501 std::ostringstream s;
1502 if (length > MaxSizeLoadEntry)
1504 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1506 s << "gdcm::NotLoaded (BinEntry)";
1507 s << " Address:" << (long)entry->GetOffset();
1508 s << " Length:" << entry->GetLength();
1509 s << " x(" << std::hex << entry->GetLength() << ")";
1510 binEntryPtr->SetValue(s.str());
1512 // to be sure we are at the end of the value ...
1513 fseek(Fp, (long)entry->GetOffset()+(long)entry->GetLength(), SEEK_SET);
1514 // Following return introduced by JPR on version 1.25. Since the
1515 // treatement of a ValEntry is never executed (doh!) this means
1516 // we were lucky up to now because we NEVER encountered a ValEntry
1517 // whose length was bigger thant MaxSizeLoadEntry !? I can't believe
1518 // this could ever work...
1519 return; //FIXME FIXME FIXME FIXME JPR ????
1521 // Be carefull : a BinEntry IS_A ValEntry ...
1522 if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1524 s << "gdcm::NotLoaded. (ValEntry)";
1525 s << " Address:" << (long)entry->GetOffset();
1526 s << " Length:" << entry->GetLength();
1527 s << " x(" << std::hex << entry->GetLength() << ")";
1528 valEntryPtr->SetValue(s.str());
1530 // to be sure we are at the end of the value ...
1531 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1536 // When we find a BinEntry not very much can be done :
1537 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1540 LoadEntryVoidArea(binEntryPtr);
1541 s << "gdcm::Loaded (BinEntry)";
1542 binEntryPtr->SetValue(s.str());
1546 /// \todo Any compacter code suggested (?)
1547 if ( IsDocEntryAnInteger(entry) )
1550 //std::ostringstream s; //shadow previous declaration
1552 // When short integer(s) are expected, read and convert the following
1553 // n *two characters properly i.e. consider them as short integers as
1554 // opposed to strings.
1555 // Elements with Value Multiplicity > 1
1556 // contain a set of integers (not a single one)
1557 if (vr == "US" || vr == "SS")
1560 NewInt = ReadInt16();
1564 for (int i=1; i < nbInt; i++)
1567 NewInt = ReadInt16();
1572 // See above comment on multiple integers (mutatis mutandis).
1573 else if (vr == "UL" || vr == "SL")
1576 NewInt = ReadInt32();
1580 for (int i=1; i < nbInt; i++)
1583 NewInt = ReadInt32();
1588 #ifdef GDCM_NO_ANSI_STRING_STREAM
1589 s << std::ends; // to avoid oddities on Solaris
1590 #endif //GDCM_NO_ANSI_STRING_STREAM
1592 ((gdcmValEntry *)entry)->SetValue(s.str());
1596 // We need an additional byte for storing \0 that is not on disk
1597 //std::string newValue(length,0);
1598 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1599 //rah !! I can't believe it could work, normally this is a const char* !!!
1600 char *str = new char[length+1];
1601 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1603 std::string newValue = str;
1605 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1607 if ( item_read != 1 )
1609 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1610 "unread element value");
1611 valEntry->SetValue("gdcm::UnRead");
1617 // Because of correspondance with the VR dic
1618 valEntry->SetValue(newValue);
1622 valEntry->SetValue(newValue);
1627 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1628 "Should have a ValEntry, here !");
1634 * \brief Find the value Length of the passed Header Entry
1635 * @param entry Header Entry whose length of the value shall be loaded.
1637 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1638 throw ( gdcmFormatError )
1640 uint16_t element = entry->GetElement();
1641 std::string vr = entry->GetVR();
1644 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1646 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1648 // The following reserved two bytes (see PS 3.5-2001, section
1649 // 7.1.2 Data element structure with explicit vr p27) must be
1650 // skipped before proceeding on reading the length on 4 bytes.
1651 fseek(Fp, 2L, SEEK_CUR);
1652 uint32_t length32 = ReadInt32();
1654 if ( vr == "OB" && length32 == 0xffffffff )
1659 lengthOB = FindDocEntryLengthOB();
1661 catch ( gdcmFormatUnexpected )
1663 // Computing the length failed (this happens with broken
1664 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1665 // chance to get the pixels by deciding the element goes
1666 // until the end of the file. Hence we artificially fix the
1667 // the length and proceed.
1668 long currentPosition = ftell(Fp);
1669 fseek(Fp,0L,SEEK_END);
1670 long lengthUntilEOF = ftell(Fp) - currentPosition;
1671 fseek(Fp, currentPosition, SEEK_SET);
1672 entry->SetLength(lengthUntilEOF);
1675 entry->SetLength(lengthOB);
1678 FixDocEntryFoundLength(entry, length32);
1682 // Length is encoded on 2 bytes.
1683 length16 = ReadInt16();
1685 // We can tell the current file is encoded in big endian (like
1686 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1687 // and it's value is the one of the encoding of a big endian file.
1688 // In order to deal with such big endian encoded files, we have
1689 // (at least) two strategies:
1690 // * when we load the "Transfer Syntax" tag with value of big endian
1691 // encoding, we raise the proper flags. Then we wait for the end
1692 // of the META group (0x0002) among which is "Transfer Syntax",
1693 // before switching the swap code to big endian. We have to postpone
1694 // the switching of the swap code since the META group is fully encoded
1695 // in little endian, and big endian coding only starts at the next
1696 // group. The corresponding code can be hard to analyse and adds
1697 // many additional unnecessary tests for regular tags.
1698 // * the second strategy consists in waiting for trouble, that shall
1699 // appear when we find the first group with big endian encoding. This
1700 // is easy to detect since the length of a "Group Length" tag (the
1701 // ones with zero as element number) has to be of 4 (0x0004). When we
1702 // encounter 1024 (0x0400) chances are the encoding changed and we
1703 // found a group with big endian encoding.
1704 // We shall use this second strategy. In order to make sure that we
1705 // can interpret the presence of an apparently big endian encoded
1706 // length of a "Group Length" without committing a big mistake, we
1707 // add an additional check: we look in the already parsed elements
1708 // for the presence of a "Transfer Syntax" whose value has to be "big
1709 // endian encoding". When this is the case, chances are we have got our
1710 // hands on a big endian encoded file: we switch the swap code to
1711 // big endian and proceed...
1712 if ( element == 0x0000 && length16 == 0x0400 )
1714 if ( !IsExplicitVRBigEndianTransferSyntax() )
1716 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1717 " not explicit VR." );
1721 SwitchSwapToBigEndian();
1722 // Restore the unproperly loaded values i.e. the group, the element
1723 // and the dictionary entry depending on them.
1724 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1725 uint16_t correctElem = SwapShort( entry->GetElement() );
1726 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1730 // This correct tag is not in the dictionary. Create a new one.
1731 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1733 // FIXME this can create a memory leaks on the old entry that be
1734 // left unreferenced.
1735 entry->SetDictEntry( newTag );
1738 // Heuristic: well, some files are really ill-formed.
1739 if ( length16 == 0xffff)
1741 // 0xffff means that we deal with 'Unknown Length' Sequence
1744 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1749 // Either implicit VR or a non DICOM conformal (see note below) explicit
1750 // VR that ommited the VR of (at least) this element. Farts happen.
1751 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1752 // on Data elements "Implicit and Explicit VR Data Elements shall
1753 // not coexist in a Data Set and Data Sets nested within it".]
1754 // Length is on 4 bytes.
1756 FixDocEntryFoundLength( entry, ReadInt32() );
1762 * \brief Find the Value Representation of the current Dicom Element.
1765 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1767 if ( Filetype != gdcmExplicitVR )
1774 long positionOnEntry = ftell(Fp);
1775 // Warning: we believe this is explicit VR (Value Representation) because
1776 // we used a heuristic that found "UL" in the first tag. Alas this
1777 // doesn't guarantee that all the tags will be in explicit VR. In some
1778 // cases (see e-film filtered files) one finds implicit VR tags mixed
1779 // within an explicit VR file. Hence we make sure the present tag
1780 // is in explicit VR and try to fix things if it happens not to be
1783 fread (vr, (size_t)2,(size_t)1, Fp);
1786 if( !CheckDocEntryVR(entry, vr) )
1788 fseek(Fp, positionOnEntry, SEEK_SET);
1789 // When this element is known in the dictionary we shall use, e.g. for
1790 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1791 // dictionary entry. Still we have to flag the element as implicit since
1792 // we know now our assumption on expliciteness is not furfilled.
1794 if ( entry->IsVRUnknown() )
1796 entry->SetVR("Implicit");
1798 entry->SetImplicitVR();
1803 * \brief Check the correspondance between the VR of the header entry
1804 * and the taken VR. If they are different, the header entry is
1805 * updated with the new VR.
1806 * @param entry Header Entry to check
1807 * @param vr Dicom Value Representation
1808 * @return false if the VR is incorrect of if the VR isn't referenced
1809 * otherwise, it returns true
1811 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1813 char msg[100]; // for sprintf
1814 bool realExplicit = true;
1816 // Assume we are reading a falsely explicit VR file i.e. we reached
1817 // a tag where we expect reading a VR but are in fact we read the
1818 // first to bytes of the length. Then we will interogate (through find)
1819 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1820 // both GCC and VC++ implementations of the STL map. Hence when the
1821 // expected VR read happens to be non-ascii characters we consider
1822 // we hit falsely explicit VR tag.
1824 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1826 realExplicit = false;
1829 // CLEANME searching the dicom_vr at each occurence is expensive.
1830 // PostPone this test in an optional integrity check at the end
1831 // of parsing or only in debug mode.
1832 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1834 realExplicit = false;
1837 if ( !realExplicit )
1839 // We thought this was explicit VR, but we end up with an
1840 // implicit VR tag. Let's backtrack.
1841 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1842 entry->GetGroup(), entry->GetElement());
1843 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1845 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1847 // Group length is UL !
1848 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1849 entry->GetGroup(), entry->GetElement(),
1850 "UL", "FIXME", "Group Length");
1851 entry->SetDictEntry( newEntry );
1856 if ( entry->IsVRUnknown() )
1858 // When not a dictionary entry, we can safely overwrite the VR.
1859 if( entry->GetElement() == 0x0000 )
1861 // Group length is UL !
1869 else if ( entry->GetVR() != vr )
1871 // The VR present in the file and the dictionary disagree. We assume
1872 // the file writer knew best and use the VR of the file. Since it would
1873 // be unwise to overwrite the VR of a dictionary (since it would
1874 // compromise it's next user), we need to clone the actual DictEntry
1875 // and change the VR for the read one.
1876 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1877 entry->GetGroup(), entry->GetElement(),
1878 vr, "FIXME", entry->GetName());
1879 entry->SetDictEntry(newEntry);
1886 * \brief Get the transformed value of the header entry. The VR value
1887 * is used to define the transformation to operate on the value
1888 * \warning NOT end user intended method !
1889 * @param entry entry to tranform
1890 * @return Transformed entry value
1892 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1894 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1896 std::string val = ((gdcmValEntry *)entry)->GetValue();
1897 std::string vr = entry->GetVR();
1898 uint32_t length = entry->GetLength();
1899 std::ostringstream s;
1902 // When short integer(s) are expected, read and convert the following
1903 // n * 2 bytes properly i.e. as a multivaluated strings
1904 // (each single value is separated fromthe next one by '\'
1905 // as usual for standard multivaluated filels
1906 // Elements with Value Multiplicity > 1
1907 // contain a set of short integers (not a single one)
1909 if( vr == "US" || vr == "SS" )
1914 for (int i=0; i < nbInt; i++)
1920 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1921 newInt16 = SwapShort( newInt16 );
1926 // When integer(s) are expected, read and convert the following
1927 // n * 4 bytes properly i.e. as a multivaluated strings
1928 // (each single value is separated fromthe next one by '\'
1929 // as usual for standard multivaluated filels
1930 // Elements with Value Multiplicity > 1
1931 // contain a set of integers (not a single one)
1932 else if( vr == "UL" || vr == "SL" )
1937 for (int i=0; i < nbInt; i++)
1943 newInt32 = ( val[4*i+0] & 0xFF )
1944 + (( val[4*i+1] & 0xFF ) << 8 )
1945 + (( val[4*i+2] & 0xFF ) << 16 )
1946 + (( val[4*i+3] & 0xFF ) << 24 );
1947 newInt32 = SwapLong( newInt32 );
1951 #ifdef GDCM_NO_ANSI_STRING_STREAM
1952 s << std::ends; // to avoid oddities on Solaris
1953 #endif //GDCM_NO_ANSI_STRING_STREAM
1957 return ((gdcmValEntry *)entry)->GetValue();
1961 * \brief Get the reverse transformed value of the header entry. The VR
1962 * value is used to define the reverse transformation to operate on
1964 * \warning NOT end user intended method !
1965 * @param entry Entry to reverse transform
1966 * @return Reverse transformed entry value
1968 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1970 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1972 std::string vr = entry->GetVR();
1973 std::vector<std::string> tokens;
1974 std::ostringstream s;
1976 if ( vr == "US" || vr == "SS" )
1980 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1981 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1982 for (unsigned int i=0; i<tokens.size(); i++)
1984 newInt16 = atoi(tokens[i].c_str());
1985 s << ( newInt16 & 0xFF )
1986 << (( newInt16 >> 8 ) & 0xFF );
1990 if ( vr == "UL" || vr == "SL")
1994 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1995 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1996 for (unsigned int i=0; i<tokens.size();i++)
1998 newInt32 = atoi(tokens[i].c_str());
1999 s << (char)( newInt32 & 0xFF )
2000 << (char)(( newInt32 >> 8 ) & 0xFF )
2001 << (char)(( newInt32 >> 16 ) & 0xFF )
2002 << (char)(( newInt32 >> 24 ) & 0xFF );
2007 #ifdef GDCM_NO_ANSI_STRING_STREAM
2008 s << std::ends; // to avoid oddities on Solaris
2009 #endif //GDCM_NO_ANSI_STRING_STREAM
2013 return ((gdcmValEntry *)entry)->GetValue();
2017 * \brief Skip a given Header Entry
2018 * \warning NOT end user intended method !
2019 * @param entry entry to skip
2021 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2023 SkipBytes(entry->GetLength());
2027 * \brief Skips to the begining of the next Header Entry
2028 * \warning NOT end user intended method !
2029 * @param entry entry to skip
2031 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2033 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2034 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2038 * \brief When the length of an element value is obviously wrong (because
2039 * the parser went Jabberwocky) one can hope improving things by
2040 * applying some heuristics.
2041 * @param entry entry to check
2042 * @param foundLength fist assumption about length
2044 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2045 uint32_t foundLength)
2047 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2048 if ( foundLength == 0xffffffff)
2053 uint16_t gr = entry->GetGroup();
2054 uint16_t el = entry->GetElement();
2056 if ( foundLength % 2)
2058 std::ostringstream s;
2059 s << "Warning : Tag with uneven length "
2061 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2062 dbg.Verbose(0, s.str().c_str());
2065 //////// Fix for some naughty General Electric images.
2066 // Allthough not recent many such GE corrupted images are still present
2067 // on Creatis hard disks. Hence this fix shall remain when such images
2068 // are no longer in user (we are talking a few years, here)...
2069 // Note: XMedCom probably uses such a trick since it is able to read
2070 // those pesky GE images ...
2071 if ( foundLength == 13)
2073 // Only happens for this length !
2074 if ( entry->GetGroup() != 0x0008
2075 || ( entry->GetElement() != 0x0070
2076 && entry->GetElement() != 0x0080 ) )
2079 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2083 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2084 // Occurence of such images is quite low (unless one leaves close to a
2085 // 'Leonardo' source. Hence, one might consider commenting out the
2086 // following fix on efficiency reasons.
2087 else if ( entry->GetGroup() == 0x0009
2088 && ( entry->GetElement() == 0x1113
2089 || entry->GetElement() == 0x1114 ) )
2092 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2095 else if ( entry->GetVR() == "SQ" )
2097 foundLength = 0; // ReadLength is unchanged
2100 //////// We encountered a 'delimiter' element i.e. a tag of the form
2101 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2102 // taken into account.
2103 else if( entry->GetGroup() == 0xfffe )
2105 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2106 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2107 // causes extra troubles...
2108 if( entry->GetElement() != 0x0000 )
2114 entry->SetUsableLength(foundLength);
2118 * \brief Apply some heuristics to predict whether the considered
2119 * element value contains/represents an integer or not.
2120 * @param entry The element value on which to apply the predicate.
2121 * @return The result of the heuristical predicate.
2123 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2125 uint16_t element = entry->GetElement();
2126 uint16_t group = entry->GetGroup();
2127 std::string vr = entry->GetVR();
2128 uint32_t length = entry->GetLength();
2130 // When we have some semantics on the element we just read, and if we
2131 // a priori know we are dealing with an integer, then we shall be
2132 // able to swap it's element value properly.
2133 if ( element == 0 ) // This is the group length of the group
2141 // Allthough this should never happen, still some images have a
2142 // corrupted group length [e.g. have a glance at offset x(8336) of
2143 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2144 // Since for dicom compliant and well behaved headers, the present
2145 // test is useless (and might even look a bit paranoid), when we
2146 // encounter such an ill-formed image, we simply display a warning
2147 // message and proceed on parsing (while crossing fingers).
2148 std::ostringstream s;
2149 int filePosition = ftell(Fp);
2150 s << "Erroneous Group Length element length on : (" \
2151 << std::hex << group << " , " << element
2152 << ") -before- position x(" << filePosition << ")"
2153 << "lgt : " << length;
2154 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2158 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2167 * \brief Find the Length till the next sequence delimiter
2168 * \warning NOT end user intended method !
2172 uint32_t gdcmDocument::FindDocEntryLengthOB()
2173 throw( gdcmFormatUnexpected )
2175 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2176 long positionOnEntry = ftell(Fp);
2177 bool foundSequenceDelimiter = false;
2178 uint32_t totalLength = 0;
2180 while ( !foundSequenceDelimiter )
2186 group = ReadInt16();
2189 catch ( gdcmFormatError )
2191 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2192 " group or element not present.");
2195 // We have to decount the group and element we just read
2198 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2200 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2201 "tag nor a Sequence delimiter tag.");
2202 fseek(Fp, positionOnEntry, SEEK_SET);
2203 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2204 "Neither an Item tag nor a Sequence "
2208 if ( elem == 0xe0dd )
2210 foundSequenceDelimiter = true;
2213 uint32_t itemLength = ReadInt32();
2214 // We add 4 bytes since we just read the ItemLength with ReadInt32
2215 totalLength += itemLength + 4;
2216 SkipBytes(itemLength);
2218 if ( foundSequenceDelimiter )
2223 fseek(Fp, positionOnEntry, SEEK_SET);
2228 * \brief Reads a supposed to be 16 Bits integer
2229 * (swaps it depending on processor endianity)
2230 * @return read value
2232 uint16_t gdcmDocument::ReadInt16()
2233 throw( gdcmFormatError )
2236 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2237 if ( item_read != 1 )
2241 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2243 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2250 * \brief Reads a supposed to be 32 Bits integer
2251 * (swaps it depending on processor endianity)
2252 * @return read value
2254 uint32_t gdcmDocument::ReadInt32()
2255 throw( gdcmFormatError )
2258 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2259 if ( item_read != 1 )
2263 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2265 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2272 * \brief skips bytes inside the source file
2273 * \warning NOT end user intended method !
2276 void gdcmDocument::SkipBytes(uint32_t nBytes)
2278 //FIXME don't dump the returned value
2279 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2283 * \brief Loads all the needed Dictionaries
2284 * \warning NOT end user intended method !
2286 void gdcmDocument::Initialise()
2288 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2293 * \brief Discover what the swap code is (among little endian, big endian,
2294 * bad little endian, bad big endian).
2296 * @return false when we are absolutely sure
2297 * it's neither ACR-NEMA nor DICOM
2298 * true when we hope ours assuptions are OK
2300 bool gdcmDocument::CheckSwap()
2302 // The only guaranted way of finding the swap code is to find a
2303 // group tag since we know it's length has to be of four bytes i.e.
2304 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2305 // occurs when we can't find such group...
2307 uint32_t x = 4; // x : for ntohs
2308 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2312 char deb[HEADER_LENGTH_TO_READ];
2314 // First, compare HostByteOrder and NetworkByteOrder in order to
2315 // determine if we shall need to swap bytes (i.e. the Endian type).
2316 if ( x == ntohs(x) )
2325 // The easiest case is the one of a DICOM header, since it possesses a
2326 // file preamble where it suffice to look for the string "DICM".
2327 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2328 (void)lgrLue; //FIXME not used
2330 char *entCur = deb + 128;
2331 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2333 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2335 // Next, determine the value representation (VR). Let's skip to the
2336 // first element (0002, 0000) and check there if we find "UL"
2337 // - or "OB" if the 1st one is (0002,0001) -,
2338 // in which case we (almost) know it is explicit VR.
2339 // WARNING: if it happens to be implicit VR then what we will read
2340 // is the length of the group. If this ascii representation of this
2341 // length happens to be "UL" then we shall believe it is explicit VR.
2342 // FIXME: in order to fix the above warning, we could read the next
2343 // element value (or a couple of elements values) in order to make
2344 // sure we are not commiting a big mistake.
2345 // We need to skip :
2346 // * the 128 bytes of File Preamble (often padded with zeroes),
2347 // * the 4 bytes of "DICM" string,
2348 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2349 // i.e. a total of 136 bytes.
2353 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2354 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2355 // *Implicit* VR. -and it is !-
2357 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2358 memcmp(entCur, "OB", (size_t)2) == 0 ||
2359 memcmp(entCur, "UI", (size_t)2) == 0 ||
2360 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2361 // when Write DCM *adds*
2363 // Use gdcmDocument::dicom_vr to test all the possibilities
2364 // instead of just checking for UL, OB and UI !? group 0000
2366 Filetype = gdcmExplicitVR;
2367 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2368 "explicit Value Representation");
2372 Filetype = gdcmImplicitVR;
2373 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2374 "not an explicit Value Representation");
2380 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2381 "HostByteOrder != NetworkByteOrder");
2386 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2387 "HostByteOrder = NetworkByteOrder");
2390 // Position the file position indicator at first tag (i.e.
2391 // after the file preamble and the "DICM" string).
2393 fseek (Fp, 132L, SEEK_SET);
2397 // Alas, this is not a DicomV3 file and whatever happens there is no file
2398 // preamble. We can reset the file position indicator to where the data
2399 // is (i.e. the beginning of the file).
2400 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2403 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2404 // By clean we mean that the length of the first tag is written down.
2405 // If this is the case and since the length of the first group HAS to be
2406 // four (bytes), then determining the proper swap code is straightforward.
2409 // We assume the array of char we are considering contains the binary
2410 // representation of a 32 bits integer. Hence the following dirty
2412 s32 = *((uint32_t *)(entCur));
2433 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2434 // It is time for despaired wild guesses.
2435 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2436 // i.e. the 'group length' element is not present :
2438 // check the supposed to be 'group number'
2439 // 0x0002 or 0x0004 or 0x0008
2440 // to determine ' SwapCode' value .
2441 // Only 0 or 4321 will be possible
2442 // (no oportunity to check for the formerly well known
2443 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2444 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2445 // the file IS NOT ACR-NEMA nor DICOM V3
2446 // Find a trick to tell it the caller...
2448 s16 = *((uint16_t *)(deb));
2465 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2466 "ACR/NEMA unfound swap info (Really hopeless !)");
2467 Filetype = gdcmUnknown;
2470 // Then the only info we have is the net2host one.
2480 * \brief Restore the unproperly loaded values i.e. the group, the element
2481 * and the dictionary entry depending on them.
2483 void gdcmDocument::SwitchSwapToBigEndian()
2485 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2486 "Switching to BigEndian mode.");
2487 if ( SwapCode == 0 )
2491 else if ( SwapCode == 4321 )
2495 else if ( SwapCode == 3412 )
2499 else if ( SwapCode == 2143 )
2506 * \brief during parsing, Header Elements too long are not loaded in memory
2509 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2515 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2517 MaxSizeLoadEntry = 0xffffffff;
2520 MaxSizeLoadEntry = newSize;
2525 * \brief Header Elements too long will not be printed
2526 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2529 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2531 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2536 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2538 MaxSizePrintEntry = 0xffffffff;
2541 MaxSizePrintEntry = newSize;
2547 * \brief Read the next tag but WITHOUT loading it's value
2548 * (read the 'Group Number', the 'Element Number',
2549 * gets the Dict Entry
2550 * gets the VR, gets the length, gets the offset value)
2551 * @return On succes the newly created DocEntry, NULL on failure.
2553 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2560 group = ReadInt16();
2563 catch ( gdcmFormatError e )
2565 // We reached the EOF (or an error occured) therefore
2566 // header parsing has to be considered as finished.
2571 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2572 FindDocEntryVR(newEntry);
2576 FindDocEntryLength(newEntry);
2578 catch ( gdcmFormatError e )
2586 newEntry->SetOffset(ftell(Fp));
2593 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2594 * in the TagHt dictionary.
2595 * @param group The generated tag must belong to this group.
2596 * @return The element of tag with given group which is fee.
2598 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2600 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2602 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2603 if (TagHT.count(key) == 0)
2612 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2613 * is placed at the beginning of a tag check whether this
2614 * tag is (TestGroup, TestElement).
2615 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2616 * is modified to point after the tag.
2617 * On failure (i.e. when the tag wasn't the expected tag
2618 * (TestGroup, TestElement) the internal file pointer
2619 * \ref gdcmDocument::Fp is restored to it's original position.
2620 * @param testGroup The expected group of the tag.
2621 * @param testElement The expected Element of the tag.
2622 * @return True on success, false otherwise.
2624 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2626 long positionOnEntry = ftell(Fp);
2627 long currentPosition = ftell(Fp); // On debugging purposes
2629 //// Read the Item Tag group and element, and make
2630 // sure they are what we expected:
2631 uint16_t itemTagGroup = ReadInt16();
2632 uint16_t itemTagElement = ReadInt16();
2633 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2635 std::ostringstream s;
2636 s << " We should have found tag (";
2637 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2638 s << " but instead we encountered tag (";
2639 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2641 s << " at address: " << (unsigned)currentPosition << std::endl;
2642 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2643 dbg.Verbose(0, s.str().c_str());
2644 fseek(Fp, positionOnEntry, SEEK_SET);
2652 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2653 * is placed at the beginning of a tag (TestGroup, TestElement),
2654 * read the length associated to the Tag.
2655 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2656 * is modified to point after the tag and it's length.
2657 * On failure (i.e. when the tag wasn't the expected tag
2658 * (TestGroup, TestElement) the internal file pointer
2659 * \ref gdcmDocument::Fp is restored to it's original position.
2660 * @param testGroup The expected group of the tag.
2661 * @param testElement The expected Element of the tag.
2662 * @return On success returns the length associated to the tag. On failure
2665 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2667 long positionOnEntry = ftell(Fp);
2668 (void)positionOnEntry;
2670 if ( !ReadTag(testGroup, testElement) )
2675 //// Then read the associated Item Length
2676 long currentPosition = ftell(Fp);
2677 uint32_t itemLength = ReadInt32();
2679 std::ostringstream s;
2680 s << "Basic Item Length is: "
2681 << itemLength << std::endl;
2682 s << " at address: " << (unsigned)currentPosition << std::endl;
2683 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2689 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2690 * No other way so 'skip' the Data
2693 void gdcmDocument::Parse7FE0 ()
2695 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2698 // Should warn user FIXME
2702 if ( IsImplicitVRLittleEndianTransferSyntax()
2703 || IsExplicitVRLittleEndianTransferSyntax()
2704 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2705 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2710 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2712 //// Read the Basic Offset Table Item Tag length...
2713 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2715 //// ... and then read length[s] itself[themselves]. We don't use
2716 // the values read (BTW what is the purpous of those lengths ?)
2717 if ( itemLength != 0 )
2719 // BTW, what is the purpous of those length anyhow !?
2720 char* basicOffsetTableItemValue = new char[itemLength + 1];
2721 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2723 for (unsigned int i=0; i < itemLength; i += 4 )
2725 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2726 std::ostringstream s;
2727 s << " Read one length: ";
2728 s << std::hex << individualLength << std::endl;
2729 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2731 delete[] basicOffsetTableItemValue;
2734 if ( ! IsRLELossLessTransferSyntax() )
2738 //// We then skip (not reading them) all the fragments of images:
2739 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2741 SkipBytes(itemLength);
2748 long rleSegmentLength[15], fragmentLength;
2750 // While we find some items:
2751 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2753 // Parse fragments of the current Fragment (Frame)
2754 //------------------ scanning (not reading) fragment pixels
2755 uint32_t nbRleSegments = ReadInt32();
2757 //// Reading RLE Segments Offset Table
2758 uint32_t rleSegmentOffsetTable[15];
2759 for(int k=1; k<=15; k++)
2761 ftellRes = ftell(Fp);
2762 rleSegmentOffsetTable[k] = ReadInt32();
2765 // skipping (not reading) RLE Segments
2766 if ( nbRleSegments > 1)
2768 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2770 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2771 - rleSegmentOffsetTable[k];
2772 ftellRes = ftell(Fp);
2773 SkipBytes(rleSegmentLength[k]);
2777 rleSegmentLength[nbRleSegments] = fragmentLength
2778 - rleSegmentOffsetTable[nbRleSegments];
2779 ftellRes = ftell(Fp);
2780 SkipBytes(rleSegmentLength[nbRleSegments]);
2783 // Make sure that at the end of the item we encounter a 'Sequence
2785 if ( !ReadTag(0xfffe, 0xe0dd) )
2787 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2788 dbg.Verbose(0, " at end of RLE item sequence");
2796 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2797 * \warning Does NOT work with ACR-NEMA files
2798 * \todo Find a trick to solve the pb (use RET fields ?)
2800 * @return true if 'smaller'
2802 bool gdcmDocument::operator<(gdcmDocument &document)
2805 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2806 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2818 s1 = GetEntryByNumber(0x0010,0x0020);
2819 s2 = document.GetEntryByNumber(0x0010,0x0020);
2830 // Study Instance UID
2831 s1 = GetEntryByNumber(0x0020,0x000d);
2832 s2 = document.GetEntryByNumber(0x0020,0x000d);
2843 // Serie Instance UID
2844 s1 = GetEntryByNumber(0x0020,0x000e);
2845 s2 = document.GetEntryByNumber(0x0020,0x000e);
2861 //-----------------------------------------------------------------------------