1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/21 04:18:25 $
7 Version: $Revision: 1.20 $
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",
903 "failed to Locate gdcmDocEntry");
906 return Entry->GetOffset();
910 * \brief Gets (from Header) a 'non string' element value
911 * (LoadElementValues has already be executed)
912 * @param Group group number of the Entry
913 * @param Elem element number of the Entry
914 * @return Pointer to the 'non string' area
916 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
918 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
921 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
922 "failed to Locate gdcmDocEntry");
925 return ((gdcmBinEntry *)Entry)->GetVoidArea();
929 * \brief Loads (from disk) the element content
930 * when a string is not suitable
931 * @param Group group number of the Entry
932 * @param Elem element number of the Entry
934 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
936 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
939 size_t o =(size_t)Element->GetOffset();
940 fseek(fp, o, SEEK_SET);
941 size_t l = Element->GetLength();
942 char* a = new char[l];
944 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
947 SetEntryVoidAreaByNumber(a, Group, Elem);
948 /// \todo check the result
949 size_t l2 = fread(a, 1, l ,fp);
960 * \brief Sets a 'non string' value to a given Dicom Element
962 * @param group Group number of the searched Dicom Element
963 * @param element Element number of the searched Dicom Element
966 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
970 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
971 if ( ! tagHT.count(key))
973 // This was for multimap ?
974 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
980 * \brief Update the entries with the shadow dictionary.
981 * Only non even entries are analyzed
983 void gdcmDocument::UpdateShaEntries(void) {
984 //gdcmDictEntry *entry;
987 /// \todo TODO : still any use to explore recursively the whole structure?
989 for(ListTag::iterator it=listEntries.begin();
990 it!=listEntries.end();
993 // Odd group => from public dictionary
994 if((*it)->GetGroup()%2==0)
997 // Peer group => search the corresponding dict entry
999 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1003 if((*it)->IsImplicitVR())
1008 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1010 // Set the new entry and the new value
1011 (*it)->SetDictEntry(entry);
1012 CheckDocEntryVR(*it,vr);
1014 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1019 // Remove precedent value transformation
1020 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1027 * \brief Searches within the Header Entries for a Dicom Element of
1029 * @param tagName name of the searched Dicom Element.
1030 * @return Corresponding Dicom Element when it exists, and NULL
1033 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1034 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1035 if( dictEntry == NULL)
1038 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1042 * \brief retrieves a Dicom Element (the first one) using (group, element)
1043 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1044 * if you think it's NOT UNIQUE, check the count number
1045 * and use iterators to retrieve ALL the Dicoms Elements within
1046 * a given couple (group, element)
1047 * @param group Group number of the searched Dicom Element
1048 * @param element Element number of the searched Dicom Element
1051 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1053 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1054 if ( ! tagHT.count(key))
1056 return tagHT.find(key)->second;
1060 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1061 * returns a result when the corresponding entry is of type
1063 * @return When present, the corresponding ValEntry.
1065 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1067 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1069 return (gdcmValEntry*)0;
1070 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1074 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1075 return (gdcmValEntry*)0;
1079 * \brief Loads the element while preserving the current
1080 * underlying file position indicator as opposed to
1081 * to LoadDocEntry that modifies it.
1082 * @param entry Header Entry whose value shall be loaded.
1085 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1086 long PositionOnEntry = ftell(fp);
1087 LoadDocEntry(entry);
1088 fseek(fp, PositionOnEntry, SEEK_SET);
1093 * \brief Writes in a file (according to the requested format)
1094 * the group, the element, the value representation and the length
1095 * of a single gdcmDocEntry passed as argument.
1096 * @param tag pointer on the gdcmDocEntry to be written
1097 * @param _fp already open file pointer
1098 * @param type type of the File to be written
1100 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1104 guint16 group = tag->GetGroup();
1105 VRKey vr = tag->GetVR();
1106 guint16 el = tag->GetElement();
1107 guint32 lgr = tag->GetReadLength();
1109 if ( (group == 0xfffe) && (el == 0x0000) )
1110 // Fix in order to make some MR PHILIPS images e-film readable
1111 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1112 // we just *always* ignore spurious fffe|0000 tag !
1115 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1116 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1118 if ( type == gdcmExplicitVR ) {
1120 // Special case of delimiters:
1121 if (group == 0xfffe) {
1122 // Delimiters have NO Value Representation and have NO length.
1123 // Hence we skip writing the VR and length and we pad by writing
1127 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1132 guint16 shortLgr = lgr;
1133 if (vr == "unkn") { // Unknown was 'written'
1134 // deal with Little Endian
1135 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1136 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1138 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1139 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1141 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1142 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1144 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1150 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1155 * \brief Writes in a file (according to the requested format)
1156 * the value of a single gdcmDocEntry passed as argument.
1157 * @param tag Pointer on the gdcmDocEntry to be written
1158 * @param _fp Already open file pointer
1159 * @param type type of the File to be written
1162 // \todo TODO : to be re -written recursively !
1163 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1166 guint16 group = tag->GetGroup();
1167 VRKey vr = tag->GetVR();
1168 guint32 lgr = tag->GetReadLength();
1171 // SeQuences have no value:
1173 if (group == 0xfffe)
1174 // Delimiters have no associated value:
1177 //--------------------------------
1179 // FIXME :right now, both value and voidArea belong to gdcmValue
1181 // -------------------------------
1183 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1185 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1186 voidArea = BinEntry->GetVoidArea();
1187 if (voidArea != NULL)
1188 { // there is a 'non string' LUT, overlay, etc
1189 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1194 if (vr == "US" || vr == "SS")
1196 // some 'Short integer' fields may be mulivaluated
1197 // each single value is separated from the next one by '\'
1198 // we split the string and write each value as a short int
1199 std::vector<std::string> tokens;
1200 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1201 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1202 for (unsigned int i=0; i<tokens.size();i++)
1204 guint16 val_uint16 = atoi(tokens[i].c_str());
1205 void *ptr = &val_uint16;
1206 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1211 if (vr == "UL" || vr == "SL")
1213 // Some 'Integer' fields may be multivaluated (multiple instances
1214 // of integers). But each single integer value is separated from the
1215 // next one by '\' (backslash character). Hence we split the string
1216 // along the '\' and write each value as an int:
1217 std::vector<std::string> tokens;
1218 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1219 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1220 for (unsigned int i=0; i<tokens.size();i++)
1222 guint32 val_uint32 = atoi(tokens[i].c_str());
1223 void *ptr = &val_uint32;
1224 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1229 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(),
1230 (size_t)lgr ,(size_t)1, _fp); // Elem value
1234 * \brief Writes in a file (according to the requested format)
1235 * a single gdcmDocEntry passed as argument.
1236 * \sa WriteEntryValue, WriteEntryTagVRLength.
1237 * @param tag Pointer on the gdcmDocEntry to be written
1238 * @param _fp Already open file pointer
1239 * @param type type of the File to be written
1242 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1244 guint32 length = tag->GetLength();
1246 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1248 // The value of a tag MUST (see the DICOM norm) be an odd number of
1249 // bytes. When this is not the case, pad with an additional byte:
1251 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1252 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1254 WriteEntryTagVRLength(ValEntry, _fp, type);
1255 WriteEntryValue(ValEntry, _fp, type);
1259 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1261 (void)BinEntry; //not used
1262 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
1265 // The value of a tag MUST (see the DICOM norm) be an odd number of
1266 // bytes. When this is not the case, pad with an additional byte:
1269 tag->SetValue(tag->GetValue()+"\0");
1270 tag->SetLength(tag->GetReadLength()+1);
1273 WriteEntryTagVRLength(tag, _fp, type);
1274 WriteEntryValue(tag, _fp, type);
1278 return false; //default behavior ?
1282 * \brief writes on disc according to the requested format
1283 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1284 * using the Chained List
1285 * \warning does NOT add the missing elements in the header :
1286 * it's up to the user doing it !
1287 * (function CheckHeaderCoherence to be written)
1288 * \warning DON'T try, right now, to write a DICOM image
1289 * from an ACR Header (meta elements will be missing!)
1290 * @param type type of the File to be written
1291 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1292 * @param _fp already open file pointer
1295 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1297 /// \todo FIXME : explore recursively the whole structure...
1298 /// \todo (?) check write failures (after *each* fwrite)
1300 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1301 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1303 gdcmDocEntry * entry = it->second;
1305 if ( type == gdcmACR ){
1306 if (entry->GetGroup() < 0x0008)
1307 // Ignore pure DICOM V3 groups
1309 if (entry->GetGroup() %2)
1310 // Ignore the "shadow" groups
1312 if (entry->GetVR() == "SQ" ) // ignore Sequences
1315 if (! WriteEntry(entry, _fp, type) ) {
1316 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1325 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1327 * @return The properly swaped 32 bits integer.
1329 guint32 gdcmDocument::SwapLong(guint32 a) {
1334 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1335 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1339 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1343 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1346 std::cout << "swapCode= " << sw << std::endl;
1347 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1354 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1356 * @return The properly unswaped 32 bits integer.
1358 guint32 gdcmDocument::UnswapLong(guint32 a) {
1359 return (SwapLong(a));
1363 * \brief Swaps the bytes so they agree with the processor order
1364 * @return The properly swaped 16 bits integer.
1366 guint16 gdcmDocument::SwapShort(guint16 a) {
1367 if ( (sw==4321) || (sw==2143) )
1368 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1373 * \brief Unswaps the bytes so they agree with the processor order
1374 * @return The properly unswaped 16 bits integer.
1376 guint16 gdcmDocument::UnswapShort(guint16 a) {
1377 return (SwapShort(a));
1380 //-----------------------------------------------------------------------------
1384 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1385 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1388 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1390 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1391 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1398 depth = set->GetDepthLevel();
1401 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1404 NewDocEntry = ReadNextDocEntry( );
1408 vr = NewDocEntry->GetVR();
1412 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1415 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1416 NewValEntry->Copy(NewDocEntry);
1417 NewValEntry->SetDepthLevel(depth);
1418 set->AddEntry(NewValEntry);
1419 LoadDocEntry(NewValEntry);
1420 if (/*!delim_mode && */NewValEntry->isItemDelimitor())
1422 if ( !delim_mode && ftell(fp)-offset >= l_max)
1429 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1431 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1432 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1433 "nor BinEntry. Probably unknown VR.");
1436 ////// BinEntry or UNKOWN VR:
1437 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1438 bn->Copy(NewDocEntry);
1443 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1444 NewDocEntry->GetElement() == 0x0010 )
1446 if (NewDocEntry->GetLength()==0xffffffff)
1447 // Broken US.3405.1.dcm
1448 Parse7FE0(); // to skip the pixels
1449 // (multipart JPEG/RLE are trouble makers)
1453 // to be sure we are at the beginning
1454 SkipToNextDocEntry(NewDocEntry);
1455 l = NewDocEntry->GetFullLength();
1461 l=NewDocEntry->GetReadLength();
1462 if (l != 0) // don't mess the delim_mode for zero-length sequence
1463 if (l == 0xffffffff)
1467 // no other way to create it ...
1468 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1469 set->GetDepthLevel());
1470 sq->Copy(NewDocEntry);
1471 sq->SetDelimitorMode(delim_mode);
1472 sq->SetDepthLevel(depth);
1475 { // Don't try to parse zero-length sequences
1476 long lgt = ParseSQ( sq,
1477 NewDocEntry->GetOffset(),
1479 (void)lgt; //not used...
1481 // FIXME : on en fait quoi, de lgt ?
1483 if ( !delim_mode && ftell(fp)-offset >= l_max)
1494 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1495 * @return parsed length for this level
1497 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1498 long offset, long l_max, bool delim_mode)
1500 int SQItemNumber = 0;
1502 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1507 int depth = set->GetDepthLevel();
1508 (void)depth; //not used
1511 NewDocEntry = ReadNextDocEntry();
1513 if (NewDocEntry->isSequenceDelimitor()) {
1514 /// \todo add the Sequence Delimitor
1515 /// \todo find the trick to put it properly !
1516 set->SetSequenceDelimitationItem(NewDocEntry);
1520 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1524 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1525 itemSQ->AddEntry(NewDocEntry);
1526 /// \todo no value, no voidArea. Think of it while printing !
1527 l= NewDocEntry->GetReadLength();
1529 if (l == 0xffffffff)
1534 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1536 set->AddEntry(itemSQ,SQItemNumber);
1538 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1542 lgth = ftell(fp) - offset;
1547 * \brief Loads the element content if its length doesn't exceed
1548 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1549 * @param Entry Header Entry (Dicom Element) to be dealt with
1551 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1554 guint16 group = Entry->GetGroup();
1555 std::string vr= Entry->GetVR();
1556 guint32 length = Entry->GetLength();
1558 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1560 // A SeQuence "contains" a set of Elements.
1561 // (fffe e000) tells us an Element is beginning
1562 // (fffe e00d) tells us an Element just ended
1563 // (fffe e0dd) tells us the current SeQuence just ended
1564 if( group == 0xfffe ) {
1565 // NO more value field for SQ !
1566 //Entry->SetValue("gdcm::Skipped");
1567 // appel recursif de Load Value
1568 // (meme pb que pour le parsing)
1572 // When the length is zero things are easy:
1573 if ( length == 0 ) {
1574 ((gdcmValEntry *)Entry)->SetValue("");
1578 // The elements whose length is bigger than the specified upper bound
1579 // are not loaded. Instead we leave a short notice of the offset of
1580 // the element content and it's length.
1581 if (length > MaxSizeLoadEntry) {
1582 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1584 std::ostringstream s;
1585 s << "gdcm::NotLoaded.";
1586 s << " Address:" << (long)Entry->GetOffset();
1587 s << " Length:" << Entry->GetLength();
1588 s << " x(" << std::hex << Entry->GetLength() << ")";
1589 ValEntryPtr->SetValue(s.str());
1591 // to be sure we are at the end of the value ...
1592 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1597 // Any compacter code suggested (?)
1598 if ( IsDocEntryAnInteger(Entry) ) {
1600 std::ostringstream s;
1602 // When short integer(s) are expected, read and convert the following
1603 // n *two characters properly i.e. as short integers as opposed to strings.
1604 // Elements with Value Multiplicity > 1
1605 // contain a set of integers (not a single one)
1606 if (vr == "US" || vr == "SS") {
1608 NewInt = ReadInt16();
1611 for (int i=1; i < nbInt; i++) {
1613 NewInt = ReadInt16();
1618 // When integer(s) are expected, read and convert the following
1619 // n * four characters properly i.e. as integers as opposed to strings.
1620 // Elements with Value Multiplicity > 1
1621 // contain a set of integers (not a single one)
1622 else if (vr == "UL" || vr == "SL") {
1624 NewInt = ReadInt32();
1627 for (int i=1; i < nbInt; i++) {
1629 NewInt = ReadInt32();
1634 #ifdef GDCM_NO_ANSI_STRING_STREAM
1635 s << std::ends; // to avoid oddities on Solaris
1636 #endif //GDCM_NO_ANSI_STRING_STREAM
1638 ((gdcmValEntry *)Entry)->SetValue(s.str());
1642 // We need an additional byte for storing \0 that is not on disk
1643 std::string NewValue(length,0);
1644 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1645 if ( item_read != 1 ) {
1646 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1647 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1651 if( (vr == "UI") ) // Because of correspondance with the VR dic
1652 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1654 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1659 * \brief Find the value Length of the passed Header Entry
1660 * @param Entry Header Entry whose length of the value shall be loaded.
1662 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1663 guint16 element = Entry->GetElement();
1664 //guint16 group = Entry->GetGroup(); //FIXME
1665 std::string vr = Entry->GetVR();
1669 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1671 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1673 // The following reserved two bytes (see PS 3.5-2001, section
1674 // 7.1.2 Data element structure with explicit vr p27) must be
1675 // skipped before proceeding on reading the length on 4 bytes.
1676 fseek(fp, 2L, SEEK_CUR);
1677 guint32 length32 = ReadInt32();
1679 if ( (vr == "OB") && (length32 == 0xffffffff) )
1681 Entry->SetLength(FindDocEntryLengthOB());
1684 FixDocEntryFoundLength(Entry, length32);
1688 // Length is encoded on 2 bytes.
1689 length16 = ReadInt16();
1691 // We can tell the current file is encoded in big endian (like
1692 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1693 // and it's value is the one of the encoding of a big endian file.
1694 // In order to deal with such big endian encoded files, we have
1695 // (at least) two strategies:
1696 // * when we load the "Transfer Syntax" tag with value of big endian
1697 // encoding, we raise the proper flags. Then we wait for the end
1698 // of the META group (0x0002) among which is "Transfer Syntax",
1699 // before switching the swap code to big endian. We have to postpone
1700 // the switching of the swap code since the META group is fully encoded
1701 // in little endian, and big endian coding only starts at the next
1702 // group. The corresponding code can be hard to analyse and adds
1703 // many additional unnecessary tests for regular tags.
1704 // * the second strategy consists in waiting for trouble, that shall
1705 // appear when we find the first group with big endian encoding. This
1706 // is easy to detect since the length of a "Group Length" tag (the
1707 // ones with zero as element number) has to be of 4 (0x0004). When we
1708 // encounter 1024 (0x0400) chances are the encoding changed and we
1709 // found a group with big endian encoding.
1710 // We shall use this second strategy. In order to make sure that we
1711 // can interpret the presence of an apparently big endian encoded
1712 // length of a "Group Length" without committing a big mistake, we
1713 // add an additional check: we look in the already parsed elements
1714 // for the presence of a "Transfer Syntax" whose value has to be "big
1715 // endian encoding". When this is the case, chances are we have got our
1716 // hands on a big endian encoded file: we switch the swap code to
1717 // big endian and proceed...
1718 if ( (element == 0x0000) && (length16 == 0x0400) )
1720 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1722 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1727 SwitchSwapToBigEndian();
1728 // Restore the unproperly loaded values i.e. the group, the element
1729 // and the dictionary entry depending on them.
1730 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1731 guint16 CorrectElem = SwapShort(Entry->GetElement());
1732 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1736 // This correct tag is not in the dictionary. Create a new one.
1737 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1739 // FIXME this can create a memory leaks on the old entry that be
1740 // left unreferenced.
1741 Entry->SetDictEntry(NewTag);
1744 // Heuristic: well some files are really ill-formed.
1745 if ( length16 == 0xffff)
1748 //dbg.Verbose(0, "gdcmDocument::FindLength",
1749 // "Erroneous element length fixed.");
1750 // Actually, length= 0xffff means that we deal with
1751 // Unknown Sequence Length
1753 FixDocEntryFoundLength(Entry, (guint32)length16);
1758 // Either implicit VR or a non DICOM conformal (see note below) explicit
1759 // VR that ommited the VR of (at least) this element. Farts happen.
1760 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1761 // on Data elements "Implicit and Explicit VR Data Elements shall
1762 // not coexist in a Data Set and Data Sets nested within it".]
1763 // Length is on 4 bytes.
1765 FixDocEntryFoundLength(Entry, ReadInt32());
1771 * \brief Find the Value Representation of the current Dicom Element.
1774 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1776 if (Filetype != gdcmExplicitVR)
1781 long PositionOnEntry = ftell(fp);
1782 // Warning: we believe this is explicit VR (Value Representation) because
1783 // we used a heuristic that found "UL" in the first tag. Alas this
1784 // doesn't guarantee that all the tags will be in explicit VR. In some
1785 // cases (see e-film filtered files) one finds implicit VR tags mixed
1786 // within an explicit VR file. Hence we make sure the present tag
1787 // is in explicit VR and try to fix things if it happens not to be
1790 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1792 if(!CheckDocEntryVR(Entry,VR))
1794 fseek(fp, PositionOnEntry, SEEK_SET);
1795 // When this element is known in the dictionary we shall use, e.g. for
1796 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1797 // dictionary entry. Still we have to flag the element as implicit since
1798 // we know now our assumption on expliciteness is not furfilled.
1800 if ( Entry->IsVRUnknown() )
1801 Entry->SetVR("Implicit");
1802 Entry->SetImplicitVR();
1807 * \brief Check the correspondance between the VR of the header entry
1808 * and the taken VR. If they are different, the header entry is
1809 * updated with the new VR.
1810 * @param Entry Header Entry to check
1811 * @param vr Dicom Value Representation
1812 * @return false if the VR is incorrect of if the VR isn't referenced
1813 * otherwise, it returns true
1815 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1817 char msg[100]; // for sprintf
1818 bool RealExplicit = true;
1820 // Assume we are reading a falsely explicit VR file i.e. we reached
1821 // a tag where we expect reading a VR but are in fact we read the
1822 // first to bytes of the length. Then we will interogate (through find)
1823 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1824 // both GCC and VC++ implementations of the STL map. Hence when the
1825 // expected VR read happens to be non-ascii characters we consider
1826 // we hit falsely explicit VR tag.
1828 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1829 RealExplicit = false;
1831 // CLEANME searching the dicom_vr at each occurence is expensive.
1832 // PostPone this test in an optional integrity check at the end
1833 // of parsing or only in debug mode.
1834 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1835 RealExplicit= false;
1837 if ( !RealExplicit )
1839 // We thought this was explicit VR, but we end up with an
1840 // implicit VR tag. Let's backtrack.
1841 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1842 Entry->GetGroup(),Entry->GetElement());
1843 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1844 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1845 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1846 Entry->GetGroup(),Entry->GetElement(),
1847 "UL","FIXME","Group Length");
1848 Entry->SetDictEntry(NewEntry);
1853 if ( Entry->IsVRUnknown() )
1855 // When not a dictionary entry, we can safely overwrite the VR.
1856 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1862 else if ( Entry->GetVR() != vr )
1864 // The VR present in the file and the dictionary disagree. We assume
1865 // the file writer knew best and use the VR of the file. Since it would
1866 // be unwise to overwrite the VR of a dictionary (since it would
1867 // compromise it's next user), we need to clone the actual DictEntry
1868 // and change the VR for the read one.
1869 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1870 Entry->GetGroup(),Entry->GetElement(),
1871 vr,"FIXME",Entry->GetName());
1872 Entry->SetDictEntry(NewEntry);
1878 * \brief Get the transformed value of the header entry. The VR value
1879 * is used to define the transformation to operate on the value
1880 * \warning NOT end user intended method !
1882 * @return Transformed entry value
1884 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1886 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1888 std::string val=((gdcmValEntry *)Entry)->GetValue();
1889 std::string vr=Entry->GetVR();
1890 guint32 length = Entry->GetLength();
1891 std::ostringstream s;
1894 // When short integer(s) are expected, read and convert the following
1895 // n * 2 bytes properly i.e. as a multivaluated strings
1896 // (each single value is separated fromthe next one by '\'
1897 // as usual for standard multivaluated filels
1898 // Elements with Value Multiplicity > 1
1899 // contain a set of short integers (not a single one)
1901 if (vr == "US" || vr == "SS")
1906 for (int i=0; i < nbInt; i++)
1910 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1911 NewInt16 = SwapShort(NewInt16);
1916 // When integer(s) are expected, read and convert the following
1917 // n * 4 bytes properly i.e. as a multivaluated strings
1918 // (each single value is separated fromthe next one by '\'
1919 // as usual for standard multivaluated filels
1920 // Elements with Value Multiplicity > 1
1921 // contain a set of integers (not a single one)
1922 else if (vr == "UL" || vr == "SL")
1927 for (int i=0; i < nbInt; i++)
1931 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1932 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1933 NewInt32=SwapLong(NewInt32);
1937 #ifdef GDCM_NO_ANSI_STRING_STREAM
1938 s << std::ends; // to avoid oddities on Solaris
1939 #endif //GDCM_NO_ANSI_STRING_STREAM
1943 return(((gdcmValEntry *)Entry)->GetValue());
1947 * \brief Get the reverse transformed value of the header entry. The VR
1948 * value is used to define the reverse transformation to operate on
1950 * \warning NOT end user intended method !
1952 * @return Reverse transformed entry value
1954 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1956 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1958 std::string vr=Entry->GetVR();
1959 std::ostringstream s;
1960 std::vector<std::string> tokens;
1962 if (vr == "US" || vr == "SS")
1966 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1967 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1968 for (unsigned int i=0; i<tokens.size();i++)
1970 NewInt16 = atoi(tokens[i].c_str());
1971 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1975 if (vr == "UL" || vr == "SL")
1979 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1980 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1981 for (unsigned int i=0; i<tokens.size();i++)
1983 NewInt32 = atoi(tokens[i].c_str());
1984 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1985 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1990 #ifdef GDCM_NO_ANSI_STRING_STREAM
1991 s << std::ends; // to avoid oddities on Solaris
1992 #endif //GDCM_NO_ANSI_STRING_STREAM
1996 return(((gdcmValEntry *)Entry)->GetValue());
2000 * \brief Skip a given Header Entry
2001 * \warning NOT end user intended method !
2004 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2006 SkipBytes(entry->GetLength());
2010 * \brief Skips to the begining of the next Header Entry
2011 * \warning NOT end user intended method !
2014 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2016 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
2017 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
2021 * \brief Loads the value for a a given VLEntry
2022 * \warning NOT end user intended method !
2025 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
2027 //SkipBytes(entry->GetLength());
2028 LoadDocEntry(entry);
2031 * \brief When the length of an element value is obviously wrong (because
2032 * the parser went Jabberwocky) one can hope improving things by
2033 * applying some heuristics.
2035 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
2036 guint32 FoundLength)
2038 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
2039 if ( FoundLength == 0xffffffff) {
2043 guint16 gr =Entry->GetGroup();
2044 guint16 el =Entry->GetElement();
2046 if (FoundLength%2) {
2047 std::ostringstream s;
2048 s << "Warning : Tag with uneven length "
2050 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2051 dbg.Verbose(0, s.str().c_str());
2054 //////// Fix for some naughty General Electric images.
2055 // Allthough not recent many such GE corrupted images are still present
2056 // on Creatis hard disks. Hence this fix shall remain when such images
2057 // are no longer in user (we are talking a few years, here)...
2058 // Note: XMedCom probably uses such a trick since it is able to read
2059 // those pesky GE images ...
2060 if (FoundLength == 13) { // Only happens for this length !
2061 if ( (Entry->GetGroup() != 0x0008)
2062 || ( (Entry->GetElement() != 0x0070)
2063 && (Entry->GetElement() != 0x0080) ) )
2066 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2070 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2071 // Occurence of such images is quite low (unless one leaves close to a
2072 // 'Leonardo' source. Hence, one might consider commenting out the
2073 // following fix on efficiency reasons.
2075 if ( (Entry->GetGroup() == 0x0009)
2076 && ( (Entry->GetElement() == 0x1113)
2077 || (Entry->GetElement() == 0x1114) ) )
2080 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2083 //////// Deal with sequences, but only on users request:
2085 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2087 FoundLength = 0; // ReadLength is unchanged
2090 //////// We encountered a 'delimiter' element i.e. a tag of the form
2091 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2092 // taken into account.
2094 if(Entry->GetGroup() == 0xfffe)
2096 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2097 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2098 // causes extra troubles...
2099 if( Entry->GetElement() != 0x0000 )
2105 Entry->SetUsableLength(FoundLength);
2109 * \brief Apply some heuristics to predict whether the considered
2110 * element value contains/represents an integer or not.
2111 * @param Entry The element value on which to apply the predicate.
2112 * @return The result of the heuristical predicate.
2114 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2115 guint16 element = Entry->GetElement();
2116 guint16 group = Entry->GetGroup();
2117 std::string vr = Entry->GetVR();
2118 guint32 length = Entry->GetLength();
2120 // When we have some semantics on the element we just read, and if we
2121 // a priori know we are dealing with an integer, then we shall be
2122 // able to swap it's element value properly.
2123 if ( element == 0 ) // This is the group length of the group
2129 // Allthough this should never happen, still some images have a
2130 // corrupted group length [e.g. have a glance at offset x(8336) of
2131 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2132 // Since for dicom compliant and well behaved headers, the present
2133 // test is useless (and might even look a bit paranoid), when we
2134 // encounter such an ill-formed image, we simply display a warning
2135 // message and proceed on parsing (while crossing fingers).
2136 std::ostringstream s;
2137 int filePosition = ftell(fp);
2138 s << "Erroneous Group Length element length on : (" \
2139 << std::hex << group << " , " << element
2140 << ") -before- position x(" << filePosition << ")"
2141 << "lgt : " << length;
2142 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2146 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2153 * \brief Find the Length till the next sequence delimiter
2154 * \warning NOT end user intended method !
2158 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2159 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2162 long PositionOnEntry = ftell(fp);
2163 bool FoundSequenceDelimiter = false;
2164 guint32 TotalLength = 0;
2167 while ( ! FoundSequenceDelimiter)
2173 TotalLength += 4; // We even have to decount the group and element
2175 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2177 char msg[100]; // for sprintf. Sorry
2178 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2179 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2183 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2184 FoundSequenceDelimiter = true;
2185 else if ( n != 0xe000 )
2187 char msg[100]; // for sprintf. Sorry
2188 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2190 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2194 ItemLength = ReadInt32();
2195 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2196 // the ItemLength with ReadInt32
2197 SkipBytes(ItemLength);
2199 fseek(fp, PositionOnEntry, SEEK_SET);
2204 * \brief Reads a supposed to be 16 Bits integer
2205 * (swaps it depending on processor endianity)
2206 * @return read value
2208 guint16 gdcmDocument::ReadInt16() {
2211 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2212 if ( item_read != 1 ) {
2214 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2224 * \brief Reads a supposed to be 32 Bits integer
2225 * (swaps it depending on processor endianity)
2226 * @return read value
2228 guint32 gdcmDocument::ReadInt32() {
2231 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2232 if ( item_read != 1 ) {
2234 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2244 * \brief skips bytes inside the source file
2245 * \warning NOT end user intended method !
2248 void gdcmDocument::SkipBytes(guint32 NBytes) {
2249 //FIXME don't dump the returned value
2250 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2254 * \brief Loads all the needed Dictionaries
2255 * \warning NOT end user intended method !
2257 void gdcmDocument::Initialise(void)
2259 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2264 * \brief Discover what the swap code is (among little endian, big endian,
2265 * bad little endian, bad big endian).
2267 * @return false when we are absolutely sure
2268 * it's neither ACR-NEMA nor DICOM
2269 * true when we hope ours assuptions are OK
2271 bool gdcmDocument::CheckSwap() {
2273 // The only guaranted way of finding the swap code is to find a
2274 // group tag since we know it's length has to be of four bytes i.e.
2275 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2276 // occurs when we can't find such group...
2278 guint32 x=4; // x : for ntohs
2279 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2285 char deb[HEADER_LENGTH_TO_READ];
2287 // First, compare HostByteOrder and NetworkByteOrder in order to
2288 // determine if we shall need to swap bytes (i.e. the Endian type).
2294 // The easiest case is the one of a DICOM header, since it possesses a
2295 // file preamble where it suffice to look for the string "DICM".
2296 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2299 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2300 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2302 // Next, determine the value representation (VR). Let's skip to the
2303 // first element (0002, 0000) and check there if we find "UL"
2304 // - or "OB" if the 1st one is (0002,0001) -,
2305 // in which case we (almost) know it is explicit VR.
2306 // WARNING: if it happens to be implicit VR then what we will read
2307 // is the length of the group. If this ascii representation of this
2308 // length happens to be "UL" then we shall believe it is explicit VR.
2309 // FIXME: in order to fix the above warning, we could read the next
2310 // element value (or a couple of elements values) in order to make
2311 // sure we are not commiting a big mistake.
2312 // We need to skip :
2313 // * the 128 bytes of File Preamble (often padded with zeroes),
2314 // * the 4 bytes of "DICM" string,
2315 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2316 // i.e. a total of 136 bytes.
2320 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2321 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2322 // *Implicit* VR. -and it is !-
2324 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2325 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2326 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2327 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2328 // when Write DCM *adds*
2330 // Use gdcmDocument::dicom_vr to test all the possibilities
2331 // instead of just checking for UL, OB and UI !? group 0000
2333 Filetype = gdcmExplicitVR;
2334 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2335 "explicit Value Representation");
2339 Filetype = gdcmImplicitVR;
2340 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2341 "not an explicit Value Representation");
2347 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2348 "HostByteOrder != NetworkByteOrder");
2353 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2354 "HostByteOrder = NetworkByteOrder");
2357 // Position the file position indicator at first tag (i.e.
2358 // after the file preamble and the "DICM" string).
2360 fseek (fp, 132L, SEEK_SET);
2364 // Alas, this is not a DicomV3 file and whatever happens there is no file
2365 // preamble. We can reset the file position indicator to where the data
2366 // is (i.e. the beginning of the file).
2367 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2370 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2371 // By clean we mean that the length of the first tag is written down.
2372 // If this is the case and since the length of the first group HAS to be
2373 // four (bytes), then determining the proper swap code is straightforward.
2376 // We assume the array of char we are considering contains the binary
2377 // representation of a 32 bits integer. Hence the following dirty
2379 s32 = *((guint32 *)(entCur));
2400 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2401 // It is time for despaired wild guesses.
2402 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2403 // i.e. the 'group length' element is not present :
2405 // check the supposed to be 'group number'
2406 // 0x0002 or 0x0004 or 0x0008
2407 // to determine ' sw' value .
2408 // Only 0 or 4321 will be possible
2409 // (no oportunity to check for the formerly well known
2410 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2411 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2412 // the file IS NOT ACR-NEMA nor DICOM V3
2413 // Find a trick to tell it the caller...
2415 s16 = *((guint16 *)(deb));
2431 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2432 "ACR/NEMA unfound swap info (Really hopeless !)");
2433 Filetype = gdcmUnknown;
2437 // Then the only info we have is the net2host one.
2447 * \brief Restore the unproperly loaded values i.e. the group, the element
2448 * and the dictionary entry depending on them.
2450 void gdcmDocument::SwitchSwapToBigEndian(void)
2452 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2453 "Switching to BigEndian mode.");
2474 * \brief during parsing, Header Elements too long are not loaded in memory
2477 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2481 if ((guint32)NewSize >= (guint32)0xffffffff)
2483 MaxSizeLoadEntry = 0xffffffff;
2486 MaxSizeLoadEntry = NewSize;
2491 * \brief Header Elements too long will not be printed
2492 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2495 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2499 if ((guint32)NewSize >= (guint32)0xffffffff)
2501 MaxSizePrintEntry = 0xffffffff;
2504 MaxSizePrintEntry = NewSize;
2510 * \brief Read the next tag but WITHOUT loading it's value
2511 * (read the 'Group Number', the 'Element Number',
2512 * gets the Dict Entry
2513 * gets the VR, gets the length, gets the offset value)
2514 * @return On succes the newly created DocEntry, NULL on failure.
2516 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2518 gdcmDocEntry *NewEntry;
2523 // We reached the EOF (or an error occured) therefore
2524 // header parsing has to be considered as finished.
2525 return (gdcmDocEntry *)0;
2527 NewEntry = NewDocEntryByNumber(g, n);
2528 FindDocEntryVR(NewEntry);
2529 FindDocEntryLength(NewEntry);
2536 NewEntry->SetOffset(ftell(fp));
2541 * \brief Build a new Element Value from all the low level arguments.
2542 * Check for existence of dictionary entry, and build
2543 * a default one when absent.
2544 * @param Name Name of the underlying DictEntry
2546 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2548 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2550 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2552 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2555 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2556 "failed to allocate gdcmDocEntry");
2557 return (gdcmDocEntry *)0;
2563 * \brief Request a new virtual dict entry to the dict set
2564 * @param group group number of the underlying DictEntry
2565 * @param element element number of the underlying DictEntry
2566 * @param vr VR of the underlying DictEntry
2567 * @param fourth owner group
2568 * @param name english name
2570 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2575 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2579 * \brief Build a new Element Value from all the low level arguments.
2580 * Check for existence of dictionary entry, and build
2581 * a default one when absent.
2582 * @param Group group number of the underlying DictEntry
2583 * @param Elem element number of the underlying DictEntry
2585 gdcmDocEntry* gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2587 // Find out if the tag we encountered is in the dictionaries:
2588 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2590 DictEntry = NewVirtualDictEntry(Group, Elem);
2592 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2595 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2596 "failed to allocate gdcmDocEntry");
2597 return (gdcmDocEntry*)0;
2604 * \brief Build a new Element Value from all the low level arguments.
2605 * Check for existence of dictionary entry, and build
2606 * a default one when absent.
2607 * @param Group group number of the underlying DictEntry
2608 * @param Elem element number of the underlying DictEntry
2610 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2612 // Find out if the tag we encountered is in the dictionaries:
2613 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2615 DictEntry = NewVirtualDictEntry(Group, Elem);
2617 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2620 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2621 "failed to allocate gdcmValEntry");
2629 * \brief Build a new Element Value from all the low level arguments.
2630 * Check for existence of dictionary entry, and build
2631 * a default one when absent.
2632 * @param Group group number of the underlying DictEntry
2633 * @param Elem element number of the underlying DictEntry
2635 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2637 // Find out if the tag we encountered is in the dictionaries:
2638 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2640 DictEntry = NewVirtualDictEntry(Group, Elem);
2642 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2645 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2646 "failed to allocate gdcmBinEntry");
2653 * \brief Generate a free TagKey i.e. a TagKey that is not present
2654 * in the TagHt dictionary.
2655 * @param group The generated tag must belong to this group.
2656 * @return The element of tag with given group which is fee.
2658 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2660 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2662 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2663 if (tagHT.count(key) == 0)
2671 * \brief Searches both the public and the shadow dictionary (when they
2672 * exist) for the presence of the DictEntry with given name.
2673 * The public dictionary has precedence on the shadow one.
2674 * @param Name name of the searched DictEntry
2675 * @return Corresponding DictEntry when it exists, NULL otherwise.
2677 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2679 gdcmDictEntry *found = (gdcmDictEntry *)0;
2680 if (!RefPubDict && !RefShaDict)
2682 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2683 "we SHOULD have a default dictionary");
2687 found = RefPubDict->GetDictEntryByName(Name);
2693 found = RefShaDict->GetDictEntryByName(Name);
2701 * \brief Searches both the public and the shadow dictionary (when they
2702 * exist) for the presence of the DictEntry with given
2703 * group and element. The public dictionary has precedence on the
2705 * @param group group number of the searched DictEntry
2706 * @param element element number of the searched DictEntry
2707 * @return Corresponding DictEntry when it exists, NULL otherwise.
2709 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2711 gdcmDictEntry *found = (gdcmDictEntry *)0;
2712 if (!RefPubDict && !RefShaDict)
2714 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2715 "we SHOULD have a default dictionary");
2719 found = RefPubDict->GetDictEntryByNumber(group, element);
2725 found = RefShaDict->GetDictEntryByNumber(group, element);
2733 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2734 * is placed at the beginning of a tag (TestGroup, TestElement),
2735 * read the length associated to the Tag.
2736 * \warning On success the internal file pointer \ref gdcmDocument::fp
2737 * is modified to point after the tag and it's length.
2738 * On failure (i.e. when the tag wasn't the expected tag
2739 * (TestGroup, TestElement) the internal file pointer
2740 * \ref gdcmDocument::fp is restored to it's original position.
2741 * @param TestGroup The expected group of the tag.
2742 * @param TestElement The expected Element of the tag.
2743 * @return On success returns the length associated to the tag. On failure
2746 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2748 guint16 ItemTagGroup;
2749 guint16 ItemTagElement;
2750 long PositionOnEntry = ftell(fp);
2751 long CurrentPosition = ftell(fp); // On debugging purposes
2753 //// Read the Item Tag group and element, and make
2754 // sure they are respectively 0xfffe and 0xe000:
2755 ItemTagGroup = ReadInt16();
2756 ItemTagElement = ReadInt16();
2757 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2759 std::ostringstream s;
2760 s << " We should have found tag (";
2761 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2762 s << " but instead we encountered tag (";
2763 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2765 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2766 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2767 dbg.Verbose(0, s.str().c_str());
2768 fseek(fp, PositionOnEntry, SEEK_SET);
2772 //// Then read the associated Item Length
2773 CurrentPosition=ftell(fp);
2775 ItemLength = ReadInt32();
2777 std::ostringstream s;
2778 s << "Basic Item Length is: "
2779 << ItemLength << std::endl;
2780 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2781 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2787 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2788 * \sa \ref gdcmDocument::ReadTagLength
2789 * \warning See warning of \ref gdcmDocument::ReadTagLength
2790 * @return On success returns the length associated to the item tag.
2791 * On failure returns 0.
2793 guint32 gdcmDocument::ReadItemTagLength(void)
2795 return ReadTagLength(0xfffe, 0xe000);
2799 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2801 * \sa \ref gdcmDocument::ReadTagLength
2802 * \warning See warning of \ref gdcmDocument::ReadTagLength
2803 * @return On success returns the length associated to the Sequence
2804 * Delimiter tag. On failure returns 0.
2806 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2808 return ReadTagLength(0xfffe, 0xe0dd);
2813 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2814 * No other way so 'skip' the Data
2817 void gdcmDocument::Parse7FE0 (void)
2819 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2823 if ( IsImplicitVRLittleEndianTransferSyntax()
2824 || IsExplicitVRLittleEndianTransferSyntax()
2825 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2826 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2829 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2831 //// Read the Basic Offset Table Item Tag length...
2832 guint32 ItemLength = ReadItemTagLength();
2834 //// ... and then read length[s] itself[themselves]. We don't use
2835 // the values read (BTW what is the purpous of those lengths ?)
2836 if (ItemLength != 0) {
2837 // BTW, what is the purpous of those length anyhow !?
2838 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2839 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2840 for (unsigned int i=0; i < ItemLength; i += 4){
2841 guint32 IndividualLength;
2842 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2843 std::ostringstream s;
2844 s << " Read one length: ";
2845 s << std::hex << IndividualLength << std::endl;
2846 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2850 if ( ! IsRLELossLessTransferSyntax() )
2854 //// We then skip (not reading them) all the fragments of images:
2855 while ( (ItemLength = ReadItemTagLength()) )
2857 SkipBytes(ItemLength);
2865 long RleSegmentLength[15], fragmentLength;
2867 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2868 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2870 // Parse fragments of the current Fragment (Frame)
2871 //------------------ scanning (not reading) fragment pixels
2872 guint32 nbRleSegments = ReadInt32();
2873 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2875 //// Reading RLE Segments Offset Table
2876 guint32 RleSegmentOffsetTable[15];
2877 for(int k=1; k<=15; k++) {
2879 RleSegmentOffsetTable[k] = ReadInt32();
2880 printf(" at : %x Offset Segment %d : %d (%x)\n",
2881 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2882 RleSegmentOffsetTable[k]);
2885 // skipping (not reading) RLE Segments
2886 if (nbRleSegments>1) {
2887 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2888 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2889 - RleSegmentOffsetTable[k];
2891 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2892 k,(unsigned)RleSegmentLength[k],
2893 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2894 SkipBytes(RleSegmentLength[k]);
2898 RleSegmentLength[nbRleSegments]= fragmentLength
2899 - RleSegmentOffsetTable[nbRleSegments];
2901 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2902 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2903 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2904 SkipBytes(RleSegmentLength[nbRleSegments]);
2910 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2911 * \warning Does NOT work with ACR-NEMA files
2912 * \todo Find a trick to solve the pb (use RET fields ?)
2914 * @return true if 'smaller'
2916 bool gdcmDocument::operator<(gdcmDocument &document)
2921 s1=this->GetEntryByNumber(0x0010,0x0010);
2922 s2=document.GetEntryByNumber(0x0010,0x0010);
2930 s1=this->GetEntryByNumber(0x0010,0x0020);
2931 s2=document.GetEntryByNumber(0x0010,0x0020);
2938 // Study Instance UID
2939 s1=this->GetEntryByNumber(0x0020,0x000d);
2940 s2=document.GetEntryByNumber(0x0020,0x000d);
2947 // Serie Instance UID
2948 s1=this->GetEntryByNumber(0x0020,0x000e);
2949 s2=document.GetEntryByNumber(0x0020,0x000e);
2962 //-----------------------------------------------------------------------------