2 //-----------------------------------------------------------------------------
4 #include "gdcmDocument.h"
5 #include "gdcmValEntry.h"
6 #include "gdcmBinEntry.h"
7 #include "gdcmSeqEntry.h"
9 #include "gdcmGlobal.h"
11 #include "gdcmDebug.h"
20 #include <netinet/in.h>
25 // Implicit VR Little Endian
26 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
27 // Explicit VR Little Endian
28 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
29 // Deflated Explicit VR Little Endian
30 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
31 // Explicit VR Big Endian
32 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
33 // JPEG Baseline (Process 1)
34 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
35 // JPEG Extended (Process 2 & 4)
36 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
37 // JPEG Extended (Process 3 & 5)
38 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
39 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
40 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
41 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
42 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
43 // JPEG Lossless, Non-Hierarchical (Process 14)
44 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
45 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
46 // [Selection Value 1])
47 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
49 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
51 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
53 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
55 #define str2num(str, typeNum) *((typeNum *)(str))
57 //-----------------------------------------------------------------------------
58 // Refer to gdcmDocument::CheckSwap()
59 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
61 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
62 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
64 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
66 //-----------------------------------------------------------------------------
67 // Constructor / Destructor
71 * @param inFilename file to be opened for parsing
72 * @param exception_on_error whether we throw an exception or not
73 * @param enable_sequences = true to allow the header
74 * to be parsed *inside* the SeQuences,
75 * when they have an actual length
76 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
77 * @param ignore_shadow to allow skipping the shadow elements,
78 * to save memory space.
79 * \warning The TRUE value for this param has to be used
80 * with a FALSE value for the 'enable_sequence' param.
81 * ('public elements' may be embedded in 'shadow Sequences')
83 gdcmDocument::gdcmDocument(const char *inFilename,
84 bool exception_on_error,
85 bool enable_sequences,
87 : gdcmElementSet(-1) {
88 enableSequences=enable_sequences;
89 ignoreShadow =ignore_shadow;
91 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
92 filename = inFilename;
95 if ( !OpenFile(exception_on_error))
98 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
102 fseek(fp,0L,SEEK_END);
103 long lgt = ftell(fp);
107 long beg = ftell(fp);
112 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
115 // --------------------------------------------------------------
116 // Special Patch to allow gdcm to read ACR-LibIDO formated images
118 // if recognition code tells us we deal with a LibIDO image
119 // we switch lineNumber and columnNumber
122 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
123 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
124 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
125 // with "little-endian strings"
127 filetype = gdcmACR_LIBIDO;
128 std::string rows = GetEntryByNumber(0x0028, 0x0010);
129 std::string columns = GetEntryByNumber(0x0028, 0x0011);
130 SetEntryByNumber(columns, 0x0028, 0x0010);
131 SetEntryByNumber(rows , 0x0028, 0x0011);
133 // ----------------- End of Special Patch ----------------
135 printLevel = 1; // 'Medium' print level by default
140 * @param exception_on_error
142 gdcmDocument::gdcmDocument(bool exception_on_error)
143 :gdcmElementSet(-1) {
144 (void)exception_on_error;
147 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
150 printLevel = 1; // 'Medium' print level by default
154 * \brief Canonical destructor.
156 gdcmDocument::~gdcmDocument (void) {
160 // Recursive clean up of sequences
161 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
168 //-----------------------------------------------------------------------------
172 * \brief Prints The Dict Entries of THE public Dicom Dictionary
175 void gdcmDocument::PrintPubDict(std::ostream & os) {
176 RefPubDict->Print(os);
180 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
183 void gdcmDocument::PrintShaDict(std::ostream & os) {
184 RefShaDict->Print(os);
187 //-----------------------------------------------------------------------------
190 * \brief Get the public dictionary used
192 gdcmDict *gdcmDocument::GetPubDict(void) {
197 * \brief Get the shadow dictionary used
199 gdcmDict *gdcmDocument::GetShaDict(void) {
204 * \brief Set the shadow dictionary used
205 * \param dict dictionary to use in shadow
207 bool gdcmDocument::SetShaDict(gdcmDict *dict){
213 * \brief Set the shadow dictionary used
214 * \param dictName name of the dictionary to use in shadow
216 bool gdcmDocument::SetShaDict(DictKey dictName){
217 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
222 * \brief This predicate, based on hopefully reasonable heuristics,
223 * decides whether or not the current gdcmDocument was properly parsed
224 * and contains the mandatory information for being considered as
225 * a well formed and usable Dicom/Acr File.
226 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
229 bool gdcmDocument::IsReadable(void) {
230 if(filetype==gdcmUnknown) {
231 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
234 if(!tagHT.empty()<=0) {
235 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
244 * \brief Internal function that checks whether the Transfer Syntax given
245 * as argument is the one present in the current document.
246 * @param SyntaxToCheck The transfert syntax we need to check against.
247 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
248 * the current document. False either when the document contains
249 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
251 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
253 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
257 // The entry might be present but not loaded (parsing and loading
258 // happen at differente stages): try loading and proceed with check...
259 LoadDocEntrySafe(Entry);
260 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
262 std::string Transfer = ValEntry->GetValue();
263 // The actual transfer (as read from disk) might be padded. We
264 // first need to remove the potential padding. We can make the
265 // weak assumption that padding was not executed with digits...
266 while ( ! isdigit(Transfer[Transfer.length()-1]) )
268 Transfer.erase(Transfer.length()-1, 1);
270 if ( Transfer == SyntaxToCheck )
277 * \brief Determines if the Transfer Syntax of the present document
278 * corresponds to a Implicit Value Representation of
280 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
281 * @return True when ImplicitVRLittleEndian found. False in all other cases.
283 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
285 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
289 * \brief Determines if the Transfer Syntax was already encountered
290 * and if it corresponds to a ExplicitVRLittleEndian one.
291 * @return True when ExplicitVRLittleEndian found. False in all other cases.
293 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
295 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
299 * \brief Determines if the Transfer Syntax was already encountered
300 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
301 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
303 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
305 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
309 * \brief Determines if the Transfer Syntax was already encountered
310 * and if it corresponds to a Explicit VR Big Endian one.
311 * @return True when big endian found. False in all other cases.
313 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
315 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
319 * \brief Determines if the Transfer Syntax was already encountered
320 * and if it corresponds to a JPEGBaseLineProcess1 one.
321 * @return True when JPEGBaseLineProcess1found. False in all other cases.
323 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
325 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
329 * \brief Determines if the Transfer Syntax was already encountered
330 * and if it corresponds to a JPEGExtendedProcess2-4 one.
331 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
333 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
335 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
339 * \brief Determines if the Transfer Syntax was already encountered
340 * and if it corresponds to a JPEGExtendeProcess3-5 one.
341 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
343 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
345 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
349 * \brief Determines if the Transfer Syntax was already encountered
350 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
351 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
354 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
356 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
360 * \brief Determines if the Transfer Syntax was already encountered
361 * and if it corresponds to a RLE Lossless one.
362 * @return True when RLE Lossless found. False in all
365 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
367 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
371 * \brief Determines if Transfer Syntax was already encountered
372 * and if it corresponds to a JPEG Lossless one.
373 * @return True when RLE Lossless found. False in all
376 bool gdcmDocument::IsJPEGLossless(void)
378 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
379 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
380 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
384 * \brief Determines if the Transfer Syntax was already encountered
385 * and if it corresponds to a JPEG2000 one
386 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
389 bool gdcmDocument::IsJPEG2000(void)
391 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
392 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
396 * \brief Predicate for dicom version 3 file.
397 * @return True when the file is a dicom version 3.
399 bool gdcmDocument::IsDicomV3(void) {
400 // Checking if Transfert Syntax exists is enough
401 // Anyway, it's to late check if the 'Preamble' was found ...
402 // And ... would it be a rich idea to check ?
403 // (some 'no Preamble' DICOM images exist !)
404 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
408 * \brief returns the File Type
409 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
410 * @return the FileType code
412 FileType gdcmDocument::GetFileType(void) {
417 * \brief opens the file
418 * @param exception_on_error
421 FILE *gdcmDocument::OpenFile(bool exception_on_error)
424 fp=fopen(filename.c_str(),"rb");
428 if(exception_on_error)
429 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
432 std::cout <<"gdcmDocument::OpenFile cannot open file: "
433 << filename.c_str() << std::endl;
434 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
443 fread(&zero, (size_t)2, (size_t)1, fp);
445 //ACR -- or DICOM with no Preamble --
446 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
450 fseek(fp, 126L, SEEK_CUR);
452 fread(dicm, (size_t)4, (size_t)1, fp);
453 if( memcmp(dicm, "DICM", 4) == 0 )
457 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
460 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
466 * \brief closes the file
467 * @return TRUE if the close was successfull
469 bool gdcmDocument::CloseFile(void) {
470 int closed = fclose(fp);
478 * \brief Writes in a file all the Header Entries (Dicom Elements)
479 * of the Chained List
480 * @param fp file pointer on an already open file
481 * @param type Type of the File to be written
482 * (ACR-NEMA, ExplicitVR, ImplicitVR)
483 * \return Always true.
485 bool gdcmDocument::Write(FILE *fp, FileType type) {
488 /// The stuff will have to be rewritten using the SeQuence based
489 /// tree-like stucture instead of the chained list .
490 /// (so we shall remove the Group*HT from the gdcmDocument)
494 /// \todo move the following lines (and a lot of others, to be written)
495 /// to a future function CheckAndCorrectHeader
499 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
500 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
501 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
503 /// a moins de se livrer a un tres complique ajout des champs manquants.
504 /// faire un CheckAndCorrectHeader (?)
506 if (type == gdcmImplicitVR)
508 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
509 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
511 /// \todo Refer to standards on page 21, chapter 6.2
512 /// "Value representation": values with a VR of UI shall be
513 /// padded with a single trailing null
514 /// Dans le cas suivant on doit pader manuellement avec un 0
516 SetEntryLengthByNumber(18, 0x0002, 0x0010);
519 if (type == gdcmExplicitVR)
521 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
522 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
524 /// \todo Refer to standards on page 21, chapter 6.2
525 /// "Value representation": values with a VR of UI shall be
526 /// padded with a single trailing null
527 /// Dans le cas suivant on doit pader manuellement avec un 0
529 SetEntryLengthByNumber(20, 0x0002, 0x0010);
533 * \todo rewrite later, if really usefull
535 * --> Warning : un-updated odd groups lengths can causes pb
536 * --> (xmedcon breaks)
537 * --> to be re- written with future org.
539 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
540 * UpdateGroupLength(false,type);
542 * UpdateGroupLength(true,ACR);
545 WriteEntries(fp,type);
550 * \brief Modifies the value of a given Header Entry (Dicom Element)
551 * when it exists. Create it with the given value when unexistant.
552 * @param Value (string) Value to be set
553 * @param Group Group number of the Entry
554 * @param Elem Element number of the Entry
555 * \return pointer to the modified/created Header Entry (NULL when creation
559 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
563 gdcmDocEntry* CurrentEntry;
564 gdcmValEntry* ValEntry;
566 CurrentEntry = GetDocEntryByNumber( Group, Elem);
569 // The entry wasn't present and we simply create the required ValEntry:
570 CurrentEntry = NewDocEntryByNumber(Group, Elem);
573 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
574 " NewDocEntryByNumber failed.");
575 return (gdcmValEntry *)0;
577 ValEntry = new gdcmValEntry(CurrentEntry);
578 if ( !AddEntry(ValEntry))
580 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
581 " failed allthough this is a creation.");
586 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
589 // We need to promote the gdcmDocEntry to a gdcmValEntry:
590 ValEntry = new gdcmValEntry(CurrentEntry);
591 if (!RemoveEntry(CurrentEntry))
593 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
594 " of previous DocEntry failed.");
595 return (gdcmValEntry *)0;
597 if ( !AddEntry(ValEntry))
599 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
600 " promoted ValEntry failed.");
601 return (gdcmValEntry *)0;
606 SetEntryByNumber(Value, Group, Elem);
612 * \brief Modifies the value of a given Header Entry (Dicom Element)
613 * when it exists. Create it with the given value when unexistant.
614 * @param voidArea (binary) value to be set
615 * @param Group Group number of the Entry
616 * @param Elem Element number of the Entry
617 * \return pointer to the modified/created Header Entry (NULL when creation
620 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
628 a = GetDocEntryByNumber( Group, Elem);
630 a =NewBinEntryByNumber(Group, Elem);
633 b = new gdcmBinEntry(a);
636 SetEntryByNumber(voidArea, lgth, Group, Elem);
637 b->SetVoidArea(voidArea);
638 return (gdcmBinEntry*)b;
644 * \brief Set a new value if the invoked element exists
645 * Seems to be useless !!!
646 * @param Value new element value
647 * @param Group group number of the Entry
648 * @param Elem element number of the Entry
651 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
653 std::string v = Value;
654 SetEntryByNumber(v, Group, Elem);
658 //-----------------------------------------------------------------------------
662 * \brief Checks if a given Dicom Element exists within the H table
663 * @param group Group number of the searched Dicom Element
664 * @param element Element number of the searched Dicom Element
665 * @return number of occurences
667 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
668 std::string key = gdcmDictEntry::TranslateToKey(group, element );
669 return (tagHT.count(key));
673 * \brief Searches within Header Entries (Dicom Elements) parsed with
674 * the public and private dictionaries
675 * for the element value of a given tag.
676 * \warning Don't use any longer : use GetPubEntryByName
677 * @param tagName name of the searched element.
678 * @return Corresponding element value when it exists,
679 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
681 std::string gdcmDocument::GetEntryByName(std::string tagName) {
682 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
683 if( dictEntry == NULL)
686 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
690 * \brief Searches within Header Entries (Dicom Elements) parsed with
691 * the public and private dictionaries
692 * for the element value representation of a given tag.
694 * Obtaining the VR (Value Representation) might be needed by caller
695 * to convert the string typed content to caller's native type
696 * (think of C++ vs Python). The VR is actually of a higher level
697 * of semantics than just the native C++ type.
698 * @param tagName name of the searched element.
699 * @return Corresponding element value representation when it exists,
700 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
702 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
703 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
704 if( dictEntry == NULL)
707 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
708 dictEntry->GetElement());
709 return elem->GetVR();
714 * \brief Searches within Header Entries (Dicom Elements) parsed with
715 * the public and private dictionaries
716 * for the element value representation of a given tag.
717 * @param group Group number of the searched tag.
718 * @param element Element number of the searched tag.
719 * @return Corresponding element value representation when it exists,
720 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
722 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
723 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
724 if ( ! tagHT.count(key))
726 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
730 * \brief Searches within Header Entries (Dicom Elements) parsed with
731 * the public and private dictionaries
732 * for the element value representation of a given tag..
734 * Obtaining the VR (Value Representation) might be needed by caller
735 * to convert the string typed content to caller's native type
736 * (think of C++ vs Python). The VR is actually of a higher level
737 * of semantics than just the native C++ type.
738 * @param group Group number of the searched tag.
739 * @param element Element number of the searched tag.
740 * @return Corresponding element value representation when it exists,
741 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
743 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
744 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
747 return elem->GetVR();
751 * \brief Searches within Header Entries (Dicom Elements) parsed with
752 * the public and private dictionaries
753 * for the value length of a given tag..
754 * @param group Group number of the searched tag.
755 * @param element Element number of the searched tag.
756 * @return Corresponding element length; -2 if not found
758 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
759 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
762 return elem->GetLength();
765 * \brief Sets the value (string) of the Header Entry (Dicom Element)
766 * @param content string value of the Dicom Element
767 * @param tagName name of the searched Dicom Element.
768 * @return true when found
770 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
771 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
772 if( dictEntry == NULL)
775 return(SetEntryByNumber(content,dictEntry->GetGroup(),
776 dictEntry->GetElement()));
780 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
781 * through it's (group, element) and modifies it's content with
783 * @param content new value (string) to substitute with
784 * @param group group number of the Dicom Element to modify
785 * @param element element number of the Dicom Element to modify
787 bool gdcmDocument::SetEntryByNumber(std::string content,
791 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
794 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
795 " ValEntry (try promotion first).");
799 // Non even content must be padded with a space (020H).
800 if((content.length())%2)
801 content = content + '\0';
803 ValEntry->SetValue(content);
805 // Integers have a special treatement for their length:
806 VRKey vr = ValEntry->GetVR();
807 if( (vr == "US") || (vr == "SS") )
808 ValEntry->SetLength(2);
809 else if( (vr == "UL") || (vr == "SL") )
810 ValEntry->SetLength(4);
812 ValEntry->SetLength(content.length());
818 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
819 * through it's (group, element) and modifies it's content with
821 * @param content new value (void *) to substitute with
822 * @param group group number of the Dicom Element to modify
823 * @param element element number of the Dicom Element to modify
825 bool gdcmDocument::SetEntryByNumber(void *content,
830 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
831 if ( ! tagHT.count(key))
834 /* Hope Binray field length is never wrong
835 if(lgth%2) // Non even length are padded with a space (020H).
838 //content = content + '\0'; // fing a trick to enlarge a binary field?
842 a = (gdcmBinEntry *)tagHT[key];
843 a->SetVoidArea(content);
844 //a->SetLength(lgth); // ???
849 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
850 * in the PubDocEntrySet of this instance
851 * through it's (group, element) and modifies it's length with
853 * \warning Use with extreme caution.
854 * @param l new length to substitute with
855 * @param group group number of the Entry to modify
856 * @param element element number of the Entry to modify
857 * @return true on success, false otherwise.
859 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
863 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
864 if ( ! tagHT.count(key))
866 if (l%2) l++; // length must be even
867 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
873 * \brief Gets (from Header) the offset of a 'non string' element value
874 * (LoadElementValues has already be executed)
875 * @param Group group number of the Entry
876 * @param Elem element number of the Entry
877 * @return File Offset of the Element Value
879 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
881 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
884 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
885 "failed to Locate gdcmDocEntry");
888 return Entry->GetOffset();
892 * \brief Gets (from Header) a 'non string' element value
893 * (LoadElementValues has already be executed)
894 * @param Group group number of the Entry
895 * @param Elem element number of the Entry
896 * @return Pointer to the 'non string' area
898 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
900 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
903 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
904 "failed to Locate gdcmDocEntry");
907 return ((gdcmBinEntry *)Entry)->GetVoidArea();
911 * \brief Loads (from disk) the element content
912 * when a string is not suitable
913 * @param Group group number of the Entry
914 * @param Elem element number of the Entry
916 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
918 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
921 size_t o =(size_t)Element->GetOffset();
922 fseek(fp, o, SEEK_SET);
923 size_t l=Element->GetLength();
924 char* a = new char[l];
928 SetEntryVoidAreaByNumber(a, Group, Elem);
929 /// \todo check the result
930 size_t l2 = fread(a, 1, l ,fp);
941 * \brief Sets a 'non string' value to a given Dicom Element
943 * @param group Group number of the searched Dicom Element
944 * @param element Element number of the searched Dicom Element
947 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
951 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
952 if ( ! tagHT.count(key))
954 // This was for multimap ?
955 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
961 * \brief Update the entries with the shadow dictionary.
962 * Only non even entries are analyzed
964 void gdcmDocument::UpdateShaEntries(void) {
965 gdcmDictEntry *entry;
968 /// \todo TODO : still any use to explore recursively the whole structure?
970 for(ListTag::iterator it=listEntries.begin();
971 it!=listEntries.end();
974 // Odd group => from public dictionary
975 if((*it)->GetGroup()%2==0)
978 // Peer group => search the corresponding dict entry
980 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
984 if((*it)->IsImplicitVR())
989 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
991 // Set the new entry and the new value
992 (*it)->SetDictEntry(entry);
993 CheckDocEntryVR(*it,vr);
995 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1000 // Remove precedent value transformation
1001 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1008 * \brief Searches within the Header Entries for a Dicom Element of
1010 * @param tagName name of the searched Dicom Element.
1011 * @return Corresponding Dicom Element when it exists, and NULL
1014 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1015 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1016 if( dictEntry == NULL)
1019 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1023 * \brief retrieves a Dicom Element (the first one) using (group, element)
1024 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1025 * if you think it's NOT UNIQUE, check the count number
1026 * and use iterators to retrieve ALL the Dicoms Elements within
1027 * a given couple (group, element)
1028 * @param group Group number of the searched Dicom Element
1029 * @param element Element number of the searched Dicom Element
1032 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1034 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1035 if ( ! tagHT.count(key))
1037 return tagHT.find(key)->second;
1041 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1042 * returns a result when the corresponding entry is of type
1044 * @return When present, the corresponding ValEntry.
1046 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1048 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1050 return (gdcmValEntry*)0;
1051 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1055 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1056 return (gdcmValEntry*)0;
1060 * \brief Loads the element while preserving the current
1061 * underlying file position indicator as opposed to
1062 * to LoadDocEntry that modifies it.
1063 * @param entry Header Entry whose value shall be loaded.
1066 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1067 long PositionOnEntry = ftell(fp);
1068 LoadDocEntry(entry);
1069 fseek(fp, PositionOnEntry, SEEK_SET);
1074 * \brief Writes in a file (according to the requested format)
1075 * the group, the element, the value representation and the length
1076 * of a single gdcmDocEntry passed as argument.
1077 * @param tag pointer on the gdcmDocEntry to be written
1078 * @param _fp already open file pointer
1079 * @param type type of the File to be written
1081 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1085 guint16 group = tag->GetGroup();
1086 VRKey vr = tag->GetVR();
1087 guint16 el = tag->GetElement();
1088 guint32 lgr = tag->GetReadLength();
1090 if ( (group == 0xfffe) && (el == 0x0000) )
1091 // Fix in order to make some MR PHILIPS images e-film readable
1092 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1093 // we just *always* ignore spurious fffe|0000 tag !
1096 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1097 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1099 if ( type == gdcmExplicitVR ) {
1101 // Special case of delimiters:
1102 if (group == 0xfffe) {
1103 // Delimiters have NO Value Representation and have NO length.
1104 // Hence we skip writing the VR and length and we pad by writing
1108 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1113 guint16 shortLgr = lgr;
1114 if (vr == "unkn") { // Unknown was 'written'
1115 // deal with Little Endian
1116 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1117 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1119 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1120 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1122 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1123 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1125 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1131 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1136 * \brief Writes in a file (according to the requested format)
1137 * the value of a single gdcmDocEntry passed as argument.
1138 * @param tag Pointer on the gdcmDocEntry to be written
1139 * @param _fp Already open file pointer
1140 * @param type type of the File to be written
1143 // \todo TODO : to be re -written recursively !
1144 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1147 guint16 group = tag->GetGroup();
1148 VRKey vr = tag->GetVR();
1149 guint32 lgr = tag->GetReadLength();
1152 // SeQuences have no value:
1154 if (group == 0xfffe)
1155 // Delimiters have no associated value:
1158 //--------------------------------
1160 // FIXME :right now, both value and voidArea belong to gdcmValue
1162 // -------------------------------
1164 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1166 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1167 voidArea = BinEntry->GetVoidArea();
1168 if (voidArea != NULL)
1169 { // there is a 'non string' LUT, overlay, etc
1170 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1175 if (vr == "US" || vr == "SS")
1177 // some 'Short integer' fields may be mulivaluated
1178 // each single value is separated from the next one by '\'
1179 // we split the string and write each value as a short int
1180 std::vector<std::string> tokens;
1181 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1182 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1183 for (unsigned int i=0; i<tokens.size();i++)
1185 guint16 val_uint16 = atoi(tokens[i].c_str());
1186 void *ptr = &val_uint16;
1187 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1192 if (vr == "UL" || vr == "SL")
1194 // Some 'Integer' fields may be multivaluated (multiple instances
1195 // of integers). But each single integer value is separated from the
1196 // next one by '\' (backslash character). Hence we split the string
1197 // along the '\' and write each value as an int:
1198 std::vector<std::string> tokens;
1199 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1200 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1201 for (unsigned int i=0; i<tokens.size();i++)
1203 guint32 val_uint32 = atoi(tokens[i].c_str());
1204 void *ptr = &val_uint32;
1205 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1210 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(),
1211 (size_t)lgr ,(size_t)1, _fp); // Elem value
1215 * \brief Writes in a file (according to the requested format)
1216 * a single gdcmDocEntry passed as argument.
1217 * \sa WriteEntryValue, WriteEntryTagVRLength.
1218 * @param tag Pointer on the gdcmDocEntry to be written
1219 * @param _fp Already open file pointer
1220 * @param type type of the File to be written
1223 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1225 guint32 length = tag->GetLength();
1227 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1229 // The value of a tag MUST (see the DICOM norm) be an odd number of
1230 // bytes. When this is not the case, pad with an additional byte:
1232 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1233 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1235 WriteEntryTagVRLength(ValEntry, _fp, type);
1236 WriteEntryValue(ValEntry, _fp, type);
1240 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1242 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
1245 // The value of a tag MUST (see the DICOM norm) be an odd number of
1246 // bytes. When this is not the case, pad with an additional byte:
1249 tag->SetValue(tag->GetValue()+"\0");
1250 tag->SetLength(tag->GetReadLength()+1);
1253 WriteEntryTagVRLength(tag, _fp, type);
1254 WriteEntryValue(tag, _fp, type);
1260 * \brief writes on disc according to the requested format
1261 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1262 * using the Chained List
1263 * \warning does NOT add the missing elements in the header :
1264 * it's up to the user doing it !
1265 * (function CheckHeaderCoherence to be written)
1266 * \warning DON'T try, right now, to write a DICOM image
1267 * from an ACR Header (meta elements will be missing!)
1268 * @param type type of the File to be written
1269 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1270 * @param _fp already open file pointer
1273 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1275 /// \todo FIXME : explore recursively the whole structure...
1276 /// \todo (?) check write failures (after *each* fwrite)
1278 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1279 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1281 gdcmDocEntry * entry = it->second;
1283 if ( type == gdcmACR ){
1284 if (entry->GetGroup() < 0x0008)
1285 // Ignore pure DICOM V3 groups
1287 if (entry->GetGroup() %2)
1288 // Ignore the "shadow" groups
1290 if (entry->GetVR() == "SQ" ) // ignore Sequences
1293 if (! WriteEntry(entry, _fp, type) ) {
1294 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1303 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1305 * @return The properly swaped 32 bits integer.
1307 guint32 gdcmDocument::SwapLong(guint32 a) {
1312 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1313 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1317 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1321 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1324 std::cout << "swapCode= " << sw << std::endl;
1325 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1332 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1334 * @return The properly unswaped 32 bits integer.
1336 guint32 gdcmDocument::UnswapLong(guint32 a) {
1337 return (SwapLong(a));
1341 * \brief Swaps the bytes so they agree with the processor order
1342 * @return The properly swaped 16 bits integer.
1344 guint16 gdcmDocument::SwapShort(guint16 a) {
1345 if ( (sw==4321) || (sw==2143) )
1346 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1351 * \brief Unswaps the bytes so they agree with the processor order
1352 * @return The properly unswaped 16 bits integer.
1354 guint16 gdcmDocument::UnswapShort(guint16 a) {
1355 return (SwapShort(a));
1358 //-----------------------------------------------------------------------------
1362 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1363 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1366 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1368 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1369 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1376 depth = set->GetDepthLevel();
1379 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1382 NewDocEntry = ReadNextDocEntry( );
1386 vr = NewDocEntry->GetVR();
1390 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1393 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1394 NewValEntry->Copy(NewDocEntry);
1395 NewValEntry->SetDepthLevel(depth);
1396 set->AddEntry(NewValEntry);
1397 LoadDocEntry(NewValEntry);
1398 if (/*!delim_mode && */NewValEntry->isItemDelimitor())
1400 if ( !delim_mode && ftell(fp)-offset >= l_max)
1407 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1409 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1410 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1411 "nor BinEntry. Probably unknown VR.");
1414 ////// BinEntry or UNKOWN VR:
1415 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1416 bn->Copy(NewDocEntry);
1421 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1422 NewDocEntry->GetElement() == 0x0010 )
1424 if (NewDocEntry->GetLength()==0xffffffff)
1425 // Broken US.3405.1.dcm
1426 Parse7FE0(); // to skip the pixels
1427 // (multipart JPEG/RLE are trouble makers)
1431 // to be sure we are at the beginning
1432 SkipToNextDocEntry(NewDocEntry);
1433 l = NewDocEntry->GetFullLength();
1439 l=NewDocEntry->GetReadLength();
1440 if (l != 0) // don't mess the delim_mode for zero-length sequence
1441 if (l == 0xffffffff)
1445 // no other way to create it ...
1446 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1447 set->GetDepthLevel());
1448 sq->Copy(NewDocEntry);
1449 sq->SetDelimitorMode(delim_mode);
1450 sq->SetDepthLevel(depth);
1453 { // Don't try to parse zero-length sequences
1454 long lgt = ParseSQ( sq,
1455 NewDocEntry->GetOffset(),
1458 // FIXME : on en fait quoi, de lgt ?
1460 if ( !delim_mode && ftell(fp)-offset >= l_max)
1471 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1472 * @return parsed length for this level
1474 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1475 long offset, long l_max, bool delim_mode)
1477 int SQItemNumber = 0;
1479 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1483 int depth = set->GetDepthLevel();
1486 NewDocEntry = ReadNextDocEntry();
1488 if (NewDocEntry->isSequenceDelimitor()) {
1489 /// \todo add the Sequence Delimitor
1490 /// \todo find the trick to put it properly !
1491 set->SetSequenceDelimitationItem(NewDocEntry);
1495 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1499 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1500 itemSQ->AddEntry(NewDocEntry);
1501 /// \todo no value, no voidArea. Think of it while printing !
1502 l= NewDocEntry->GetReadLength();
1504 if (l == 0xffffffff)
1509 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1511 set->AddEntry(itemSQ,SQItemNumber);
1513 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1517 lgth = ftell(fp) - offset;
1522 * \brief Loads the element content if its length doesn't exceed
1523 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1524 * @param Entry Header Entry (Dicom Element) to be dealt with
1526 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1529 guint16 group = Entry->GetGroup();
1530 std::string vr= Entry->GetVR();
1531 guint32 length = Entry->GetLength();
1533 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1535 // A SeQuence "contains" a set of Elements.
1536 // (fffe e000) tells us an Element is beginning
1537 // (fffe e00d) tells us an Element just ended
1538 // (fffe e0dd) tells us the current SeQuence just ended
1539 if( group == 0xfffe ) {
1540 // NO more value field for SQ !
1541 //Entry->SetValue("gdcm::Skipped");
1542 // appel recursif de Load Value
1543 // (meme pb que pour le parsing)
1547 // When the length is zero things are easy:
1548 if ( length == 0 ) {
1549 ((gdcmValEntry *)Entry)->SetValue("");
1553 // The elements whose length is bigger than the specified upper bound
1554 // are not loaded. Instead we leave a short notice of the offset of
1555 // the element content and it's length.
1556 if (length > MaxSizeLoadEntry) {
1557 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1559 std::ostringstream s;
1560 s << "gdcm::NotLoaded.";
1561 s << " Address:" << (long)Entry->GetOffset();
1562 s << " Length:" << Entry->GetLength();
1563 s << " x(" << std::hex << Entry->GetLength() << ")";
1564 ValEntryPtr->SetValue(s.str());
1566 // to be sure we are at the end of the value ...
1567 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1572 // Any compacter code suggested (?)
1573 if ( IsDocEntryAnInteger(Entry) ) {
1575 std::ostringstream s;
1577 // When short integer(s) are expected, read and convert the following
1578 // n *two characters properly i.e. as short integers as opposed to strings.
1579 // Elements with Value Multiplicity > 1
1580 // contain a set of integers (not a single one)
1581 if (vr == "US" || vr == "SS") {
1583 NewInt = ReadInt16();
1586 for (int i=1; i < nbInt; i++) {
1588 NewInt = ReadInt16();
1593 // When integer(s) are expected, read and convert the following
1594 // n * four characters properly i.e. as integers as opposed to strings.
1595 // Elements with Value Multiplicity > 1
1596 // contain a set of integers (not a single one)
1597 else if (vr == "UL" || vr == "SL") {
1599 NewInt = ReadInt32();
1602 for (int i=1; i < nbInt; i++) {
1604 NewInt = ReadInt32();
1609 #ifdef GDCM_NO_ANSI_STRING_STREAM
1610 s << std::ends; // to avoid oddities on Solaris
1611 #endif //GDCM_NO_ANSI_STRING_STREAM
1613 ((gdcmValEntry *)Entry)->SetValue(s.str());
1617 // We need an additional byte for storing \0 that is not on disk
1618 std::string NewValue(length,0);
1619 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1620 if ( item_read != 1 ) {
1621 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1622 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1626 if( (vr == "UI") ) // Because of correspondance with the VR dic
1627 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1629 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1634 * \brief Find the value Length of the passed Header Entry
1635 * @param Entry Header Entry whose length of the value shall be loaded.
1637 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1638 guint16 element = Entry->GetElement();
1639 //guint16 group = Entry->GetGroup(); //FIXME
1640 std::string vr = Entry->GetVR();
1644 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1646 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1648 // The following reserved two bytes (see PS 3.5-2001, section
1649 // 7.1.2 Data element structure with explicit vr p27) must be
1650 // skipped before proceeding on reading the length on 4 bytes.
1651 fseek(fp, 2L, SEEK_CUR);
1652 guint32 length32 = ReadInt32();
1654 if ( (vr == "OB") && (length32 == 0xffffffff) )
1656 Entry->SetLength(FindDocEntryLengthOB());
1659 FixDocEntryFoundLength(Entry, length32);
1663 // Length is encoded on 2 bytes.
1664 length16 = ReadInt16();
1666 // We can tell the current file is encoded in big endian (like
1667 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1668 // and it's value is the one of the encoding of a big endian file.
1669 // In order to deal with such big endian encoded files, we have
1670 // (at least) two strategies:
1671 // * when we load the "Transfer Syntax" tag with value of big endian
1672 // encoding, we raise the proper flags. Then we wait for the end
1673 // of the META group (0x0002) among which is "Transfer Syntax",
1674 // before switching the swap code to big endian. We have to postpone
1675 // the switching of the swap code since the META group is fully encoded
1676 // in little endian, and big endian coding only starts at the next
1677 // group. The corresponding code can be hard to analyse and adds
1678 // many additional unnecessary tests for regular tags.
1679 // * the second strategy consists in waiting for trouble, that shall
1680 // appear when we find the first group with big endian encoding. This
1681 // is easy to detect since the length of a "Group Length" tag (the
1682 // ones with zero as element number) has to be of 4 (0x0004). When we
1683 // encounter 1024 (0x0400) chances are the encoding changed and we
1684 // found a group with big endian encoding.
1685 // We shall use this second strategy. In order to make sure that we
1686 // can interpret the presence of an apparently big endian encoded
1687 // length of a "Group Length" without committing a big mistake, we
1688 // add an additional check: we look in the already parsed elements
1689 // for the presence of a "Transfer Syntax" whose value has to be "big
1690 // endian encoding". When this is the case, chances are we have got our
1691 // hands on a big endian encoded file: we switch the swap code to
1692 // big endian and proceed...
1693 if ( (element == 0x0000) && (length16 == 0x0400) )
1695 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1697 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1702 SwitchSwapToBigEndian();
1703 // Restore the unproperly loaded values i.e. the group, the element
1704 // and the dictionary entry depending on them.
1705 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1706 guint16 CorrectElem = SwapShort(Entry->GetElement());
1707 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1711 // This correct tag is not in the dictionary. Create a new one.
1712 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1714 // FIXME this can create a memory leaks on the old entry that be
1715 // left unreferenced.
1716 Entry->SetDictEntry(NewTag);
1719 // Heuristic: well some files are really ill-formed.
1720 if ( length16 == 0xffff)
1723 //dbg.Verbose(0, "gdcmDocument::FindLength",
1724 // "Erroneous element length fixed.");
1725 // Actually, length= 0xffff means that we deal with
1726 // Unknown Sequence Length
1728 FixDocEntryFoundLength(Entry, (guint32)length16);
1733 // Either implicit VR or a non DICOM conformal (see note below) explicit
1734 // VR that ommited the VR of (at least) this element. Farts happen.
1735 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1736 // on Data elements "Implicit and Explicit VR Data Elements shall
1737 // not coexist in a Data Set and Data Sets nested within it".]
1738 // Length is on 4 bytes.
1740 FixDocEntryFoundLength(Entry, ReadInt32());
1746 * \brief Find the Value Representation of the current Dicom Element.
1749 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1751 if (filetype != gdcmExplicitVR)
1756 long PositionOnEntry = ftell(fp);
1757 // Warning: we believe this is explicit VR (Value Representation) because
1758 // we used a heuristic that found "UL" in the first tag. Alas this
1759 // doesn't guarantee that all the tags will be in explicit VR. In some
1760 // cases (see e-film filtered files) one finds implicit VR tags mixed
1761 // within an explicit VR file. Hence we make sure the present tag
1762 // is in explicit VR and try to fix things if it happens not to be
1765 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1767 if(!CheckDocEntryVR(Entry,VR))
1769 fseek(fp, PositionOnEntry, SEEK_SET);
1770 // When this element is known in the dictionary we shall use, e.g. for
1771 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1772 // dictionary entry. Still we have to flag the element as implicit since
1773 // we know now our assumption on expliciteness is not furfilled.
1775 if ( Entry->IsVRUnknown() )
1776 Entry->SetVR("Implicit");
1777 Entry->SetImplicitVR();
1782 * \brief Check the correspondance between the VR of the header entry
1783 * and the taken VR. If they are different, the header entry is
1784 * updated with the new VR.
1785 * @param Entry Header Entry to check
1786 * @param vr Dicom Value Representation
1787 * @return false if the VR is incorrect of if the VR isn't referenced
1788 * otherwise, it returns true
1790 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1792 char msg[100]; // for sprintf
1793 bool RealExplicit = true;
1795 // Assume we are reading a falsely explicit VR file i.e. we reached
1796 // a tag where we expect reading a VR but are in fact we read the
1797 // first to bytes of the length. Then we will interogate (through find)
1798 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1799 // both GCC and VC++ implementations of the STL map. Hence when the
1800 // expected VR read happens to be non-ascii characters we consider
1801 // we hit falsely explicit VR tag.
1803 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1804 RealExplicit = false;
1806 // CLEANME searching the dicom_vr at each occurence is expensive.
1807 // PostPone this test in an optional integrity check at the end
1808 // of parsing or only in debug mode.
1809 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1810 RealExplicit= false;
1812 if ( !RealExplicit )
1814 // We thought this was explicit VR, but we end up with an
1815 // implicit VR tag. Let's backtrack.
1816 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1817 Entry->GetGroup(),Entry->GetElement());
1818 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1819 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1820 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1821 Entry->GetGroup(),Entry->GetElement(),
1822 "UL","FIXME","Group Length");
1823 Entry->SetDictEntry(NewEntry);
1828 if ( Entry->IsVRUnknown() )
1830 // When not a dictionary entry, we can safely overwrite the VR.
1831 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1837 else if ( Entry->GetVR() != vr )
1839 // The VR present in the file and the dictionary disagree. We assume
1840 // the file writer knew best and use the VR of the file. Since it would
1841 // be unwise to overwrite the VR of a dictionary (since it would
1842 // compromise it's next user), we need to clone the actual DictEntry
1843 // and change the VR for the read one.
1844 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1845 Entry->GetGroup(),Entry->GetElement(),
1846 vr,"FIXME",Entry->GetName());
1847 Entry->SetDictEntry(NewEntry);
1853 * \brief Get the transformed value of the header entry. The VR value
1854 * is used to define the transformation to operate on the value
1855 * \warning NOT end user intended method !
1857 * @return Transformed entry value
1859 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1861 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1863 std::string val=((gdcmValEntry *)Entry)->GetValue();
1864 std::string vr=Entry->GetVR();
1865 guint32 length = Entry->GetLength();
1866 std::ostringstream s;
1869 // When short integer(s) are expected, read and convert the following
1870 // n * 2 bytes properly i.e. as a multivaluated strings
1871 // (each single value is separated fromthe next one by '\'
1872 // as usual for standard multivaluated filels
1873 // Elements with Value Multiplicity > 1
1874 // contain a set of short integers (not a single one)
1876 if (vr == "US" || vr == "SS")
1881 for (int i=0; i < nbInt; i++)
1885 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1886 NewInt16 = SwapShort(NewInt16);
1891 // When integer(s) are expected, read and convert the following
1892 // n * 4 bytes properly i.e. as a multivaluated strings
1893 // (each single value is separated fromthe next one by '\'
1894 // as usual for standard multivaluated filels
1895 // Elements with Value Multiplicity > 1
1896 // contain a set of integers (not a single one)
1897 else if (vr == "UL" || vr == "SL")
1902 for (int i=0; i < nbInt; i++)
1906 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1907 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1908 NewInt32=SwapLong(NewInt32);
1912 #ifdef GDCM_NO_ANSI_STRING_STREAM
1913 s << std::ends; // to avoid oddities on Solaris
1914 #endif //GDCM_NO_ANSI_STRING_STREAM
1918 return(((gdcmValEntry *)Entry)->GetValue());
1922 * \brief Get the reverse transformed value of the header entry. The VR
1923 * value is used to define the reverse transformation to operate on
1925 * \warning NOT end user intended method !
1927 * @return Reverse transformed entry value
1929 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1931 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1933 std::string vr=Entry->GetVR();
1934 std::ostringstream s;
1935 std::vector<std::string> tokens;
1937 if (vr == "US" || vr == "SS")
1941 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1942 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1943 for (unsigned int i=0; i<tokens.size();i++)
1945 NewInt16 = atoi(tokens[i].c_str());
1946 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1950 if (vr == "UL" || vr == "SL")
1954 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1955 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1956 for (unsigned int i=0; i<tokens.size();i++)
1958 NewInt32 = atoi(tokens[i].c_str());
1959 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1960 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1965 #ifdef GDCM_NO_ANSI_STRING_STREAM
1966 s << std::ends; // to avoid oddities on Solaris
1967 #endif //GDCM_NO_ANSI_STRING_STREAM
1971 return(((gdcmValEntry *)Entry)->GetValue());
1975 * \brief Skip a given Header Entry
1976 * \warning NOT end user intended method !
1979 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1981 SkipBytes(entry->GetLength());
1985 * \brief Skips to the begining of the next Header Entry
1986 * \warning NOT end user intended method !
1989 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1991 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1992 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1996 * \brief Loads the value for a a given VLEntry
1997 * \warning NOT end user intended method !
2000 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
2002 //SkipBytes(entry->GetLength());
2003 LoadDocEntry(entry);
2006 * \brief When the length of an element value is obviously wrong (because
2007 * the parser went Jabberwocky) one can hope improving things by
2008 * applying some heuristics.
2010 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
2011 guint32 FoundLength)
2013 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
2014 if ( FoundLength == 0xffffffff) {
2018 guint16 gr =Entry->GetGroup();
2019 guint16 el =Entry->GetElement();
2021 if (FoundLength%2) {
2022 std::ostringstream s;
2023 s << "Warning : Tag with uneven length "
2025 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2026 dbg.Verbose(0, s.str().c_str());
2029 //////// Fix for some naughty General Electric images.
2030 // Allthough not recent many such GE corrupted images are still present
2031 // on Creatis hard disks. Hence this fix shall remain when such images
2032 // are no longer in user (we are talking a few years, here)...
2033 // Note: XMedCom probably uses such a trick since it is able to read
2034 // those pesky GE images ...
2035 if (FoundLength == 13) { // Only happens for this length !
2036 if ( (Entry->GetGroup() != 0x0008)
2037 || ( (Entry->GetElement() != 0x0070)
2038 && (Entry->GetElement() != 0x0080) ) )
2041 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2045 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2046 // Occurence of such images is quite low (unless one leaves close to a
2047 // 'Leonardo' source. Hence, one might consider commenting out the
2048 // following fix on efficiency reasons.
2050 if ( (Entry->GetGroup() == 0x0009)
2051 && ( (Entry->GetElement() == 0x1113)
2052 || (Entry->GetElement() == 0x1114) ) )
2055 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2058 //////// Deal with sequences, but only on users request:
2060 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2062 FoundLength = 0; // ReadLength is unchanged
2065 //////// We encountered a 'delimiter' element i.e. a tag of the form
2066 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2067 // taken into account.
2069 if(Entry->GetGroup() == 0xfffe)
2071 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2072 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2073 // causes extra troubles...
2074 if( Entry->GetElement() != 0x0000 )
2080 Entry->SetUsableLength(FoundLength);
2084 * \brief Apply some heuristics to predict whether the considered
2085 * element value contains/represents an integer or not.
2086 * @param Entry The element value on which to apply the predicate.
2087 * @return The result of the heuristical predicate.
2089 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2090 guint16 element = Entry->GetElement();
2091 guint16 group = Entry->GetGroup();
2092 std::string vr = Entry->GetVR();
2093 guint32 length = Entry->GetLength();
2095 // When we have some semantics on the element we just read, and if we
2096 // a priori know we are dealing with an integer, then we shall be
2097 // able to swap it's element value properly.
2098 if ( element == 0 ) // This is the group length of the group
2104 // Allthough this should never happen, still some images have a
2105 // corrupted group length [e.g. have a glance at offset x(8336) of
2106 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2107 // Since for dicom compliant and well behaved headers, the present
2108 // test is useless (and might even look a bit paranoid), when we
2109 // encounter such an ill-formed image, we simply display a warning
2110 // message and proceed on parsing (while crossing fingers).
2111 std::ostringstream s;
2112 int filePosition = ftell(fp);
2113 s << "Erroneous Group Length element length on : (" \
2114 << std::hex << group << " , " << element
2115 << ") -before- position x(" << filePosition << ")"
2116 << "lgt : " << length;
2117 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2121 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2128 * \brief Find the Length till the next sequence delimiter
2129 * \warning NOT end user intended method !
2133 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2134 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2137 long PositionOnEntry = ftell(fp);
2138 bool FoundSequenceDelimiter = false;
2139 guint32 TotalLength = 0;
2142 while ( ! FoundSequenceDelimiter)
2148 TotalLength += 4; // We even have to decount the group and element
2150 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2152 char msg[100]; // for sprintf. Sorry
2153 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2154 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2158 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2159 FoundSequenceDelimiter = true;
2160 else if ( n != 0xe000 )
2162 char msg[100]; // for sprintf. Sorry
2163 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2165 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2169 ItemLength = ReadInt32();
2170 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2171 // the ItemLength with ReadInt32
2172 SkipBytes(ItemLength);
2174 fseek(fp, PositionOnEntry, SEEK_SET);
2179 * \brief Reads a supposed to be 16 Bits integer
2180 * (swaps it depending on processor endianity)
2181 * @return read value
2183 guint16 gdcmDocument::ReadInt16(void) {
2186 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2187 if ( item_read != 1 ) {
2189 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2199 * \brief Reads a supposed to be 32 Bits integer
2200 * (swaps it depending on processor endianity)
2201 * @return read value
2203 guint32 gdcmDocument::ReadInt32(void) {
2206 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2207 if ( item_read != 1 ) {
2209 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2219 * \brief skips bytes inside the source file
2220 * \warning NOT end user intended method !
2223 void gdcmDocument::SkipBytes(guint32 NBytes) {
2224 //FIXME don't dump the returned value
2225 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2229 * \brief Loads all the needed Dictionaries
2230 * \warning NOT end user intended method !
2232 void gdcmDocument::Initialise(void)
2234 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2235 RefShaDict = (gdcmDict*)0;
2239 * \brief Discover what the swap code is (among little endian, big endian,
2240 * bad little endian, bad big endian).
2242 * @return false when we are absolutely sure
2243 * it's neither ACR-NEMA nor DICOM
2244 * true when we hope ours assuptions are OK
2246 bool gdcmDocument::CheckSwap() {
2248 // The only guaranted way of finding the swap code is to find a
2249 // group tag since we know it's length has to be of four bytes i.e.
2250 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2251 // occurs when we can't find such group...
2253 guint32 x=4; // x : for ntohs
2254 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2260 char deb[HEADER_LENGTH_TO_READ];
2262 // First, compare HostByteOrder and NetworkByteOrder in order to
2263 // determine if we shall need to swap bytes (i.e. the Endian type).
2269 // The easiest case is the one of a DICOM header, since it possesses a
2270 // file preamble where it suffice to look for the string "DICM".
2271 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2274 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2275 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2277 // Next, determine the value representation (VR). Let's skip to the
2278 // first element (0002, 0000) and check there if we find "UL"
2279 // - or "OB" if the 1st one is (0002,0001) -,
2280 // in which case we (almost) know it is explicit VR.
2281 // WARNING: if it happens to be implicit VR then what we will read
2282 // is the length of the group. If this ascii representation of this
2283 // length happens to be "UL" then we shall believe it is explicit VR.
2284 // FIXME: in order to fix the above warning, we could read the next
2285 // element value (or a couple of elements values) in order to make
2286 // sure we are not commiting a big mistake.
2287 // We need to skip :
2288 // * the 128 bytes of File Preamble (often padded with zeroes),
2289 // * the 4 bytes of "DICM" string,
2290 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2291 // i.e. a total of 136 bytes.
2295 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2296 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2297 // *Implicit* VR. -and it is !-
2299 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2300 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2301 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2302 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2303 // when Write DCM *adds*
2305 // Use gdcmDocument::dicom_vr to test all the possibilities
2306 // instead of just checking for UL, OB and UI !? group 0000
2308 filetype = gdcmExplicitVR;
2309 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2310 "explicit Value Representation");
2314 filetype = gdcmImplicitVR;
2315 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2316 "not an explicit Value Representation");
2322 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2323 "HostByteOrder != NetworkByteOrder");
2328 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2329 "HostByteOrder = NetworkByteOrder");
2332 // Position the file position indicator at first tag (i.e.
2333 // after the file preamble and the "DICM" string).
2335 fseek (fp, 132L, SEEK_SET);
2339 // Alas, this is not a DicomV3 file and whatever happens there is no file
2340 // preamble. We can reset the file position indicator to where the data
2341 // is (i.e. the beginning of the file).
2342 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2345 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2346 // By clean we mean that the length of the first tag is written down.
2347 // If this is the case and since the length of the first group HAS to be
2348 // four (bytes), then determining the proper swap code is straightforward.
2351 // We assume the array of char we are considering contains the binary
2352 // representation of a 32 bits integer. Hence the following dirty
2354 s32 = *((guint32 *)(entCur));
2375 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2376 // It is time for despaired wild guesses.
2377 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2378 // i.e. the 'group length' element is not present :
2380 // check the supposed to be 'group number'
2381 // 0x0002 or 0x0004 or 0x0008
2382 // to determine ' sw' value .
2383 // Only 0 or 4321 will be possible
2384 // (no oportunity to check for the formerly well known
2385 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2386 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2387 // the file IS NOT ACR-NEMA nor DICOM V3
2388 // Find a trick to tell it the caller...
2390 s16 = *((guint16 *)(deb));
2406 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2407 "ACR/NEMA unfound swap info (Really hopeless !)");
2408 filetype = gdcmUnknown;
2412 // Then the only info we have is the net2host one.
2422 * \brief Restore the unproperly loaded values i.e. the group, the element
2423 * and the dictionary entry depending on them.
2425 void gdcmDocument::SwitchSwapToBigEndian(void)
2427 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2428 "Switching to BigEndian mode.");
2449 * \brief during parsing, Header Elements too long are not loaded in memory
2452 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2456 if ((guint32)NewSize >= (guint32)0xffffffff)
2458 MaxSizeLoadEntry = 0xffffffff;
2461 MaxSizeLoadEntry = NewSize;
2466 * \brief Header Elements too long will not be printed
2467 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2470 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2474 if ((guint32)NewSize >= (guint32)0xffffffff)
2476 MaxSizePrintEntry = 0xffffffff;
2479 MaxSizePrintEntry = NewSize;
2485 * \brief Read the next tag but WITHOUT loading it's value
2486 * (read the 'Group Number', the 'Element Number',
2487 * gets the Dict Entry
2488 * gets the VR, gets the length, gets the offset value)
2489 * @return On succes the newly created DocEntry, NULL on failure.
2491 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2493 gdcmDocEntry *NewEntry;
2498 // We reached the EOF (or an error occured) therefore
2499 // header parsing has to be considered as finished.
2500 return (gdcmDocEntry *)0;
2502 NewEntry = NewDocEntryByNumber(g, n);
2503 FindDocEntryVR(NewEntry);
2504 FindDocEntryLength(NewEntry);
2511 NewEntry->SetOffset(ftell(fp));
2516 * \brief Build a new Element Value from all the low level arguments.
2517 * Check for existence of dictionary entry, and build
2518 * a default one when absent.
2519 * @param Name Name of the underlying DictEntry
2521 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2523 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2525 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2527 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2530 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2531 "failed to allocate gdcmDocEntry");
2532 return (gdcmDocEntry *)0;
2538 * \brief Request a new virtual dict entry to the dict set
2539 * @param group group number of the underlying DictEntry
2540 * @param element element number of the underlying DictEntry
2541 * @param vr VR of the underlying DictEntry
2542 * @param fourth owner group
2543 * @param name english name
2545 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2550 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2554 * \brief Build a new Element Value from all the low level arguments.
2555 * Check for existence of dictionary entry, and build
2556 * a default one when absent.
2557 * @param Group group number of the underlying DictEntry
2558 * @param Elem element number of the underlying DictEntry
2560 gdcmDocEntry* gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2562 // Find out if the tag we encountered is in the dictionaries:
2563 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2565 DictEntry = NewVirtualDictEntry(Group, Elem);
2567 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2570 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2571 "failed to allocate gdcmDocEntry");
2572 return (gdcmDocEntry*)0;
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 gdcmValEntry *gdcmDocument::NewValEntryByNumber(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 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2595 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2596 "failed to allocate gdcmValEntry");
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 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(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 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2620 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2621 "failed to allocate gdcmBinEntry");
2628 * \brief Generate a free TagKey i.e. a TagKey that is not present
2629 * in the TagHt dictionary.
2630 * @param group The generated tag must belong to this group.
2631 * @return The element of tag with given group which is fee.
2633 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2635 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2637 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2638 if (tagHT.count(key) == 0)
2646 * \brief Searches both the public and the shadow dictionary (when they
2647 * exist) for the presence of the DictEntry with given name.
2648 * The public dictionary has precedence on the shadow one.
2649 * @param Name name of the searched DictEntry
2650 * @return Corresponding DictEntry when it exists, NULL otherwise.
2652 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2654 gdcmDictEntry *found = (gdcmDictEntry *)0;
2655 if (!RefPubDict && !RefShaDict)
2657 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2658 "we SHOULD have a default dictionary");
2662 found = RefPubDict->GetDictEntryByName(Name);
2668 found = RefShaDict->GetDictEntryByName(Name);
2676 * \brief Searches both the public and the shadow dictionary (when they
2677 * exist) for the presence of the DictEntry with given
2678 * group and element. The public dictionary has precedence on the
2680 * @param group group number of the searched DictEntry
2681 * @param element element number of the searched DictEntry
2682 * @return Corresponding DictEntry when it exists, NULL otherwise.
2684 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2686 gdcmDictEntry *found = (gdcmDictEntry *)0;
2687 if (!RefPubDict && !RefShaDict)
2689 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2690 "we SHOULD have a default dictionary");
2694 found = RefPubDict->GetDictEntryByNumber(group, element);
2700 found = RefShaDict->GetDictEntryByNumber(group, element);
2708 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2709 * is placed at the beginning of a tag (TestGroup, TestElement),
2710 * read the length associated to the Tag.
2711 * \warning On success the internal file pointer \ref gdcmDocument::fp
2712 * is modified to point after the tag and it's length.
2713 * On failure (i.e. when the tag wasn't the expected tag
2714 * (TestGroup, TestElement) the internal file pointer
2715 * \ref gdcmDocument::fp is restored to it's original position.
2716 * @param TestGroup The expected group of the tag.
2717 * @param TestElement The expected Element of the tag.
2718 * @return On success returns the length associated to the tag. On failure
2721 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2723 guint16 ItemTagGroup;
2724 guint16 ItemTagElement;
2725 long PositionOnEntry = ftell(fp);
2726 long CurrentPosition = ftell(fp); // On debugging purposes
2728 //// Read the Item Tag group and element, and make
2729 // sure they are respectively 0xfffe and 0xe000:
2730 ItemTagGroup = ReadInt16();
2731 ItemTagElement = ReadInt16();
2732 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2734 std::ostringstream s;
2735 s << " We should have found tag (";
2736 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2737 s << " but instead we encountered tag (";
2738 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2740 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2741 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2742 dbg.Verbose(0, s.str().c_str());
2743 fseek(fp, PositionOnEntry, SEEK_SET);
2747 //// Then read the associated Item Length
2748 CurrentPosition=ftell(fp);
2750 ItemLength = ReadInt32();
2752 std::ostringstream s;
2753 s << "Basic Item Length is: "
2754 << ItemLength << std::endl;
2755 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2756 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2762 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2763 * \sa \ref gdcmDocument::ReadTagLength
2764 * \warning See warning of \ref gdcmDocument::ReadTagLength
2765 * @return On success returns the length associated to the item tag.
2766 * On failure returns 0.
2768 guint32 gdcmDocument::ReadItemTagLength(void)
2770 return ReadTagLength(0xfffe, 0xe000);
2774 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2776 * \sa \ref gdcmDocument::ReadTagLength
2777 * \warning See warning of \ref gdcmDocument::ReadTagLength
2778 * @return On success returns the length associated to the Sequence
2779 * Delimiter tag. On failure returns 0.
2781 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2783 return ReadTagLength(0xfffe, 0xe0dd);
2788 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2789 * No other way so 'skip' the Data
2792 void gdcmDocument::Parse7FE0 (void)
2794 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2798 if ( IsImplicitVRLittleEndianTransferSyntax()
2799 || IsExplicitVRLittleEndianTransferSyntax()
2800 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2801 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2804 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2806 //// Read the Basic Offset Table Item Tag length...
2807 guint32 ItemLength = ReadItemTagLength();
2809 //// ... and then read length[s] itself[themselves]. We don't use
2810 // the values read (BTW what is the purpous of those lengths ?)
2811 if (ItemLength != 0) {
2812 // BTW, what is the purpous of those length anyhow !?
2813 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2814 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2815 for (int i=0; i < ItemLength; i += 4){
2816 guint32 IndividualLength;
2817 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2818 std::ostringstream s;
2819 s << " Read one length: ";
2820 s << std::hex << IndividualLength << std::endl;
2821 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2825 if ( ! IsRLELossLessTransferSyntax() )
2829 //// We then skip (not reading them) all the fragments of images:
2830 while ( ItemLength = ReadItemTagLength() )
2832 SkipBytes(ItemLength);
2840 long RleSegmentLength[15], fragmentLength;
2842 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2843 while ( fragmentLength = ReadSequenceDelimiterTagLength() )
2845 // Parse fragments of the current Fragment (Frame)
2846 //------------------ scanning (not reading) fragment pixels
2847 guint32 nbRleSegments = ReadInt32();
2848 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2850 //// Reading RLE Segments Offset Table
2851 guint32 RleSegmentOffsetTable[15];
2852 for(int k=1; k<=15; k++) {
2854 RleSegmentOffsetTable[k] = ReadInt32();
2855 printf(" at : %x Offset Segment %d : %d (%x)\n",
2856 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2857 RleSegmentOffsetTable[k]);
2860 // skipping (not reading) RLE Segments
2861 if (nbRleSegments>1) {
2862 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2863 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2864 - RleSegmentOffsetTable[k];
2866 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2867 k,(unsigned)RleSegmentLength[k],
2868 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2869 SkipBytes(RleSegmentLength[k]);
2873 RleSegmentLength[nbRleSegments]= fragmentLength
2874 - RleSegmentOffsetTable[nbRleSegments];
2876 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2877 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2878 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2879 SkipBytes(RleSegmentLength[nbRleSegments]);
2886 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2887 * \warning Does NOT work with ACR-NEMA files
2888 * \todo Find a trick to solve the pb (use RET fields ?)
2890 * @return true if 'smaller'
2892 bool gdcmDocument::operator<(gdcmDocument &document){
2896 s1=this->GetEntryByNumber(0x0010,0x0010);
2897 s2=document.GetEntryByNumber(0x0010,0x0010);
2905 s1=this->GetEntryByNumber(0x0010,0x0020);
2906 s2=document.GetEntryByNumber(0x0010,0x0020);
2913 // Study Instance UID
2914 s1=this->GetEntryByNumber(0x0020,0x000d);
2915 s2=document.GetEntryByNumber(0x0020,0x000d);
2922 // Serie Instance UID
2923 s1=this->GetEntryByNumber(0x0020,0x000e);
2924 s2=document.GetEntryByNumber(0x0020,0x000e);
2936 //-----------------------------------------------------------------------------