1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/21 12:38:29 $
7 Version: $Revision: 1.21 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.htm for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
24 #include "gdcmGlobal.h"
26 #include "gdcmDebug.h"
35 #include <netinet/in.h>
40 // Implicit VR Little Endian
41 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
42 // Explicit VR Little Endian
43 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
44 // Deflated Explicit VR Little Endian
45 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
46 // Explicit VR Big Endian
47 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
48 // JPEG Baseline (Process 1)
49 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
50 // JPEG Extended (Process 2 & 4)
51 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
52 // JPEG Extended (Process 3 & 5)
53 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
54 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
55 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
56 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
57 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
58 // JPEG Lossless, Non-Hierarchical (Process 14)
59 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
60 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
61 // [Selection Value 1])
62 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
64 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
66 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
68 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
70 #define str2num(str, typeNum) *((typeNum *)(str))
72 //-----------------------------------------------------------------------------
73 // Refer to gdcmDocument::CheckSwap()
74 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
76 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
77 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
79 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
81 //-----------------------------------------------------------------------------
82 // Constructor / Destructor
86 * @param inFilename file to be opened for parsing
87 * @param exception_on_error whether we throw an exception or not
88 * @param enable_sequences = true to allow the header
89 * to be parsed *inside* the SeQuences,
90 * when they have an actual length
91 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
92 * @param ignore_shadow to allow skipping the shadow elements,
93 * to save memory space.
94 * \warning The TRUE value for this param has to be used
95 * with a FALSE value for the 'enable_sequence' param.
96 * ('public elements' may be embedded in 'shadow Sequences')
98 gdcmDocument::gdcmDocument(std::string const & inFilename,
99 bool exception_on_error,
100 bool enable_sequences,
102 : gdcmElementSet(-1) {
103 enableSequences=enable_sequences;
104 IgnoreShadow =ignore_shadow;
106 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
107 Filename = inFilename;
110 if ( !OpenFile(exception_on_error))
113 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
117 fseek(fp,0L,SEEK_END);
118 long lgt = ftell(fp);
122 long beg = ftell(fp);
127 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
128 (void)l; //is l used anywhere ?
131 // --------------------------------------------------------------
132 // Special Patch to allow gdcm to read ACR-LibIDO formated images
134 // if recognition code tells us we deal with a LibIDO image
135 // we switch lineNumber and columnNumber
138 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
139 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
140 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
141 // with "little-endian strings"
143 Filetype = gdcmACR_LIBIDO;
144 std::string rows = GetEntryByNumber(0x0028, 0x0010);
145 std::string columns = GetEntryByNumber(0x0028, 0x0011);
146 SetEntryByNumber(columns, 0x0028, 0x0010);
147 SetEntryByNumber(rows , 0x0028, 0x0011);
149 // ----------------- End of Special Patch ----------------
151 printLevel = 1; // 'Medium' print level by default
156 * @param exception_on_error
158 gdcmDocument::gdcmDocument(bool exception_on_error)
159 :gdcmElementSet(-1) {
160 (void)exception_on_error;
163 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
166 printLevel = 1; // 'Medium' print level by default
170 * \brief Canonical destructor.
172 gdcmDocument::~gdcmDocument (void) {
176 // Recursive clean up of sequences
177 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
184 //-----------------------------------------------------------------------------
188 * \brief Prints The Dict Entries of THE public Dicom Dictionary
191 void gdcmDocument::PrintPubDict(std::ostream & os) {
192 RefPubDict->Print(os);
196 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
199 void gdcmDocument::PrintShaDict(std::ostream & os) {
200 RefShaDict->Print(os);
203 //-----------------------------------------------------------------------------
206 * \brief Get the public dictionary used
208 gdcmDict *gdcmDocument::GetPubDict(void) {
213 * \brief Get the shadow dictionary used
215 gdcmDict *gdcmDocument::GetShaDict(void) {
220 * \brief Set the shadow dictionary used
221 * \param dict dictionary to use in shadow
223 bool gdcmDocument::SetShaDict(gdcmDict *dict){
229 * \brief Set the shadow dictionary used
230 * \param dictName name of the dictionary to use in shadow
232 bool gdcmDocument::SetShaDict(DictKey dictName){
233 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
238 * \brief This predicate, based on hopefully reasonable heuristics,
239 * decides whether or not the current gdcmDocument was properly parsed
240 * and contains the mandatory information for being considered as
241 * a well formed and usable Dicom/Acr File.
242 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
245 bool gdcmDocument::IsReadable(void) {
246 if(Filetype==gdcmUnknown) {
247 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
250 if(!tagHT.empty()<=0) {
251 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
260 * \brief Internal function that checks whether the Transfer Syntax given
261 * as argument is the one present in the current document.
262 * @param SyntaxToCheck The transfert syntax we need to check against.
263 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
264 * the current document. False either when the document contains
265 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
267 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
269 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
273 // The entry might be present but not loaded (parsing and loading
274 // happen at differente stages): try loading and proceed with check...
275 LoadDocEntrySafe(Entry);
276 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
278 std::string Transfer = ValEntry->GetValue();
279 // The actual transfer (as read from disk) might be padded. We
280 // first need to remove the potential padding. We can make the
281 // weak assumption that padding was not executed with digits...
282 while ( ! isdigit(Transfer[Transfer.length()-1]) )
284 Transfer.erase(Transfer.length()-1, 1);
286 if ( Transfer == SyntaxToCheck )
293 * \brief Determines if the Transfer Syntax of the present document
294 * corresponds to a Implicit Value Representation of
296 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
297 * @return True when ImplicitVRLittleEndian found. False in all other cases.
299 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
301 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
305 * \brief Determines if the Transfer Syntax was already encountered
306 * and if it corresponds to a ExplicitVRLittleEndian one.
307 * @return True when ExplicitVRLittleEndian found. False in all other cases.
309 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
311 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
315 * \brief Determines if the Transfer Syntax was already encountered
316 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
317 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
319 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
321 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
325 * \brief Determines if the Transfer Syntax was already encountered
326 * and if it corresponds to a Explicit VR Big Endian one.
327 * @return True when big endian found. False in all other cases.
329 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
331 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
335 * \brief Determines if the Transfer Syntax was already encountered
336 * and if it corresponds to a JPEGBaseLineProcess1 one.
337 * @return True when JPEGBaseLineProcess1found. False in all other cases.
339 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
341 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
345 * \brief Determines if the Transfer Syntax was already encountered
346 * and if it corresponds to a JPEGExtendedProcess2-4 one.
347 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
349 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
351 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
355 * \brief Determines if the Transfer Syntax was already encountered
356 * and if it corresponds to a JPEGExtendeProcess3-5 one.
357 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
359 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
361 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
365 * \brief Determines if the Transfer Syntax was already encountered
366 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
367 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
370 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
372 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
376 * \brief Determines if the Transfer Syntax was already encountered
377 * and if it corresponds to a RLE Lossless one.
378 * @return True when RLE Lossless found. False in all
381 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
383 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
387 * \brief Determines if Transfer Syntax was already encountered
388 * and if it corresponds to a JPEG Lossless one.
389 * @return True when RLE Lossless found. False in all
392 bool gdcmDocument::IsJPEGLossless(void)
394 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
395 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
396 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
400 * \brief Determines if the Transfer Syntax was already encountered
401 * and if it corresponds to a JPEG2000 one
402 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
405 bool gdcmDocument::IsJPEG2000(void)
407 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
408 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
412 * \brief Predicate for dicom version 3 file.
413 * @return True when the file is a dicom version 3.
415 bool gdcmDocument::IsDicomV3(void) {
416 // Checking if Transfert Syntax exists is enough
417 // Anyway, it's to late check if the 'Preamble' was found ...
418 // And ... would it be a rich idea to check ?
419 // (some 'no Preamble' DICOM images exist !)
420 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
424 * \brief returns the File Type
425 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
426 * @return the FileType code
428 FileType gdcmDocument::GetFileType(void) {
433 * \brief opens the file
434 * @param exception_on_error
437 FILE *gdcmDocument::OpenFile(bool exception_on_error)
440 fp=fopen(Filename.c_str(),"rb");
444 if(exception_on_error)
445 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
448 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
457 fread(&zero, (size_t)2, (size_t)1, fp);
459 //ACR -- or DICOM with no Preamble --
460 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
464 fseek(fp, 126L, SEEK_CUR);
466 fread(dicm, (size_t)4, (size_t)1, fp);
467 if( memcmp(dicm, "DICM", 4) == 0 )
471 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
474 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
480 * \brief closes the file
481 * @return TRUE if the close was successfull
483 bool gdcmDocument::CloseFile(void) {
484 int closed = fclose(fp);
492 * \brief Writes in a file all the Header Entries (Dicom Elements)
493 * of the Chained List
494 * @param fp file pointer on an already open file
495 * @param type Type of the File to be written
496 * (ACR-NEMA, ExplicitVR, ImplicitVR)
497 * \return Always true.
499 bool gdcmDocument::Write(FILE *fp, FileType type) {
502 /// The stuff will have to be rewritten using the SeQuence based
503 /// tree-like stucture instead of the chained list .
504 /// (so we shall remove the Group*HT from the gdcmDocument)
508 /// \todo move the following lines (and a lot of others, to be written)
509 /// to a future function CheckAndCorrectHeader
513 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
514 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
515 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
517 /// a moins de se livrer a un tres complique ajout des champs manquants.
518 /// faire un CheckAndCorrectHeader (?)
520 if (type == gdcmImplicitVR)
522 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
523 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
525 /// \todo Refer to standards on page 21, chapter 6.2
526 /// "Value representation": values with a VR of UI shall be
527 /// padded with a single trailing null
528 /// Dans le cas suivant on doit pader manuellement avec un 0
530 SetEntryLengthByNumber(18, 0x0002, 0x0010);
533 if (type == gdcmExplicitVR)
535 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
536 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,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 /// Dans le cas suivant on doit pader manuellement avec un 0
543 SetEntryLengthByNumber(20, 0x0002, 0x0010);
547 * \todo rewrite later, if really usefull
549 * --> Warning : un-updated odd groups lengths can causes pb
550 * --> (xmedcon breaks)
551 * --> to be re- written with future org.
553 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
554 * UpdateGroupLength(false,type);
556 * UpdateGroupLength(true,ACR);
559 WriteEntries(fp,type);
564 * \brief Modifies the value of a given Header Entry (Dicom Element)
565 * when it exists. Create it with the given value when unexistant.
566 * @param Value (string) Value to be set
567 * @param Group Group number of the Entry
568 * @param Elem Element number of the Entry
569 * \return pointer to the modified/created Header Entry (NULL when creation
573 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
578 gdcmDocEntry* CurrentEntry;
579 gdcmValEntry* ValEntry;
581 CurrentEntry = GetDocEntryByNumber( Group, Elem);
584 // The entry wasn't present and we simply create the required ValEntry:
585 CurrentEntry = NewDocEntryByNumber(Group, Elem);
588 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
589 " NewDocEntryByNumber failed.");
592 ValEntry = new gdcmValEntry(CurrentEntry);
593 if ( !AddEntry(ValEntry))
595 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
596 " failed allthough this is a creation.");
601 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
604 // We need to promote the gdcmDocEntry to a gdcmValEntry:
605 ValEntry = new gdcmValEntry(CurrentEntry);
606 if (!RemoveEntry(CurrentEntry))
608 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
609 " of previous DocEntry failed.");
612 if ( !AddEntry(ValEntry))
614 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
615 " promoted ValEntry failed.");
621 SetEntryByNumber(Value, Group, Elem);
627 * \brief Modifies the value of a given Header Entry (Dicom Element)
628 * when it exists. Create it with the given value when unexistant.
629 * @param voidArea (binary) value to be set
630 * @param Group Group number of the Entry
631 * @param Elem Element number of the Entry
632 * \return pointer to the modified/created Header Entry (NULL when creation
635 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
643 a = GetDocEntryByNumber( Group, Elem);
645 a =NewBinEntryByNumber(Group, Elem);
649 b = new gdcmBinEntry(a);
652 SetEntryByNumber(voidArea, lgth, Group, Elem);
653 b->SetVoidArea(voidArea);
661 * \brief Set a new value if the invoked element exists
662 * Seems to be useless !!!
663 * @param Value new element value
664 * @param Group group number of the Entry
665 * @param Elem element number of the Entry
668 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
670 std::string v = Value;
671 SetEntryByNumber(v, Group, Elem);
675 //-----------------------------------------------------------------------------
679 * \brief Checks if a given Dicom Element exists within the H table
680 * @param group Group number of the searched Dicom Element
681 * @param element Element number of the searched Dicom Element
682 * @return number of occurences
684 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
685 std::string key = gdcmDictEntry::TranslateToKey(group, element );
686 return tagHT.count(key);
690 * \brief Searches within Header Entries (Dicom Elements) parsed with
691 * the public and private dictionaries
692 * for the element value of a given tag.
693 * \warning Don't use any longer : use GetPubEntryByName
694 * @param tagName name of the searched element.
695 * @return Corresponding element value when it exists,
696 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
698 std::string gdcmDocument::GetEntryByName(std::string tagName) {
699 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
700 if( dictEntry == NULL)
703 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
707 * \brief Searches within Header Entries (Dicom Elements) parsed with
708 * the public and private dictionaries
709 * for the element value representation of a given tag.
711 * Obtaining the VR (Value Representation) might be needed by caller
712 * to convert the string typed content to caller's native type
713 * (think of C++ vs Python). The VR is actually of a higher level
714 * of semantics than just the native C++ type.
715 * @param tagName name of the searched element.
716 * @return Corresponding element value representation when it exists,
717 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
719 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
720 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
721 if( dictEntry == NULL)
724 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
725 dictEntry->GetElement());
726 return elem->GetVR();
731 * \brief Searches within Header Entries (Dicom Elements) parsed with
732 * the public and private dictionaries
733 * for the element value representation of a given tag.
734 * @param group Group number of the searched tag.
735 * @param element Element number of the searched tag.
736 * @return Corresponding element value representation when it exists,
737 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
739 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
740 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
741 if ( ! tagHT.count(key))
743 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
747 * \brief Searches within Header Entries (Dicom Elements) parsed with
748 * the public and private dictionaries
749 * for the element value representation of a given tag..
751 * Obtaining the VR (Value Representation) might be needed by caller
752 * to convert the string typed content to caller's native type
753 * (think of C++ vs Python). The VR is actually of a higher level
754 * of semantics than just the native C++ type.
755 * @param group Group number of the searched tag.
756 * @param element Element number of the searched tag.
757 * @return Corresponding element value representation when it exists,
758 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
760 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
761 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
764 return elem->GetVR();
768 * \brief Searches within Header Entries (Dicom Elements) parsed with
769 * the public and private dictionaries
770 * for the value length of a given tag..
771 * @param group Group number of the searched tag.
772 * @param element Element number of the searched tag.
773 * @return Corresponding element length; -2 if not found
775 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
776 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
779 return elem->GetLength();
782 * \brief Sets the value (string) of the Header Entry (Dicom Element)
783 * @param content string value of the Dicom Element
784 * @param tagName name of the searched Dicom Element.
785 * @return true when found
787 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
788 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
789 if( dictEntry == NULL)
792 return SetEntryByNumber(content,dictEntry->GetGroup(),
793 dictEntry->GetElement());
797 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
798 * through it's (group, element) and modifies it's content with
800 * @param content new value (string) to substitute with
801 * @param group group number of the Dicom Element to modify
802 * @param element element number of the Dicom Element to modify
804 bool gdcmDocument::SetEntryByNumber(std::string content,
808 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
811 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
812 " ValEntry (try promotion first).");
816 // Non even content must be padded with a space (020H).
817 if((content.length())%2)
818 content = content + '\0';
820 ValEntry->SetValue(content);
822 // Integers have a special treatement for their length:
823 VRKey vr = ValEntry->GetVR();
824 if( (vr == "US") || (vr == "SS") )
825 ValEntry->SetLength(2);
826 else if( (vr == "UL") || (vr == "SL") )
827 ValEntry->SetLength(4);
829 ValEntry->SetLength(content.length());
835 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
836 * through it's (group, element) and modifies it's content with
838 * @param content new value (void *) to substitute with
839 * @param group group number of the Dicom Element to modify
840 * @param element element number of the Dicom Element to modify
842 bool gdcmDocument::SetEntryByNumber(void *content,
847 (void)lgth; //not used
848 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
849 if ( ! tagHT.count(key))
852 /* Hope Binray field length is never wrong
853 if(lgth%2) // Non even length are padded with a space (020H).
856 //content = content + '\0'; // fing a trick to enlarge a binary field?
860 a = (gdcmBinEntry *)tagHT[key];
861 a->SetVoidArea(content);
862 //a->SetLength(lgth); // ???
867 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
868 * in the PubDocEntrySet of this instance
869 * through it's (group, element) and modifies it's length with
871 * \warning Use with extreme caution.
872 * @param l new length to substitute with
873 * @param group group number of the Entry to modify
874 * @param element element number of the Entry to modify
875 * @return true on success, false otherwise.
877 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
881 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
882 if ( ! tagHT.count(key))
884 if (l%2) l++; // length must be even
885 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
891 * \brief Gets (from Header) the offset of a 'non string' element value
892 * (LoadElementValues has already be executed)
893 * @param Group group number of the Entry
894 * @param Elem element number of the Entry
895 * @return File Offset of the Element Value
897 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
899 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
902 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
905 return Entry->GetOffset();
909 * \brief Gets (from Header) a 'non string' element value
910 * (LoadElementValues has already be executed)
911 * @param Group group number of the Entry
912 * @param Elem element number of the Entry
913 * @return Pointer to the 'non string' area
915 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
917 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
920 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
923 return ((gdcmBinEntry *)Entry)->GetVoidArea();
927 * \brief Loads (from disk) the element content
928 * when a string is not suitable
929 * @param Group group number of the Entry
930 * @param Elem element number of the Entry
932 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
934 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
937 size_t o =(size_t)Element->GetOffset();
938 fseek(fp, o, SEEK_SET);
939 size_t l = Element->GetLength();
940 char* a = new char[l];
942 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
945 SetEntryVoidAreaByNumber(a, Group, Elem);
946 /// \todo check the result
947 size_t l2 = fread(a, 1, l ,fp);
958 * \brief Sets a 'non string' value to a given Dicom Element
960 * @param group Group number of the searched Dicom Element
961 * @param element Element number of the searched Dicom Element
964 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
968 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
969 if ( ! tagHT.count(key))
971 // This was for multimap ?
972 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
978 * \brief Update the entries with the shadow dictionary.
979 * Only non even entries are analyzed
981 void gdcmDocument::UpdateShaEntries(void) {
982 //gdcmDictEntry *entry;
985 /// \todo TODO : still any use to explore recursively the whole structure?
987 for(ListTag::iterator it=listEntries.begin();
988 it!=listEntries.end();
991 // Odd group => from public dictionary
992 if((*it)->GetGroup()%2==0)
995 // Peer group => search the corresponding dict entry
997 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1001 if((*it)->IsImplicitVR())
1006 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1008 // Set the new entry and the new value
1009 (*it)->SetDictEntry(entry);
1010 CheckDocEntryVR(*it,vr);
1012 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1017 // Remove precedent value transformation
1018 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1025 * \brief Searches within the Header Entries for a Dicom Element of
1027 * @param tagName name of the searched Dicom Element.
1028 * @return Corresponding Dicom Element when it exists, and NULL
1031 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1032 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1033 if( dictEntry == NULL)
1036 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1040 * \brief retrieves a Dicom Element (the first one) using (group, element)
1041 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1042 * if you think it's NOT UNIQUE, check the count number
1043 * and use iterators to retrieve ALL the Dicoms Elements within
1044 * a given couple (group, element)
1045 * @param group Group number of the searched Dicom Element
1046 * @param element Element number of the searched Dicom Element
1049 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1051 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1052 if ( ! tagHT.count(key))
1054 return tagHT.find(key)->second;
1058 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1059 * returns a result when the corresponding entry is of type
1061 * @return When present, the corresponding ValEntry.
1063 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1065 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1067 return (gdcmValEntry*)0;
1068 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1072 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1073 return (gdcmValEntry*)0;
1077 * \brief Loads the element while preserving the current
1078 * underlying file position indicator as opposed to
1079 * to LoadDocEntry that modifies it.
1080 * @param entry Header Entry whose value shall be loaded.
1083 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1084 long PositionOnEntry = ftell(fp);
1085 LoadDocEntry(entry);
1086 fseek(fp, PositionOnEntry, SEEK_SET);
1091 * \brief Writes in a file (according to the requested format)
1092 * the group, the element, the value representation and the length
1093 * of a single gdcmDocEntry passed as argument.
1094 * @param tag pointer on the gdcmDocEntry to be written
1095 * @param _fp already open file pointer
1096 * @param type type of the File to be written
1098 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1102 guint16 group = tag->GetGroup();
1103 VRKey vr = tag->GetVR();
1104 guint16 el = tag->GetElement();
1105 guint32 lgr = tag->GetReadLength();
1107 if ( (group == 0xfffe) && (el == 0x0000) )
1108 // Fix in order to make some MR PHILIPS images e-film readable
1109 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1110 // we just *always* ignore spurious fffe|0000 tag !
1113 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1114 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1116 if ( type == gdcmExplicitVR ) {
1118 // Special case of delimiters:
1119 if (group == 0xfffe) {
1120 // Delimiters have NO Value Representation and have NO length.
1121 // Hence we skip writing the VR and length and we pad by writing
1125 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1130 guint16 shortLgr = lgr;
1131 if (vr == "unkn") { // Unknown was 'written'
1132 // deal with Little Endian
1133 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1134 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1136 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1137 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1139 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1140 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1142 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1148 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1153 * \brief Writes in a file (according to the requested format)
1154 * the value of a single gdcmDocEntry passed as argument.
1155 * @param tag Pointer on the gdcmDocEntry to be written
1156 * @param _fp Already open file pointer
1157 * @param type type of the File to be written
1160 // \todo TODO : to be re -written recursively !
1161 void gdcmDocument::WriteEntryValue(gdcmDocEntry *Entry, FILE *_fp,FileType type)
1164 guint16 group = Entry->GetGroup();
1165 VRKey vr = Entry->GetVR();
1166 guint32 lgr = Entry->GetReadLength();
1169 // SeQuences have no value:
1171 if (group == 0xfffe)
1172 // Delimiters have no associated value:
1175 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1177 gdcmBinEntry *BinEntry= (gdcmBinEntry *)Entry;;
1178 voidArea = BinEntry->GetVoidArea();
1179 if (voidArea != NULL)
1180 { // there is a 'non string' LUT, overlay, etc
1181 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1186 if (vr == "US" || vr == "SS")
1188 // some 'Short integer' fields may be mulivaluated
1189 // each single value is separated from the next one by '\'
1190 // we split the string and write each value as a short int
1191 std::vector<std::string> tokens;
1192 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1193 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1194 for (unsigned int i=0; i<tokens.size();i++)
1196 guint16 val_uint16 = atoi(tokens[i].c_str());
1197 void *ptr = &val_uint16;
1198 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1203 if (vr == "UL" || vr == "SL")
1205 // Some 'Integer' fields may be multivaluated (multiple instances
1206 // of integers). But each single integer value is separated from the
1207 // next one by '\' (backslash character). Hence we split the string
1208 // along the '\' and write each value as an int:
1209 std::vector<std::string> tokens;
1210 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1211 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1212 for (unsigned int i=0; i<tokens.size();i++)
1214 guint32 val_uint32 = atoi(tokens[i].c_str());
1215 void *ptr = &val_uint32;
1216 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1221 fwrite (((gdcmValEntry *)Entry)->GetValue().c_str(),
1222 (size_t)lgr ,(size_t)1, _fp); // Elem value
1226 * \brief Writes in a file (according to the requested format)
1227 * a single gdcmDocEntry passed as argument.
1228 * \sa WriteEntryValue, WriteEntryTagVRLength.
1229 * @param tag Pointer on the gdcmDocEntry to be written
1230 * @param _fp Already open file pointer
1231 * @param type type of the File to be written
1234 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1236 guint32 length = tag->GetLength();
1238 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1240 // The value of a tag MUST (see the DICOM norm) be an odd number of
1241 // bytes. When this is not the case, pad with an additional byte:
1243 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1244 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1246 WriteEntryTagVRLength(ValEntry, _fp, type);
1247 WriteEntryValue(ValEntry, _fp, type);
1251 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1253 (void)BinEntry; //not used
1254 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
1257 // The value of a tag MUST (see the DICOM norm) be an odd number of
1258 // bytes. When this is not the case, pad with an additional byte:
1261 tag->SetValue(tag->GetValue()+"\0");
1262 tag->SetLength(tag->GetReadLength()+1);
1265 WriteEntryTagVRLength(tag, _fp, type);
1266 WriteEntryValue(tag, _fp, type);
1270 return false; //default behavior ?
1274 * \brief writes on disc according to the requested format
1275 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1276 * using the Chained List
1277 * \warning does NOT add the missing elements in the header :
1278 * it's up to the user doing it !
1279 * (function CheckHeaderCoherence to be written)
1280 * \warning DON'T try, right now, to write a DICOM image
1281 * from an ACR Header (meta elements will be missing!)
1282 * @param type type of the File to be written
1283 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1284 * @param _fp already open file pointer
1287 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1289 /// \todo FIXME : explore recursively the whole structure...
1290 /// \todo (?) check write failures (after *each* fwrite)
1292 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1293 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1295 gdcmDocEntry * entry = it->second;
1297 if ( type == gdcmACR ){
1298 if (entry->GetGroup() < 0x0008)
1299 // Ignore pure DICOM V3 groups
1301 if (entry->GetGroup() %2)
1302 // Ignore the "shadow" groups
1304 if (entry->GetVR() == "SQ" ) // ignore Sequences
1307 if (! WriteEntry(entry, _fp, type) ) {
1308 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1317 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1319 * @return The properly swaped 32 bits integer.
1321 guint32 gdcmDocument::SwapLong(guint32 a) {
1326 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1327 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1331 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1335 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1338 std::cout << "swapCode= " << sw << std::endl;
1339 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1346 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1348 * @return The properly unswaped 32 bits integer.
1350 guint32 gdcmDocument::UnswapLong(guint32 a) {
1351 return (SwapLong(a));
1355 * \brief Swaps the bytes so they agree with the processor order
1356 * @return The properly swaped 16 bits integer.
1358 guint16 gdcmDocument::SwapShort(guint16 a) {
1359 if ( (sw==4321) || (sw==2143) )
1360 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1365 * \brief Unswaps the bytes so they agree with the processor order
1366 * @return The properly unswaped 16 bits integer.
1368 guint16 gdcmDocument::UnswapShort(guint16 a) {
1369 return (SwapShort(a));
1372 //-----------------------------------------------------------------------------
1376 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1377 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1380 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1382 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1383 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1390 depth = set->GetDepthLevel();
1393 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1396 NewDocEntry = ReadNextDocEntry( );
1400 vr = NewDocEntry->GetVR();
1404 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1407 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1408 NewValEntry->Copy(NewDocEntry);
1409 NewValEntry->SetDepthLevel(depth);
1410 set->AddEntry(NewValEntry);
1411 LoadDocEntry(NewValEntry);
1412 if (/*!delim_mode && */NewValEntry->isItemDelimitor())
1414 if ( !delim_mode && ftell(fp)-offset >= l_max)
1421 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1423 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1424 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1425 "nor BinEntry. Probably unknown VR.");
1428 ////// BinEntry or UNKOWN VR:
1429 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1430 bn->Copy(NewDocEntry);
1435 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1436 NewDocEntry->GetElement() == 0x0010 )
1438 if (NewDocEntry->GetLength()==0xffffffff)
1439 // Broken US.3405.1.dcm
1440 Parse7FE0(); // to skip the pixels
1441 // (multipart JPEG/RLE are trouble makers)
1445 // to be sure we are at the beginning
1446 SkipToNextDocEntry(NewDocEntry);
1447 l = NewDocEntry->GetFullLength();
1453 l=NewDocEntry->GetReadLength();
1454 if (l != 0) // don't mess the delim_mode for zero-length sequence
1455 if (l == 0xffffffff)
1459 // no other way to create it ...
1460 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1461 set->GetDepthLevel());
1462 sq->Copy(NewDocEntry);
1463 sq->SetDelimitorMode(delim_mode);
1464 sq->SetDepthLevel(depth);
1467 { // Don't try to parse zero-length sequences
1468 long lgt = ParseSQ( sq,
1469 NewDocEntry->GetOffset(),
1471 (void)lgt; //not used...
1473 // FIXME : on en fait quoi, de lgt ?
1475 if ( !delim_mode && ftell(fp)-offset >= l_max)
1486 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1487 * @return parsed length for this level
1489 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1490 long offset, long l_max, bool delim_mode)
1492 int SQItemNumber = 0;
1494 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1499 int depth = set->GetDepthLevel();
1500 (void)depth; //not used
1503 NewDocEntry = ReadNextDocEntry();
1505 if (NewDocEntry->isSequenceDelimitor()) {
1506 /// \todo add the Sequence Delimitor
1507 /// \todo find the trick to put it properly !
1508 set->SetSequenceDelimitationItem(NewDocEntry);
1512 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1516 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1517 itemSQ->AddEntry(NewDocEntry);
1518 /// \todo no value, no voidArea. Think of it while printing !
1519 l= NewDocEntry->GetReadLength();
1521 if (l == 0xffffffff)
1526 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1528 set->AddEntry(itemSQ,SQItemNumber);
1530 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1534 lgth = ftell(fp) - offset;
1539 * \brief Loads the element content if its length doesn't exceed
1540 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1541 * @param Entry Header Entry (Dicom Element) to be dealt with
1543 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1546 guint16 group = Entry->GetGroup();
1547 std::string vr= Entry->GetVR();
1548 guint32 length = Entry->GetLength();
1550 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1552 // A SeQuence "contains" a set of Elements.
1553 // (fffe e000) tells us an Element is beginning
1554 // (fffe e00d) tells us an Element just ended
1555 // (fffe e0dd) tells us the current SeQuence just ended
1556 if( group == 0xfffe ) {
1557 // NO more value field for SQ !
1558 //Entry->SetValue("gdcm::Skipped");
1559 // appel recursif de Load Value
1560 // (meme pb que pour le parsing)
1564 // When the length is zero things are easy:
1565 if ( length == 0 ) {
1566 ((gdcmValEntry *)Entry)->SetValue("");
1570 // The elements whose length is bigger than the specified upper bound
1571 // are not loaded. Instead we leave a short notice of the offset of
1572 // the element content and it's length.
1573 if (length > MaxSizeLoadEntry) {
1574 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1576 std::ostringstream s;
1577 s << "gdcm::NotLoaded.";
1578 s << " Address:" << (long)Entry->GetOffset();
1579 s << " Length:" << Entry->GetLength();
1580 s << " x(" << std::hex << Entry->GetLength() << ")";
1581 ValEntryPtr->SetValue(s.str());
1583 // to be sure we are at the end of the value ...
1584 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1589 // Any compacter code suggested (?)
1590 if ( IsDocEntryAnInteger(Entry) ) {
1592 std::ostringstream s;
1594 // When short integer(s) are expected, read and convert the following
1595 // n *two characters properly i.e. as short integers as opposed to strings.
1596 // Elements with Value Multiplicity > 1
1597 // contain a set of integers (not a single one)
1598 if (vr == "US" || vr == "SS") {
1600 NewInt = ReadInt16();
1603 for (int i=1; i < nbInt; i++) {
1605 NewInt = ReadInt16();
1610 // When integer(s) are expected, read and convert the following
1611 // n * four characters properly i.e. as integers as opposed to strings.
1612 // Elements with Value Multiplicity > 1
1613 // contain a set of integers (not a single one)
1614 else if (vr == "UL" || vr == "SL") {
1616 NewInt = ReadInt32();
1619 for (int i=1; i < nbInt; i++) {
1621 NewInt = ReadInt32();
1626 #ifdef GDCM_NO_ANSI_STRING_STREAM
1627 s << std::ends; // to avoid oddities on Solaris
1628 #endif //GDCM_NO_ANSI_STRING_STREAM
1630 ((gdcmValEntry *)Entry)->SetValue(s.str());
1634 // We need an additional byte for storing \0 that is not on disk
1635 std::string NewValue(length,0);
1636 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1637 if ( item_read != 1 ) {
1638 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1639 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1643 if( (vr == "UI") ) // Because of correspondance with the VR dic
1644 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1646 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1651 * \brief Find the value Length of the passed Header Entry
1652 * @param Entry Header Entry whose length of the value shall be loaded.
1654 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1655 guint16 element = Entry->GetElement();
1656 //guint16 group = Entry->GetGroup(); //FIXME
1657 std::string vr = Entry->GetVR();
1661 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1663 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1665 // The following reserved two bytes (see PS 3.5-2001, section
1666 // 7.1.2 Data element structure with explicit vr p27) must be
1667 // skipped before proceeding on reading the length on 4 bytes.
1668 fseek(fp, 2L, SEEK_CUR);
1669 guint32 length32 = ReadInt32();
1671 if ( (vr == "OB") && (length32 == 0xffffffff) )
1673 Entry->SetLength(FindDocEntryLengthOB());
1676 FixDocEntryFoundLength(Entry, length32);
1680 // Length is encoded on 2 bytes.
1681 length16 = ReadInt16();
1683 // We can tell the current file is encoded in big endian (like
1684 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1685 // and it's value is the one of the encoding of a big endian file.
1686 // In order to deal with such big endian encoded files, we have
1687 // (at least) two strategies:
1688 // * when we load the "Transfer Syntax" tag with value of big endian
1689 // encoding, we raise the proper flags. Then we wait for the end
1690 // of the META group (0x0002) among which is "Transfer Syntax",
1691 // before switching the swap code to big endian. We have to postpone
1692 // the switching of the swap code since the META group is fully encoded
1693 // in little endian, and big endian coding only starts at the next
1694 // group. The corresponding code can be hard to analyse and adds
1695 // many additional unnecessary tests for regular tags.
1696 // * the second strategy consists in waiting for trouble, that shall
1697 // appear when we find the first group with big endian encoding. This
1698 // is easy to detect since the length of a "Group Length" tag (the
1699 // ones with zero as element number) has to be of 4 (0x0004). When we
1700 // encounter 1024 (0x0400) chances are the encoding changed and we
1701 // found a group with big endian encoding.
1702 // We shall use this second strategy. In order to make sure that we
1703 // can interpret the presence of an apparently big endian encoded
1704 // length of a "Group Length" without committing a big mistake, we
1705 // add an additional check: we look in the already parsed elements
1706 // for the presence of a "Transfer Syntax" whose value has to be "big
1707 // endian encoding". When this is the case, chances are we have got our
1708 // hands on a big endian encoded file: we switch the swap code to
1709 // big endian and proceed...
1710 if ( (element == 0x0000) && (length16 == 0x0400) )
1712 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1714 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1719 SwitchSwapToBigEndian();
1720 // Restore the unproperly loaded values i.e. the group, the element
1721 // and the dictionary entry depending on them.
1722 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1723 guint16 CorrectElem = SwapShort(Entry->GetElement());
1724 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1728 // This correct tag is not in the dictionary. Create a new one.
1729 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1731 // FIXME this can create a memory leaks on the old entry that be
1732 // left unreferenced.
1733 Entry->SetDictEntry(NewTag);
1736 // Heuristic: well some files are really ill-formed.
1737 if ( length16 == 0xffff)
1740 //dbg.Verbose(0, "gdcmDocument::FindLength",
1741 // "Erroneous element length fixed.");
1742 // Actually, length= 0xffff means that we deal with
1743 // Unknown Sequence Length
1745 FixDocEntryFoundLength(Entry, (guint32)length16);
1750 // Either implicit VR or a non DICOM conformal (see note below) explicit
1751 // VR that ommited the VR of (at least) this element. Farts happen.
1752 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1753 // on Data elements "Implicit and Explicit VR Data Elements shall
1754 // not coexist in a Data Set and Data Sets nested within it".]
1755 // Length is on 4 bytes.
1757 FixDocEntryFoundLength(Entry, ReadInt32());
1763 * \brief Find the Value Representation of the current Dicom Element.
1766 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1768 if (Filetype != gdcmExplicitVR)
1773 long PositionOnEntry = ftell(fp);
1774 // Warning: we believe this is explicit VR (Value Representation) because
1775 // we used a heuristic that found "UL" in the first tag. Alas this
1776 // doesn't guarantee that all the tags will be in explicit VR. In some
1777 // cases (see e-film filtered files) one finds implicit VR tags mixed
1778 // within an explicit VR file. Hence we make sure the present tag
1779 // is in explicit VR and try to fix things if it happens not to be
1782 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1784 if(!CheckDocEntryVR(Entry,VR))
1786 fseek(fp, PositionOnEntry, SEEK_SET);
1787 // When this element is known in the dictionary we shall use, e.g. for
1788 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1789 // dictionary entry. Still we have to flag the element as implicit since
1790 // we know now our assumption on expliciteness is not furfilled.
1792 if ( Entry->IsVRUnknown() )
1793 Entry->SetVR("Implicit");
1794 Entry->SetImplicitVR();
1799 * \brief Check the correspondance between the VR of the header entry
1800 * and the taken VR. If they are different, the header entry is
1801 * updated with the new VR.
1802 * @param Entry Header Entry to check
1803 * @param vr Dicom Value Representation
1804 * @return false if the VR is incorrect of if the VR isn't referenced
1805 * otherwise, it returns true
1807 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1809 char msg[100]; // for sprintf
1810 bool RealExplicit = true;
1812 // Assume we are reading a falsely explicit VR file i.e. we reached
1813 // a tag where we expect reading a VR but are in fact we read the
1814 // first to bytes of the length. Then we will interogate (through find)
1815 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1816 // both GCC and VC++ implementations of the STL map. Hence when the
1817 // expected VR read happens to be non-ascii characters we consider
1818 // we hit falsely explicit VR tag.
1820 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1821 RealExplicit = false;
1823 // CLEANME searching the dicom_vr at each occurence is expensive.
1824 // PostPone this test in an optional integrity check at the end
1825 // of parsing or only in debug mode.
1826 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1827 RealExplicit= false;
1829 if ( !RealExplicit )
1831 // We thought this was explicit VR, but we end up with an
1832 // implicit VR tag. Let's backtrack.
1833 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1834 Entry->GetGroup(),Entry->GetElement());
1835 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1836 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1837 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1838 Entry->GetGroup(),Entry->GetElement(),
1839 "UL","FIXME","Group Length");
1840 Entry->SetDictEntry(NewEntry);
1845 if ( Entry->IsVRUnknown() )
1847 // When not a dictionary entry, we can safely overwrite the VR.
1848 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1854 else if ( Entry->GetVR() != vr )
1856 // The VR present in the file and the dictionary disagree. We assume
1857 // the file writer knew best and use the VR of the file. Since it would
1858 // be unwise to overwrite the VR of a dictionary (since it would
1859 // compromise it's next user), we need to clone the actual DictEntry
1860 // and change the VR for the read one.
1861 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1862 Entry->GetGroup(),Entry->GetElement(),
1863 vr,"FIXME",Entry->GetName());
1864 Entry->SetDictEntry(NewEntry);
1870 * \brief Get the transformed value of the header entry. The VR value
1871 * is used to define the transformation to operate on the value
1872 * \warning NOT end user intended method !
1874 * @return Transformed entry value
1876 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1878 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1880 std::string val=((gdcmValEntry *)Entry)->GetValue();
1881 std::string vr=Entry->GetVR();
1882 guint32 length = Entry->GetLength();
1883 std::ostringstream s;
1886 // When short integer(s) are expected, read and convert the following
1887 // n * 2 bytes properly i.e. as a multivaluated strings
1888 // (each single value is separated fromthe next one by '\'
1889 // as usual for standard multivaluated filels
1890 // Elements with Value Multiplicity > 1
1891 // contain a set of short integers (not a single one)
1893 if (vr == "US" || vr == "SS")
1898 for (int i=0; i < nbInt; i++)
1902 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1903 NewInt16 = SwapShort(NewInt16);
1908 // When integer(s) are expected, read and convert the following
1909 // n * 4 bytes properly i.e. as a multivaluated strings
1910 // (each single value is separated fromthe next one by '\'
1911 // as usual for standard multivaluated filels
1912 // Elements with Value Multiplicity > 1
1913 // contain a set of integers (not a single one)
1914 else if (vr == "UL" || vr == "SL")
1919 for (int i=0; i < nbInt; i++)
1923 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1924 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1925 NewInt32=SwapLong(NewInt32);
1929 #ifdef GDCM_NO_ANSI_STRING_STREAM
1930 s << std::ends; // to avoid oddities on Solaris
1931 #endif //GDCM_NO_ANSI_STRING_STREAM
1935 return(((gdcmValEntry *)Entry)->GetValue());
1939 * \brief Get the reverse transformed value of the header entry. The VR
1940 * value is used to define the reverse transformation to operate on
1942 * \warning NOT end user intended method !
1944 * @return Reverse transformed entry value
1946 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1948 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1950 std::string vr=Entry->GetVR();
1951 std::ostringstream s;
1952 std::vector<std::string> tokens;
1954 if (vr == "US" || vr == "SS")
1958 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1959 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1960 for (unsigned int i=0; i<tokens.size();i++)
1962 NewInt16 = atoi(tokens[i].c_str());
1963 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1967 if (vr == "UL" || vr == "SL")
1971 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1972 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1973 for (unsigned int i=0; i<tokens.size();i++)
1975 NewInt32 = atoi(tokens[i].c_str());
1976 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1977 <<(char)((NewInt32>>16)&0xFF)<<(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 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
2009 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
2013 * \brief Loads the value for a a given VLEntry
2014 * \warning NOT end user intended method !
2017 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
2019 //SkipBytes(entry->GetLength());
2020 LoadDocEntry(entry);
2023 * \brief When the length of an element value is obviously wrong (because
2024 * the parser went Jabberwocky) one can hope improving things by
2025 * applying some heuristics.
2027 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
2028 guint32 FoundLength)
2030 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
2031 if ( FoundLength == 0xffffffff) {
2035 guint16 gr =Entry->GetGroup();
2036 guint16 el =Entry->GetElement();
2038 if (FoundLength%2) {
2039 std::ostringstream s;
2040 s << "Warning : Tag with uneven length "
2042 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2043 dbg.Verbose(0, s.str().c_str());
2046 //////// Fix for some naughty General Electric images.
2047 // Allthough not recent many such GE corrupted images are still present
2048 // on Creatis hard disks. Hence this fix shall remain when such images
2049 // are no longer in user (we are talking a few years, here)...
2050 // Note: XMedCom probably uses such a trick since it is able to read
2051 // those pesky GE images ...
2052 if (FoundLength == 13) { // Only happens for this length !
2053 if ( (Entry->GetGroup() != 0x0008)
2054 || ( (Entry->GetElement() != 0x0070)
2055 && (Entry->GetElement() != 0x0080) ) )
2058 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2062 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2063 // Occurence of such images is quite low (unless one leaves close to a
2064 // 'Leonardo' source. Hence, one might consider commenting out the
2065 // following fix on efficiency reasons.
2067 if ( (Entry->GetGroup() == 0x0009)
2068 && ( (Entry->GetElement() == 0x1113)
2069 || (Entry->GetElement() == 0x1114) ) )
2072 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2075 //////// Deal with sequences, but only on users request:
2077 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2079 FoundLength = 0; // ReadLength is unchanged
2082 //////// We encountered a 'delimiter' element i.e. a tag of the form
2083 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2084 // taken into account.
2086 if(Entry->GetGroup() == 0xfffe)
2088 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2089 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2090 // causes extra troubles...
2091 if( Entry->GetElement() != 0x0000 )
2097 Entry->SetUsableLength(FoundLength);
2101 * \brief Apply some heuristics to predict whether the considered
2102 * element value contains/represents an integer or not.
2103 * @param Entry The element value on which to apply the predicate.
2104 * @return The result of the heuristical predicate.
2106 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2107 guint16 element = Entry->GetElement();
2108 guint16 group = Entry->GetGroup();
2109 std::string vr = Entry->GetVR();
2110 guint32 length = Entry->GetLength();
2112 // When we have some semantics on the element we just read, and if we
2113 // a priori know we are dealing with an integer, then we shall be
2114 // able to swap it's element value properly.
2115 if ( element == 0 ) // This is the group length of the group
2121 // Allthough this should never happen, still some images have a
2122 // corrupted group length [e.g. have a glance at offset x(8336) of
2123 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2124 // Since for dicom compliant and well behaved headers, the present
2125 // test is useless (and might even look a bit paranoid), when we
2126 // encounter such an ill-formed image, we simply display a warning
2127 // message and proceed on parsing (while crossing fingers).
2128 std::ostringstream s;
2129 int filePosition = ftell(fp);
2130 s << "Erroneous Group Length element length on : (" \
2131 << std::hex << group << " , " << element
2132 << ") -before- position x(" << filePosition << ")"
2133 << "lgt : " << length;
2134 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2138 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2145 * \brief Find the Length till the next sequence delimiter
2146 * \warning NOT end user intended method !
2150 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2151 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2154 long PositionOnEntry = ftell(fp);
2155 bool FoundSequenceDelimiter = false;
2156 guint32 TotalLength = 0;
2159 while ( ! FoundSequenceDelimiter)
2165 TotalLength += 4; // We even have to decount the group and element
2167 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2169 char msg[100]; // for sprintf. Sorry
2170 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2171 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2175 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2176 FoundSequenceDelimiter = true;
2177 else if ( n != 0xe000 )
2179 char msg[100]; // for sprintf. Sorry
2180 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2182 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2186 ItemLength = ReadInt32();
2187 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2188 // the ItemLength with ReadInt32
2189 SkipBytes(ItemLength);
2191 fseek(fp, PositionOnEntry, SEEK_SET);
2196 * \brief Reads a supposed to be 16 Bits integer
2197 * (swaps it depending on processor endianity)
2198 * @return read value
2200 guint16 gdcmDocument::ReadInt16() {
2203 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2204 if ( item_read != 1 ) {
2206 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2216 * \brief Reads a supposed to be 32 Bits integer
2217 * (swaps it depending on processor endianity)
2218 * @return read value
2220 guint32 gdcmDocument::ReadInt32() {
2223 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2224 if ( item_read != 1 ) {
2226 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2236 * \brief skips bytes inside the source file
2237 * \warning NOT end user intended method !
2240 void gdcmDocument::SkipBytes(guint32 NBytes) {
2241 //FIXME don't dump the returned value
2242 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2246 * \brief Loads all the needed Dictionaries
2247 * \warning NOT end user intended method !
2249 void gdcmDocument::Initialise(void)
2251 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2256 * \brief Discover what the swap code is (among little endian, big endian,
2257 * bad little endian, bad big endian).
2259 * @return false when we are absolutely sure
2260 * it's neither ACR-NEMA nor DICOM
2261 * true when we hope ours assuptions are OK
2263 bool gdcmDocument::CheckSwap() {
2265 // The only guaranted way of finding the swap code is to find a
2266 // group tag since we know it's length has to be of four bytes i.e.
2267 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2268 // occurs when we can't find such group...
2270 guint32 x=4; // x : for ntohs
2271 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2277 char deb[HEADER_LENGTH_TO_READ];
2279 // First, compare HostByteOrder and NetworkByteOrder in order to
2280 // determine if we shall need to swap bytes (i.e. the Endian type).
2286 // The easiest case is the one of a DICOM header, since it possesses a
2287 // file preamble where it suffice to look for the string "DICM".
2288 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2291 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2292 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2294 // Next, determine the value representation (VR). Let's skip to the
2295 // first element (0002, 0000) and check there if we find "UL"
2296 // - or "OB" if the 1st one is (0002,0001) -,
2297 // in which case we (almost) know it is explicit VR.
2298 // WARNING: if it happens to be implicit VR then what we will read
2299 // is the length of the group. If this ascii representation of this
2300 // length happens to be "UL" then we shall believe it is explicit VR.
2301 // FIXME: in order to fix the above warning, we could read the next
2302 // element value (or a couple of elements values) in order to make
2303 // sure we are not commiting a big mistake.
2304 // We need to skip :
2305 // * the 128 bytes of File Preamble (often padded with zeroes),
2306 // * the 4 bytes of "DICM" string,
2307 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2308 // i.e. a total of 136 bytes.
2312 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2313 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2314 // *Implicit* VR. -and it is !-
2316 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2317 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2318 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2319 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2320 // when Write DCM *adds*
2322 // Use gdcmDocument::dicom_vr to test all the possibilities
2323 // instead of just checking for UL, OB and UI !? group 0000
2325 Filetype = gdcmExplicitVR;
2326 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2327 "explicit Value Representation");
2331 Filetype = gdcmImplicitVR;
2332 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2333 "not an explicit Value Representation");
2339 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2340 "HostByteOrder != NetworkByteOrder");
2345 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2346 "HostByteOrder = NetworkByteOrder");
2349 // Position the file position indicator at first tag (i.e.
2350 // after the file preamble and the "DICM" string).
2352 fseek (fp, 132L, SEEK_SET);
2356 // Alas, this is not a DicomV3 file and whatever happens there is no file
2357 // preamble. We can reset the file position indicator to where the data
2358 // is (i.e. the beginning of the file).
2359 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2362 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2363 // By clean we mean that the length of the first tag is written down.
2364 // If this is the case and since the length of the first group HAS to be
2365 // four (bytes), then determining the proper swap code is straightforward.
2368 // We assume the array of char we are considering contains the binary
2369 // representation of a 32 bits integer. Hence the following dirty
2371 s32 = *((guint32 *)(entCur));
2392 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2393 // It is time for despaired wild guesses.
2394 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2395 // i.e. the 'group length' element is not present :
2397 // check the supposed to be 'group number'
2398 // 0x0002 or 0x0004 or 0x0008
2399 // to determine ' sw' value .
2400 // Only 0 or 4321 will be possible
2401 // (no oportunity to check for the formerly well known
2402 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2403 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2404 // the file IS NOT ACR-NEMA nor DICOM V3
2405 // Find a trick to tell it the caller...
2407 s16 = *((guint16 *)(deb));
2423 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2424 "ACR/NEMA unfound swap info (Really hopeless !)");
2425 Filetype = gdcmUnknown;
2429 // Then the only info we have is the net2host one.
2439 * \brief Restore the unproperly loaded values i.e. the group, the element
2440 * and the dictionary entry depending on them.
2442 void gdcmDocument::SwitchSwapToBigEndian(void)
2444 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2445 "Switching to BigEndian mode.");
2466 * \brief during parsing, Header Elements too long are not loaded in memory
2469 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2473 if ((guint32)NewSize >= (guint32)0xffffffff)
2475 MaxSizeLoadEntry = 0xffffffff;
2478 MaxSizeLoadEntry = NewSize;
2483 * \brief Header Elements too long will not be printed
2484 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2487 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2491 if ((guint32)NewSize >= (guint32)0xffffffff)
2493 MaxSizePrintEntry = 0xffffffff;
2496 MaxSizePrintEntry = NewSize;
2502 * \brief Read the next tag but WITHOUT loading it's value
2503 * (read the 'Group Number', the 'Element Number',
2504 * gets the Dict Entry
2505 * gets the VR, gets the length, gets the offset value)
2506 * @return On succes the newly created DocEntry, NULL on failure.
2508 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2510 gdcmDocEntry *NewEntry;
2515 // We reached the EOF (or an error occured) therefore
2516 // header parsing has to be considered as finished.
2517 return (gdcmDocEntry *)0;
2519 NewEntry = NewDocEntryByNumber(g, n);
2520 FindDocEntryVR(NewEntry);
2521 FindDocEntryLength(NewEntry);
2528 NewEntry->SetOffset(ftell(fp));
2533 * \brief Build a new Element Value from all the low level arguments.
2534 * Check for existence of dictionary entry, and build
2535 * a default one when absent.
2536 * @param Name Name of the underlying DictEntry
2538 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2540 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2542 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2544 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2547 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2548 "failed to allocate gdcmDocEntry");
2549 return (gdcmDocEntry *)0;
2555 * \brief Request a new virtual dict entry to the dict set
2556 * @param group group number of the underlying DictEntry
2557 * @param element element number of the underlying DictEntry
2558 * @param vr VR of the underlying DictEntry
2559 * @param fourth owner group
2560 * @param name english name
2562 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2567 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2571 * \brief Build a new Element Value from all the low level arguments.
2572 * Check for existence of dictionary entry, and build
2573 * a default one when absent.
2574 * @param Group group number of the underlying DictEntry
2575 * @param Elem element number of the underlying DictEntry
2577 gdcmDocEntry* gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2579 // Find out if the tag we encountered is in the dictionaries:
2580 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2582 DictEntry = NewVirtualDictEntry(Group, Elem);
2584 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2587 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2588 "failed to allocate gdcmDocEntry");
2589 return (gdcmDocEntry*)0;
2596 * \brief Build a new Element Value from all the low level arguments.
2597 * Check for existence of dictionary entry, and build
2598 * a default one when absent.
2599 * @param Group group number of the underlying DictEntry
2600 * @param Elem element number of the underlying DictEntry
2602 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2604 // Find out if the tag we encountered is in the dictionaries:
2605 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2607 DictEntry = NewVirtualDictEntry(Group, Elem);
2609 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2612 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2613 "failed to allocate gdcmValEntry");
2621 * \brief Build a new Element Value from all the low level arguments.
2622 * Check for existence of dictionary entry, and build
2623 * a default one when absent.
2624 * @param Group group number of the underlying DictEntry
2625 * @param Elem element number of the underlying DictEntry
2627 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2629 // Find out if the tag we encountered is in the dictionaries:
2630 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2632 DictEntry = NewVirtualDictEntry(Group, Elem);
2634 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2637 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2638 "failed to allocate gdcmBinEntry");
2645 * \brief Generate a free TagKey i.e. a TagKey that is not present
2646 * in the TagHt dictionary.
2647 * @param group The generated tag must belong to this group.
2648 * @return The element of tag with given group which is fee.
2650 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2652 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2654 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2655 if (tagHT.count(key) == 0)
2663 * \brief Searches both the public and the shadow dictionary (when they
2664 * exist) for the presence of the DictEntry with given name.
2665 * The public dictionary has precedence on the shadow one.
2666 * @param Name name of the searched DictEntry
2667 * @return Corresponding DictEntry when it exists, NULL otherwise.
2669 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2671 gdcmDictEntry *found = (gdcmDictEntry *)0;
2672 if (!RefPubDict && !RefShaDict)
2674 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2675 "we SHOULD have a default dictionary");
2679 found = RefPubDict->GetDictEntryByName(Name);
2685 found = RefShaDict->GetDictEntryByName(Name);
2693 * \brief Searches both the public and the shadow dictionary (when they
2694 * exist) for the presence of the DictEntry with given
2695 * group and element. The public dictionary has precedence on the
2697 * @param group group number of the searched DictEntry
2698 * @param element element number of the searched DictEntry
2699 * @return Corresponding DictEntry when it exists, NULL otherwise.
2701 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2703 gdcmDictEntry *found = (gdcmDictEntry *)0;
2704 if (!RefPubDict && !RefShaDict)
2706 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2707 "we SHOULD have a default dictionary");
2711 found = RefPubDict->GetDictEntryByNumber(group, element);
2717 found = RefShaDict->GetDictEntryByNumber(group, element);
2725 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2726 * is placed at the beginning of a tag (TestGroup, TestElement),
2727 * read the length associated to the Tag.
2728 * \warning On success the internal file pointer \ref gdcmDocument::fp
2729 * is modified to point after the tag and it's length.
2730 * On failure (i.e. when the tag wasn't the expected tag
2731 * (TestGroup, TestElement) the internal file pointer
2732 * \ref gdcmDocument::fp is restored to it's original position.
2733 * @param TestGroup The expected group of the tag.
2734 * @param TestElement The expected Element of the tag.
2735 * @return On success returns the length associated to the tag. On failure
2738 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2740 guint16 ItemTagGroup;
2741 guint16 ItemTagElement;
2742 long PositionOnEntry = ftell(fp);
2743 long CurrentPosition = ftell(fp); // On debugging purposes
2745 //// Read the Item Tag group and element, and make
2746 // sure they are respectively 0xfffe and 0xe000:
2747 ItemTagGroup = ReadInt16();
2748 ItemTagElement = ReadInt16();
2749 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2751 std::ostringstream s;
2752 s << " We should have found tag (";
2753 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2754 s << " but instead we encountered tag (";
2755 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2757 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2758 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2759 dbg.Verbose(0, s.str().c_str());
2760 fseek(fp, PositionOnEntry, SEEK_SET);
2764 //// Then read the associated Item Length
2765 CurrentPosition=ftell(fp);
2767 ItemLength = ReadInt32();
2769 std::ostringstream s;
2770 s << "Basic Item Length is: "
2771 << ItemLength << std::endl;
2772 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2773 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2779 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2780 * \sa \ref gdcmDocument::ReadTagLength
2781 * \warning See warning of \ref gdcmDocument::ReadTagLength
2782 * @return On success returns the length associated to the item tag.
2783 * On failure returns 0.
2785 guint32 gdcmDocument::ReadItemTagLength(void)
2787 return ReadTagLength(0xfffe, 0xe000);
2791 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2793 * \sa \ref gdcmDocument::ReadTagLength
2794 * \warning See warning of \ref gdcmDocument::ReadTagLength
2795 * @return On success returns the length associated to the Sequence
2796 * Delimiter tag. On failure returns 0.
2798 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2800 return ReadTagLength(0xfffe, 0xe0dd);
2805 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2806 * No other way so 'skip' the Data
2809 void gdcmDocument::Parse7FE0 (void)
2811 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2815 if ( IsImplicitVRLittleEndianTransferSyntax()
2816 || IsExplicitVRLittleEndianTransferSyntax()
2817 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2818 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2821 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2823 //// Read the Basic Offset Table Item Tag length...
2824 guint32 ItemLength = ReadItemTagLength();
2826 //// ... and then read length[s] itself[themselves]. We don't use
2827 // the values read (BTW what is the purpous of those lengths ?)
2828 if (ItemLength != 0) {
2829 // BTW, what is the purpous of those length anyhow !?
2830 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2831 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2832 for (unsigned int i=0; i < ItemLength; i += 4){
2833 guint32 IndividualLength;
2834 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2835 std::ostringstream s;
2836 s << " Read one length: ";
2837 s << std::hex << IndividualLength << std::endl;
2838 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2842 if ( ! IsRLELossLessTransferSyntax() )
2846 //// We then skip (not reading them) all the fragments of images:
2847 while ( (ItemLength = ReadItemTagLength()) )
2849 SkipBytes(ItemLength);
2857 long RleSegmentLength[15], fragmentLength;
2859 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2860 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2862 // Parse fragments of the current Fragment (Frame)
2863 //------------------ scanning (not reading) fragment pixels
2864 guint32 nbRleSegments = ReadInt32();
2865 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2867 //// Reading RLE Segments Offset Table
2868 guint32 RleSegmentOffsetTable[15];
2869 for(int k=1; k<=15; k++) {
2871 RleSegmentOffsetTable[k] = ReadInt32();
2872 printf(" at : %x Offset Segment %d : %d (%x)\n",
2873 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2874 RleSegmentOffsetTable[k]);
2877 // skipping (not reading) RLE Segments
2878 if (nbRleSegments>1) {
2879 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2880 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2881 - RleSegmentOffsetTable[k];
2883 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2884 k,(unsigned)RleSegmentLength[k],
2885 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2886 SkipBytes(RleSegmentLength[k]);
2890 RleSegmentLength[nbRleSegments]= fragmentLength
2891 - RleSegmentOffsetTable[nbRleSegments];
2893 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2894 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2895 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2896 SkipBytes(RleSegmentLength[nbRleSegments]);
2902 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2903 * \warning Does NOT work with ACR-NEMA files
2904 * \todo Find a trick to solve the pb (use RET fields ?)
2906 * @return true if 'smaller'
2908 bool gdcmDocument::operator<(gdcmDocument &document)
2913 s1=this->GetEntryByNumber(0x0010,0x0010);
2914 s2=document.GetEntryByNumber(0x0010,0x0010);
2922 s1=this->GetEntryByNumber(0x0010,0x0020);
2923 s2=document.GetEntryByNumber(0x0010,0x0020);
2930 // Study Instance UID
2931 s1=this->GetEntryByNumber(0x0020,0x000d);
2932 s2=document.GetEntryByNumber(0x0020,0x000d);
2939 // Serie Instance UID
2940 s1=this->GetEntryByNumber(0x0020,0x000e);
2941 s2=document.GetEntryByNumber(0x0020,0x000e);
2954 //-----------------------------------------------------------------------------