1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/20 18:08:47 $
7 Version: $Revision: 1.19 $
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(const char *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
130 // --------------------------------------------------------------
131 // Special Patch to allow gdcm to read ACR-LibIDO formated images
133 // if recognition code tells us we deal with a LibIDO image
134 // we switch lineNumber and columnNumber
137 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
138 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
139 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
140 // with "little-endian strings"
142 filetype = gdcmACR_LIBIDO;
143 std::string rows = GetEntryByNumber(0x0028, 0x0010);
144 std::string columns = GetEntryByNumber(0x0028, 0x0011);
145 SetEntryByNumber(columns, 0x0028, 0x0010);
146 SetEntryByNumber(rows , 0x0028, 0x0011);
148 // ----------------- End of Special Patch ----------------
150 printLevel = 1; // 'Medium' print level by default
155 * @param exception_on_error
157 gdcmDocument::gdcmDocument(bool exception_on_error)
158 :gdcmElementSet(-1) {
159 (void)exception_on_error;
162 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
165 printLevel = 1; // 'Medium' print level by default
169 * \brief Canonical destructor.
171 gdcmDocument::~gdcmDocument (void) {
175 // Recursive clean up of sequences
176 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
183 //-----------------------------------------------------------------------------
187 * \brief Prints The Dict Entries of THE public Dicom Dictionary
190 void gdcmDocument::PrintPubDict(std::ostream & os) {
191 RefPubDict->Print(os);
195 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
198 void gdcmDocument::PrintShaDict(std::ostream & os) {
199 RefShaDict->Print(os);
202 //-----------------------------------------------------------------------------
205 * \brief Get the public dictionary used
207 gdcmDict *gdcmDocument::GetPubDict(void) {
212 * \brief Get the shadow dictionary used
214 gdcmDict *gdcmDocument::GetShaDict(void) {
219 * \brief Set the shadow dictionary used
220 * \param dict dictionary to use in shadow
222 bool gdcmDocument::SetShaDict(gdcmDict *dict){
228 * \brief Set the shadow dictionary used
229 * \param dictName name of the dictionary to use in shadow
231 bool gdcmDocument::SetShaDict(DictKey dictName){
232 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
237 * \brief This predicate, based on hopefully reasonable heuristics,
238 * decides whether or not the current gdcmDocument was properly parsed
239 * and contains the mandatory information for being considered as
240 * a well formed and usable Dicom/Acr File.
241 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
244 bool gdcmDocument::IsReadable(void) {
245 if(filetype==gdcmUnknown) {
246 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
249 if(!tagHT.empty()<=0) {
250 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
259 * \brief Internal function that checks whether the Transfer Syntax given
260 * as argument is the one present in the current document.
261 * @param SyntaxToCheck The transfert syntax we need to check against.
262 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
263 * the current document. False either when the document contains
264 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
266 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
268 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
272 // The entry might be present but not loaded (parsing and loading
273 // happen at differente stages): try loading and proceed with check...
274 LoadDocEntrySafe(Entry);
275 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
277 std::string Transfer = ValEntry->GetValue();
278 // The actual transfer (as read from disk) might be padded. We
279 // first need to remove the potential padding. We can make the
280 // weak assumption that padding was not executed with digits...
281 while ( ! isdigit(Transfer[Transfer.length()-1]) )
283 Transfer.erase(Transfer.length()-1, 1);
285 if ( Transfer == SyntaxToCheck )
292 * \brief Determines if the Transfer Syntax of the present document
293 * corresponds to a Implicit Value Representation of
295 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
296 * @return True when ImplicitVRLittleEndian found. False in all other cases.
298 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
300 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
304 * \brief Determines if the Transfer Syntax was already encountered
305 * and if it corresponds to a ExplicitVRLittleEndian one.
306 * @return True when ExplicitVRLittleEndian found. False in all other cases.
308 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
310 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
314 * \brief Determines if the Transfer Syntax was already encountered
315 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
316 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
318 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
320 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
324 * \brief Determines if the Transfer Syntax was already encountered
325 * and if it corresponds to a Explicit VR Big Endian one.
326 * @return True when big endian found. False in all other cases.
328 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
330 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
334 * \brief Determines if the Transfer Syntax was already encountered
335 * and if it corresponds to a JPEGBaseLineProcess1 one.
336 * @return True when JPEGBaseLineProcess1found. False in all other cases.
338 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
340 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
344 * \brief Determines if the Transfer Syntax was already encountered
345 * and if it corresponds to a JPEGExtendedProcess2-4 one.
346 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
348 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
350 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
354 * \brief Determines if the Transfer Syntax was already encountered
355 * and if it corresponds to a JPEGExtendeProcess3-5 one.
356 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
358 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
360 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
364 * \brief Determines if the Transfer Syntax was already encountered
365 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
366 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
369 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
371 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
375 * \brief Determines if the Transfer Syntax was already encountered
376 * and if it corresponds to a RLE Lossless one.
377 * @return True when RLE Lossless found. False in all
380 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
382 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
386 * \brief Determines if Transfer Syntax was already encountered
387 * and if it corresponds to a JPEG Lossless one.
388 * @return True when RLE Lossless found. False in all
391 bool gdcmDocument::IsJPEGLossless(void)
393 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
394 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
395 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
399 * \brief Determines if the Transfer Syntax was already encountered
400 * and if it corresponds to a JPEG2000 one
401 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
404 bool gdcmDocument::IsJPEG2000(void)
406 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
407 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
411 * \brief Predicate for dicom version 3 file.
412 * @return True when the file is a dicom version 3.
414 bool gdcmDocument::IsDicomV3(void) {
415 // Checking if Transfert Syntax exists is enough
416 // Anyway, it's to late check if the 'Preamble' was found ...
417 // And ... would it be a rich idea to check ?
418 // (some 'no Preamble' DICOM images exist !)
419 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
423 * \brief returns the File Type
424 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
425 * @return the FileType code
427 FileType gdcmDocument::GetFileType(void) {
432 * \brief opens the file
433 * @param exception_on_error
436 FILE *gdcmDocument::OpenFile(bool exception_on_error)
439 fp=fopen(filename.c_str(),"rb");
443 if(exception_on_error)
444 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
447 std::cout <<"gdcmDocument::OpenFile cannot open file: "
448 << filename.c_str() << std::endl;
449 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
458 fread(&zero, (size_t)2, (size_t)1, fp);
460 //ACR -- or DICOM with no Preamble --
461 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
465 fseek(fp, 126L, SEEK_CUR);
467 fread(dicm, (size_t)4, (size_t)1, fp);
468 if( memcmp(dicm, "DICM", 4) == 0 )
472 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
475 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
481 * \brief closes the file
482 * @return TRUE if the close was successfull
484 bool gdcmDocument::CloseFile(void) {
485 int closed = fclose(fp);
493 * \brief Writes in a file all the Header Entries (Dicom Elements)
494 * of the Chained List
495 * @param fp file pointer on an already open file
496 * @param type Type of the File to be written
497 * (ACR-NEMA, ExplicitVR, ImplicitVR)
498 * \return Always true.
500 bool gdcmDocument::Write(FILE *fp, FileType type) {
503 /// The stuff will have to be rewritten using the SeQuence based
504 /// tree-like stucture instead of the chained list .
505 /// (so we shall remove the Group*HT from the gdcmDocument)
509 /// \todo move the following lines (and a lot of others, to be written)
510 /// to a future function CheckAndCorrectHeader
514 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
515 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
516 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
518 /// a moins de se livrer a un tres complique ajout des champs manquants.
519 /// faire un CheckAndCorrectHeader (?)
521 if (type == gdcmImplicitVR)
523 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
524 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
526 /// \todo Refer to standards on page 21, chapter 6.2
527 /// "Value representation": values with a VR of UI shall be
528 /// padded with a single trailing null
529 /// Dans le cas suivant on doit pader manuellement avec un 0
531 SetEntryLengthByNumber(18, 0x0002, 0x0010);
534 if (type == gdcmExplicitVR)
536 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
537 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
539 /// \todo Refer to standards on page 21, chapter 6.2
540 /// "Value representation": values with a VR of UI shall be
541 /// padded with a single trailing null
542 /// Dans le cas suivant on doit pader manuellement avec un 0
544 SetEntryLengthByNumber(20, 0x0002, 0x0010);
548 * \todo rewrite later, if really usefull
550 * --> Warning : un-updated odd groups lengths can causes pb
551 * --> (xmedcon breaks)
552 * --> to be re- written with future org.
554 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
555 * UpdateGroupLength(false,type);
557 * UpdateGroupLength(true,ACR);
560 WriteEntries(fp,type);
565 * \brief Modifies the value of a given Header Entry (Dicom Element)
566 * when it exists. Create it with the given value when unexistant.
567 * @param Value (string) Value to be set
568 * @param Group Group number of the Entry
569 * @param Elem Element number of the Entry
570 * \return pointer to the modified/created Header Entry (NULL when creation
574 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.");
590 return (gdcmValEntry *)0;
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.");
610 return (gdcmValEntry *)0;
612 if ( !AddEntry(ValEntry))
614 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
615 " promoted ValEntry failed.");
616 return (gdcmValEntry *)0;
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);
648 b = new gdcmBinEntry(a);
651 SetEntryByNumber(voidArea, lgth, Group, Elem);
652 b->SetVoidArea(voidArea);
653 return (gdcmBinEntry*)b;
659 * \brief Set a new value if the invoked element exists
660 * Seems to be useless !!!
661 * @param Value new element value
662 * @param Group group number of the Entry
663 * @param Elem element number of the Entry
666 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
668 std::string v = Value;
669 SetEntryByNumber(v, Group, Elem);
673 //-----------------------------------------------------------------------------
677 * \brief Checks if a given Dicom Element exists within the H table
678 * @param group Group number of the searched Dicom Element
679 * @param element Element number of the searched Dicom Element
680 * @return number of occurences
682 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
683 std::string key = gdcmDictEntry::TranslateToKey(group, element );
684 return (tagHT.count(key));
688 * \brief Searches within Header Entries (Dicom Elements) parsed with
689 * the public and private dictionaries
690 * for the element value of a given tag.
691 * \warning Don't use any longer : use GetPubEntryByName
692 * @param tagName name of the searched element.
693 * @return Corresponding element value when it exists,
694 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
696 std::string gdcmDocument::GetEntryByName(std::string tagName) {
697 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
698 if( dictEntry == NULL)
701 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
705 * \brief Searches within Header Entries (Dicom Elements) parsed with
706 * the public and private dictionaries
707 * for the element value representation of a given tag.
709 * Obtaining the VR (Value Representation) might be needed by caller
710 * to convert the string typed content to caller's native type
711 * (think of C++ vs Python). The VR is actually of a higher level
712 * of semantics than just the native C++ type.
713 * @param tagName name of the searched element.
714 * @return Corresponding element value representation when it exists,
715 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
717 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
718 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
719 if( dictEntry == NULL)
722 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
723 dictEntry->GetElement());
724 return elem->GetVR();
729 * \brief Searches within Header Entries (Dicom Elements) parsed with
730 * the public and private dictionaries
731 * for the element value representation of a given tag.
732 * @param group Group number of the searched tag.
733 * @param element Element number of the searched tag.
734 * @return Corresponding element value representation when it exists,
735 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
737 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
738 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
739 if ( ! tagHT.count(key))
741 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
745 * \brief Searches within Header Entries (Dicom Elements) parsed with
746 * the public and private dictionaries
747 * for the element value representation of a given tag..
749 * Obtaining the VR (Value Representation) might be needed by caller
750 * to convert the string typed content to caller's native type
751 * (think of C++ vs Python). The VR is actually of a higher level
752 * of semantics than just the native C++ type.
753 * @param group Group number of the searched tag.
754 * @param element Element number of the searched tag.
755 * @return Corresponding element value representation when it exists,
756 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
758 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
759 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
762 return elem->GetVR();
766 * \brief Searches within Header Entries (Dicom Elements) parsed with
767 * the public and private dictionaries
768 * for the value length of a given tag..
769 * @param group Group number of the searched tag.
770 * @param element Element number of the searched tag.
771 * @return Corresponding element length; -2 if not found
773 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
774 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
777 return elem->GetLength();
780 * \brief Sets the value (string) of the Header Entry (Dicom Element)
781 * @param content string value of the Dicom Element
782 * @param tagName name of the searched Dicom Element.
783 * @return true when found
785 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
786 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
787 if( dictEntry == NULL)
790 return(SetEntryByNumber(content,dictEntry->GetGroup(),
791 dictEntry->GetElement()));
795 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
796 * through it's (group, element) and modifies it's content with
798 * @param content new value (string) to substitute with
799 * @param group group number of the Dicom Element to modify
800 * @param element element number of the Dicom Element to modify
802 bool gdcmDocument::SetEntryByNumber(std::string content,
806 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
809 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
810 " ValEntry (try promotion first).");
814 // Non even content must be padded with a space (020H).
815 if((content.length())%2)
816 content = content + '\0';
818 ValEntry->SetValue(content);
820 // Integers have a special treatement for their length:
821 VRKey vr = ValEntry->GetVR();
822 if( (vr == "US") || (vr == "SS") )
823 ValEntry->SetLength(2);
824 else if( (vr == "UL") || (vr == "SL") )
825 ValEntry->SetLength(4);
827 ValEntry->SetLength(content.length());
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 (void *) 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(void *content,
845 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
846 if ( ! tagHT.count(key))
849 /* Hope Binray field length is never wrong
850 if(lgth%2) // Non even length are padded with a space (020H).
853 //content = content + '\0'; // fing a trick to enlarge a binary field?
857 a = (gdcmBinEntry *)tagHT[key];
858 a->SetVoidArea(content);
859 //a->SetLength(lgth); // ???
864 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
865 * in the PubDocEntrySet of this instance
866 * through it's (group, element) and modifies it's length with
868 * \warning Use with extreme caution.
869 * @param l new length to substitute with
870 * @param group group number of the Entry to modify
871 * @param element element number of the Entry to modify
872 * @return true on success, false otherwise.
874 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
878 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
879 if ( ! tagHT.count(key))
881 if (l%2) l++; // length must be even
882 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
888 * \brief Gets (from Header) the offset of a 'non string' element value
889 * (LoadElementValues has already be executed)
890 * @param Group group number of the Entry
891 * @param Elem element number of the Entry
892 * @return File Offset of the Element Value
894 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
896 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
899 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
900 "failed to Locate gdcmDocEntry");
903 return Entry->GetOffset();
907 * \brief Gets (from Header) a 'non string' element value
908 * (LoadElementValues has already be executed)
909 * @param Group group number of the Entry
910 * @param Elem element number of the Entry
911 * @return Pointer to the 'non string' area
913 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
915 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
918 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
919 "failed to Locate gdcmDocEntry");
922 return ((gdcmBinEntry *)Entry)->GetVoidArea();
926 * \brief Loads (from disk) the element content
927 * when a string is not suitable
928 * @param Group group number of the Entry
929 * @param Elem element number of the Entry
931 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
933 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
936 size_t o =(size_t)Element->GetOffset();
937 fseek(fp, o, SEEK_SET);
938 size_t l=Element->GetLength();
939 char* a = new char[l];
943 SetEntryVoidAreaByNumber(a, Group, Elem);
944 /// \todo check the result
945 size_t l2 = fread(a, 1, l ,fp);
956 * \brief Sets a 'non string' value to a given Dicom Element
958 * @param group Group number of the searched Dicom Element
959 * @param element Element number of the searched Dicom Element
962 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
966 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
967 if ( ! tagHT.count(key))
969 // This was for multimap ?
970 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
976 * \brief Update the entries with the shadow dictionary.
977 * Only non even entries are analyzed
979 void gdcmDocument::UpdateShaEntries(void) {
980 gdcmDictEntry *entry;
983 /// \todo TODO : still any use to explore recursively the whole structure?
985 for(ListTag::iterator it=listEntries.begin();
986 it!=listEntries.end();
989 // Odd group => from public dictionary
990 if((*it)->GetGroup()%2==0)
993 // Peer group => search the corresponding dict entry
995 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
999 if((*it)->IsImplicitVR())
1004 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1006 // Set the new entry and the new value
1007 (*it)->SetDictEntry(entry);
1008 CheckDocEntryVR(*it,vr);
1010 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1015 // Remove precedent value transformation
1016 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1023 * \brief Searches within the Header Entries for a Dicom Element of
1025 * @param tagName name of the searched Dicom Element.
1026 * @return Corresponding Dicom Element when it exists, and NULL
1029 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1030 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1031 if( dictEntry == NULL)
1034 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1038 * \brief retrieves a Dicom Element (the first one) using (group, element)
1039 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1040 * if you think it's NOT UNIQUE, check the count number
1041 * and use iterators to retrieve ALL the Dicoms Elements within
1042 * a given couple (group, element)
1043 * @param group Group number of the searched Dicom Element
1044 * @param element Element number of the searched Dicom Element
1047 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1049 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1050 if ( ! tagHT.count(key))
1052 return tagHT.find(key)->second;
1056 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1057 * returns a result when the corresponding entry is of type
1059 * @return When present, the corresponding ValEntry.
1061 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1063 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1065 return (gdcmValEntry*)0;
1066 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1070 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1071 return (gdcmValEntry*)0;
1075 * \brief Loads the element while preserving the current
1076 * underlying file position indicator as opposed to
1077 * to LoadDocEntry that modifies it.
1078 * @param entry Header Entry whose value shall be loaded.
1081 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1082 long PositionOnEntry = ftell(fp);
1083 LoadDocEntry(entry);
1084 fseek(fp, PositionOnEntry, SEEK_SET);
1089 * \brief Writes in a file (according to the requested format)
1090 * the group, the element, the value representation and the length
1091 * of a single gdcmDocEntry passed as argument.
1092 * @param tag pointer on the gdcmDocEntry to be written
1093 * @param _fp already open file pointer
1094 * @param type type of the File to be written
1096 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1100 guint16 group = tag->GetGroup();
1101 VRKey vr = tag->GetVR();
1102 guint16 el = tag->GetElement();
1103 guint32 lgr = tag->GetReadLength();
1105 if ( (group == 0xfffe) && (el == 0x0000) )
1106 // Fix in order to make some MR PHILIPS images e-film readable
1107 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1108 // we just *always* ignore spurious fffe|0000 tag !
1111 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1112 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1114 if ( type == gdcmExplicitVR ) {
1116 // Special case of delimiters:
1117 if (group == 0xfffe) {
1118 // Delimiters have NO Value Representation and have NO length.
1119 // Hence we skip writing the VR and length and we pad by writing
1123 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1128 guint16 shortLgr = lgr;
1129 if (vr == "unkn") { // Unknown was 'written'
1130 // deal with Little Endian
1131 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1132 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1134 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1135 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1137 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1138 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1140 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1146 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1151 * \brief Writes in a file (according to the requested format)
1152 * the value of a single gdcmDocEntry passed as argument.
1153 * @param tag Pointer on the gdcmDocEntry to be written
1154 * @param _fp Already open file pointer
1155 * @param type type of the File to be written
1158 // \todo TODO : to be re -written recursively !
1159 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1162 guint16 group = tag->GetGroup();
1163 VRKey vr = tag->GetVR();
1164 guint32 lgr = tag->GetReadLength();
1167 // SeQuences have no value:
1169 if (group == 0xfffe)
1170 // Delimiters have no associated value:
1173 //--------------------------------
1175 // FIXME :right now, both value and voidArea belong to gdcmValue
1177 // -------------------------------
1179 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1181 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1182 voidArea = BinEntry->GetVoidArea();
1183 if (voidArea != NULL)
1184 { // there is a 'non string' LUT, overlay, etc
1185 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1190 if (vr == "US" || vr == "SS")
1192 // some 'Short integer' fields may be mulivaluated
1193 // each single value is separated from the next one by '\'
1194 // we split the string and write each value as a short int
1195 std::vector<std::string> tokens;
1196 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1197 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1198 for (unsigned int i=0; i<tokens.size();i++)
1200 guint16 val_uint16 = atoi(tokens[i].c_str());
1201 void *ptr = &val_uint16;
1202 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1207 if (vr == "UL" || vr == "SL")
1209 // Some 'Integer' fields may be multivaluated (multiple instances
1210 // of integers). But each single integer value is separated from the
1211 // next one by '\' (backslash character). Hence we split the string
1212 // along the '\' and write each value as an int:
1213 std::vector<std::string> tokens;
1214 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1215 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1216 for (unsigned int i=0; i<tokens.size();i++)
1218 guint32 val_uint32 = atoi(tokens[i].c_str());
1219 void *ptr = &val_uint32;
1220 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1225 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(),
1226 (size_t)lgr ,(size_t)1, _fp); // Elem value
1230 * \brief Writes in a file (according to the requested format)
1231 * a single gdcmDocEntry passed as argument.
1232 * \sa WriteEntryValue, WriteEntryTagVRLength.
1233 * @param tag Pointer on the gdcmDocEntry to be written
1234 * @param _fp Already open file pointer
1235 * @param type type of the File to be written
1238 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1240 guint32 length = tag->GetLength();
1242 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1244 // The value of a tag MUST (see the DICOM norm) be an odd number of
1245 // bytes. When this is not the case, pad with an additional byte:
1247 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1248 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1250 WriteEntryTagVRLength(ValEntry, _fp, type);
1251 WriteEntryValue(ValEntry, _fp, type);
1255 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1257 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
1260 // The value of a tag MUST (see the DICOM norm) be an odd number of
1261 // bytes. When this is not the case, pad with an additional byte:
1264 tag->SetValue(tag->GetValue()+"\0");
1265 tag->SetLength(tag->GetReadLength()+1);
1268 WriteEntryTagVRLength(tag, _fp, type);
1269 WriteEntryValue(tag, _fp, type);
1275 * \brief writes on disc according to the requested format
1276 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1277 * using the Chained List
1278 * \warning does NOT add the missing elements in the header :
1279 * it's up to the user doing it !
1280 * (function CheckHeaderCoherence to be written)
1281 * \warning DON'T try, right now, to write a DICOM image
1282 * from an ACR Header (meta elements will be missing!)
1283 * @param type type of the File to be written
1284 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1285 * @param _fp already open file pointer
1288 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1290 /// \todo FIXME : explore recursively the whole structure...
1291 /// \todo (?) check write failures (after *each* fwrite)
1293 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1294 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1296 gdcmDocEntry * entry = it->second;
1298 if ( type == gdcmACR ){
1299 if (entry->GetGroup() < 0x0008)
1300 // Ignore pure DICOM V3 groups
1302 if (entry->GetGroup() %2)
1303 // Ignore the "shadow" groups
1305 if (entry->GetVR() == "SQ" ) // ignore Sequences
1308 if (! WriteEntry(entry, _fp, type) ) {
1309 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1318 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1320 * @return The properly swaped 32 bits integer.
1322 guint32 gdcmDocument::SwapLong(guint32 a) {
1327 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1328 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1332 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1336 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1339 std::cout << "swapCode= " << sw << std::endl;
1340 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1347 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1349 * @return The properly unswaped 32 bits integer.
1351 guint32 gdcmDocument::UnswapLong(guint32 a) {
1352 return (SwapLong(a));
1356 * \brief Swaps the bytes so they agree with the processor order
1357 * @return The properly swaped 16 bits integer.
1359 guint16 gdcmDocument::SwapShort(guint16 a) {
1360 if ( (sw==4321) || (sw==2143) )
1361 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1366 * \brief Unswaps the bytes so they agree with the processor order
1367 * @return The properly unswaped 16 bits integer.
1369 guint16 gdcmDocument::UnswapShort(guint16 a) {
1370 return (SwapShort(a));
1373 //-----------------------------------------------------------------------------
1377 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1378 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1381 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1383 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1384 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1391 depth = set->GetDepthLevel();
1394 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1397 NewDocEntry = ReadNextDocEntry( );
1401 vr = NewDocEntry->GetVR();
1405 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1408 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1409 NewValEntry->Copy(NewDocEntry);
1410 NewValEntry->SetDepthLevel(depth);
1411 set->AddEntry(NewValEntry);
1412 LoadDocEntry(NewValEntry);
1413 if (/*!delim_mode && */NewValEntry->isItemDelimitor())
1415 if ( !delim_mode && ftell(fp)-offset >= l_max)
1422 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1424 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1425 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1426 "nor BinEntry. Probably unknown VR.");
1429 ////// BinEntry or UNKOWN VR:
1430 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1431 bn->Copy(NewDocEntry);
1436 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1437 NewDocEntry->GetElement() == 0x0010 )
1439 if (NewDocEntry->GetLength()==0xffffffff)
1440 // Broken US.3405.1.dcm
1441 Parse7FE0(); // to skip the pixels
1442 // (multipart JPEG/RLE are trouble makers)
1446 // to be sure we are at the beginning
1447 SkipToNextDocEntry(NewDocEntry);
1448 l = NewDocEntry->GetFullLength();
1454 l=NewDocEntry->GetReadLength();
1455 if (l != 0) // don't mess the delim_mode for zero-length sequence
1456 if (l == 0xffffffff)
1460 // no other way to create it ...
1461 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1462 set->GetDepthLevel());
1463 sq->Copy(NewDocEntry);
1464 sq->SetDelimitorMode(delim_mode);
1465 sq->SetDepthLevel(depth);
1468 { // Don't try to parse zero-length sequences
1469 long lgt = ParseSQ( sq,
1470 NewDocEntry->GetOffset(),
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;
1498 int depth = set->GetDepthLevel();
1501 NewDocEntry = ReadNextDocEntry();
1503 if (NewDocEntry->isSequenceDelimitor()) {
1504 /// \todo add the Sequence Delimitor
1505 /// \todo find the trick to put it properly !
1506 set->SetSequenceDelimitationItem(NewDocEntry);
1510 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1514 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1515 itemSQ->AddEntry(NewDocEntry);
1516 /// \todo no value, no voidArea. Think of it while printing !
1517 l= NewDocEntry->GetReadLength();
1519 if (l == 0xffffffff)
1524 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1526 set->AddEntry(itemSQ,SQItemNumber);
1528 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1532 lgth = ftell(fp) - offset;
1537 * \brief Loads the element content if its length doesn't exceed
1538 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1539 * @param Entry Header Entry (Dicom Element) to be dealt with
1541 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1544 guint16 group = Entry->GetGroup();
1545 std::string vr= Entry->GetVR();
1546 guint32 length = Entry->GetLength();
1548 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1550 // A SeQuence "contains" a set of Elements.
1551 // (fffe e000) tells us an Element is beginning
1552 // (fffe e00d) tells us an Element just ended
1553 // (fffe e0dd) tells us the current SeQuence just ended
1554 if( group == 0xfffe ) {
1555 // NO more value field for SQ !
1556 //Entry->SetValue("gdcm::Skipped");
1557 // appel recursif de Load Value
1558 // (meme pb que pour le parsing)
1562 // When the length is zero things are easy:
1563 if ( length == 0 ) {
1564 ((gdcmValEntry *)Entry)->SetValue("");
1568 // The elements whose length is bigger than the specified upper bound
1569 // are not loaded. Instead we leave a short notice of the offset of
1570 // the element content and it's length.
1571 if (length > MaxSizeLoadEntry) {
1572 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1574 std::ostringstream s;
1575 s << "gdcm::NotLoaded.";
1576 s << " Address:" << (long)Entry->GetOffset();
1577 s << " Length:" << Entry->GetLength();
1578 s << " x(" << std::hex << Entry->GetLength() << ")";
1579 ValEntryPtr->SetValue(s.str());
1581 // to be sure we are at the end of the value ...
1582 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1587 // Any compacter code suggested (?)
1588 if ( IsDocEntryAnInteger(Entry) ) {
1590 std::ostringstream s;
1592 // When short integer(s) are expected, read and convert the following
1593 // n *two characters properly i.e. as short integers as opposed to strings.
1594 // Elements with Value Multiplicity > 1
1595 // contain a set of integers (not a single one)
1596 if (vr == "US" || vr == "SS") {
1598 NewInt = ReadInt16();
1601 for (int i=1; i < nbInt; i++) {
1603 NewInt = ReadInt16();
1608 // When integer(s) are expected, read and convert the following
1609 // n * four characters properly i.e. as integers as opposed to strings.
1610 // Elements with Value Multiplicity > 1
1611 // contain a set of integers (not a single one)
1612 else if (vr == "UL" || vr == "SL") {
1614 NewInt = ReadInt32();
1617 for (int i=1; i < nbInt; i++) {
1619 NewInt = ReadInt32();
1624 #ifdef GDCM_NO_ANSI_STRING_STREAM
1625 s << std::ends; // to avoid oddities on Solaris
1626 #endif //GDCM_NO_ANSI_STRING_STREAM
1628 ((gdcmValEntry *)Entry)->SetValue(s.str());
1632 // We need an additional byte for storing \0 that is not on disk
1633 std::string NewValue(length,0);
1634 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1635 if ( item_read != 1 ) {
1636 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1637 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1641 if( (vr == "UI") ) // Because of correspondance with the VR dic
1642 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1644 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1649 * \brief Find the value Length of the passed Header Entry
1650 * @param Entry Header Entry whose length of the value shall be loaded.
1652 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1653 guint16 element = Entry->GetElement();
1654 //guint16 group = Entry->GetGroup(); //FIXME
1655 std::string vr = Entry->GetVR();
1659 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1661 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1663 // The following reserved two bytes (see PS 3.5-2001, section
1664 // 7.1.2 Data element structure with explicit vr p27) must be
1665 // skipped before proceeding on reading the length on 4 bytes.
1666 fseek(fp, 2L, SEEK_CUR);
1667 guint32 length32 = ReadInt32();
1669 if ( (vr == "OB") && (length32 == 0xffffffff) )
1671 Entry->SetLength(FindDocEntryLengthOB());
1674 FixDocEntryFoundLength(Entry, length32);
1678 // Length is encoded on 2 bytes.
1679 length16 = ReadInt16();
1681 // We can tell the current file is encoded in big endian (like
1682 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1683 // and it's value is the one of the encoding of a big endian file.
1684 // In order to deal with such big endian encoded files, we have
1685 // (at least) two strategies:
1686 // * when we load the "Transfer Syntax" tag with value of big endian
1687 // encoding, we raise the proper flags. Then we wait for the end
1688 // of the META group (0x0002) among which is "Transfer Syntax",
1689 // before switching the swap code to big endian. We have to postpone
1690 // the switching of the swap code since the META group is fully encoded
1691 // in little endian, and big endian coding only starts at the next
1692 // group. The corresponding code can be hard to analyse and adds
1693 // many additional unnecessary tests for regular tags.
1694 // * the second strategy consists in waiting for trouble, that shall
1695 // appear when we find the first group with big endian encoding. This
1696 // is easy to detect since the length of a "Group Length" tag (the
1697 // ones with zero as element number) has to be of 4 (0x0004). When we
1698 // encounter 1024 (0x0400) chances are the encoding changed and we
1699 // found a group with big endian encoding.
1700 // We shall use this second strategy. In order to make sure that we
1701 // can interpret the presence of an apparently big endian encoded
1702 // length of a "Group Length" without committing a big mistake, we
1703 // add an additional check: we look in the already parsed elements
1704 // for the presence of a "Transfer Syntax" whose value has to be "big
1705 // endian encoding". When this is the case, chances are we have got our
1706 // hands on a big endian encoded file: we switch the swap code to
1707 // big endian and proceed...
1708 if ( (element == 0x0000) && (length16 == 0x0400) )
1710 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1712 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1717 SwitchSwapToBigEndian();
1718 // Restore the unproperly loaded values i.e. the group, the element
1719 // and the dictionary entry depending on them.
1720 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1721 guint16 CorrectElem = SwapShort(Entry->GetElement());
1722 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1726 // This correct tag is not in the dictionary. Create a new one.
1727 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1729 // FIXME this can create a memory leaks on the old entry that be
1730 // left unreferenced.
1731 Entry->SetDictEntry(NewTag);
1734 // Heuristic: well some files are really ill-formed.
1735 if ( length16 == 0xffff)
1738 //dbg.Verbose(0, "gdcmDocument::FindLength",
1739 // "Erroneous element length fixed.");
1740 // Actually, length= 0xffff means that we deal with
1741 // Unknown Sequence Length
1743 FixDocEntryFoundLength(Entry, (guint32)length16);
1748 // Either implicit VR or a non DICOM conformal (see note below) explicit
1749 // VR that ommited the VR of (at least) this element. Farts happen.
1750 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1751 // on Data elements "Implicit and Explicit VR Data Elements shall
1752 // not coexist in a Data Set and Data Sets nested within it".]
1753 // Length is on 4 bytes.
1755 FixDocEntryFoundLength(Entry, ReadInt32());
1761 * \brief Find the Value Representation of the current Dicom Element.
1764 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1766 if (filetype != gdcmExplicitVR)
1771 long PositionOnEntry = ftell(fp);
1772 // Warning: we believe this is explicit VR (Value Representation) because
1773 // we used a heuristic that found "UL" in the first tag. Alas this
1774 // doesn't guarantee that all the tags will be in explicit VR. In some
1775 // cases (see e-film filtered files) one finds implicit VR tags mixed
1776 // within an explicit VR file. Hence we make sure the present tag
1777 // is in explicit VR and try to fix things if it happens not to be
1780 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1782 if(!CheckDocEntryVR(Entry,VR))
1784 fseek(fp, PositionOnEntry, SEEK_SET);
1785 // When this element is known in the dictionary we shall use, e.g. for
1786 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1787 // dictionary entry. Still we have to flag the element as implicit since
1788 // we know now our assumption on expliciteness is not furfilled.
1790 if ( Entry->IsVRUnknown() )
1791 Entry->SetVR("Implicit");
1792 Entry->SetImplicitVR();
1797 * \brief Check the correspondance between the VR of the header entry
1798 * and the taken VR. If they are different, the header entry is
1799 * updated with the new VR.
1800 * @param Entry Header Entry to check
1801 * @param vr Dicom Value Representation
1802 * @return false if the VR is incorrect of if the VR isn't referenced
1803 * otherwise, it returns true
1805 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1807 char msg[100]; // for sprintf
1808 bool RealExplicit = true;
1810 // Assume we are reading a falsely explicit VR file i.e. we reached
1811 // a tag where we expect reading a VR but are in fact we read the
1812 // first to bytes of the length. Then we will interogate (through find)
1813 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1814 // both GCC and VC++ implementations of the STL map. Hence when the
1815 // expected VR read happens to be non-ascii characters we consider
1816 // we hit falsely explicit VR tag.
1818 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1819 RealExplicit = false;
1821 // CLEANME searching the dicom_vr at each occurence is expensive.
1822 // PostPone this test in an optional integrity check at the end
1823 // of parsing or only in debug mode.
1824 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1825 RealExplicit= false;
1827 if ( !RealExplicit )
1829 // We thought this was explicit VR, but we end up with an
1830 // implicit VR tag. Let's backtrack.
1831 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1832 Entry->GetGroup(),Entry->GetElement());
1833 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1834 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1835 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1836 Entry->GetGroup(),Entry->GetElement(),
1837 "UL","FIXME","Group Length");
1838 Entry->SetDictEntry(NewEntry);
1843 if ( Entry->IsVRUnknown() )
1845 // When not a dictionary entry, we can safely overwrite the VR.
1846 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1852 else if ( Entry->GetVR() != vr )
1854 // The VR present in the file and the dictionary disagree. We assume
1855 // the file writer knew best and use the VR of the file. Since it would
1856 // be unwise to overwrite the VR of a dictionary (since it would
1857 // compromise it's next user), we need to clone the actual DictEntry
1858 // and change the VR for the read one.
1859 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1860 Entry->GetGroup(),Entry->GetElement(),
1861 vr,"FIXME",Entry->GetName());
1862 Entry->SetDictEntry(NewEntry);
1868 * \brief Get the transformed value of the header entry. The VR value
1869 * is used to define the transformation to operate on the value
1870 * \warning NOT end user intended method !
1872 * @return Transformed entry value
1874 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1876 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1878 std::string val=((gdcmValEntry *)Entry)->GetValue();
1879 std::string vr=Entry->GetVR();
1880 guint32 length = Entry->GetLength();
1881 std::ostringstream s;
1884 // When short integer(s) are expected, read and convert the following
1885 // n * 2 bytes properly i.e. as a multivaluated strings
1886 // (each single value is separated fromthe next one by '\'
1887 // as usual for standard multivaluated filels
1888 // Elements with Value Multiplicity > 1
1889 // contain a set of short integers (not a single one)
1891 if (vr == "US" || vr == "SS")
1896 for (int i=0; i < nbInt; i++)
1900 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1901 NewInt16 = SwapShort(NewInt16);
1906 // When integer(s) are expected, read and convert the following
1907 // n * 4 bytes properly i.e. as a multivaluated strings
1908 // (each single value is separated fromthe next one by '\'
1909 // as usual for standard multivaluated filels
1910 // Elements with Value Multiplicity > 1
1911 // contain a set of integers (not a single one)
1912 else if (vr == "UL" || vr == "SL")
1917 for (int i=0; i < nbInt; i++)
1921 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1922 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1923 NewInt32=SwapLong(NewInt32);
1927 #ifdef GDCM_NO_ANSI_STRING_STREAM
1928 s << std::ends; // to avoid oddities on Solaris
1929 #endif //GDCM_NO_ANSI_STRING_STREAM
1933 return(((gdcmValEntry *)Entry)->GetValue());
1937 * \brief Get the reverse transformed value of the header entry. The VR
1938 * value is used to define the reverse transformation to operate on
1940 * \warning NOT end user intended method !
1942 * @return Reverse transformed entry value
1944 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1946 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1948 std::string vr=Entry->GetVR();
1949 std::ostringstream s;
1950 std::vector<std::string> tokens;
1952 if (vr == "US" || vr == "SS")
1956 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1957 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1958 for (unsigned int i=0; i<tokens.size();i++)
1960 NewInt16 = atoi(tokens[i].c_str());
1961 s<<(NewInt16&0xFF)<<((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)<<(char)((NewInt32>>8)&0xFF)
1975 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1980 #ifdef GDCM_NO_ANSI_STRING_STREAM
1981 s << std::ends; // to avoid oddities on Solaris
1982 #endif //GDCM_NO_ANSI_STRING_STREAM
1986 return(((gdcmValEntry *)Entry)->GetValue());
1990 * \brief Skip a given Header Entry
1991 * \warning NOT end user intended method !
1994 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1996 SkipBytes(entry->GetLength());
2000 * \brief Skips to the begining of the next Header Entry
2001 * \warning NOT end user intended method !
2004 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2006 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
2007 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
2011 * \brief Loads the value for a a given VLEntry
2012 * \warning NOT end user intended method !
2015 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
2017 //SkipBytes(entry->GetLength());
2018 LoadDocEntry(entry);
2021 * \brief When the length of an element value is obviously wrong (because
2022 * the parser went Jabberwocky) one can hope improving things by
2023 * applying some heuristics.
2025 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
2026 guint32 FoundLength)
2028 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
2029 if ( FoundLength == 0xffffffff) {
2033 guint16 gr =Entry->GetGroup();
2034 guint16 el =Entry->GetElement();
2036 if (FoundLength%2) {
2037 std::ostringstream s;
2038 s << "Warning : Tag with uneven length "
2040 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2041 dbg.Verbose(0, s.str().c_str());
2044 //////// Fix for some naughty General Electric images.
2045 // Allthough not recent many such GE corrupted images are still present
2046 // on Creatis hard disks. Hence this fix shall remain when such images
2047 // are no longer in user (we are talking a few years, here)...
2048 // Note: XMedCom probably uses such a trick since it is able to read
2049 // those pesky GE images ...
2050 if (FoundLength == 13) { // Only happens for this length !
2051 if ( (Entry->GetGroup() != 0x0008)
2052 || ( (Entry->GetElement() != 0x0070)
2053 && (Entry->GetElement() != 0x0080) ) )
2056 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2060 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2061 // Occurence of such images is quite low (unless one leaves close to a
2062 // 'Leonardo' source. Hence, one might consider commenting out the
2063 // following fix on efficiency reasons.
2065 if ( (Entry->GetGroup() == 0x0009)
2066 && ( (Entry->GetElement() == 0x1113)
2067 || (Entry->GetElement() == 0x1114) ) )
2070 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2073 //////// Deal with sequences, but only on users request:
2075 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2077 FoundLength = 0; // ReadLength is unchanged
2080 //////// We encountered a 'delimiter' element i.e. a tag of the form
2081 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2082 // taken into account.
2084 if(Entry->GetGroup() == 0xfffe)
2086 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2087 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2088 // causes extra troubles...
2089 if( Entry->GetElement() != 0x0000 )
2095 Entry->SetUsableLength(FoundLength);
2099 * \brief Apply some heuristics to predict whether the considered
2100 * element value contains/represents an integer or not.
2101 * @param Entry The element value on which to apply the predicate.
2102 * @return The result of the heuristical predicate.
2104 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2105 guint16 element = Entry->GetElement();
2106 guint16 group = Entry->GetGroup();
2107 std::string vr = Entry->GetVR();
2108 guint32 length = Entry->GetLength();
2110 // When we have some semantics on the element we just read, and if we
2111 // a priori know we are dealing with an integer, then we shall be
2112 // able to swap it's element value properly.
2113 if ( element == 0 ) // This is the group length of the group
2119 // Allthough this should never happen, still some images have a
2120 // corrupted group length [e.g. have a glance at offset x(8336) of
2121 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2122 // Since for dicom compliant and well behaved headers, the present
2123 // test is useless (and might even look a bit paranoid), when we
2124 // encounter such an ill-formed image, we simply display a warning
2125 // message and proceed on parsing (while crossing fingers).
2126 std::ostringstream s;
2127 int filePosition = ftell(fp);
2128 s << "Erroneous Group Length element length on : (" \
2129 << std::hex << group << " , " << element
2130 << ") -before- position x(" << filePosition << ")"
2131 << "lgt : " << length;
2132 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2136 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2143 * \brief Find the Length till the next sequence delimiter
2144 * \warning NOT end user intended method !
2148 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2149 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2152 long PositionOnEntry = ftell(fp);
2153 bool FoundSequenceDelimiter = false;
2154 guint32 TotalLength = 0;
2157 while ( ! FoundSequenceDelimiter)
2163 TotalLength += 4; // We even have to decount the group and element
2165 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2167 char msg[100]; // for sprintf. Sorry
2168 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2169 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2173 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2174 FoundSequenceDelimiter = true;
2175 else if ( n != 0xe000 )
2177 char msg[100]; // for sprintf. Sorry
2178 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2180 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2184 ItemLength = ReadInt32();
2185 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2186 // the ItemLength with ReadInt32
2187 SkipBytes(ItemLength);
2189 fseek(fp, PositionOnEntry, SEEK_SET);
2194 * \brief Reads a supposed to be 16 Bits integer
2195 * (swaps it depending on processor endianity)
2196 * @return read value
2198 guint16 gdcmDocument::ReadInt16(void) {
2201 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2202 if ( item_read != 1 ) {
2204 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2214 * \brief Reads a supposed to be 32 Bits integer
2215 * (swaps it depending on processor endianity)
2216 * @return read value
2218 guint32 gdcmDocument::ReadInt32(void) {
2221 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2222 if ( item_read != 1 ) {
2224 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2234 * \brief skips bytes inside the source file
2235 * \warning NOT end user intended method !
2238 void gdcmDocument::SkipBytes(guint32 NBytes) {
2239 //FIXME don't dump the returned value
2240 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2244 * \brief Loads all the needed Dictionaries
2245 * \warning NOT end user intended method !
2247 void gdcmDocument::Initialise(void)
2249 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2250 RefShaDict = (gdcmDict*)0;
2254 * \brief Discover what the swap code is (among little endian, big endian,
2255 * bad little endian, bad big endian).
2257 * @return false when we are absolutely sure
2258 * it's neither ACR-NEMA nor DICOM
2259 * true when we hope ours assuptions are OK
2261 bool gdcmDocument::CheckSwap() {
2263 // The only guaranted way of finding the swap code is to find a
2264 // group tag since we know it's length has to be of four bytes i.e.
2265 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2266 // occurs when we can't find such group...
2268 guint32 x=4; // x : for ntohs
2269 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2275 char deb[HEADER_LENGTH_TO_READ];
2277 // First, compare HostByteOrder and NetworkByteOrder in order to
2278 // determine if we shall need to swap bytes (i.e. the Endian type).
2284 // The easiest case is the one of a DICOM header, since it possesses a
2285 // file preamble where it suffice to look for the string "DICM".
2286 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2289 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2290 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2292 // Next, determine the value representation (VR). Let's skip to the
2293 // first element (0002, 0000) and check there if we find "UL"
2294 // - or "OB" if the 1st one is (0002,0001) -,
2295 // in which case we (almost) know it is explicit VR.
2296 // WARNING: if it happens to be implicit VR then what we will read
2297 // is the length of the group. If this ascii representation of this
2298 // length happens to be "UL" then we shall believe it is explicit VR.
2299 // FIXME: in order to fix the above warning, we could read the next
2300 // element value (or a couple of elements values) in order to make
2301 // sure we are not commiting a big mistake.
2302 // We need to skip :
2303 // * the 128 bytes of File Preamble (often padded with zeroes),
2304 // * the 4 bytes of "DICM" string,
2305 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2306 // i.e. a total of 136 bytes.
2310 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2311 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2312 // *Implicit* VR. -and it is !-
2314 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2315 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2316 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2317 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2318 // when Write DCM *adds*
2320 // Use gdcmDocument::dicom_vr to test all the possibilities
2321 // instead of just checking for UL, OB and UI !? group 0000
2323 filetype = gdcmExplicitVR;
2324 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2325 "explicit Value Representation");
2329 filetype = gdcmImplicitVR;
2330 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2331 "not an explicit Value Representation");
2337 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2338 "HostByteOrder != NetworkByteOrder");
2343 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2344 "HostByteOrder = NetworkByteOrder");
2347 // Position the file position indicator at first tag (i.e.
2348 // after the file preamble and the "DICM" string).
2350 fseek (fp, 132L, SEEK_SET);
2354 // Alas, this is not a DicomV3 file and whatever happens there is no file
2355 // preamble. We can reset the file position indicator to where the data
2356 // is (i.e. the beginning of the file).
2357 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2360 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2361 // By clean we mean that the length of the first tag is written down.
2362 // If this is the case and since the length of the first group HAS to be
2363 // four (bytes), then determining the proper swap code is straightforward.
2366 // We assume the array of char we are considering contains the binary
2367 // representation of a 32 bits integer. Hence the following dirty
2369 s32 = *((guint32 *)(entCur));
2390 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2391 // It is time for despaired wild guesses.
2392 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2393 // i.e. the 'group length' element is not present :
2395 // check the supposed to be 'group number'
2396 // 0x0002 or 0x0004 or 0x0008
2397 // to determine ' sw' value .
2398 // Only 0 or 4321 will be possible
2399 // (no oportunity to check for the formerly well known
2400 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2401 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2402 // the file IS NOT ACR-NEMA nor DICOM V3
2403 // Find a trick to tell it the caller...
2405 s16 = *((guint16 *)(deb));
2421 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2422 "ACR/NEMA unfound swap info (Really hopeless !)");
2423 filetype = gdcmUnknown;
2427 // Then the only info we have is the net2host one.
2437 * \brief Restore the unproperly loaded values i.e. the group, the element
2438 * and the dictionary entry depending on them.
2440 void gdcmDocument::SwitchSwapToBigEndian(void)
2442 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2443 "Switching to BigEndian mode.");
2464 * \brief during parsing, Header Elements too long are not loaded in memory
2467 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2471 if ((guint32)NewSize >= (guint32)0xffffffff)
2473 MaxSizeLoadEntry = 0xffffffff;
2476 MaxSizeLoadEntry = NewSize;
2481 * \brief Header Elements too long will not be printed
2482 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2485 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2489 if ((guint32)NewSize >= (guint32)0xffffffff)
2491 MaxSizePrintEntry = 0xffffffff;
2494 MaxSizePrintEntry = NewSize;
2500 * \brief Read the next tag but WITHOUT loading it's value
2501 * (read the 'Group Number', the 'Element Number',
2502 * gets the Dict Entry
2503 * gets the VR, gets the length, gets the offset value)
2504 * @return On succes the newly created DocEntry, NULL on failure.
2506 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2508 gdcmDocEntry *NewEntry;
2513 // We reached the EOF (or an error occured) therefore
2514 // header parsing has to be considered as finished.
2515 return (gdcmDocEntry *)0;
2517 NewEntry = NewDocEntryByNumber(g, n);
2518 FindDocEntryVR(NewEntry);
2519 FindDocEntryLength(NewEntry);
2526 NewEntry->SetOffset(ftell(fp));
2531 * \brief Build a new Element Value from all the low level arguments.
2532 * Check for existence of dictionary entry, and build
2533 * a default one when absent.
2534 * @param Name Name of the underlying DictEntry
2536 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2538 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2540 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2542 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2545 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2546 "failed to allocate gdcmDocEntry");
2547 return (gdcmDocEntry *)0;
2553 * \brief Request a new virtual dict entry to the dict set
2554 * @param group group number of the underlying DictEntry
2555 * @param element element number of the underlying DictEntry
2556 * @param vr VR of the underlying DictEntry
2557 * @param fourth owner group
2558 * @param name english name
2560 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2565 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2569 * \brief Build a new Element Value from all the low level arguments.
2570 * Check for existence of dictionary entry, and build
2571 * a default one when absent.
2572 * @param Group group number of the underlying DictEntry
2573 * @param Elem element number of the underlying DictEntry
2575 gdcmDocEntry* gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2577 // Find out if the tag we encountered is in the dictionaries:
2578 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2580 DictEntry = NewVirtualDictEntry(Group, Elem);
2582 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2585 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2586 "failed to allocate gdcmDocEntry");
2587 return (gdcmDocEntry*)0;
2594 * \brief Build a new Element Value from all the low level arguments.
2595 * Check for existence of dictionary entry, and build
2596 * a default one when absent.
2597 * @param Group group number of the underlying DictEntry
2598 * @param Elem element number of the underlying DictEntry
2600 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2602 // Find out if the tag we encountered is in the dictionaries:
2603 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2605 DictEntry = NewVirtualDictEntry(Group, Elem);
2607 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2610 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2611 "failed to allocate gdcmValEntry");
2619 * \brief Build a new Element Value from all the low level arguments.
2620 * Check for existence of dictionary entry, and build
2621 * a default one when absent.
2622 * @param Group group number of the underlying DictEntry
2623 * @param Elem element number of the underlying DictEntry
2625 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2627 // Find out if the tag we encountered is in the dictionaries:
2628 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2630 DictEntry = NewVirtualDictEntry(Group, Elem);
2632 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2635 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2636 "failed to allocate gdcmBinEntry");
2643 * \brief Generate a free TagKey i.e. a TagKey that is not present
2644 * in the TagHt dictionary.
2645 * @param group The generated tag must belong to this group.
2646 * @return The element of tag with given group which is fee.
2648 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2650 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2652 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2653 if (tagHT.count(key) == 0)
2661 * \brief Searches both the public and the shadow dictionary (when they
2662 * exist) for the presence of the DictEntry with given name.
2663 * The public dictionary has precedence on the shadow one.
2664 * @param Name name of the searched DictEntry
2665 * @return Corresponding DictEntry when it exists, NULL otherwise.
2667 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2669 gdcmDictEntry *found = (gdcmDictEntry *)0;
2670 if (!RefPubDict && !RefShaDict)
2672 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2673 "we SHOULD have a default dictionary");
2677 found = RefPubDict->GetDictEntryByName(Name);
2683 found = RefShaDict->GetDictEntryByName(Name);
2691 * \brief Searches both the public and the shadow dictionary (when they
2692 * exist) for the presence of the DictEntry with given
2693 * group and element. The public dictionary has precedence on the
2695 * @param group group number of the searched DictEntry
2696 * @param element element number of the searched DictEntry
2697 * @return Corresponding DictEntry when it exists, NULL otherwise.
2699 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2701 gdcmDictEntry *found = (gdcmDictEntry *)0;
2702 if (!RefPubDict && !RefShaDict)
2704 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2705 "we SHOULD have a default dictionary");
2709 found = RefPubDict->GetDictEntryByNumber(group, element);
2715 found = RefShaDict->GetDictEntryByNumber(group, element);
2723 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2724 * is placed at the beginning of a tag (TestGroup, TestElement),
2725 * read the length associated to the Tag.
2726 * \warning On success the internal file pointer \ref gdcmDocument::fp
2727 * is modified to point after the tag and it's length.
2728 * On failure (i.e. when the tag wasn't the expected tag
2729 * (TestGroup, TestElement) the internal file pointer
2730 * \ref gdcmDocument::fp is restored to it's original position.
2731 * @param TestGroup The expected group of the tag.
2732 * @param TestElement The expected Element of the tag.
2733 * @return On success returns the length associated to the tag. On failure
2736 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2738 guint16 ItemTagGroup;
2739 guint16 ItemTagElement;
2740 long PositionOnEntry = ftell(fp);
2741 long CurrentPosition = ftell(fp); // On debugging purposes
2743 //// Read the Item Tag group and element, and make
2744 // sure they are respectively 0xfffe and 0xe000:
2745 ItemTagGroup = ReadInt16();
2746 ItemTagElement = ReadInt16();
2747 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2749 std::ostringstream s;
2750 s << " We should have found tag (";
2751 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2752 s << " but instead we encountered tag (";
2753 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2755 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2756 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2757 dbg.Verbose(0, s.str().c_str());
2758 fseek(fp, PositionOnEntry, SEEK_SET);
2762 //// Then read the associated Item Length
2763 CurrentPosition=ftell(fp);
2765 ItemLength = ReadInt32();
2767 std::ostringstream s;
2768 s << "Basic Item Length is: "
2769 << ItemLength << std::endl;
2770 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2771 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2777 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2778 * \sa \ref gdcmDocument::ReadTagLength
2779 * \warning See warning of \ref gdcmDocument::ReadTagLength
2780 * @return On success returns the length associated to the item tag.
2781 * On failure returns 0.
2783 guint32 gdcmDocument::ReadItemTagLength(void)
2785 return ReadTagLength(0xfffe, 0xe000);
2789 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2791 * \sa \ref gdcmDocument::ReadTagLength
2792 * \warning See warning of \ref gdcmDocument::ReadTagLength
2793 * @return On success returns the length associated to the Sequence
2794 * Delimiter tag. On failure returns 0.
2796 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2798 return ReadTagLength(0xfffe, 0xe0dd);
2803 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2804 * No other way so 'skip' the Data
2807 void gdcmDocument::Parse7FE0 (void)
2809 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2813 if ( IsImplicitVRLittleEndianTransferSyntax()
2814 || IsExplicitVRLittleEndianTransferSyntax()
2815 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2816 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2819 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2821 //// Read the Basic Offset Table Item Tag length...
2822 guint32 ItemLength = ReadItemTagLength();
2824 //// ... and then read length[s] itself[themselves]. We don't use
2825 // the values read (BTW what is the purpous of those lengths ?)
2826 if (ItemLength != 0) {
2827 // BTW, what is the purpous of those length anyhow !?
2828 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2829 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2830 for (int i=0; i < ItemLength; i += 4){
2831 guint32 IndividualLength;
2832 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2833 std::ostringstream s;
2834 s << " Read one length: ";
2835 s << std::hex << IndividualLength << std::endl;
2836 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2840 if ( ! IsRLELossLessTransferSyntax() )
2844 //// We then skip (not reading them) all the fragments of images:
2845 while ( ItemLength = ReadItemTagLength() )
2847 SkipBytes(ItemLength);
2855 long RleSegmentLength[15], fragmentLength;
2857 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2858 while ( fragmentLength = ReadSequenceDelimiterTagLength() )
2860 // Parse fragments of the current Fragment (Frame)
2861 //------------------ scanning (not reading) fragment pixels
2862 guint32 nbRleSegments = ReadInt32();
2863 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2865 //// Reading RLE Segments Offset Table
2866 guint32 RleSegmentOffsetTable[15];
2867 for(int k=1; k<=15; k++) {
2869 RleSegmentOffsetTable[k] = ReadInt32();
2870 printf(" at : %x Offset Segment %d : %d (%x)\n",
2871 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2872 RleSegmentOffsetTable[k]);
2875 // skipping (not reading) RLE Segments
2876 if (nbRleSegments>1) {
2877 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2878 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2879 - RleSegmentOffsetTable[k];
2881 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2882 k,(unsigned)RleSegmentLength[k],
2883 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2884 SkipBytes(RleSegmentLength[k]);
2888 RleSegmentLength[nbRleSegments]= fragmentLength
2889 - RleSegmentOffsetTable[nbRleSegments];
2891 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2892 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2893 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2894 SkipBytes(RleSegmentLength[nbRleSegments]);
2901 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2902 * \warning Does NOT work with ACR-NEMA files
2903 * \todo Find a trick to solve the pb (use RET fields ?)
2905 * @return true if 'smaller'
2907 bool gdcmDocument::operator<(gdcmDocument &document){
2911 s1=this->GetEntryByNumber(0x0010,0x0010);
2912 s2=document.GetEntryByNumber(0x0010,0x0010);
2920 s1=this->GetEntryByNumber(0x0010,0x0020);
2921 s2=document.GetEntryByNumber(0x0010,0x0020);
2928 // Study Instance UID
2929 s1=this->GetEntryByNumber(0x0020,0x000d);
2930 s2=document.GetEntryByNumber(0x0020,0x000d);
2937 // Serie Instance UID
2938 s1=this->GetEntryByNumber(0x0020,0x000e);
2939 s2=document.GetEntryByNumber(0x0020,0x000e);
2951 //-----------------------------------------------------------------------------