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 )
163 gdcmDocEntry * entry = it->second;
164 if ( gdcmSeqEntry* SeqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
167 RemoveEntry(SeqEntry);
177 //-----------------------------------------------------------------------------
181 * \brief Prints The Dict Entries of THE public Dicom Dictionary
184 void gdcmDocument::PrintPubDict(std::ostream & os) {
185 RefPubDict->Print(os);
189 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
192 void gdcmDocument::PrintShaDict(std::ostream & os) {
193 RefShaDict->Print(os);
196 //-----------------------------------------------------------------------------
199 * \brief Get the public dictionary used
201 gdcmDict *gdcmDocument::GetPubDict(void) {
206 * \brief Get the shadow dictionary used
208 gdcmDict *gdcmDocument::GetShaDict(void) {
213 * \brief Set the shadow dictionary used
214 * \param dict dictionary to use in shadow
216 bool gdcmDocument::SetShaDict(gdcmDict *dict){
222 * \brief Set the shadow dictionary used
223 * \param dictName name of the dictionary to use in shadow
225 bool gdcmDocument::SetShaDict(DictKey dictName){
226 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
231 * \brief This predicate, based on hopefully reasonable heuristics,
232 * decides whether or not the current gdcmDocument was properly parsed
233 * and contains the mandatory information for being considered as
234 * a well formed and usable Dicom/Acr File.
235 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
238 bool gdcmDocument::IsReadable(void) {
239 if(filetype==gdcmUnknown) {
240 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
243 if(!tagHT.empty()<=0) {
244 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
253 * \brief Internal function that checks whether the Transfer Syntax given
254 * as argument is the one present in the current document.
255 * @param SyntaxToCheck The transfert syntax we need to check against.
256 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
257 * the current document. False either when the document contains
258 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
260 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
262 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
266 // The entry might be present but not loaded (parsing and loading
267 // happen at differente stages): try loading and proceed with check...
268 LoadDocEntrySafe(Entry);
269 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
271 std::string Transfer = ValEntry->GetValue();
272 // The actual transfer (as read from disk) might be padded. We
273 // first need to remove the potential padding. We can make the
274 // weak assumption that padding was not executed with digits...
275 while ( ! isdigit(Transfer[Transfer.length()-1]) )
277 Transfer.erase(Transfer.length()-1, 1);
279 if ( Transfer == SyntaxToCheck )
286 * \brief Determines if the Transfer Syntax of the present document
287 * corresponds to a Implicit Value Representation of
289 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
290 * @return True when ImplicitVRLittleEndian found. False in all other cases.
292 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
294 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
298 * \brief Determines if the Transfer Syntax was already encountered
299 * and if it corresponds to a ExplicitVRLittleEndian one.
300 * @return True when ExplicitVRLittleEndian found. False in all other cases.
302 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
304 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
308 * \brief Determines if the Transfer Syntax was already encountered
309 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
310 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
312 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
314 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
318 * \brief Determines if the Transfer Syntax was already encountered
319 * and if it corresponds to a Explicit VR Big Endian one.
320 * @return True when big endian found. False in all other cases.
322 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
324 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
328 * \brief Determines if the Transfer Syntax was already encountered
329 * and if it corresponds to a JPEGBaseLineProcess1 one.
330 * @return True when JPEGBaseLineProcess1found. False in all other cases.
332 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
334 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
338 * \brief Determines if the Transfer Syntax was already encountered
339 * and if it corresponds to a JPEGExtendedProcess2-4 one.
340 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
342 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
344 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
348 * \brief Determines if the Transfer Syntax was already encountered
349 * and if it corresponds to a JPEGExtendeProcess3-5 one.
350 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
352 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
354 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
358 * \brief Determines if the Transfer Syntax was already encountered
359 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
360 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
363 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
365 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
369 * \brief Determines if the Transfer Syntax was already encountered
370 * and if it corresponds to a RLE Lossless one.
371 * @return True when RLE Lossless found. False in all
374 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
376 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
380 * \brief Determines if Transfer Syntax was already encountered
381 * and if it corresponds to a JPEG Lossless one.
382 * @return True when RLE Lossless found. False in all
385 bool gdcmDocument::IsJPEGLossless(void)
387 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
388 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
389 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
393 * \brief Determines if the Transfer Syntax was already encountered
394 * and if it corresponds to a JPEG2000 one
395 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
398 bool gdcmDocument::IsJPEG2000(void)
400 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
401 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
405 * \brief Predicate for dicom version 3 file.
406 * @return True when the file is a dicom version 3.
408 bool gdcmDocument::IsDicomV3(void) {
409 // Checking if Transfert Syntax exists is enough
410 // Anyway, it's to late check if the 'Preamble' was found ...
411 // And ... would it be a rich idea to check ?
412 // (some 'no Preamble' DICOM images exist !)
413 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
417 * \brief returns the File Type
418 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
419 * @return the FileType code
421 FileType gdcmDocument::GetFileType(void) {
426 * \brief opens the file
427 * @param exception_on_error
430 FILE *gdcmDocument::OpenFile(bool exception_on_error)
433 fp=fopen(filename.c_str(),"rb");
437 if(exception_on_error)
438 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
441 std::cout <<"gdcmDocument::OpenFile cannot open file: "
442 << filename.c_str() << std::endl;
443 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
452 fread(&zero, (size_t)2, (size_t)1, fp);
454 //ACR -- or DICOM with no Preamble --
455 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
459 fseek(fp, 126L, SEEK_CUR);
461 fread(dicm, (size_t)4, (size_t)1, fp);
462 if( memcmp(dicm, "DICM", 4) == 0 )
466 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
469 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
475 * \brief closes the file
476 * @return TRUE if the close was successfull
478 bool gdcmDocument::CloseFile(void) {
479 int closed = fclose(fp);
487 * \brief Writes in a file all the Header Entries (Dicom Elements)
488 * of the Chained List
489 * @param fp file pointer on an already open file
490 * @param type Type of the File to be written
491 * (ACR-NEMA, ExplicitVR, ImplicitVR)
492 * \return Always true.
494 bool gdcmDocument::Write(FILE *fp, FileType type) {
497 /// The stuff will have to be rewritten using the SeQuence based
498 /// tree-like stucture instead of the chained list .
499 /// (so we shall remove the Group*HT from the gdcmDocument)
503 /// \todo move the following lines (and a lot of others, to be written)
504 /// to a future function CheckAndCorrectHeader
508 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
509 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
510 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
512 /// a moins de se livrer a un tres complique ajout des champs manquants.
513 /// faire un CheckAndCorrectHeader (?)
515 if (type == gdcmImplicitVR)
517 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
518 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
520 /// \todo Refer to standards on page 21, chapter 6.2
521 /// "Value representation": values with a VR of UI shall be
522 /// padded with a single trailing null
523 /// Dans le cas suivant on doit pader manuellement avec un 0
525 SetEntryLengthByNumber(18, 0x0002, 0x0010);
528 if (type == gdcmExplicitVR)
530 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
531 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
533 /// \todo Refer to standards on page 21, chapter 6.2
534 /// "Value representation": values with a VR of UI shall be
535 /// padded with a single trailing null
536 /// Dans le cas suivant on doit pader manuellement avec un 0
538 SetEntryLengthByNumber(20, 0x0002, 0x0010);
542 * \todo rewrite later, if really usefull
544 * --> Warning : un-updated odd groups lengths can causes pb
545 * --> (xmedcon breaks)
546 * --> to be re- written with future org.
548 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
549 * UpdateGroupLength(false,type);
551 * UpdateGroupLength(true,ACR);
554 WriteEntries(fp,type);
559 * \brief Modifies the value of a given Header Entry (Dicom Element)
560 * when it exists. Create it with the given value when unexistant.
561 * @param Value (string) Value to be set
562 * @param Group Group number of the Entry
563 * @param Elem Element number of the Entry
564 * \return pointer to the modified/created Header Entry (NULL when creation
568 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
572 gdcmDocEntry* CurrentEntry;
573 gdcmValEntry* ValEntry;
575 CurrentEntry = GetDocEntryByNumber( Group, Elem);
578 // The entry wasn't present and we simply create the required ValEntry:
579 CurrentEntry = NewDocEntryByNumber(Group, Elem);
582 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
583 " NewDocEntryByNumber failed.");
584 return (gdcmValEntry *)0;
586 ValEntry = new gdcmValEntry(CurrentEntry);
587 if ( !AddEntry(ValEntry))
589 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
590 " failed allthough this is a creation.");
595 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
598 // We need to promote the gdcmDocEntry to a gdcmValEntry:
599 ValEntry = new gdcmValEntry(CurrentEntry);
600 if (!RemoveEntry(CurrentEntry))
602 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
603 " of previous DocEntry failed.");
604 return (gdcmValEntry *)0;
606 if ( !AddEntry(ValEntry))
608 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
609 " promoted ValEntry failed.");
610 return (gdcmValEntry *)0;
615 SetEntryByNumber(Value, Group, Elem);
621 * \brief Modifies the value of a given Header Entry (Dicom Element)
622 * when it exists. Create it with the given value when unexistant.
623 * @param voidArea (binary) value to be set
624 * @param Group Group number of the Entry
625 * @param Elem Element number of the Entry
626 * \return pointer to the modified/created Header Entry (NULL when creation
631 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
638 a = GetDocEntryByNumber( Group, Elem);
640 a =NewBinEntryByNumber(Group, Elem);
643 b = new gdcmBinEntry(a);
646 SetEntryByNumber(voidArea, lgth, Group, Elem);
647 b->SetVoidArea(voidArea);
648 return (gdcmBinEntry*)b;
654 * \brief Set a new value if the invoked element exists
655 * Seems to be useless !!!
656 * @param Value new element value
657 * @param Group group number of the Entry
658 * @param Elem element number of the Entry
661 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
663 std::string v = Value;
664 SetEntryByNumber(v, Group, Elem);
668 //-----------------------------------------------------------------------------
672 * \brief Checks if a given Dicom Element exists within the H table
673 * @param group Group number of the searched Dicom Element
674 * @param element Element number of the searched Dicom Element
675 * @return number of occurences
677 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
678 std::string key = gdcmDictEntry::TranslateToKey(group, element );
679 return (tagHT.count(key));
683 * \brief Searches within Header Entries (Dicom Elements) parsed with
684 * the public and private dictionaries
685 * for the element value of a given tag.
686 * \warning Don't use any longer : use GetPubEntryByName
687 * @param tagName name of the searched element.
688 * @return Corresponding element value when it exists,
689 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
691 std::string gdcmDocument::GetEntryByName(std::string tagName) {
692 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
693 if( dictEntry == NULL)
696 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
700 * \brief Searches within Header Entries (Dicom Elements) parsed with
701 * the public and private dictionaries
702 * for the element value representation of a given tag.
704 * Obtaining the VR (Value Representation) might be needed by caller
705 * to convert the string typed content to caller's native type
706 * (think of C++ vs Python). The VR is actually of a higher level
707 * of semantics than just the native C++ type.
708 * @param tagName name of the searched element.
709 * @return Corresponding element value representation when it exists,
710 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
712 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
713 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
714 if( dictEntry == NULL)
717 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
718 dictEntry->GetElement());
719 return elem->GetVR();
724 * \brief Searches within Header Entries (Dicom Elements) parsed with
725 * the public and private dictionaries
726 * for the element value representation of a given tag.
727 * @param group Group number of the searched tag.
728 * @param element Element number of the searched tag.
729 * @return Corresponding element value representation when it exists,
730 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
732 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
733 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
734 if ( ! tagHT.count(key))
736 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
740 * \brief Searches within Header Entries (Dicom Elements) parsed with
741 * the public and private dictionaries
742 * for the element value representation of a given tag..
744 * Obtaining the VR (Value Representation) might be needed by caller
745 * to convert the string typed content to caller's native type
746 * (think of C++ vs Python). The VR is actually of a higher level
747 * of semantics than just the native C++ type.
748 * @param group Group number of the searched tag.
749 * @param element Element number of the searched tag.
750 * @return Corresponding element value representation when it exists,
751 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
753 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
754 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
757 return elem->GetVR();
761 * \brief Searches within Header Entries (Dicom Elements) parsed with
762 * the public and private dictionaries
763 * for the value length of a given tag..
764 * @param group Group number of the searched tag.
765 * @param element Element number of the searched tag.
766 * @return Corresponding element length; -2 if not found
768 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
769 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
772 return elem->GetLength();
775 * \brief Sets the value (string) of the Header Entry (Dicom Element)
776 * @param content string value of the Dicom Element
777 * @param tagName name of the searched Dicom Element.
778 * @return true when found
780 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
781 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
782 if( dictEntry == NULL)
785 return(SetEntryByNumber(content,dictEntry->GetGroup(),
786 dictEntry->GetElement()));
790 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
791 * through it's (group, element) and modifies it's content with
793 * @param content new value (string) to substitute with
794 * @param group group number of the Dicom Element to modify
795 * @param element element number of the Dicom Element to modify
797 bool gdcmDocument::SetEntryByNumber(std::string content,
801 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
804 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
805 " ValEntry (try promotion first).");
809 // Non even content must be padded with a space (020H).
810 if((content.length())%2)
811 content = content + '\0';
813 ValEntry->SetValue(content);
815 // Integers have a special treatement for their length:
816 VRKey vr = ValEntry->GetVR();
817 if( (vr == "US") || (vr == "SS") )
818 ValEntry->SetLength(2);
819 else if( (vr == "UL") || (vr == "SL") )
820 ValEntry->SetLength(4);
822 ValEntry->SetLength(content.length());
828 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
829 * through it's (group, element) and modifies it's content with
831 * @param content new value (void *) to substitute with
832 * @param group group number of the Dicom Element to modify
833 * @param element element number of the Dicom Element to modify
835 bool gdcmDocument::SetEntryByNumber(void *content,
840 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
841 if ( ! tagHT.count(key))
844 /* Hope Binray field length is never wrong
845 if(lgth%2) // Non even length are padded with a space (020H).
848 //content = content + '\0'; // fing a trick to enlarge a binary field?
852 a = (gdcmBinEntry *)tagHT[key];
853 a->SetVoidArea(content);
854 //a->SetLength(lgth); // ???
859 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
860 * in the PubDocEntrySet of this instance
861 * through it's (group, element) and modifies it's length with
863 * \warning Use with extreme caution.
864 * @param l new length to substitute with
865 * @param group group number of the Entry to modify
866 * @param element element number of the Entry to modify
867 * @return true on success, false otherwise.
869 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
873 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
874 if ( ! tagHT.count(key))
876 if (l%2) l++; // length must be even
877 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
883 * \brief Gets (from Header) the offset of a 'non string' element value
884 * (LoadElementValues has already be executed)
885 * @param Group group number of the Entry
886 * @param Elem element number of the Entry
887 * @return File Offset of the Element Value
889 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
891 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
894 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
895 "failed to Locate gdcmDocEntry");
898 return Entry->GetOffset();
902 * \brief Gets (from Header) a 'non string' element value
903 * (LoadElementValues has already be executed)
904 * @param Group group number of the Entry
905 * @param Elem element number of the Entry
906 * @return Pointer to the 'non string' area
908 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
910 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
913 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
914 "failed to Locate gdcmDocEntry");
917 return ((gdcmBinEntry *)Entry)->GetVoidArea();
921 * \brief Loads (from disk) the element content
922 * when a string is not suitable
923 * @param Group group number of the Entry
924 * @param Elem element number of the Entry
926 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
928 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
931 size_t o =(size_t)Element->GetOffset();
932 fseek(fp, o, SEEK_SET);
933 size_t l=Element->GetLength();
934 char* a = new char[l];
938 SetEntryVoidAreaByNumber(a, Group, Elem);
939 /// \todo check the result
940 size_t l2 = fread(a, 1, l ,fp);
951 * \brief Sets a 'non string' value to a given Dicom Element
953 * @param group Group number of the searched Dicom Element
954 * @param element Element number of the searched Dicom Element
957 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
961 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
962 if ( ! tagHT.count(key))
964 // This was for multimap ?
965 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
971 * \brief Update the entries with the shadow dictionary.
972 * Only non even entries are analyzed
974 void gdcmDocument::UpdateShaEntries(void) {
975 gdcmDictEntry *entry;
978 /// \todo TODO : still any use to explore recursively the whole structure?
980 for(ListTag::iterator it=listEntries.begin();
981 it!=listEntries.end();
984 // Odd group => from public dictionary
985 if((*it)->GetGroup()%2==0)
988 // Peer group => search the corresponding dict entry
990 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
994 if((*it)->IsImplicitVR())
999 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1001 // Set the new entry and the new value
1002 (*it)->SetDictEntry(entry);
1003 CheckDocEntryVR(*it,vr);
1005 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1010 // Remove precedent value transformation
1011 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1018 * \brief Searches within the Header Entries for a Dicom Element of
1020 * @param tagName name of the searched Dicom Element.
1021 * @return Corresponding Dicom Element when it exists, and NULL
1024 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1025 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1026 if( dictEntry == NULL)
1029 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1033 * \brief retrieves a Dicom Element (the first one) using (group, element)
1034 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1035 * if you think it's NOT UNIQUE, check the count number
1036 * and use iterators to retrieve ALL the Dicoms Elements within
1037 * a given couple (group, element)
1038 * @param group Group number of the searched Dicom Element
1039 * @param element Element number of the searched Dicom Element
1042 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1044 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1045 if ( ! tagHT.count(key))
1047 return tagHT.find(key)->second;
1051 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1052 * returns a result when the corresponding entry is of type
1054 * @return When present, the corresponding ValEntry.
1056 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1058 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1060 return (gdcmValEntry*)0;
1061 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1065 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1066 return (gdcmValEntry*)0;
1070 * \brief Loads the element while preserving the current
1071 * underlying file position indicator as opposed to
1072 * to LoadDocEntry that modifies it.
1073 * @param entry Header Entry whose value shall be loaded.
1076 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1077 long PositionOnEntry = ftell(fp);
1078 LoadDocEntry(entry);
1079 fseek(fp, PositionOnEntry, SEEK_SET);
1084 * \brief Writes in a file (according to the requested format)
1085 * the group, the element, the value representation and the length
1086 * of a single gdcmDocEntry passed as argument.
1087 * @param tag pointer on the gdcmDocEntry to be written
1088 * @param _fp already open file pointer
1089 * @param type type of the File to be written
1091 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1095 guint16 group = tag->GetGroup();
1096 VRKey vr = tag->GetVR();
1097 guint16 el = tag->GetElement();
1098 guint32 lgr = tag->GetReadLength();
1100 if ( (group == 0xfffe) && (el == 0x0000) )
1101 // Fix in order to make some MR PHILIPS images e-film readable
1102 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1103 // we just *always* ignore spurious fffe|0000 tag !
1106 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1107 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1109 if ( type == gdcmExplicitVR ) {
1111 // Special case of delimiters:
1112 if (group == 0xfffe) {
1113 // Delimiters have NO Value Representation and have NO length.
1114 // Hence we skip writing the VR and length and we pad by writing
1118 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1123 guint16 shortLgr = lgr;
1124 if (vr == "unkn") { // Unknown was 'written'
1125 // deal with Little Endian
1126 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1127 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1129 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1130 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1132 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1133 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1135 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1141 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1146 * \brief Writes in a file (according to the requested format)
1147 * the value of a single gdcmDocEntry passed as argument.
1148 * @param tag Pointer on the gdcmDocEntry to be written
1149 * @param _fp Already open file pointer
1150 * @param type type of the File to be written
1153 // \todo TODO : to be re -written recursively !
1154 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1157 guint16 group = tag->GetGroup();
1158 VRKey vr = tag->GetVR();
1159 guint32 lgr = tag->GetReadLength();
1162 // SeQuences have no value:
1164 if (group == 0xfffe)
1165 // Delimiters have no associated value:
1168 //--------------------------------
1170 // FIXME :right now, both value and voidArea belong to gdcmValue
1172 // -------------------------------
1174 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1176 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1177 voidArea = BinEntry->GetVoidArea();
1178 if (voidArea != NULL)
1179 { // there is a 'non string' LUT, overlay, etc
1180 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1185 if (vr == "US" || vr == "SS")
1187 // some 'Short integer' fields may be mulivaluated
1188 // each single value is separated from the next one by '\'
1189 // we split the string and write each value as a short int
1190 std::vector<std::string> tokens;
1191 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1192 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1193 for (unsigned int i=0; i<tokens.size();i++)
1195 guint16 val_uint16 = atoi(tokens[i].c_str());
1196 void *ptr = &val_uint16;
1197 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1202 if (vr == "UL" || vr == "SL")
1204 // Some 'Integer' fields may be multivaluated (multiple instances
1205 // of integers). But each single integer value is separated from the
1206 // next one by '\' (backslash character). Hence we split the string
1207 // along the '\' and write each value as an int:
1208 std::vector<std::string> tokens;
1209 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1210 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1211 for (unsigned int i=0; i<tokens.size();i++)
1213 guint32 val_uint32 = atoi(tokens[i].c_str());
1214 void *ptr = &val_uint32;
1215 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1220 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(),
1221 (size_t)lgr ,(size_t)1, _fp); // Elem value
1225 * \brief Writes in a file (according to the requested format)
1226 * a single gdcmDocEntry passed as argument.
1227 * \sa WriteEntryValue, WriteEntryTagVRLength.
1228 * @param tag Pointer on the gdcmDocEntry to be written
1229 * @param _fp Already open file pointer
1230 * @param type type of the File to be written
1233 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1235 guint32 length = tag->GetLength();
1237 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1239 // The value of a tag MUST (see the DICOM norm) be an odd number of
1240 // bytes. When this is not the case, pad with an additional byte:
1242 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1243 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1245 WriteEntryTagVRLength(ValEntry, _fp, type);
1246 WriteEntryValue(ValEntry, _fp, type);
1250 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1252 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
1255 // The value of a tag MUST (see the DICOM norm) be an odd number of
1256 // bytes. When this is not the case, pad with an additional byte:
1259 tag->SetValue(tag->GetValue()+"\0");
1260 tag->SetLength(tag->GetReadLength()+1);
1263 WriteEntryTagVRLength(tag, _fp, type);
1264 WriteEntryValue(tag, _fp, type);
1270 * \brief writes on disc according to the requested format
1271 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1272 * using the Chained List
1273 * \warning does NOT add the missing elements in the header :
1274 * it's up to the user doing it !
1275 * (function CheckHeaderCoherence to be written)
1276 * \warning DON'T try, right now, to write a DICOM image
1277 * from an ACR Header (meta elements will be missing!)
1278 * @param type type of the File to be written
1279 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1280 * @param _fp already open file pointer
1283 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1285 /// \todo FIXME : explore recursively the whole structure...
1286 /// \todo (?) check write failures (after *each* fwrite)
1288 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1289 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1291 gdcmDocEntry * entry = it->second;
1293 if ( type == gdcmACR ){
1294 if (entry->GetGroup() < 0x0008)
1295 // Ignore pure DICOM V3 groups
1297 if (entry->GetGroup() %2)
1298 // Ignore the "shadow" groups
1300 if (entry->GetVR() == "SQ" ) // ignore Sequences
1303 if (! WriteEntry(entry, _fp, type) ) {
1304 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1313 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1315 * @return The properly swaped 32 bits integer.
1317 guint32 gdcmDocument::SwapLong(guint32 a) {
1322 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1323 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1327 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1331 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1334 std::cout << "swapCode= " << sw << std::endl;
1335 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1342 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1344 * @return The properly unswaped 32 bits integer.
1346 guint32 gdcmDocument::UnswapLong(guint32 a) {
1347 return (SwapLong(a));
1351 * \brief Swaps the bytes so they agree with the processor order
1352 * @return The properly swaped 16 bits integer.
1354 guint16 gdcmDocument::SwapShort(guint16 a) {
1355 if ( (sw==4321) || (sw==2143) )
1356 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1361 * \brief Unswaps the bytes so they agree with the processor order
1362 * @return The properly unswaped 16 bits integer.
1364 guint16 gdcmDocument::UnswapShort(guint16 a) {
1365 return (SwapShort(a));
1368 //-----------------------------------------------------------------------------
1372 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1373 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1376 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1378 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1386 depth = set->GetDepthLevel();
1389 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1392 NewDocEntry = ReadNextDocEntry( );
1396 vr = NewDocEntry->GetVR();
1399 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1402 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1403 vl->Copy(NewDocEntry);
1404 vl->SetDepthLevel(depth);
1407 if (/*!delim_mode && */vl->isItemDelimitor())
1409 if ( !delim_mode && ftell(fp)-offset >= l_max)
1416 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1418 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1419 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1420 "nor BinEntry. Probably unknown VR.");
1423 ////// BinEntry or UNKOWN VR:
1424 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1425 bn->Copy(NewDocEntry);
1430 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1431 NewDocEntry->GetElement() == 0x0010 )
1433 if (NewDocEntry->GetLength()==0xffffffff)
1434 // Broken US.3405.1.dcm
1435 Parse7FE0(); // to skip the pixels
1436 // (multipart JPEG/RLE are trouble makers)
1440 // to be sure we are at the beginning
1441 SkipToNextDocEntry(NewDocEntry);
1442 l = NewDocEntry->GetFullLength();
1444 } else { // VR = "SQ"
1446 l=NewDocEntry->GetReadLength();
1447 if (l != 0) // don't mess the delim_mode for zero-length sequence
1448 if (l == 0xffffffff)
1452 // no other way to create it ...
1453 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1454 set->GetDepthLevel());
1455 sq->Copy(NewDocEntry);
1456 sq->SetDelimitorMode(delim_mode);
1457 sq->SetDepthLevel(depth);
1460 { // Don't try to parse zero-length sequences
1461 long lgt = ParseSQ( sq,
1462 NewDocEntry->GetOffset(),
1465 // FIXME : on en fait quoi, de lgt ?
1467 if ( !delim_mode && ftell(fp)-offset >= l_max)
1478 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1479 * @return parsed length for this level
1481 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1482 long offset, long l_max, bool delim_mode)
1484 int SQItemNumber = 0;
1486 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1490 int depth = set->GetDepthLevel();
1493 NewDocEntry = ReadNextDocEntry();
1495 if (NewDocEntry->isSequenceDelimitor()) {
1496 /// \todo add the Sequence Delimitor
1497 /// \todo find the trick to put it properly !
1498 set->SetSequenceDelimitationItem(NewDocEntry);
1502 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1506 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1507 itemSQ->AddEntry(NewDocEntry);
1508 /// \todo no value, no voidArea. Think of it while printing !
1509 l= NewDocEntry->GetReadLength();
1511 if (l == 0xffffffff)
1516 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1518 set->AddEntry(itemSQ,SQItemNumber);
1520 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1524 lgth = ftell(fp) - offset;
1529 * \brief Loads the element content if its length doesn't exceed
1530 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1531 * @param Entry Header Entry (Dicom Element) to be dealt with
1533 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1535 guint16 group = Entry->GetGroup();
1536 std::string vr= Entry->GetVR();
1537 guint32 length = Entry->GetLength();
1539 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1541 // A SeQuence "contains" a set of Elements.
1542 // (fffe e000) tells us an Element is beginning
1543 // (fffe e00d) tells us an Element just ended
1544 // (fffe e0dd) tells us the current SeQuence just ended
1545 if( group == 0xfffe ) {
1546 // NO more value field for SQ !
1547 //Entry->SetValue("gdcm::Skipped");
1548 // appel recursif de Load Value
1549 // (meme pb que pour le parsing)
1553 // When the length is zero things are easy:
1554 if ( length == 0 ) {
1555 ((gdcmValEntry *)Entry)->SetValue("");
1559 // The elements whose length is bigger than the specified upper bound
1560 // are not loaded. Instead we leave a short notice of the offset of
1561 // the element content and it's length.
1562 if (length > MaxSizeLoadEntry) {
1563 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1565 std::ostringstream s;
1566 s << "gdcm::NotLoaded.";
1567 s << " Address:" << (long)Entry->GetOffset();
1568 s << " Length:" << Entry->GetLength();
1569 s << " x(" << std::hex << Entry->GetLength() << ")";
1570 ValEntryPtr->SetValue(s.str());
1572 // to be sure we are at the end of the value ...
1573 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1578 // Any compacter code suggested (?)
1579 if ( IsDocEntryAnInteger(Entry) ) {
1581 std::ostringstream s;
1583 // When short integer(s) are expected, read and convert the following
1584 // n *two characters properly i.e. as short integers as opposed to strings.
1585 // Elements with Value Multiplicity > 1
1586 // contain a set of integers (not a single one)
1587 if (vr == "US" || vr == "SS") {
1589 NewInt = ReadInt16();
1592 for (int i=1; i < nbInt; i++) {
1594 NewInt = ReadInt16();
1599 // When integer(s) are expected, read and convert the following
1600 // n * four characters properly i.e. as integers as opposed to strings.
1601 // Elements with Value Multiplicity > 1
1602 // contain a set of integers (not a single one)
1603 else if (vr == "UL" || vr == "SL") {
1605 NewInt = ReadInt32();
1608 for (int i=1; i < nbInt; i++) {
1610 NewInt = ReadInt32();
1615 #ifdef GDCM_NO_ANSI_STRING_STREAM
1616 s << std::ends; // to avoid oddities on Solaris
1617 #endif //GDCM_NO_ANSI_STRING_STREAM
1619 ((gdcmValEntry *)Entry)->SetValue(s.str());
1623 // We need an additional byte for storing \0 that is not on disk
1624 std::string NewValue(length,0);
1625 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1626 if ( item_read != 1 ) {
1627 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1628 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1632 if( (vr == "UI") ) // Because of correspondance with the VR dic
1633 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1635 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1640 * \brief Find the value Length of the passed Header Entry
1641 * @param Entry Header Entry whose length of the value shall be loaded.
1643 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1644 guint16 element = Entry->GetElement();
1645 //guint16 group = Entry->GetGroup(); //FIXME
1646 std::string vr = Entry->GetVR();
1650 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1652 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1654 // The following reserved two bytes (see PS 3.5-2001, section
1655 // 7.1.2 Data element structure with explicit vr p27) must be
1656 // skipped before proceeding on reading the length on 4 bytes.
1657 fseek(fp, 2L, SEEK_CUR);
1658 guint32 length32 = ReadInt32();
1660 if ( (vr == "OB") && (length32 == 0xffffffff) )
1662 Entry->SetLength(FindDocEntryLengthOB());
1665 FixDocEntryFoundLength(Entry, length32);
1669 // Length is encoded on 2 bytes.
1670 length16 = ReadInt16();
1672 // We can tell the current file is encoded in big endian (like
1673 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1674 // and it's value is the one of the encoding of a big endian file.
1675 // In order to deal with such big endian encoded files, we have
1676 // (at least) two strategies:
1677 // * when we load the "Transfer Syntax" tag with value of big endian
1678 // encoding, we raise the proper flags. Then we wait for the end
1679 // of the META group (0x0002) among which is "Transfer Syntax",
1680 // before switching the swap code to big endian. We have to postpone
1681 // the switching of the swap code since the META group is fully encoded
1682 // in little endian, and big endian coding only starts at the next
1683 // group. The corresponding code can be hard to analyse and adds
1684 // many additional unnecessary tests for regular tags.
1685 // * the second strategy consists in waiting for trouble, that shall
1686 // appear when we find the first group with big endian encoding. This
1687 // is easy to detect since the length of a "Group Length" tag (the
1688 // ones with zero as element number) has to be of 4 (0x0004). When we
1689 // encounter 1024 (0x0400) chances are the encoding changed and we
1690 // found a group with big endian encoding.
1691 // We shall use this second strategy. In order to make sure that we
1692 // can interpret the presence of an apparently big endian encoded
1693 // length of a "Group Length" without committing a big mistake, we
1694 // add an additional check: we look in the already parsed elements
1695 // for the presence of a "Transfer Syntax" whose value has to be "big
1696 // endian encoding". When this is the case, chances are we have got our
1697 // hands on a big endian encoded file: we switch the swap code to
1698 // big endian and proceed...
1699 if ( (element == 0x0000) && (length16 == 0x0400) )
1701 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1703 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1708 SwitchSwapToBigEndian();
1709 // Restore the unproperly loaded values i.e. the group, the element
1710 // and the dictionary entry depending on them.
1711 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1712 guint16 CorrectElem = SwapShort(Entry->GetElement());
1713 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1717 // This correct tag is not in the dictionary. Create a new one.
1718 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1720 // FIXME this can create a memory leaks on the old entry that be
1721 // left unreferenced.
1722 Entry->SetDictEntry(NewTag);
1725 // Heuristic: well some files are really ill-formed.
1726 if ( length16 == 0xffff)
1729 //dbg.Verbose(0, "gdcmDocument::FindLength",
1730 // "Erroneous element length fixed.");
1731 // Actually, length= 0xffff means that we deal with
1732 // Unknown Sequence Length
1734 FixDocEntryFoundLength(Entry, (guint32)length16);
1739 // Either implicit VR or a non DICOM conformal (see note below) explicit
1740 // VR that ommited the VR of (at least) this element. Farts happen.
1741 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1742 // on Data elements "Implicit and Explicit VR Data Elements shall
1743 // not coexist in a Data Set and Data Sets nested within it".]
1744 // Length is on 4 bytes.
1746 FixDocEntryFoundLength(Entry, ReadInt32());
1752 * \brief Find the Value Representation of the current Dicom Element.
1755 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1757 if (filetype != gdcmExplicitVR)
1762 long PositionOnEntry = ftell(fp);
1763 // Warning: we believe this is explicit VR (Value Representation) because
1764 // we used a heuristic that found "UL" in the first tag. Alas this
1765 // doesn't guarantee that all the tags will be in explicit VR. In some
1766 // cases (see e-film filtered files) one finds implicit VR tags mixed
1767 // within an explicit VR file. Hence we make sure the present tag
1768 // is in explicit VR and try to fix things if it happens not to be
1771 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1773 if(!CheckDocEntryVR(Entry,VR))
1775 fseek(fp, PositionOnEntry, SEEK_SET);
1776 // When this element is known in the dictionary we shall use, e.g. for
1777 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1778 // dictionary entry. Still we have to flag the element as implicit since
1779 // we know now our assumption on expliciteness is not furfilled.
1781 if ( Entry->IsVRUnknown() )
1782 Entry->SetVR("Implicit");
1783 Entry->SetImplicitVR();
1788 * \brief Check the correspondance between the VR of the header entry
1789 * and the taken VR. If they are different, the header entry is
1790 * updated with the new VR.
1791 * @param Entry Header Entry to check
1792 * @param vr Dicom Value Representation
1793 * @return false if the VR is incorrect of if the VR isn't referenced
1794 * otherwise, it returns true
1796 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1798 char msg[100]; // for sprintf
1799 bool RealExplicit = true;
1801 // Assume we are reading a falsely explicit VR file i.e. we reached
1802 // a tag where we expect reading a VR but are in fact we read the
1803 // first to bytes of the length. Then we will interogate (through find)
1804 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1805 // both GCC and VC++ implementations of the STL map. Hence when the
1806 // expected VR read happens to be non-ascii characters we consider
1807 // we hit falsely explicit VR tag.
1809 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1810 RealExplicit = false;
1812 // CLEANME searching the dicom_vr at each occurence is expensive.
1813 // PostPone this test in an optional integrity check at the end
1814 // of parsing or only in debug mode.
1815 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1816 RealExplicit= false;
1818 if ( !RealExplicit )
1820 // We thought this was explicit VR, but we end up with an
1821 // implicit VR tag. Let's backtrack.
1822 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1823 Entry->GetGroup(),Entry->GetElement());
1824 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1825 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1826 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1827 Entry->GetGroup(),Entry->GetElement(),
1828 "UL","FIXME","Group Length");
1829 Entry->SetDictEntry(NewEntry);
1834 if ( Entry->IsVRUnknown() )
1836 // When not a dictionary entry, we can safely overwrite the VR.
1837 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1843 else if ( Entry->GetVR() != vr )
1845 // The VR present in the file and the dictionary disagree. We assume
1846 // the file writer knew best and use the VR of the file. Since it would
1847 // be unwise to overwrite the VR of a dictionary (since it would
1848 // compromise it's next user), we need to clone the actual DictEntry
1849 // and change the VR for the read one.
1850 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1851 Entry->GetGroup(),Entry->GetElement(),
1852 vr,"FIXME",Entry->GetName());
1853 Entry->SetDictEntry(NewEntry);
1859 * \brief Get the transformed value of the header entry. The VR value
1860 * is used to define the transformation to operate on the value
1861 * \warning NOT end user intended method !
1863 * @return Transformed entry value
1865 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1867 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1869 std::string val=((gdcmValEntry *)Entry)->GetValue();
1870 std::string vr=Entry->GetVR();
1871 guint32 length = Entry->GetLength();
1872 std::ostringstream s;
1875 // When short integer(s) are expected, read and convert the following
1876 // n * 2 bytes properly i.e. as a multivaluated strings
1877 // (each single value is separated fromthe next one by '\'
1878 // as usual for standard multivaluated filels
1879 // Elements with Value Multiplicity > 1
1880 // contain a set of short integers (not a single one)
1882 if (vr == "US" || vr == "SS")
1887 for (int i=0; i < nbInt; i++)
1891 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1892 NewInt16 = SwapShort(NewInt16);
1897 // When integer(s) are expected, read and convert the following
1898 // n * 4 bytes properly i.e. as a multivaluated strings
1899 // (each single value is separated fromthe next one by '\'
1900 // as usual for standard multivaluated filels
1901 // Elements with Value Multiplicity > 1
1902 // contain a set of integers (not a single one)
1903 else if (vr == "UL" || vr == "SL")
1908 for (int i=0; i < nbInt; i++)
1912 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1913 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1914 NewInt32=SwapLong(NewInt32);
1918 #ifdef GDCM_NO_ANSI_STRING_STREAM
1919 s << std::ends; // to avoid oddities on Solaris
1920 #endif //GDCM_NO_ANSI_STRING_STREAM
1924 return(((gdcmValEntry *)Entry)->GetValue());
1928 * \brief Get the reverse transformed value of the header entry. The VR
1929 * value is used to define the reverse transformation to operate on
1931 * \warning NOT end user intended method !
1933 * @return Reverse transformed entry value
1935 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1937 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1939 std::string vr=Entry->GetVR();
1940 std::ostringstream s;
1941 std::vector<std::string> tokens;
1943 if (vr == "US" || vr == "SS")
1947 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1948 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1949 for (unsigned int i=0; i<tokens.size();i++)
1951 NewInt16 = atoi(tokens[i].c_str());
1952 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1956 if (vr == "UL" || vr == "SL")
1960 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1961 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1962 for (unsigned int i=0; i<tokens.size();i++)
1964 NewInt32 = atoi(tokens[i].c_str());
1965 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1966 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1971 #ifdef GDCM_NO_ANSI_STRING_STREAM
1972 s << std::ends; // to avoid oddities on Solaris
1973 #endif //GDCM_NO_ANSI_STRING_STREAM
1977 return(((gdcmValEntry *)Entry)->GetValue());
1981 * \brief Skip a given Header Entry
1982 * \warning NOT end user intended method !
1985 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1987 SkipBytes(entry->GetLength());
1991 * \brief Skips to the begining of the next Header Entry
1992 * \warning NOT end user intended method !
1995 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1997 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1998 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
2002 * \brief Loads the value for a a given VLEntry
2003 * \warning NOT end user intended method !
2006 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
2008 //SkipBytes(entry->GetLength());
2009 LoadDocEntry(entry);
2012 * \brief When the length of an element value is obviously wrong (because
2013 * the parser went Jabberwocky) one can hope improving things by
2014 * applying some heuristics.
2016 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
2017 guint32 FoundLength)
2019 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
2020 if ( FoundLength == 0xffffffff) {
2024 guint16 gr =Entry->GetGroup();
2025 guint16 el =Entry->GetElement();
2027 if (FoundLength%2) {
2028 std::ostringstream s;
2029 s << "Warning : Tag with uneven length "
2031 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2032 dbg.Verbose(0, s.str().c_str());
2035 //////// Fix for some naughty General Electric images.
2036 // Allthough not recent many such GE corrupted images are still present
2037 // on Creatis hard disks. Hence this fix shall remain when such images
2038 // are no longer in user (we are talking a few years, here)...
2039 // Note: XMedCom probably uses such a trick since it is able to read
2040 // those pesky GE images ...
2041 if (FoundLength == 13) { // Only happens for this length !
2042 if ( (Entry->GetGroup() != 0x0008)
2043 || ( (Entry->GetElement() != 0x0070)
2044 && (Entry->GetElement() != 0x0080) ) )
2047 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2051 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2052 // Occurence of such images is quite low (unless one leaves close to a
2053 // 'Leonardo' source. Hence, one might consider commenting out the
2054 // following fix on efficiency reasons.
2056 if ( (Entry->GetGroup() == 0x0009)
2057 && ( (Entry->GetElement() == 0x1113)
2058 || (Entry->GetElement() == 0x1114) ) )
2061 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2064 //////// Deal with sequences, but only on users request:
2066 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2068 FoundLength = 0; // ReadLength is unchanged
2071 //////// We encountered a 'delimiter' element i.e. a tag of the form
2072 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2073 // taken into account.
2075 if(Entry->GetGroup() == 0xfffe)
2077 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2078 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2079 // causes extra troubles...
2080 if( Entry->GetElement() != 0x0000 )
2086 Entry->SetUsableLength(FoundLength);
2090 * \brief Apply some heuristics to predict whether the considered
2091 * element value contains/represents an integer or not.
2092 * @param Entry The element value on which to apply the predicate.
2093 * @return The result of the heuristical predicate.
2095 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2096 guint16 element = Entry->GetElement();
2097 guint16 group = Entry->GetGroup();
2098 std::string vr = Entry->GetVR();
2099 guint32 length = Entry->GetLength();
2101 // When we have some semantics on the element we just read, and if we
2102 // a priori know we are dealing with an integer, then we shall be
2103 // able to swap it's element value properly.
2104 if ( element == 0 ) // This is the group length of the group
2110 // Allthough this should never happen, still some images have a
2111 // corrupted group length [e.g. have a glance at offset x(8336) of
2112 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2113 // Since for dicom compliant and well behaved headers, the present
2114 // test is useless (and might even look a bit paranoid), when we
2115 // encounter such an ill-formed image, we simply display a warning
2116 // message and proceed on parsing (while crossing fingers).
2117 std::ostringstream s;
2118 int filePosition = ftell(fp);
2119 s << "Erroneous Group Length element length on : (" \
2120 << std::hex << group << " , " << element
2121 << ") -before- position x(" << filePosition << ")"
2122 << "lgt : " << length;
2123 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2127 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2134 * \brief Find the Length till the next sequence delimiter
2135 * \warning NOT end user intended method !
2139 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2140 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2143 long PositionOnEntry = ftell(fp);
2144 bool FoundSequenceDelimiter = false;
2145 guint32 TotalLength = 0;
2148 while ( ! FoundSequenceDelimiter)
2154 TotalLength += 4; // We even have to decount the group and element
2156 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2158 char msg[100]; // for sprintf. Sorry
2159 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2160 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2164 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2165 FoundSequenceDelimiter = true;
2166 else if ( n != 0xe000 )
2168 char msg[100]; // for sprintf. Sorry
2169 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2171 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2175 ItemLength = ReadInt32();
2176 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2177 // the ItemLength with ReadInt32
2178 SkipBytes(ItemLength);
2180 fseek(fp, PositionOnEntry, SEEK_SET);
2185 * \brief Reads a supposed to be 16 Bits integer
2186 * (swaps it depending on processor endianity)
2187 * @return read value
2189 guint16 gdcmDocument::ReadInt16(void) {
2192 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2193 if ( item_read != 1 ) {
2195 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2205 * \brief Reads a supposed to be 32 Bits integer
2206 * (swaps it depending on processor endianity)
2207 * @return read value
2209 guint32 gdcmDocument::ReadInt32(void) {
2212 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2213 if ( item_read != 1 ) {
2215 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2225 * \brief skips bytes inside the source file
2226 * \warning NOT end user intended method !
2229 void gdcmDocument::SkipBytes(guint32 NBytes) {
2230 //FIXME don't dump the returned value
2231 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2235 * \brief Loads all the needed Dictionaries
2236 * \warning NOT end user intended method !
2238 void gdcmDocument::Initialise(void)
2240 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2241 RefShaDict = (gdcmDict*)0;
2245 * \brief Discover what the swap code is (among little endian, big endian,
2246 * bad little endian, bad big endian).
2248 * @return false when we are absolutely sure
2249 * it's neither ACR-NEMA nor DICOM
2250 * true when we hope ours assuptions are OK
2252 bool gdcmDocument::CheckSwap() {
2254 // The only guaranted way of finding the swap code is to find a
2255 // group tag since we know it's length has to be of four bytes i.e.
2256 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2257 // occurs when we can't find such group...
2259 guint32 x=4; // x : for ntohs
2260 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2266 char deb[HEADER_LENGTH_TO_READ];
2268 // First, compare HostByteOrder and NetworkByteOrder in order to
2269 // determine if we shall need to swap bytes (i.e. the Endian type).
2275 // The easiest case is the one of a DICOM header, since it possesses a
2276 // file preamble where it suffice to look for the string "DICM".
2277 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2280 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2281 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2283 // Next, determine the value representation (VR). Let's skip to the
2284 // first element (0002, 0000) and check there if we find "UL"
2285 // - or "OB" if the 1st one is (0002,0001) -,
2286 // in which case we (almost) know it is explicit VR.
2287 // WARNING: if it happens to be implicit VR then what we will read
2288 // is the length of the group. If this ascii representation of this
2289 // length happens to be "UL" then we shall believe it is explicit VR.
2290 // FIXME: in order to fix the above warning, we could read the next
2291 // element value (or a couple of elements values) in order to make
2292 // sure we are not commiting a big mistake.
2293 // We need to skip :
2294 // * the 128 bytes of File Preamble (often padded with zeroes),
2295 // * the 4 bytes of "DICM" string,
2296 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2297 // i.e. a total of 136 bytes.
2301 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2302 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2303 // *Implicit* VR. -and it is !-
2305 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2306 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2307 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2308 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2309 // when Write DCM *adds*
2311 // Use gdcmDocument::dicom_vr to test all the possibilities
2312 // instead of just checking for UL, OB and UI !? group 0000
2314 filetype = gdcmExplicitVR;
2315 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2316 "explicit Value Representation");
2320 filetype = gdcmImplicitVR;
2321 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2322 "not an explicit Value Representation");
2328 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2329 "HostByteOrder != NetworkByteOrder");
2334 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2335 "HostByteOrder = NetworkByteOrder");
2338 // Position the file position indicator at first tag (i.e.
2339 // after the file preamble and the "DICM" string).
2341 fseek (fp, 132L, SEEK_SET);
2345 // Alas, this is not a DicomV3 file and whatever happens there is no file
2346 // preamble. We can reset the file position indicator to where the data
2347 // is (i.e. the beginning of the file).
2348 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2351 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2352 // By clean we mean that the length of the first tag is written down.
2353 // If this is the case and since the length of the first group HAS to be
2354 // four (bytes), then determining the proper swap code is straightforward.
2357 // We assume the array of char we are considering contains the binary
2358 // representation of a 32 bits integer. Hence the following dirty
2360 s32 = *((guint32 *)(entCur));
2381 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2382 // It is time for despaired wild guesses.
2383 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2384 // i.e. the 'group length' element is not present :
2386 // check the supposed to be 'group number'
2387 // 0x0002 or 0x0004 or 0x0008
2388 // to determine ' sw' value .
2389 // Only 0 or 4321 will be possible
2390 // (no oportunity to check for the formerly well known
2391 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2392 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2393 // the file IS NOT ACR-NEMA nor DICOM V3
2394 // Find a trick to tell it the caller...
2396 s16 = *((guint16 *)(deb));
2412 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2413 "ACR/NEMA unfound swap info (Really hopeless !)");
2414 filetype = gdcmUnknown;
2418 // Then the only info we have is the net2host one.
2428 * \brief Restore the unproperly loaded values i.e. the group, the element
2429 * and the dictionary entry depending on them.
2431 void gdcmDocument::SwitchSwapToBigEndian(void)
2433 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2434 "Switching to BigEndian mode.");
2455 * \brief during parsing, Header Elements too long are not loaded in memory
2458 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2462 if ((guint32)NewSize >= (guint32)0xffffffff)
2464 MaxSizeLoadEntry = 0xffffffff;
2467 MaxSizeLoadEntry = NewSize;
2472 * \brief Header Elements too long will not be printed
2473 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2476 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2480 if ((guint32)NewSize >= (guint32)0xffffffff)
2482 MaxSizePrintEntry = 0xffffffff;
2485 MaxSizePrintEntry = NewSize;
2491 * \brief Read the next tag but WITHOUT loading it's value
2492 * (read the 'Group Number', the 'Element Number',
2493 * gets the Dict Entry
2494 * gets the VR, gets the length, gets the offset value)
2495 * @return On succes the newly created DocEntry, NULL on failure.
2497 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2499 gdcmDocEntry *NewEntry;
2504 // We reached the EOF (or an error occured) therefore
2505 // header parsing has to be considered as finished.
2506 return (gdcmDocEntry *)0;
2508 // Pb : how to propagate the element length (used in SkipDocEntry)
2509 // direct call to SkipBytes ?
2511 // if (ignoreShadow == 1 && g%2 ==1)
2512 // if user wants to skip shadow groups
2513 // and current element *is* a shadow element
2514 // we don't create anything
2515 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2517 NewEntry = NewDocEntryByNumber(g, n);
2518 FindDocEntryVR(NewEntry);
2519 FindDocEntryLength(NewEntry);
2526 NewEntry->SetOffset(ftell(fp));
2531 * \brief Build a new Element Value from all the low level arguments.
2532 * Check for existence of dictionary entry, and build
2533 * a default one when absent.
2534 * @param Name Name of the underlying DictEntry
2536 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2538 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2540 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2542 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2545 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2546 "failed to allocate gdcmDocEntry");
2547 return (gdcmDocEntry *)0;
2553 * \brief Request a new virtual dict entry to the dict set
2554 * @param group group number of the underlying DictEntry
2555 * @param element element number of the underlying DictEntry
2556 * @param vr VR of the underlying DictEntry
2557 * @param fourth owner group
2558 * @param name english name
2560 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2565 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2569 * \brief Build a new Element Value from all the low level arguments.
2570 * Check for existence of dictionary entry, and build
2571 * a default one when absent.
2572 * @param Group group number of the underlying DictEntry
2573 * @param Elem element number of the underlying DictEntry
2575 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2577 // Find out if the tag we encountered is in the dictionaries:
2578 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2580 DictEntry = NewVirtualDictEntry(Group, Elem);
2582 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2585 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2586 "failed to allocate gdcmDocEntry");
2594 * \brief Build a new Element Value from all the low level arguments.
2595 * Check for existence of dictionary entry, and build
2596 * a default one when absent.
2597 * @param Group group number of the underlying DictEntry
2598 * @param Elem element number of the underlying DictEntry
2600 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2602 // Find out if the tag we encountered is in the dictionaries:
2603 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2605 DictEntry = NewVirtualDictEntry(Group, Elem);
2607 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2610 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2611 "failed to allocate gdcmValEntry");
2619 * \brief Build a new Element Value from all the low level arguments.
2620 * Check for existence of dictionary entry, and build
2621 * a default one when absent.
2622 * @param Group group number of the underlying DictEntry
2623 * @param Elem element number of the underlying DictEntry
2625 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2627 // Find out if the tag we encountered is in the dictionaries:
2628 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2630 DictEntry = NewVirtualDictEntry(Group, Elem);
2632 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2635 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2636 "failed to allocate gdcmBinEntry");
2643 * \brief Generate a free TagKey i.e. a TagKey that is not present
2644 * in the TagHt dictionary.
2645 * @param group The generated tag must belong to this group.
2646 * @return The element of tag with given group which is fee.
2648 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2650 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2652 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2653 if (tagHT.count(key) == 0)
2661 * \brief Searches both the public and the shadow dictionary (when they
2662 * exist) for the presence of the DictEntry with given name.
2663 * The public dictionary has precedence on the shadow one.
2664 * @param Name name of the searched DictEntry
2665 * @return Corresponding DictEntry when it exists, NULL otherwise.
2667 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2669 gdcmDictEntry *found = (gdcmDictEntry *)0;
2670 if (!RefPubDict && !RefShaDict)
2672 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2673 "we SHOULD have a default dictionary");
2677 found = RefPubDict->GetDictEntryByName(Name);
2683 found = RefShaDict->GetDictEntryByName(Name);
2691 * \brief Searches both the public and the shadow dictionary (when they
2692 * exist) for the presence of the DictEntry with given
2693 * group and element. The public dictionary has precedence on the
2695 * @param group group number of the searched DictEntry
2696 * @param element element number of the searched DictEntry
2697 * @return Corresponding DictEntry when it exists, NULL otherwise.
2699 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2701 gdcmDictEntry *found = (gdcmDictEntry *)0;
2702 if (!RefPubDict && !RefShaDict)
2704 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2705 "we SHOULD have a default dictionary");
2709 found = RefPubDict->GetDictEntryByNumber(group, element);
2715 found = RefShaDict->GetDictEntryByNumber(group, element);
2723 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2724 * is placed at the beginning of a tag (TestGroup, TestElement),
2725 * read the length associated to the Tag.
2726 * \warning On success the internal file pointer \ref gdcmDocument::fp
2727 * is modified to point after the tag and it's length.
2728 * On failure (i.e. when the tag wasn't the expected tag
2729 * (TestGroup, TestElement) the internal file pointer
2730 * \ref gdcmDocument::fp is restored to it's original position.
2731 * @param TestGroup The expected group of the tag.
2732 * @param TestElement The expected Element of the tag.
2733 * @return On success returns the length associated to the tag. On failure
2736 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2738 guint16 ItemTagGroup;
2739 guint16 ItemTagElement;
2740 long PositionOnEntry = ftell(fp);
2741 long CurrentPosition = ftell(fp); // On debugging purposes
2743 //// Read the Item Tag group and element, and make
2744 // sure they are respectively 0xfffe and 0xe000:
2745 ItemTagGroup = ReadInt16();
2746 ItemTagElement = ReadInt16();
2747 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2749 std::ostringstream s;
2750 s << " We should have found tag (";
2751 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2752 s << " but instead we encountered tag (";
2753 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2755 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2756 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2757 dbg.Verbose(0, s.str().c_str());
2758 fseek(fp, PositionOnEntry, SEEK_SET);
2762 //// Then read the associated Item Length
2763 CurrentPosition=ftell(fp);
2765 ItemLength = ReadInt32();
2767 std::ostringstream s;
2768 s << "Basic Item Length is: "
2769 << ItemLength << std::endl;
2770 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2771 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2777 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2778 * \sa \ref gdcmDocument::ReadTagLength
2779 * \warning See warning of \ref gdcmDocument::ReadTagLength
2780 * @return On success returns the length associated to the item tag.
2781 * On failure returns 0.
2783 guint32 gdcmDocument::ReadItemTagLength(void)
2785 return ReadTagLength(0xfffe, 0xe000);
2789 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2791 * \sa \ref gdcmDocument::ReadTagLength
2792 * \warning See warning of \ref gdcmDocument::ReadTagLength
2793 * @return On success returns the length associated to the Sequence
2794 * Delimiter tag. On failure returns 0.
2796 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2798 return ReadTagLength(0xfffe, 0xe0dd);
2803 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2804 * No other way so 'skip' the Data
2807 void gdcmDocument::Parse7FE0 (void)
2809 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2813 if ( IsImplicitVRLittleEndianTransferSyntax()
2814 || IsExplicitVRLittleEndianTransferSyntax()
2815 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2816 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2819 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2821 //// Read the Basic Offset Table Item Tag length...
2822 guint32 ItemLength = ReadItemTagLength();
2824 //// ... and then read length[s] itself[themselves]. We don't use
2825 // the values read (BTW what is the purpous of those lengths ?)
2826 if (ItemLength != 0) {
2827 // BTW, what is the purpous of those length anyhow !?
2828 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2829 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2830 for (int i=0; i < ItemLength; i += 4){
2831 guint32 IndividualLength;
2832 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2833 std::ostringstream s;
2834 s << " Read one length: ";
2835 s << std::hex << IndividualLength << std::endl;
2836 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2840 if ( ! IsRLELossLessTransferSyntax() )
2844 //// We then skip (not reading them) all the fragments of images:
2845 while ( ItemLength = ReadItemTagLength() )
2847 SkipBytes(ItemLength);
2855 long RleSegmentLength[15], fragmentLength;
2857 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2858 while ( fragmentLength = ReadSequenceDelimiterTagLength() )
2860 // Parse fragments of the current Fragment (Frame)
2861 //------------------ scanning (not reading) fragment pixels
2862 guint32 nbRleSegments = ReadInt32();
2863 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2865 //// Reading RLE Segments Offset Table
2866 guint32 RleSegmentOffsetTable[15];
2867 for(int k=1; k<=15; k++) {
2869 RleSegmentOffsetTable[k] = ReadInt32();
2870 printf(" at : %x Offset Segment %d : %d (%x)\n",
2871 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2872 RleSegmentOffsetTable[k]);
2875 // skipping (not reading) RLE Segments
2876 if (nbRleSegments>1) {
2877 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2878 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2879 - RleSegmentOffsetTable[k];
2881 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2882 k,(unsigned)RleSegmentLength[k],
2883 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2884 SkipBytes(RleSegmentLength[k]);
2888 RleSegmentLength[nbRleSegments]= fragmentLength
2889 - RleSegmentOffsetTable[nbRleSegments];
2891 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2892 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2893 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2894 SkipBytes(RleSegmentLength[nbRleSegments]);
2901 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2902 * \warning Does NOT work with ACR-NEMA files
2903 * \todo Find a trick to solve the pb (use RET fields ?)
2905 * @return true if 'smaller'
2907 bool gdcmDocument::operator<(gdcmDocument &document){
2911 s1=this->GetEntryByNumber(0x0010,0x0010);
2912 s2=document.GetEntryByNumber(0x0010,0x0010);
2920 s1=this->GetEntryByNumber(0x0010,0x0020);
2921 s2=document.GetEntryByNumber(0x0010,0x0020);
2928 // Study Instance UID
2929 s1=this->GetEntryByNumber(0x0020,0x000d);
2930 s2=document.GetEntryByNumber(0x0020,0x000d);
2937 // Serie Instance UID
2938 s1=this->GetEntryByNumber(0x0020,0x000e);
2939 s2=document.GetEntryByNumber(0x0020,0x000e);
2951 //-----------------------------------------------------------------------------