1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/08/16 04:34:56 $
7 Version: $Revision: 1.67 $
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 inFilename 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 std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
264 << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
265 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
271 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
281 * \brief Internal function that checks whether the Transfer Syntax given
282 * as argument is the one present in the current document.
283 * @param SyntaxToCheck The transfert syntax we need to check against.
284 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
285 * the current document. False either when the document contains
286 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
288 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
290 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
296 // The entry might be present but not loaded (parsing and loading
297 // happen at different stages): try loading and proceed with check...
298 LoadDocEntrySafe(entry);
299 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
301 std::string transfer = valEntry->GetValue();
302 // The actual transfer (as read from disk) might be padded. We
303 // first need to remove the potential padding. We can make the
304 // weak assumption that padding was not executed with digits...
305 if ( transfer.length() == 0 ) { // for brain damaged headers
308 while ( ! isdigit(transfer[transfer.length()-1]) )
310 transfer.erase(transfer.length()-1, 1);
312 if ( transfer == syntaxToCheck )
321 * \brief Determines if the Transfer Syntax of the present document
322 * corresponds to a Implicit Value Representation of
324 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
325 * @return True when ImplicitVRLittleEndian found. False in all other cases.
327 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
329 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
333 * \brief Determines if the Transfer Syntax was already encountered
334 * and if it corresponds to a ExplicitVRLittleEndian one.
335 * @return True when ExplicitVRLittleEndian found. False in all other cases.
337 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
339 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
343 * \brief Determines if the Transfer Syntax was already encountered
344 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
345 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
347 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
349 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
353 * \brief Determines if the Transfer Syntax was already encountered
354 * and if it corresponds to a Explicit VR Big Endian one.
355 * @return True when big endian found. False in all other cases.
357 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
359 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
363 * \brief Determines if the Transfer Syntax was already encountered
364 * and if it corresponds to a JPEGBaseLineProcess1 one.
365 * @return True when JPEGBaseLineProcess1found. False in all other cases.
367 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
369 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
373 * \brief Determines if the Transfer Syntax was already encountered
374 * and if it corresponds to a JPEGExtendedProcess2-4 one.
375 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
377 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
379 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
383 * \brief Determines if the Transfer Syntax was already encountered
384 * and if it corresponds to a JPEGExtendeProcess3-5 one.
385 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
387 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
389 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
393 * \brief Determines if the Transfer Syntax was already encountered
394 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
395 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
398 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
400 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
404 * \brief Determines if the Transfer Syntax was already encountered
405 * and if it corresponds to a RLE Lossless one.
406 * @return True when RLE Lossless found. False in all
409 bool gdcmDocument::IsRLELossLessTransferSyntax()
411 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
415 * \brief Determines if Transfer Syntax was already encountered
416 * and if it corresponds to a JPEG Lossless one.
417 * @return True when RLE Lossless found. False in all
421 bool gdcmDocument::IsJPEGLossless()
423 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
424 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
425 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
429 * \brief Determines if the Transfer Syntax was already encountered
430 * and if it corresponds to a JPEG2000 one
431 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
434 bool gdcmDocument::IsJPEG2000()
436 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
437 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
441 * \brief Predicate for dicom version 3 file.
442 * @return True when the file is a dicom version 3.
444 bool gdcmDocument::IsDicomV3()
446 // Checking if Transfert Syntax exists is enough
447 // Anyway, it's to late check if the 'Preamble' was found ...
448 // And ... would it be a rich idea to check ?
449 // (some 'no Preamble' DICOM images exist !)
450 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
454 * \brief returns the File Type
455 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
456 * @return the FileType code
458 FileType gdcmDocument::GetFileType()
464 * \brief Tries to open the file \ref gdcmDocument::Filename and
465 * checks the preamble when existing.
466 * @return The FILE pointer on success.
468 FILE* gdcmDocument::OpenFile()
470 Fp = fopen(Filename.c_str(),"rb");
475 "gdcmDocument::OpenFile cannot open file: ",
481 fread(&zero, (size_t)2, (size_t)1, Fp);
483 //ACR -- or DICOM with no Preamble --
484 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
490 fseek(Fp, 126L, SEEK_CUR);
492 fread(dicm, (size_t)4, (size_t)1, Fp);
493 if( memcmp(dicm, "DICM", 4) == 0 )
500 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
507 * \brief closes the file
508 * @return TRUE if the close was successfull
510 bool gdcmDocument::CloseFile()
512 int closed = fclose(Fp);
519 * \brief Writes in a file all the Header Entries (Dicom Elements)
520 * @param fp file pointer on an already open file
521 * @param filetype Type of the File to be written
522 * (ACR-NEMA, ExplicitVR, ImplicitVR)
523 * \return Always true.
525 void gdcmDocument::Write(FILE* fp,FileType filetype)
527 /// \todo move the following lines (and a lot of others, to be written)
528 /// to a future function CheckAndCorrectHeader
530 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
531 /// no way (check : FileType est un champ de gdcmDocument ...)
532 /// a moins de se livrer a un tres complique ajout des champs manquants.
533 /// faire un CheckAndCorrectHeader (?)
535 if (filetype == gdcmImplicitVR)
537 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
538 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
540 /// \todo Refer to standards on page 21, chapter 6.2
541 /// "Value representation": values with a VR of UI shall be
542 /// padded with a single trailing null
543 /// in the following case we have to padd manually with a 0
545 SetEntryLengthByNumber(18, 0x0002, 0x0010);
548 if (filetype == gdcmExplicitVR)
550 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
551 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
553 /// \todo Refer to standards on page 21, chapter 6.2
554 /// "Value representation": values with a VR of UI shall be
555 /// padded with a single trailing null
556 /// Dans le cas suivant on doit pader manuellement avec un 0
558 SetEntryLengthByNumber(20, 0x0002, 0x0010);
562 * \todo rewrite later, if really usefull
563 * - 'Group Length' element is optional in DICOM
564 * - but un-updated odd groups lengthes can causes pb
567 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
568 * UpdateGroupLength(false,filetype);
569 * if ( filetype == ACR)
570 * UpdateGroupLength(true,ACR);
573 gdcmElementSet::Write(fp, filetype); // This one is recursive
578 * \brief Modifies the value of a given Header Entry (Dicom Element)
579 * when it exists. Create it with the given value when unexistant.
580 * @param Value (string) Value to be set
581 * @param Group Group number of the Entry
582 * @param Elem Element number of the Entry
583 * \return pointer to the modified/created Header Entry (NULL when creation
587 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
588 std::string const & value,
592 gdcmValEntry* valEntry = 0;
594 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
597 // The entry wasn't present and we simply create the required ValEntry:
598 currentEntry = NewDocEntryByNumber(group, elem);
601 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
602 " NewDocEntryByNumber failed.");
605 valEntry = new gdcmValEntry(currentEntry);
606 if ( !AddEntry(valEntry))
608 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
609 " failed allthough this is a creation.");
614 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
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 !!
675 * \brief Set a new value if the invoked element exists
676 * Seems to be useless !!!
677 * @param Value new element value
678 * @param Group group number of the Entry
679 * @param Elem element number of the Entry
682 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
683 uint16_t group, uint16_t elem )
685 SetEntryByNumber(value, group, elem);
690 //-----------------------------------------------------------------------------
694 * \brief Checks if a given Dicom Element exists within the H table
695 * @param group Group number of the searched Dicom Element
696 * @param element Element number of the searched Dicom Element
697 * @return number of occurences
699 int gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
701 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
702 return TagHT.count(key);
706 * \brief Searches within Header Entries (Dicom Elements) parsed with
707 * the public and private dictionaries
708 * for the element value of a given tag.
709 * \warning Don't use any longer : use GetPubEntryByName
710 * @param tagName name of the searched element.
711 * @return Corresponding element value when it exists,
712 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
714 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
716 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
722 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
726 * \brief Searches within Header Entries (Dicom Elements) parsed with
727 * the public and private dictionaries
728 * for the element value representation of a given tag.
730 * Obtaining the VR (Value Representation) might be needed by caller
731 * to convert the string typed content to caller's native type
732 * (think of C++ vs Python). The VR is actually of a higher level
733 * of semantics than just the native C++ type.
734 * @param tagName name of the searched element.
735 * @return Corresponding element value representation when it exists,
736 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
738 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
740 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
741 if( dictEntry == NULL)
746 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
747 dictEntry->GetElement());
748 return elem->GetVR();
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.
756 * @param group Group number of the searched tag.
757 * @param element Element number of the searched tag.
758 * @return Corresponding element value representation when it exists,
759 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
761 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
763 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
764 /// \todo use map methods, instead of multimap JPR
765 if ( !TagHT.count(key))
770 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
774 * \brief Searches within Header Entries (Dicom Elements) parsed with
775 * the public and private dictionaries
776 * for the element value representation of a given tag..
778 * Obtaining the VR (Value Representation) might be needed by caller
779 * to convert the string typed content to caller's native type
780 * (think of C++ vs Python). The VR is actually of a higher level
781 * of semantics than just the native C++ type.
782 * @param group Group number of the searched tag.
783 * @param element Element number of the searched tag.
784 * @return Corresponding element value representation when it exists,
785 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
787 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
789 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
794 return elem->GetVR();
798 * \brief Searches within Header Entries (Dicom Elements) parsed with
799 * the public and private dictionaries
800 * for the value length of a given tag..
801 * @param group Group number of the searched tag.
802 * @param element Element number of the searched tag.
803 * @return Corresponding element length; -2 if not found
805 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
807 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
810 return -2; //magic number
812 return elem->GetLength();
815 * \brief Sets the value (string) of the Header Entry (Dicom Element)
816 * @param content string value of the Dicom Element
817 * @param tagName name of the searched Dicom Element.
818 * @return true when found
820 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
822 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
828 return SetEntryByNumber(content,dictEntry->GetGroup(),
829 dictEntry->GetElement());
833 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
834 * through it's (group, element) and modifies it's content with
836 * @param content new value (string) to substitute with
837 * @param group group number of the Dicom Element to modify
838 * @param element element number of the Dicom Element to modify
840 bool gdcmDocument::SetEntryByNumber(std::string const & content,
844 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
847 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
848 " ValEntry (try promotion first).");
851 // Non even content must be padded with a space (020H)...
852 std::string evenContent = content;
853 if( evenContent.length() % 2 )
855 evenContent += '\0'; // ... therefore we padd with (000H) .!?!
857 valEntry->SetValue(evenContent);
859 // Integers have a special treatement for their length:
860 gdcmVRKey vr = valEntry->GetVR();
861 if( vr == "US" || vr == "SS" )
863 valEntry->SetLength(2);
865 else if( vr == "UL" || vr == "SL" )
867 valEntry->SetLength(4);
871 valEntry->SetLength(evenContent.length());
878 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
879 * through it's (group, element) and modifies it's content with
881 * @param content new value (void *) to substitute with
882 * @param lgth new value length
883 * @param group group number of the Dicom Element to modify
884 * @param element element number of the Dicom Element to modify
886 bool gdcmDocument::SetEntryByNumber(void *content,
891 (void)lgth; //not used
892 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
893 if ( !TagHT.count(key))
898 /* Hope Binary field length is *never* wrong
899 if(lgth%2) // Non even length are padded with a space (020H).
902 //content = content + '\0'; // fing a trick to enlarge a binary field?
905 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
906 a->SetVoidArea(content);
907 //a->SetLength(lgth); // ???
913 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
914 * in the PubDocEntrySet of this instance
915 * through it's (group, element) and modifies it's length with
917 * \warning Use with extreme caution.
918 * @param l new length to substitute with
919 * @param group group number of the Entry to modify
920 * @param element element number of the Entry to modify
921 * @return true on success, false otherwise.
923 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
927 /// \todo use map methods, instead of multimap JPR
928 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
929 if ( !TagHT.count(key) )
935 l++; // length must be even
937 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
943 * \brief Gets (from Header) the offset of a 'non string' element value
944 * (LoadElementValues has already be executed)
945 * @param Group group number of the Entry
946 * @param Elem element number of the Entry
947 * @return File Offset of the Element Value
949 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
951 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
954 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
957 return entry->GetOffset();
961 * \brief Gets (from Header) a 'non string' element value
962 * (LoadElementValues has already be executed)
963 * @param Group group number of the Entry
964 * @param Elem element number of the Entry
965 * @return Pointer to the 'non string' area
967 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
969 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
972 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
975 return ((gdcmBinEntry *)entry)->GetVoidArea();
979 * \brief Loads (from disk) the element content
980 * when a string is not suitable
981 * @param Group group number of the Entry
982 * @param Elem element number of the Entry
984 void *gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
986 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
991 size_t o =(size_t)docElement->GetOffset();
992 fseek(Fp, o, SEEK_SET);
993 size_t l = docElement->GetLength();
994 char* a = new char[l];
997 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1000 size_t l2 = fread(a, 1, l , Fp);
1006 /// \todo Drop any already existing void area! JPR
1007 SetEntryVoidAreaByNumber(a, group, elem);
1012 * \brief Loads (from disk) the element content
1013 * when a string is not suitable
1014 * @param Element Entry whose voidArea is going to be loaded
1016 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1018 size_t o =(size_t)element->GetOffset();
1019 fseek(Fp, o, SEEK_SET);
1020 size_t l = element->GetLength();
1021 char* a = new char[l];
1024 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1027 element->SetVoidArea((void *)a);
1028 /// \todo check the result
1029 size_t l2 = fread(a, 1, l , Fp);
1040 * \brief Sets a 'non string' value to a given Dicom Element
1041 * @param area area containing the 'non string' value
1042 * @param group Group number of the searched Dicom Element
1043 * @param element Element number of the searched Dicom Element
1046 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1050 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1051 if ( !TagHT.count(key))
1056 // This was for multimap ?
1057 (( gdcmBinEntry *)( ((TagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1063 * \brief Update the entries with the shadow dictionary.
1064 * Only non even entries are analyzed
1066 void gdcmDocument::UpdateShaEntries()
1068 //gdcmDictEntry *entry;
1071 /// \todo TODO : still any use to explore recursively the whole structure?
1073 for(ListTag::iterator it=listEntries.begin();
1074 it!=listEntries.end();
1077 // Odd group => from public dictionary
1078 if((*it)->GetGroup()%2==0)
1081 // Peer group => search the corresponding dict entry
1083 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1087 if((*it)->IsImplicitVR())
1092 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1094 // Set the new entry and the new value
1095 (*it)->SetDictEntry(entry);
1096 CheckDocEntryVR(*it,vr);
1098 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1103 // Remove precedent value transformation
1104 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1111 * \brief Searches within the Header Entries for a Dicom Element of
1113 * @param tagName name of the searched Dicom Element.
1114 * @return Corresponding Dicom Element when it exists, and NULL
1117 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1119 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1125 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1129 * \brief retrieves a Dicom Element (the first one) using (group, element)
1130 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1131 * if you think it's NOT UNIQUE, check the count number
1132 * and use iterators to retrieve ALL the Dicoms Elements within
1133 * a given couple (group, element)
1134 * @param group Group number of the searched Dicom Element
1135 * @param element Element number of the searched Dicom Element
1138 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1141 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1142 if ( !TagHT.count(key))
1146 return TagHT.find(key)->second;
1150 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1151 * returns a result when the corresponding entry is of type
1153 * @return When present, the corresponding ValEntry.
1155 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1158 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1159 if ( !currentEntry )
1163 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1167 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1173 * \brief Loads the element while preserving the current
1174 * underlying file position indicator as opposed to
1175 * to LoadDocEntry that modifies it.
1176 * @param entry Header Entry whose value shall be loaded.
1179 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1181 long PositionOnEntry = ftell(Fp);
1182 LoadDocEntry(entry);
1183 fseek(Fp, PositionOnEntry, SEEK_SET);
1187 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1189 * @return The properly swaped 32 bits integer.
1191 uint32_t gdcmDocument::SwapLong(uint32_t a)
1198 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1199 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1203 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1207 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1210 std::cout << "swapCode= " << SwapCode << std::endl;
1211 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1218 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1220 * @return The properly unswaped 32 bits integer.
1222 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1228 * \brief Swaps the bytes so they agree with the processor order
1229 * @return The properly swaped 16 bits integer.
1231 uint16_t gdcmDocument::SwapShort(uint16_t a)
1233 if ( SwapCode == 4321 || SwapCode == 2143 )
1235 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1241 * \brief Unswaps the bytes so they agree with the processor order
1242 * @return The properly unswaped 16 bits integer.
1244 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1246 return SwapShort(a);
1249 //-----------------------------------------------------------------------------
1253 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1254 * @return length of the parsed set.
1257 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1262 gdcmDocEntry *newDocEntry = 0;
1263 gdcmValEntry *newValEntry = 0;
1264 unsigned long l = 0;
1266 int depth = set->GetDepthLevel();
1269 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1273 newDocEntry = ReadNextDocEntry( );
1279 gdcmVRKey vr = newDocEntry->GetVR();
1283 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1286 newValEntry = new gdcmValEntry(newDocEntry->GetDictEntry());
1287 newValEntry->Copy(newDocEntry);
1288 newValEntry->SetDepthLevel(depth);
1289 set->AddEntry(newValEntry);
1290 LoadDocEntry(newValEntry);
1291 if (newValEntry->IsItemDelimitor())
1295 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1302 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1304 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1305 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1306 "nor BinEntry. Probably unknown VR.");
1309 ////// BinEntry or UNKOWN VR:
1310 gdcmBinEntry *bn = new gdcmBinEntry(newDocEntry->GetDictEntry());
1311 bn->Copy(newDocEntry);
1316 if (newDocEntry->GetGroup() == 0x7fe0 &&
1317 newDocEntry->GetElement() == 0x0010 )
1319 if (newDocEntry->GetReadLength()==0xffffffff)
1321 // Broken US.3405.1.dcm
1322 Parse7FE0(); // to skip the pixels
1323 // (multipart JPEG/RLE are trouble makers)
1327 SkipToNextDocEntry(newDocEntry);
1328 l = newDocEntry->GetFullLength();
1333 // to be sure we are at the beginning
1334 SkipToNextDocEntry(newDocEntry);
1335 l = newDocEntry->GetFullLength();
1341 l = newDocEntry->GetReadLength();
1342 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1344 if ( l == 0xffffffff )
1353 // no other way to create it ...
1354 gdcmSeqEntry *sq = new gdcmSeqEntry(newDocEntry->GetDictEntry(),
1355 set->GetDepthLevel());
1356 sq->Copy(newDocEntry);
1357 sq->SetDelimitorMode(delim_mode);
1358 sq->SetDepthLevel(depth);
1361 { // Don't try to parse zero-length sequences
1362 long lgt = ParseSQ( sq,
1363 newDocEntry->GetOffset(),
1365 (void)lgt; //not used...
1368 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1376 return l; // Probably useless
1380 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1381 * @return parsed length for this level
1383 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1384 long offset, long l_max, bool delim_mode)
1386 int SQItemNumber = 0;
1388 //int depth = set->GetDepthLevel();
1389 //(void)depth; //not used
1393 gdcmDocEntry *newDocEntry = ReadNextDocEntry();
1396 // FIXME Should warn user
1401 if ( newDocEntry->IsSequenceDelimitor() )
1403 set->SetSequenceDelimitationItem( newDocEntry );
1407 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1412 gdcmSQItem *itemSQ = new gdcmSQItem(set->GetDepthLevel());
1413 itemSQ->AddEntry(newDocEntry);
1414 unsigned int l = newDocEntry->GetReadLength();
1416 if ( l == 0xffffffff )
1425 int lgr = ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1426 (void)lgr; //FIXME not used
1428 set->AddEntry(itemSQ, SQItemNumber);
1430 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1436 int lgth = ftell(Fp) - offset;
1441 * \brief Loads the element content if its length doesn't exceed
1442 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1443 * @param Entry Header Entry (Dicom Element) to be dealt with
1445 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1448 uint16_t group = entry->GetGroup();
1449 std::string vr = entry->GetVR();
1450 uint32_t length = entry->GetLength();
1452 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1454 // A SeQuence "contains" a set of Elements.
1455 // (fffe e000) tells us an Element is beginning
1456 // (fffe e00d) tells us an Element just ended
1457 // (fffe e0dd) tells us the current SeQuence just ended
1458 if( group == 0xfffe )
1460 // NO more value field for SQ !
1464 // When the length is zero things are easy:
1467 ((gdcmValEntry *)entry)->SetValue("");
1471 // The elements whose length is bigger than the specified upper bound
1472 // are not loaded. Instead we leave a short notice of the offset of
1473 // the element content and it's length.
1475 std::ostringstream s;
1476 if (length > MaxSizeLoadEntry)
1478 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1480 s << "gdcm::NotLoaded (BinEntry)";
1481 s << " Address:" << (long)entry->GetOffset();
1482 s << " Length:" << entry->GetLength();
1483 s << " x(" << std::hex << entry->GetLength() << ")";
1484 binEntryPtr->SetValue(s.str());
1486 // to be sure we are at the end of the value ...
1487 fseek(Fp, (long)entry->GetOffset()+(long)entry->GetLength(), SEEK_SET);
1488 // Following return introduced by JPR on version 1.25. Since the
1489 // treatement of a ValEntry is never executed (doh!) this means
1490 // we were lucky up to now because we NEVER encountered a ValEntry
1491 // whose length was bigger thant MaxSizeLoadEntry !? I can't believe
1492 // this could ever work...
1493 return; //FIXME FIXME FIXME FIXME JPR ????
1495 // Be carefull : a BinEntry IS_A ValEntry ...
1496 if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1498 s << "gdcm::NotLoaded. (ValEntry)";
1499 s << " Address:" << (long)entry->GetOffset();
1500 s << " Length:" << entry->GetLength();
1501 s << " x(" << std::hex << entry->GetLength() << ")";
1502 valEntryPtr->SetValue(s.str());
1504 // to be sure we are at the end of the value ...
1505 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1510 // When we find a BinEntry not very much can be done :
1511 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1514 LoadEntryVoidArea(binEntryPtr);
1515 s << "gdcm::Loaded (BinEntry)";
1516 binEntryPtr->SetValue(s.str());
1520 /// \todo Any compacter code suggested (?)
1521 if ( IsDocEntryAnInteger(entry) )
1524 //std::ostringstream s; //shadow previous declaration
1526 // When short integer(s) are expected, read and convert the following
1527 // n *two characters properly i.e. consider them as short integers as
1528 // opposed to strings.
1529 // Elements with Value Multiplicity > 1
1530 // contain a set of integers (not a single one)
1531 if (vr == "US" || vr == "SS")
1534 NewInt = ReadInt16();
1538 for (int i=1; i < nbInt; i++)
1541 NewInt = ReadInt16();
1546 // See above comment on multiple integers (mutatis mutandis).
1547 else if (vr == "UL" || vr == "SL")
1550 NewInt = ReadInt32();
1554 for (int i=1; i < nbInt; i++)
1557 NewInt = ReadInt32();
1562 #ifdef GDCM_NO_ANSI_STRING_STREAM
1563 s << std::ends; // to avoid oddities on Solaris
1564 #endif //GDCM_NO_ANSI_STRING_STREAM
1566 ((gdcmValEntry *)entry)->SetValue(s.str());
1570 // We need an additional byte for storing \0 that is not on disk
1571 //std::string newValue(length,0);
1572 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1573 //rah !! I can't believe it could work, normally this is a const char* !!!
1574 char *str = new char[length+1];
1575 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1577 std::string newValue = str;
1579 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1581 if ( item_read != 1 )
1583 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1584 "unread element value");
1585 valEntry->SetValue("gdcm::UnRead");
1591 // Because of correspondance with the VR dic
1592 valEntry->SetValue(newValue);
1596 valEntry->SetValue(newValue);
1601 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1602 "Should have a ValEntry, here !");
1608 * \brief Find the value Length of the passed Header Entry
1609 * @param Entry Header Entry whose length of the value shall be loaded.
1611 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1612 throw ( gdcmFormatError )
1614 uint16_t element = entry->GetElement();
1615 std::string vr = entry->GetVR();
1619 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1621 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1623 // The following reserved two bytes (see PS 3.5-2001, section
1624 // 7.1.2 Data element structure with explicit vr p27) must be
1625 // skipped before proceeding on reading the length on 4 bytes.
1626 fseek(Fp, 2L, SEEK_CUR);
1627 uint32_t length32 = ReadInt32();
1629 if ( vr == "OB" && length32 == 0xffffffff )
1634 lengthOB = FindDocEntryLengthOB();
1636 catch ( gdcmFormatUnexpected )
1638 // Computing the length failed (this happens with broken
1639 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1640 // chance to get the pixels by deciding the element goes
1641 // until the end of the file. Hence we artificially fix the
1642 // the length and proceed.
1643 long currentPosition = ftell(Fp);
1644 fseek(Fp,0L,SEEK_END);
1645 long lengthUntilEOF = ftell(Fp) - currentPosition;
1646 fseek(Fp, currentPosition, SEEK_SET);
1647 entry->SetLength(lengthUntilEOF);
1650 entry->SetLength(lengthOB);
1653 FixDocEntryFoundLength(entry, length32);
1657 // Length is encoded on 2 bytes.
1658 length16 = ReadInt16();
1660 // We can tell the current file is encoded in big endian (like
1661 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1662 // and it's value is the one of the encoding of a big endian file.
1663 // In order to deal with such big endian encoded files, we have
1664 // (at least) two strategies:
1665 // * when we load the "Transfer Syntax" tag with value of big endian
1666 // encoding, we raise the proper flags. Then we wait for the end
1667 // of the META group (0x0002) among which is "Transfer Syntax",
1668 // before switching the swap code to big endian. We have to postpone
1669 // the switching of the swap code since the META group is fully encoded
1670 // in little endian, and big endian coding only starts at the next
1671 // group. The corresponding code can be hard to analyse and adds
1672 // many additional unnecessary tests for regular tags.
1673 // * the second strategy consists in waiting for trouble, that shall
1674 // appear when we find the first group with big endian encoding. This
1675 // is easy to detect since the length of a "Group Length" tag (the
1676 // ones with zero as element number) has to be of 4 (0x0004). When we
1677 // encounter 1024 (0x0400) chances are the encoding changed and we
1678 // found a group with big endian encoding.
1679 // We shall use this second strategy. In order to make sure that we
1680 // can interpret the presence of an apparently big endian encoded
1681 // length of a "Group Length" without committing a big mistake, we
1682 // add an additional check: we look in the already parsed elements
1683 // for the presence of a "Transfer Syntax" whose value has to be "big
1684 // endian encoding". When this is the case, chances are we have got our
1685 // hands on a big endian encoded file: we switch the swap code to
1686 // big endian and proceed...
1687 if ( element == 0x0000 && length16 == 0x0400 )
1689 if ( !IsExplicitVRBigEndianTransferSyntax() )
1691 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1692 " not explicit VR." );
1696 SwitchSwapToBigEndian();
1697 // Restore the unproperly loaded values i.e. the group, the element
1698 // and the dictionary entry depending on them.
1699 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1700 uint16_t correctElem = SwapShort( entry->GetElement() );
1701 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1705 // This correct tag is not in the dictionary. Create a new one.
1706 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1708 // FIXME this can create a memory leaks on the old entry that be
1709 // left unreferenced.
1710 entry->SetDictEntry( newTag );
1713 // Heuristic: well, some files are really ill-formed.
1714 if ( length16 == 0xffff)
1716 // 0xffff means that we deal with 'Unknown Length' Sequence
1719 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1724 // Either implicit VR or a non DICOM conformal (see note below) explicit
1725 // VR that ommited the VR of (at least) this element. Farts happen.
1726 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1727 // on Data elements "Implicit and Explicit VR Data Elements shall
1728 // not coexist in a Data Set and Data Sets nested within it".]
1729 // Length is on 4 bytes.
1731 FixDocEntryFoundLength( entry, ReadInt32() );
1737 * \brief Find the Value Representation of the current Dicom Element.
1740 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1742 if ( Filetype != gdcmExplicitVR )
1749 long positionOnEntry = ftell(Fp);
1750 // Warning: we believe this is explicit VR (Value Representation) because
1751 // we used a heuristic that found "UL" in the first tag. Alas this
1752 // doesn't guarantee that all the tags will be in explicit VR. In some
1753 // cases (see e-film filtered files) one finds implicit VR tags mixed
1754 // within an explicit VR file. Hence we make sure the present tag
1755 // is in explicit VR and try to fix things if it happens not to be
1758 fread (vr, (size_t)2,(size_t)1, Fp);
1761 if( !CheckDocEntryVR(entry, vr) )
1763 fseek(Fp, positionOnEntry, SEEK_SET);
1764 // When this element is known in the dictionary we shall use, e.g. for
1765 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1766 // dictionary entry. Still we have to flag the element as implicit since
1767 // we know now our assumption on expliciteness is not furfilled.
1769 if ( entry->IsVRUnknown() )
1771 entry->SetVR("Implicit");
1773 entry->SetImplicitVR();
1778 * \brief Check the correspondance between the VR of the header entry
1779 * and the taken VR. If they are different, the header entry is
1780 * updated with the new VR.
1781 * @param Entry Header Entry to check
1782 * @param vr Dicom Value Representation
1783 * @return false if the VR is incorrect of if the VR isn't referenced
1784 * otherwise, it returns true
1786 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1788 char msg[100]; // for sprintf
1789 bool realExplicit = true;
1791 // Assume we are reading a falsely explicit VR file i.e. we reached
1792 // a tag where we expect reading a VR but are in fact we read the
1793 // first to bytes of the length. Then we will interogate (through find)
1794 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1795 // both GCC and VC++ implementations of the STL map. Hence when the
1796 // expected VR read happens to be non-ascii characters we consider
1797 // we hit falsely explicit VR tag.
1799 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1801 realExplicit = false;
1804 // CLEANME searching the dicom_vr at each occurence is expensive.
1805 // PostPone this test in an optional integrity check at the end
1806 // of parsing or only in debug mode.
1807 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1809 realExplicit = false;
1812 if ( !realExplicit )
1814 // We thought this was explicit VR, but we end up with an
1815 // implicit VR tag. Let's backtrack.
1816 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1817 entry->GetGroup(), entry->GetElement());
1818 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1820 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1822 // Group length is UL !
1823 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1824 entry->GetGroup(), entry->GetElement(),
1825 "UL", "FIXME", "Group Length");
1826 entry->SetDictEntry( newEntry );
1831 if ( entry->IsVRUnknown() )
1833 // When not a dictionary entry, we can safely overwrite the VR.
1834 if( entry->GetElement() == 0x0000 )
1836 // Group length is UL !
1844 else if ( entry->GetVR() != vr )
1846 // The VR present in the file and the dictionary disagree. We assume
1847 // the file writer knew best and use the VR of the file. Since it would
1848 // be unwise to overwrite the VR of a dictionary (since it would
1849 // compromise it's next user), we need to clone the actual DictEntry
1850 // and change the VR for the read one.
1851 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1852 entry->GetGroup(), entry->GetElement(),
1853 vr, "FIXME", entry->GetName());
1854 entry->SetDictEntry(newEntry);
1861 * \brief Get the transformed value of the header entry. The VR value
1862 * is used to define the transformation to operate on the value
1863 * \warning NOT end user intended method !
1865 * @return Transformed entry value
1867 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1869 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1871 std::string val = ((gdcmValEntry *)entry)->GetValue();
1872 std::string vr = entry->GetVR();
1873 uint32_t length = entry->GetLength();
1874 std::ostringstream s;
1877 // When short integer(s) are expected, read and convert the following
1878 // n * 2 bytes properly i.e. as a multivaluated strings
1879 // (each single value is separated fromthe next one by '\'
1880 // as usual for standard multivaluated filels
1881 // Elements with Value Multiplicity > 1
1882 // contain a set of short integers (not a single one)
1884 if( vr == "US" || vr == "SS" )
1889 for (int i=0; i < nbInt; i++)
1895 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1896 newInt16 = SwapShort( newInt16 );
1901 // When integer(s) are expected, read and convert the following
1902 // n * 4 bytes properly i.e. as a multivaluated strings
1903 // (each single value is separated fromthe next one by '\'
1904 // as usual for standard multivaluated filels
1905 // Elements with Value Multiplicity > 1
1906 // contain a set of integers (not a single one)
1907 else if( vr == "UL" || vr == "SL" )
1912 for (int i=0; i < nbInt; i++)
1918 newInt32 = ( val[4*i+0] & 0xFF )
1919 + (( val[4*i+1] & 0xFF ) << 8 )
1920 + (( val[4*i+2] & 0xFF ) << 16 )
1921 + (( val[4*i+3] & 0xFF ) << 24 );
1922 newInt32 = SwapLong( newInt32 );
1926 #ifdef GDCM_NO_ANSI_STRING_STREAM
1927 s << std::ends; // to avoid oddities on Solaris
1928 #endif //GDCM_NO_ANSI_STRING_STREAM
1932 return ((gdcmValEntry *)entry)->GetValue();
1936 * \brief Get the reverse transformed value of the header entry. The VR
1937 * value is used to define the reverse transformation to operate on
1939 * \warning NOT end user intended method !
1941 * @return Reverse transformed entry value
1943 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1945 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1947 std::string vr = entry->GetVR();
1948 std::vector<std::string> tokens;
1949 std::ostringstream s;
1951 if ( vr == "US" || vr == "SS" )
1955 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1956 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1957 for (unsigned int i=0; i<tokens.size(); i++)
1959 newInt16 = atoi(tokens[i].c_str());
1960 s << ( newInt16 & 0xFF )
1961 << (( newInt16 >> 8 ) & 0xFF );
1965 if ( vr == "UL" || vr == "SL")
1969 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1970 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1971 for (unsigned int i=0; i<tokens.size();i++)
1973 newInt32 = atoi(tokens[i].c_str());
1974 s << (char)( newInt32 & 0xFF )
1975 << (char)(( newInt32 >> 8 ) & 0xFF )
1976 << (char)(( newInt32 >> 16 ) & 0xFF )
1977 << (char)(( newInt32 >> 24 ) & 0xFF );
1982 #ifdef GDCM_NO_ANSI_STRING_STREAM
1983 s << std::ends; // to avoid oddities on Solaris
1984 #endif //GDCM_NO_ANSI_STRING_STREAM
1988 return ((gdcmValEntry *)entry)->GetValue();
1992 * \brief Skip a given Header Entry
1993 * \warning NOT end user intended method !
1996 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1998 SkipBytes(entry->GetLength());
2002 * \brief Skips to the begining of the next Header Entry
2003 * \warning NOT end user intended method !
2006 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2008 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2009 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2013 * \brief When the length of an element value is obviously wrong (because
2014 * the parser went Jabberwocky) one can hope improving things by
2015 * applying some heuristics.
2017 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2018 uint32_t foundLength)
2020 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2021 if ( foundLength == 0xffffffff)
2026 uint16_t gr = entry->GetGroup();
2027 uint16_t el = entry->GetElement();
2029 if ( foundLength % 2)
2031 std::ostringstream s;
2032 s << "Warning : Tag with uneven length "
2034 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2035 dbg.Verbose(0, s.str().c_str());
2038 //////// Fix for some naughty General Electric images.
2039 // Allthough not recent many such GE corrupted images are still present
2040 // on Creatis hard disks. Hence this fix shall remain when such images
2041 // are no longer in user (we are talking a few years, here)...
2042 // Note: XMedCom probably uses such a trick since it is able to read
2043 // those pesky GE images ...
2044 if ( foundLength == 13)
2046 // Only happens for this length !
2047 if ( entry->GetGroup() != 0x0008
2048 || ( entry->GetElement() != 0x0070
2049 && entry->GetElement() != 0x0080 ) )
2052 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2056 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2057 // Occurence of such images is quite low (unless one leaves close to a
2058 // 'Leonardo' source. Hence, one might consider commenting out the
2059 // following fix on efficiency reasons.
2060 else if ( entry->GetGroup() == 0x0009
2061 && ( entry->GetElement() == 0x1113
2062 || entry->GetElement() == 0x1114 ) )
2065 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2068 else if ( entry->GetVR() == "SQ" )
2070 foundLength = 0; // ReadLength is unchanged
2073 //////// We encountered a 'delimiter' element i.e. a tag of the form
2074 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2075 // taken into account.
2076 else if( entry->GetGroup() == 0xfffe )
2078 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2079 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2080 // causes extra troubles...
2081 if( entry->GetElement() != 0x0000 )
2087 entry->SetUsableLength(foundLength);
2091 * \brief Apply some heuristics to predict whether the considered
2092 * element value contains/represents an integer or not.
2093 * @param Entry The element value on which to apply the predicate.
2094 * @return The result of the heuristical predicate.
2096 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2098 uint16_t element = entry->GetElement();
2099 uint16_t group = entry->GetGroup();
2100 std::string vr = entry->GetVR();
2101 uint32_t length = entry->GetLength();
2103 // When we have some semantics on the element we just read, and if we
2104 // a priori know we are dealing with an integer, then we shall be
2105 // able to swap it's element value properly.
2106 if ( element == 0 ) // This is the group length of the group
2114 // Allthough this should never happen, still some images have a
2115 // corrupted group length [e.g. have a glance at offset x(8336) of
2116 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2117 // Since for dicom compliant and well behaved headers, the present
2118 // test is useless (and might even look a bit paranoid), when we
2119 // encounter such an ill-formed image, we simply display a warning
2120 // message and proceed on parsing (while crossing fingers).
2121 std::ostringstream s;
2122 int filePosition = ftell(Fp);
2123 s << "Erroneous Group Length element length on : (" \
2124 << std::hex << group << " , " << element
2125 << ") -before- position x(" << filePosition << ")"
2126 << "lgt : " << length;
2127 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2131 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2140 * \brief Find the Length till the next sequence delimiter
2141 * \warning NOT end user intended method !
2145 uint32_t gdcmDocument::FindDocEntryLengthOB()
2146 throw( gdcmFormatUnexpected )
2148 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2149 long positionOnEntry = ftell(Fp);
2150 bool foundSequenceDelimiter = false;
2151 uint32_t totalLength = 0;
2153 while ( !foundSequenceDelimiter )
2159 group = ReadInt16();
2162 catch ( gdcmFormatError )
2164 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2165 " group or element not present.");
2168 // We have to decount the group and element we just read
2171 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2173 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2174 "tag nor a Sequence delimiter tag.");
2175 fseek(Fp, positionOnEntry, SEEK_SET);
2176 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2177 "Neither an Item tag nor a Sequence "
2181 if ( elem == 0xe0dd )
2183 foundSequenceDelimiter = true;
2186 uint32_t itemLength = ReadInt32();
2187 // We add 4 bytes since we just read the ItemLength with ReadInt32
2188 totalLength += itemLength + 4;
2189 SkipBytes(itemLength);
2191 if ( foundSequenceDelimiter )
2196 fseek(Fp, positionOnEntry, SEEK_SET);
2201 * \brief Reads a supposed to be 16 Bits integer
2202 * (swaps it depending on processor endianity)
2203 * @return read value
2205 uint16_t gdcmDocument::ReadInt16()
2206 throw( gdcmFormatError )
2209 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2210 if ( item_read != 1 )
2214 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2216 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2223 * \brief Reads a supposed to be 32 Bits integer
2224 * (swaps it depending on processor endianity)
2225 * @return read value
2227 uint32_t gdcmDocument::ReadInt32()
2228 throw( gdcmFormatError )
2231 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2232 if ( item_read != 1 )
2236 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2238 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2245 * \brief skips bytes inside the source file
2246 * \warning NOT end user intended method !
2249 void gdcmDocument::SkipBytes(uint32_t nBytes)
2251 //FIXME don't dump the returned value
2252 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2256 * \brief Loads all the needed Dictionaries
2257 * \warning NOT end user intended method !
2259 void gdcmDocument::Initialise()
2261 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2266 * \brief Discover what the swap code is (among little endian, big endian,
2267 * bad little endian, bad big endian).
2269 * @return false when we are absolutely sure
2270 * it's neither ACR-NEMA nor DICOM
2271 * true when we hope ours assuptions are OK
2273 bool gdcmDocument::CheckSwap()
2275 // The only guaranted way of finding the swap code is to find a
2276 // group tag since we know it's length has to be of four bytes i.e.
2277 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2278 // occurs when we can't find such group...
2280 uint32_t x = 4; // x : for ntohs
2281 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2285 char deb[HEADER_LENGTH_TO_READ];
2287 // First, compare HostByteOrder and NetworkByteOrder in order to
2288 // determine if we shall need to swap bytes (i.e. the Endian type).
2289 if ( x == ntohs(x) )
2298 // The easiest case is the one of a DICOM header, since it possesses a
2299 // file preamble where it suffice to look for the string "DICM".
2300 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2301 (void)lgrLue; //FIXME not used
2303 char *entCur = deb + 128;
2304 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2306 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2308 // Next, determine the value representation (VR). Let's skip to the
2309 // first element (0002, 0000) and check there if we find "UL"
2310 // - or "OB" if the 1st one is (0002,0001) -,
2311 // in which case we (almost) know it is explicit VR.
2312 // WARNING: if it happens to be implicit VR then what we will read
2313 // is the length of the group. If this ascii representation of this
2314 // length happens to be "UL" then we shall believe it is explicit VR.
2315 // FIXME: in order to fix the above warning, we could read the next
2316 // element value (or a couple of elements values) in order to make
2317 // sure we are not commiting a big mistake.
2318 // We need to skip :
2319 // * the 128 bytes of File Preamble (often padded with zeroes),
2320 // * the 4 bytes of "DICM" string,
2321 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2322 // i.e. a total of 136 bytes.
2326 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2327 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2328 // *Implicit* VR. -and it is !-
2330 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2331 memcmp(entCur, "OB", (size_t)2) == 0 ||
2332 memcmp(entCur, "UI", (size_t)2) == 0 ||
2333 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2334 // when Write DCM *adds*
2336 // Use gdcmDocument::dicom_vr to test all the possibilities
2337 // instead of just checking for UL, OB and UI !? group 0000
2339 Filetype = gdcmExplicitVR;
2340 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2341 "explicit Value Representation");
2345 Filetype = gdcmImplicitVR;
2346 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2347 "not an explicit Value Representation");
2353 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2354 "HostByteOrder != NetworkByteOrder");
2359 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2360 "HostByteOrder = NetworkByteOrder");
2363 // Position the file position indicator at first tag (i.e.
2364 // after the file preamble and the "DICM" string).
2366 fseek (Fp, 132L, SEEK_SET);
2370 // Alas, this is not a DicomV3 file and whatever happens there is no file
2371 // preamble. We can reset the file position indicator to where the data
2372 // is (i.e. the beginning of the file).
2373 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2376 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2377 // By clean we mean that the length of the first tag is written down.
2378 // If this is the case and since the length of the first group HAS to be
2379 // four (bytes), then determining the proper swap code is straightforward.
2382 // We assume the array of char we are considering contains the binary
2383 // representation of a 32 bits integer. Hence the following dirty
2385 s32 = *((uint32_t *)(entCur));
2406 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2407 // It is time for despaired wild guesses.
2408 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2409 // i.e. the 'group length' element is not present :
2411 // check the supposed to be 'group number'
2412 // 0x0002 or 0x0004 or 0x0008
2413 // to determine ' SwapCode' value .
2414 // Only 0 or 4321 will be possible
2415 // (no oportunity to check for the formerly well known
2416 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2417 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2418 // the file IS NOT ACR-NEMA nor DICOM V3
2419 // Find a trick to tell it the caller...
2421 s16 = *((uint16_t *)(deb));
2438 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2439 "ACR/NEMA unfound swap info (Really hopeless !)");
2440 Filetype = gdcmUnknown;
2443 // Then the only info we have is the net2host one.
2453 * \brief Restore the unproperly loaded values i.e. the group, the element
2454 * and the dictionary entry depending on them.
2456 void gdcmDocument::SwitchSwapToBigEndian()
2458 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2459 "Switching to BigEndian mode.");
2460 if ( SwapCode == 0 )
2464 else if ( SwapCode == 4321 )
2468 else if ( SwapCode == 3412 )
2472 else if ( SwapCode == 2143 )
2479 * \brief during parsing, Header Elements too long are not loaded in memory
2482 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2488 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2490 MaxSizeLoadEntry = 0xffffffff;
2493 MaxSizeLoadEntry = newSize;
2498 * \brief Header Elements too long will not be printed
2499 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2502 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2504 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2509 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2511 MaxSizePrintEntry = 0xffffffff;
2514 MaxSizePrintEntry = newSize;
2520 * \brief Read the next tag but WITHOUT loading it's value
2521 * (read the 'Group Number', the 'Element Number',
2522 * gets the Dict Entry
2523 * gets the VR, gets the length, gets the offset value)
2524 * @return On succes the newly created DocEntry, NULL on failure.
2526 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2533 group = ReadInt16();
2536 catch ( gdcmFormatError e )
2538 // We reached the EOF (or an error occured) therefore
2539 // header parsing has to be considered as finished.
2544 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2545 FindDocEntryVR(newEntry);
2549 FindDocEntryLength(newEntry);
2551 catch ( gdcmFormatError e )
2559 newEntry->SetOffset(ftell(Fp));
2566 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2567 * in the TagHt dictionary.
2568 * @param group The generated tag must belong to this group.
2569 * @return The element of tag with given group which is fee.
2571 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2573 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2575 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2576 if (TagHT.count(key) == 0)
2585 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2586 * is placed at the beginning of a tag check whether this
2587 * tag is (TestGroup, TestElement).
2588 * \warning On success the internal file pointer \ref gdcmDocument::fp
2589 * is modified to point after the tag.
2590 * On failure (i.e. when the tag wasn't the expected tag
2591 * (TestGroup, TestElement) the internal file pointer
2592 * \ref gdcmDocument::fp is restored to it's original position.
2593 * @param TestGroup The expected group of the tag.
2594 * @param TestElement The expected Element of the tag.
2595 * @return True on success, false otherwise.
2597 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2599 long positionOnEntry = ftell(Fp);
2600 long currentPosition = ftell(Fp); // On debugging purposes
2602 //// Read the Item Tag group and element, and make
2603 // sure they are what we expected:
2604 uint16_t itemTagGroup = ReadInt16();
2605 uint16_t itemTagElement = ReadInt16();
2606 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2608 std::ostringstream s;
2609 s << " We should have found tag (";
2610 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2611 s << " but instead we encountered tag (";
2612 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2614 s << " at address: " << (unsigned)currentPosition << std::endl;
2615 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2616 dbg.Verbose(0, s.str().c_str());
2617 fseek(Fp, positionOnEntry, SEEK_SET);
2625 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2626 * is placed at the beginning of a tag (TestGroup, TestElement),
2627 * read the length associated to the Tag.
2628 * \warning On success the internal file pointer \ref gdcmDocument::fp
2629 * is modified to point after the tag and it's length.
2630 * On failure (i.e. when the tag wasn't the expected tag
2631 * (TestGroup, TestElement) the internal file pointer
2632 * \ref gdcmDocument::fp is restored to it's original position.
2633 * @param TestGroup The expected group of the tag.
2634 * @param TestElement The expected Element of the tag.
2635 * @return On success returns the length associated to the tag. On failure
2638 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2640 long positionOnEntry = ftell(Fp);
2641 (void)positionOnEntry;
2643 if ( !ReadTag(testGroup, testElement) )
2648 //// Then read the associated Item Length
2649 long currentPosition = ftell(Fp);
2650 uint32_t itemLength = ReadInt32();
2652 std::ostringstream s;
2653 s << "Basic Item Length is: "
2654 << itemLength << std::endl;
2655 s << " at address: " << (unsigned)currentPosition << std::endl;
2656 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2662 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2663 * No other way so 'skip' the Data
2666 void gdcmDocument::Parse7FE0 ()
2668 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2671 // Should warn user FIXME
2675 if ( IsImplicitVRLittleEndianTransferSyntax()
2676 || IsExplicitVRLittleEndianTransferSyntax()
2677 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2678 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2683 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2685 //// Read the Basic Offset Table Item Tag length...
2686 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2688 //// ... and then read length[s] itself[themselves]. We don't use
2689 // the values read (BTW what is the purpous of those lengths ?)
2690 if ( itemLength != 0 )
2692 // BTW, what is the purpous of those length anyhow !?
2693 char* basicOffsetTableItemValue = new char[itemLength + 1];
2694 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2696 for (unsigned int i=0; i < itemLength; i += 4 )
2698 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2699 std::ostringstream s;
2700 s << " Read one length: ";
2701 s << std::hex << individualLength << std::endl;
2702 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2704 delete[] basicOffsetTableItemValue;
2707 if ( ! IsRLELossLessTransferSyntax() )
2711 //// We then skip (not reading them) all the fragments of images:
2712 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2714 SkipBytes(itemLength);
2721 long rleSegmentLength[15], fragmentLength;
2723 // While we find some items:
2724 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2726 // Parse fragments of the current Fragment (Frame)
2727 //------------------ scanning (not reading) fragment pixels
2728 uint32_t nbRleSegments = ReadInt32();
2730 //// Reading RLE Segments Offset Table
2731 uint32_t rleSegmentOffsetTable[15];
2732 for(int k=1; k<=15; k++)
2734 ftellRes = ftell(Fp);
2735 rleSegmentOffsetTable[k] = ReadInt32();
2738 // skipping (not reading) RLE Segments
2739 if ( nbRleSegments > 1)
2741 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2743 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2744 - rleSegmentOffsetTable[k];
2745 ftellRes = ftell(Fp);
2746 SkipBytes(rleSegmentLength[k]);
2750 rleSegmentLength[nbRleSegments] = fragmentLength
2751 - rleSegmentOffsetTable[nbRleSegments];
2752 ftellRes = ftell(Fp);
2753 SkipBytes(rleSegmentLength[nbRleSegments]);
2756 // Make sure that at the end of the item we encounter a 'Sequence
2758 if ( !ReadTag(0xfffe, 0xe0dd) )
2760 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2761 dbg.Verbose(0, " at end of RLE item sequence");
2769 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2770 * \warning Does NOT work with ACR-NEMA files
2771 * \todo Find a trick to solve the pb (use RET fields ?)
2773 * @return true if 'smaller'
2775 bool gdcmDocument::operator<(gdcmDocument &document)
2778 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2779 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2791 s1 = GetEntryByNumber(0x0010,0x0020);
2792 s2 = document.GetEntryByNumber(0x0010,0x0020);
2803 // Study Instance UID
2804 s1 = GetEntryByNumber(0x0020,0x000d);
2805 s2 = document.GetEntryByNumber(0x0020,0x000d);
2816 // Serie Instance UID
2817 s1 = GetEntryByNumber(0x0020,0x000e);
2818 s2 = document.GetEntryByNumber(0x0020,0x000e);
2834 //-----------------------------------------------------------------------------