1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/28 09:30:58 $
7 Version: $Revision: 1.36 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.htm for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
24 #include "gdcmGlobal.h"
26 #include "gdcmDebug.h"
35 #include <netinet/in.h>
40 // Implicit VR Little Endian
41 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
42 // Explicit VR Little Endian
43 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
44 // Deflated Explicit VR Little Endian
45 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
46 // Explicit VR Big Endian
47 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
48 // JPEG Baseline (Process 1)
49 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
50 // JPEG Extended (Process 2 & 4)
51 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
52 // JPEG Extended (Process 3 & 5)
53 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
54 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
55 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
56 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
57 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
58 // JPEG Lossless, Non-Hierarchical (Process 14)
59 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
60 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
61 // [Selection Value 1])
62 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
64 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
66 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
68 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
69 // UI1_1_2_840_10008_1_2_5
70 #define str2num(str, typeNum) *((typeNum *)(str))
72 //-----------------------------------------------------------------------------
73 // Refer to gdcmDocument::CheckSwap()
74 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
76 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
77 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0x7fffffff;// 4096;//
78 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;//64;
80 //-----------------------------------------------------------------------------
81 // Constructor / Destructor
85 * @param inFilename file to be opened for parsing
86 * @param exception_on_error whether we throw an exception or not
87 * @param enable_sequences = true to allow the header
88 * to be parsed *inside* the SeQuences,
89 * when they have an actual length
90 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
91 * @param ignore_shadow to allow skipping the shadow elements,
92 * to save memory space.
93 * \warning The TRUE value for this param has to be used
94 * with a FALSE value for the 'enable_sequence' param.
95 * ('public elements' may be embedded in 'shadow Sequences')
97 gdcmDocument::gdcmDocument(std::string const & inFilename,
98 bool exception_on_error,
99 bool enable_sequences,
101 : gdcmElementSet(-1) {
102 enableSequences=enable_sequences;
103 IgnoreShadow =ignore_shadow;
105 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
106 Filename = inFilename;
109 if ( !OpenFile(exception_on_error))
112 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
116 fseek(fp,0L,SEEK_END);
117 long lgt = ftell(fp);
121 long beg = ftell(fp);
126 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
127 (void)l; //is l used anywhere ?
131 // Load 'non string' values
133 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
134 if( PhotometricInterpretation == "PALETTE COLOR " ) {
135 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
136 LoadEntryVoidArea(0x0028,0x1201); // R LUT
137 LoadEntryVoidArea(0x0028,0x1202); // G LUT
138 LoadEntryVoidArea(0x0028,0x1203); // B LUT
140 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
141 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
142 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
144 //FIXME later : how to use it?
145 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
149 // --------------------------------------------------------------
150 // Special Patch to allow gdcm to read ACR-LibIDO formated images
152 // if recognition code tells us we deal with a LibIDO image
153 // we switch lineNumber and columnNumber
156 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
157 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
158 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
159 // with "little-endian strings"
161 Filetype = gdcmACR_LIBIDO;
162 std::string rows = GetEntryByNumber(0x0028, 0x0010);
163 std::string columns = GetEntryByNumber(0x0028, 0x0011);
164 SetEntryByNumber(columns, 0x0028, 0x0010);
165 SetEntryByNumber(rows , 0x0028, 0x0011);
167 // ----------------- End of Special Patch ----------------
169 printLevel = 1; // 'Medium' print level by default
174 * @param exception_on_error
176 gdcmDocument::gdcmDocument(bool exception_on_error)
177 :gdcmElementSet(-1) {
178 (void)exception_on_error;
181 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
184 printLevel = 1; // 'Medium' print level by default
188 * \brief Canonical destructor.
190 gdcmDocument::~gdcmDocument (void) {
194 // Recursive clean up of sequences
195 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
202 //-----------------------------------------------------------------------------
206 * \brief Prints The Dict Entries of THE public Dicom Dictionary
209 void gdcmDocument::PrintPubDict(std::ostream & os) {
210 RefPubDict->Print(os);
214 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
217 void gdcmDocument::PrintShaDict(std::ostream & os) {
218 RefShaDict->Print(os);
221 //-----------------------------------------------------------------------------
224 * \brief Get the public dictionary used
226 gdcmDict *gdcmDocument::GetPubDict(void) {
231 * \brief Get the shadow dictionary used
233 gdcmDict *gdcmDocument::GetShaDict(void) {
238 * \brief Set the shadow dictionary used
239 * \param dict dictionary to use in shadow
241 bool gdcmDocument::SetShaDict(gdcmDict *dict){
247 * \brief Set the shadow dictionary used
248 * \param dictName name of the dictionary to use in shadow
250 bool gdcmDocument::SetShaDict(DictKey dictName){
251 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
256 * \brief This predicate, based on hopefully reasonable heuristics,
257 * decides whether or not the current gdcmDocument was properly parsed
258 * and contains the mandatory information for being considered as
259 * a well formed and usable Dicom/Acr File.
260 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
263 bool gdcmDocument::IsReadable(void) {
264 if(Filetype==gdcmUnknown) {
265 //std::cout << " gdcmDocument::IsReadable: Filetype " << Filetype
266 // << " " << "gdcmUnknown " << gdcmUnknown << std::endl; //JPR
267 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
271 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
281 * \brief Internal function that checks whether the Transfer Syntax given
282 * as argument is the one present in the current document.
283 * @param SyntaxToCheck The transfert syntax we need to check against.
284 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
285 * the current document. False either when the document contains
286 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
288 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
290 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
294 // The entry might be present but not loaded (parsing and loading
295 // happen at differente stages): try loading and proceed with check...
296 LoadDocEntrySafe(Entry);
297 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
299 std::string Transfer = ValEntry->GetValue();
300 // The actual transfer (as read from disk) might be padded. We
301 // first need to remove the potential padding. We can make the
302 // weak assumption that padding was not executed with digits...
303 while ( ! isdigit(Transfer[Transfer.length()-1]) )
305 Transfer.erase(Transfer.length()-1, 1);
307 if ( Transfer == SyntaxToCheck )
314 * \brief Determines if the Transfer Syntax of the present document
315 * corresponds to a Implicit Value Representation of
317 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
318 * @return True when ImplicitVRLittleEndian found. False in all other cases.
320 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
322 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
326 * \brief Determines if the Transfer Syntax was already encountered
327 * and if it corresponds to a ExplicitVRLittleEndian one.
328 * @return True when ExplicitVRLittleEndian found. False in all other cases.
330 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
332 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
336 * \brief Determines if the Transfer Syntax was already encountered
337 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
338 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
340 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
342 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
346 * \brief Determines if the Transfer Syntax was already encountered
347 * and if it corresponds to a Explicit VR Big Endian one.
348 * @return True when big endian found. False in all other cases.
350 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
352 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
356 * \brief Determines if the Transfer Syntax was already encountered
357 * and if it corresponds to a JPEGBaseLineProcess1 one.
358 * @return True when JPEGBaseLineProcess1found. False in all other cases.
360 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
362 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
366 * \brief Determines if the Transfer Syntax was already encountered
367 * and if it corresponds to a JPEGExtendedProcess2-4 one.
368 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
370 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
372 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
376 * \brief Determines if the Transfer Syntax was already encountered
377 * and if it corresponds to a JPEGExtendeProcess3-5 one.
378 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
380 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
382 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
386 * \brief Determines if the Transfer Syntax was already encountered
387 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
388 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
391 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
393 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
397 * \brief Determines if the Transfer Syntax was already encountered
398 * and if it corresponds to a RLE Lossless one.
399 * @return True when RLE Lossless found. False in all
402 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
404 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
408 * \brief Determines if Transfer Syntax was already encountered
409 * and if it corresponds to a JPEG Lossless one.
410 * @return True when RLE Lossless found. False in all
414 bool gdcmDocument::IsJPEGLossless(void)
416 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
417 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
418 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
422 * \brief Determines if the Transfer Syntax was already encountered
423 * and if it corresponds to a JPEG2000 one
424 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
427 bool gdcmDocument::IsJPEG2000(void)
429 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
430 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
434 * \brief Predicate for dicom version 3 file.
435 * @return True when the file is a dicom version 3.
437 bool gdcmDocument::IsDicomV3(void) {
438 // Checking if Transfert Syntax exists is enough
439 // Anyway, it's to late check if the 'Preamble' was found ...
440 // And ... would it be a rich idea to check ?
441 // (some 'no Preamble' DICOM images exist !)
442 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
446 * \brief returns the File Type
447 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
448 * @return the FileType code
450 FileType gdcmDocument::GetFileType(void) {
455 * \brief opens the file
456 * @param exception_on_error
459 FILE *gdcmDocument::OpenFile(bool exception_on_error)
462 fp=fopen(Filename.c_str(),"rb");
466 if(exception_on_error)
467 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
470 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
479 fread(&zero, (size_t)2, (size_t)1, fp);
481 //ACR -- or DICOM with no Preamble --
482 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
486 fseek(fp, 126L, SEEK_CUR);
488 fread(dicm, (size_t)4, (size_t)1, fp);
489 if( memcmp(dicm, "DICM", 4) == 0 )
493 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
496 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
502 * \brief closes the file
503 * @return TRUE if the close was successfull
505 bool gdcmDocument::CloseFile(void) {
506 int closed = fclose(fp);
514 * \brief Writes in a file all the Header Entries (Dicom Elements)
515 * @param fp file pointer on an already open file
516 * @param filetype Type of the File to be written
517 * (ACR-NEMA, ExplicitVR, ImplicitVR)
518 * \return Always true.
520 void gdcmDocument::Write(FILE* fp,FileType filetype) {
523 /// The stuff is rewritten using the SeQuence based
524 /// tree-like stucture (cf : Print )
528 /// \todo move the following lines (and a lot of others, to be written)
529 /// to a future function CheckAndCorrectHeader
531 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
532 /// no way (check : FileType est un champ de gdcmDocument ...)
533 /// a moins de se livrer a un tres complique ajout des champs manquants.
534 /// faire un CheckAndCorrectHeader (?)
536 if (filetype == gdcmImplicitVR)
538 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
539 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
541 /// \todo Refer to standards on page 21, chapter 6.2
542 /// "Value representation": values with a VR of UI shall be
543 /// padded with a single trailing null
544 /// Dans le cas suivant on doit pader manuellement avec un 0
546 SetEntryLengthByNumber(18, 0x0002, 0x0010);
549 if (filetype == gdcmExplicitVR)
551 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
552 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
554 /// \todo Refer to standards on page 21, chapter 6.2
555 /// "Value representation": values with a VR of UI shall be
556 /// padded with a single trailing null
557 /// Dans le cas suivant on doit pader manuellement avec un 0
559 SetEntryLengthByNumber(20, 0x0002, 0x0010);
562 // TODO : move to gdcmHeader::Write
563 // -----------------------------------------------------
565 if ( GetEntryByNumber(0x0028,0x0100) == "12") {
566 SetEntryByNumber("16", 0x0028,0x0100);
569 // correct Pixel group Length if necessary
571 guint16 GrPixel = 0x7fe0;
572 guint16 NumPixel = 0x0010;
574 // TODO : create a gdcmHeader::Write method and move this part.
575 // (only gdcmHeader knows GrPixel, NumPixel)
577 int i_lgPix = GetEntryLengthByNumber(GrPixel, NumPixel);
578 if (i_lgPix != -2) { // no (GrPixel, NumPixel) element
579 char * dumm = new char[20];
580 sprintf(dumm ,"%d", i_lgPix+12);
581 std::string s_lgPix = dumm;
583 ReplaceOrCreateByNumber(s_lgPix,GrPixel, 0x0000);
586 // Drop Palette Color, if necessary
588 // FIXME : Why is it always false ???
590 // std::cout << "entry 0x0028,0x0002 " << GetEntryByNumber(0x0028,0x0002).c_str() << std::endl;
592 /* if ( GetEntryByNumber(0x0028,0x0002).c_str() == "3" ) */{
594 // Drop 0028|1101, 0028|1102, 0028|1103
595 // Drop 0028|1201, 0028|1202, 0028|1203
598 e=GetDocEntryByNumber(0x0028,0x01101);
601 e=GetDocEntryByNumber(0x0028,0x1102);
604 e=GetDocEntryByNumber(0x0028,0x1103);
608 e=GetDocEntryByNumber(0x0028,0x01201);
611 e=GetDocEntryByNumber(0x0028,0x1202);
614 e=GetDocEntryByNumber(0x0028,0x1203);
619 // ----------- end move to gdcmHeader::Write -----------------
622 * \todo rewrite later, if really usefull
623 * ('Group Length' element is optional in DICOM)
625 * --> Warning : un-updated odd groups lengthes can causes pb
626 * --> (xmedcon breaker)
628 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
629 * UpdateGroupLength(false,filetype);
630 * if ( filetype == ACR)
631 * UpdateGroupLength(true,ACR);
634 gdcmElementSet::Write(fp,filetype); // This one is recursive
639 * \brief Modifies the value of a given Header Entry (Dicom Element)
640 * when it exists. Create it with the given value when unexistant.
641 * @param Value (string) Value to be set
642 * @param Group Group number of the Entry
643 * @param Elem Element number of the Entry
644 * \return pointer to the modified/created Header Entry (NULL when creation
648 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
653 gdcmDocEntry* CurrentEntry;
654 gdcmValEntry* ValEntry;
656 CurrentEntry = GetDocEntryByNumber( Group, Elem);
659 // The entry wasn't present and we simply create the required ValEntry:
660 CurrentEntry = NewDocEntryByNumber(Group, Elem);
663 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
664 " NewDocEntryByNumber failed.");
667 ValEntry = new gdcmValEntry(CurrentEntry);
668 if ( !AddEntry(ValEntry))
670 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
671 " failed allthough this is a creation.");
676 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
679 // We need to promote the gdcmDocEntry to a gdcmValEntry:
680 ValEntry = new gdcmValEntry(CurrentEntry);
681 if (!RemoveEntry(CurrentEntry))
683 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
684 " of previous DocEntry failed.");
687 if ( !AddEntry(ValEntry))
689 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
690 " promoted ValEntry failed.");
696 SetEntryByNumber(Value, Group, Elem);
702 * \brief Modifies the value of a given Header Entry (Dicom Element)
703 * when it exists. Create it with the given value when unexistant.
704 * @param voidArea (binary) value to be set
705 * @param Group Group number of the Entry
706 * @param Elem Element number of the Entry
707 * \return pointer to the modified/created Header Entry (NULL when creation
710 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
718 a = GetDocEntryByNumber( Group, Elem);
720 a =NewBinEntryByNumber(Group, Elem);
724 b = new gdcmBinEntry(a);
727 SetEntryByNumber(voidArea, lgth, Group, Elem);
728 b->SetVoidArea(voidArea);
736 * \brief Set a new value if the invoked element exists
737 * Seems to be useless !!!
738 * @param Value new element value
739 * @param Group group number of the Entry
740 * @param Elem element number of the Entry
743 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
745 std::string v = Value;
746 SetEntryByNumber(v, Group, Elem);
750 //-----------------------------------------------------------------------------
754 * \brief Checks if a given Dicom Element exists within the H table
755 * @param group Group number of the searched Dicom Element
756 * @param element Element number of the searched Dicom Element
757 * @return number of occurences
759 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
760 std::string key = gdcmDictEntry::TranslateToKey(group, element );
761 return tagHT.count(key);
765 * \brief Searches within Header Entries (Dicom Elements) parsed with
766 * the public and private dictionaries
767 * for the element value of a given tag.
768 * \warning Don't use any longer : use GetPubEntryByName
769 * @param tagName name of the searched element.
770 * @return Corresponding element value when it exists,
771 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
773 std::string gdcmDocument::GetEntryByName(std::string tagName) {
774 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
775 if( dictEntry == NULL)
778 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
782 * \brief Searches within Header Entries (Dicom Elements) parsed with
783 * the public and private dictionaries
784 * for the element value representation of a given tag.
786 * Obtaining the VR (Value Representation) might be needed by caller
787 * to convert the string typed content to caller's native type
788 * (think of C++ vs Python). The VR is actually of a higher level
789 * of semantics than just the native C++ type.
790 * @param tagName name of the searched element.
791 * @return Corresponding element value representation when it exists,
792 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
794 std::string gdcmDocument::GetEntryVRByName(TagName tagName) {
795 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
796 if( dictEntry == NULL)
799 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
800 dictEntry->GetElement());
801 return elem->GetVR();
806 * \brief Searches within Header Entries (Dicom Elements) parsed with
807 * the public and private dictionaries
808 * for the element value representation of a given tag.
809 * @param group Group number of the searched tag.
810 * @param element Element number of the searched tag.
811 * @return Corresponding element value representation when it exists,
812 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
814 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
815 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
816 if ( ! tagHT.count(key))
818 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
822 * \brief Searches within Header Entries (Dicom Elements) parsed with
823 * the public and private dictionaries
824 * for the element value representation of a given tag..
826 * Obtaining the VR (Value Representation) might be needed by caller
827 * to convert the string typed content to caller's native type
828 * (think of C++ vs Python). The VR is actually of a higher level
829 * of semantics than just the native C++ type.
830 * @param group Group number of the searched tag.
831 * @param element Element number of the searched tag.
832 * @return Corresponding element value representation when it exists,
833 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
835 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
836 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
839 return elem->GetVR();
843 * \brief Searches within Header Entries (Dicom Elements) parsed with
844 * the public and private dictionaries
845 * for the value length of a given tag..
846 * @param group Group number of the searched tag.
847 * @param element Element number of the searched tag.
848 * @return Corresponding element length; -2 if not found
850 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
851 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
854 return elem->GetLength();
857 * \brief Sets the value (string) of the Header Entry (Dicom Element)
858 * @param content string value of the Dicom Element
859 * @param tagName name of the searched Dicom Element.
860 * @return true when found
862 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
863 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
864 if( dictEntry == NULL)
867 return SetEntryByNumber(content,dictEntry->GetGroup(),
868 dictEntry->GetElement());
872 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
873 * through it's (group, element) and modifies it's content with
875 * @param content new value (string) to substitute with
876 * @param group group number of the Dicom Element to modify
877 * @param element element number of the Dicom Element to modify
879 bool gdcmDocument::SetEntryByNumber(std::string content,
883 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
886 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
887 " ValEntry (try promotion first).");
891 // Non even content must be padded with a space (020H).
892 if((content.length())%2)
893 content = content + '\0';
895 ValEntry->SetValue(content);
897 // Integers have a special treatement for their length:
898 VRKey vr = ValEntry->GetVR();
899 if( (vr == "US") || (vr == "SS") )
900 ValEntry->SetLength(2);
901 else if( (vr == "UL") || (vr == "SL") )
902 ValEntry->SetLength(4);
904 ValEntry->SetLength(content.length());
910 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
911 * through it's (group, element) and modifies it's content with
913 * @param content new value (void *) to substitute with
914 * @param group group number of the Dicom Element to modify
915 * @param element element number of the Dicom Element to modify
917 bool gdcmDocument::SetEntryByNumber(void *content,
922 (void)lgth; //not used
923 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
924 if ( ! tagHT.count(key))
927 /* Hope Binray field length is never wrong
928 if(lgth%2) // Non even length are padded with a space (020H).
931 //content = content + '\0'; // fing a trick to enlarge a binary field?
935 a = (gdcmBinEntry *)tagHT[key];
936 a->SetVoidArea(content);
937 //a->SetLength(lgth); // ???
942 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
943 * in the PubDocEntrySet of this instance
944 * through it's (group, element) and modifies it's length with
946 * \warning Use with extreme caution.
947 * @param l new length to substitute with
948 * @param group group number of the Entry to modify
949 * @param element element number of the Entry to modify
950 * @return true on success, false otherwise.
952 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
956 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
957 if ( ! tagHT.count(key))
959 if (l%2) l++; // length must be even
960 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
966 * \brief Gets (from Header) the offset of a 'non string' element value
967 * (LoadElementValues has already be executed)
968 * @param Group group number of the Entry
969 * @param Elem element number of the Entry
970 * @return File Offset of the Element Value
972 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
974 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
977 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
980 return Entry->GetOffset();
984 * \brief Gets (from Header) a 'non string' element value
985 * (LoadElementValues has already be executed)
986 * @param Group group number of the Entry
987 * @param Elem element number of the Entry
988 * @return Pointer to the 'non string' area
990 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
992 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
995 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
998 return ((gdcmBinEntry *)Entry)->GetVoidArea();
1002 * \brief Loads (from disk) the element content
1003 * when a string is not suitable
1004 * @param Group group number of the Entry
1005 * @param Elem element number of the Entry
1007 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
1009 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
1012 size_t o =(size_t)Element->GetOffset();
1013 fseek(fp, o, SEEK_SET);
1014 size_t l = Element->GetLength();
1015 char* a = new char[l];
1017 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1020 SetEntryVoidAreaByNumber(a, Group, Elem);
1021 /// \todo check the result
1022 size_t l2 = fread(a, 1, l ,fp);
1031 * \brief Loads (from disk) the element content
1032 * when a string is not suitable
1033 * @param Element Entry whose voidArea is going to be loaded
1035 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element)
1037 size_t o =(size_t)Element->GetOffset();
1038 fseek(fp, o, SEEK_SET);
1039 size_t l = Element->GetLength();
1040 char* a = new char[l];
1042 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1045 Element->SetVoidArea((void *)a);
1046 /// \todo check the result
1047 size_t l2 = fread(a, 1, l ,fp);
1057 * \brief Sets a 'non string' value to a given Dicom Element
1058 * @param area area containing the 'non string' value
1059 * @param group Group number of the searched Dicom Element
1060 * @param element Element number of the searched Dicom Element
1063 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1067 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1068 if ( ! tagHT.count(key))
1070 // This was for multimap ?
1071 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1077 * \brief Update the entries with the shadow dictionary.
1078 * Only non even entries are analyzed
1080 void gdcmDocument::UpdateShaEntries(void) {
1081 //gdcmDictEntry *entry;
1084 /// \todo TODO : still any use to explore recursively the whole structure?
1086 for(ListTag::iterator it=listEntries.begin();
1087 it!=listEntries.end();
1090 // Odd group => from public dictionary
1091 if((*it)->GetGroup()%2==0)
1094 // Peer group => search the corresponding dict entry
1096 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1100 if((*it)->IsImplicitVR())
1105 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1107 // Set the new entry and the new value
1108 (*it)->SetDictEntry(entry);
1109 CheckDocEntryVR(*it,vr);
1111 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1116 // Remove precedent value transformation
1117 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1124 * \brief Searches within the Header Entries for a Dicom Element of
1126 * @param tagName name of the searched Dicom Element.
1127 * @return Corresponding Dicom Element when it exists, and NULL
1130 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1131 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1132 if( dictEntry == NULL)
1135 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1139 * \brief retrieves a Dicom Element (the first one) using (group, element)
1140 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1141 * if you think it's NOT UNIQUE, check the count number
1142 * and use iterators to retrieve ALL the Dicoms Elements within
1143 * a given couple (group, element)
1144 * @param group Group number of the searched Dicom Element
1145 * @param element Element number of the searched Dicom Element
1148 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1150 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1151 if ( ! tagHT.count(key))
1153 return tagHT.find(key)->second;
1157 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1158 * returns a result when the corresponding entry is of type
1160 * @return When present, the corresponding ValEntry.
1162 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1164 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1166 return (gdcmValEntry*)0;
1167 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1171 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1172 return (gdcmValEntry*)0;
1176 * \brief Loads the element while preserving the current
1177 * underlying file position indicator as opposed to
1178 * to LoadDocEntry that modifies it.
1179 * @param entry Header Entry whose value shall be loaded.
1182 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1183 long PositionOnEntry = ftell(fp);
1184 LoadDocEntry(entry);
1185 fseek(fp, PositionOnEntry, SEEK_SET);
1189 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1191 * @return The properly swaped 32 bits integer.
1193 guint32 gdcmDocument::SwapLong(guint32 a) {
1198 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1199 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1203 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1207 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1210 std::cout << "swapCode= " << sw << std::endl;
1211 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1218 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1220 * @return The properly unswaped 32 bits integer.
1222 guint32 gdcmDocument::UnswapLong(guint32 a) {
1227 * \brief Swaps the bytes so they agree with the processor order
1228 * @return The properly swaped 16 bits integer.
1230 guint16 gdcmDocument::SwapShort(guint16 a) {
1231 if ( (sw==4321) || (sw==2143) )
1232 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1237 * \brief Unswaps the bytes so they agree with the processor order
1238 * @return The properly unswaped 16 bits integer.
1240 guint16 gdcmDocument::UnswapShort(guint16 a) {
1241 return SwapShort(a);
1244 //-----------------------------------------------------------------------------
1248 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1249 * @return length of the parsed set.
1252 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1254 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1255 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1259 unsigned long l = 0;
1262 depth = set->GetDepthLevel();
1265 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1268 NewDocEntry = ReadNextDocEntry( );
1271 // NewDocEntry->Print(); cout << endl; //JPR
1272 vr = NewDocEntry->GetVR();
1276 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1279 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1280 NewValEntry->Copy(NewDocEntry);
1281 NewValEntry->SetDepthLevel(depth);
1282 set->AddEntry(NewValEntry);
1283 LoadDocEntry(NewValEntry);
1284 if (NewValEntry->isItemDelimitor())
1286 if ( !delim_mode && ftell(fp)-offset >= l_max)
1293 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1295 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1296 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1297 "nor BinEntry. Probably unknown VR.");
1300 ////// BinEntry or UNKOWN VR:
1301 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1302 bn->Copy(NewDocEntry);
1307 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1308 NewDocEntry->GetElement() == 0x0010 )
1310 if (NewDocEntry->GetReadLength()==0xffffffff)
1312 // Broken US.3405.1.dcm
1313 Parse7FE0(); // to skip the pixels
1314 // (multipart JPEG/RLE are trouble makers)
1318 SkipToNextDocEntry(NewDocEntry);
1319 l = NewDocEntry->GetFullLength();
1324 // to be sure we are at the beginning
1325 SkipToNextDocEntry(NewDocEntry);
1326 l = NewDocEntry->GetFullLength();
1332 l=NewDocEntry->GetReadLength();
1333 if (l != 0) // don't mess the delim_mode for zero-length sequence
1334 if (l == 0xffffffff)
1338 // no other way to create it ...
1339 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1340 set->GetDepthLevel());
1341 sq->Copy(NewDocEntry);
1342 sq->SetDelimitorMode(delim_mode);
1343 sq->SetDepthLevel(depth);
1346 { // Don't try to parse zero-length sequences
1347 long lgt = ParseSQ( sq,
1348 NewDocEntry->GetOffset(),
1350 (void)lgt; //not used...
1353 if ( !delim_mode && ftell(fp)-offset >= l_max)
1360 return l; // Probably useless
1364 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1365 * @return parsed length for this level
1367 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1368 long offset, long l_max, bool delim_mode)
1370 int SQItemNumber = 0;
1372 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1377 int depth = set->GetDepthLevel();
1378 (void)depth; //not used
1382 NewDocEntry = ReadNextDocEntry();
1386 if (NewDocEntry->isSequenceDelimitor()) {
1387 set->SetSequenceDelimitationItem(NewDocEntry);
1391 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1395 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1396 itemSQ->AddEntry(NewDocEntry);
1397 l= NewDocEntry->GetReadLength();
1399 if (l == 0xffffffff)
1404 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1406 set->AddEntry(itemSQ,SQItemNumber);
1408 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1412 lgth = ftell(fp) - offset;
1417 * \brief Loads the element content if its length doesn't exceed
1418 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1419 * @param Entry Header Entry (Dicom Element) to be dealt with
1421 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1424 guint16 group = Entry->GetGroup();
1425 std::string vr= Entry->GetVR();
1426 guint32 length = Entry->GetLength();
1428 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1430 // A SeQuence "contains" a set of Elements.
1431 // (fffe e000) tells us an Element is beginning
1432 // (fffe e00d) tells us an Element just ended
1433 // (fffe e0dd) tells us the current SeQuence just ended
1434 if( group == 0xfffe ) {
1435 // NO more value field for SQ !
1439 // When the length is zero things are easy:
1440 if ( length == 0 ) {
1441 ((gdcmValEntry *)Entry)->SetValue("");
1445 // The elements whose length is bigger than the specified upper bound
1446 // are not loaded. Instead we leave a short notice of the offset of
1447 // the element content and it's length.
1449 std::ostringstream s;
1450 if (length > MaxSizeLoadEntry) {
1451 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1453 s << "gdcm::NotLoaded (BinEntry)";
1454 s << " Address:" << (long)Entry->GetOffset();
1455 s << " Length:" << Entry->GetLength();
1456 s << " x(" << std::hex << Entry->GetLength() << ")";
1457 BinEntryPtr->SetValue(s.str());
1459 // to be sure we are at the end of the value ...
1460 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1462 // Be carefull : a BinEntry IS_A ValEntry ...
1463 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1465 s << "gdcm::NotLoaded. (ValEntry)";
1466 s << " Address:" << (long)Entry->GetOffset();
1467 s << " Length:" << Entry->GetLength();
1468 s << " x(" << std::hex << Entry->GetLength() << ")";
1469 ValEntryPtr->SetValue(s.str());
1471 // to be sure we are at the end of the value ...
1472 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1476 // When we find a BinEntry not very much can be done :
1477 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1479 LoadEntryVoidArea(BinEntryPtr);
1480 s << "gdcm::Loaded (BinEntry)";
1481 BinEntryPtr->SetValue(s.str());
1486 // Any compacter code suggested (?)
1487 if ( IsDocEntryAnInteger(Entry) ) {
1489 std::ostringstream s;
1491 // When short integer(s) are expected, read and convert the following
1492 // n *two characters properly i.e. as short integers as opposed to strings.
1493 // Elements with Value Multiplicity > 1
1494 // contain a set of integers (not a single one)
1495 if (vr == "US" || vr == "SS") {
1497 NewInt = ReadInt16();
1500 for (int i=1; i < nbInt; i++) {
1502 NewInt = ReadInt16();
1507 // When integer(s) are expected, read and convert the following
1508 // n * four characters properly i.e. as integers as opposed to strings.
1509 // Elements with Value Multiplicity > 1
1510 // contain a set of integers (not a single one)
1511 else if (vr == "UL" || vr == "SL") {
1513 NewInt = ReadInt32();
1516 for (int i=1; i < nbInt; i++) {
1518 NewInt = ReadInt32();
1523 #ifdef GDCM_NO_ANSI_STRING_STREAM
1524 s << std::ends; // to avoid oddities on Solaris
1525 #endif //GDCM_NO_ANSI_STRING_STREAM
1527 ((gdcmValEntry *)Entry)->SetValue(s.str());
1531 // We need an additional byte for storing \0 that is not on disk
1532 std::string NewValue(length,0);
1533 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1534 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) ) {
1535 if ( item_read != 1 ) {
1536 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1537 ValEntry->SetValue("gdcm::UnRead");
1541 if( (vr == "UI") ) // Because of correspondance with the VR dic
1542 ValEntry->SetValue(NewValue.c_str());
1544 ValEntry->SetValue(NewValue);
1547 std::cout << "Should have a ValEntry, here !" << std::endl;
1554 * \brief Find the value Length of the passed Header Entry
1555 * @param Entry Header Entry whose length of the value shall be loaded.
1557 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1558 guint16 element = Entry->GetElement();
1559 //guint16 group = Entry->GetGroup(); //FIXME
1560 std::string vr = Entry->GetVR();
1564 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1566 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1568 // The following reserved two bytes (see PS 3.5-2001, section
1569 // 7.1.2 Data element structure with explicit vr p27) must be
1570 // skipped before proceeding on reading the length on 4 bytes.
1571 fseek(fp, 2L, SEEK_CUR);
1572 guint32 length32 = ReadInt32();
1574 if ( (vr == "OB") && (length32 == 0xffffffff) )
1576 Entry->SetLength(FindDocEntryLengthOB());
1579 FixDocEntryFoundLength(Entry, length32);
1583 // Length is encoded on 2 bytes.
1584 length16 = ReadInt16();
1586 // We can tell the current file is encoded in big endian (like
1587 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1588 // and it's value is the one of the encoding of a big endian file.
1589 // In order to deal with such big endian encoded files, we have
1590 // (at least) two strategies:
1591 // * when we load the "Transfer Syntax" tag with value of big endian
1592 // encoding, we raise the proper flags. Then we wait for the end
1593 // of the META group (0x0002) among which is "Transfer Syntax",
1594 // before switching the swap code to big endian. We have to postpone
1595 // the switching of the swap code since the META group is fully encoded
1596 // in little endian, and big endian coding only starts at the next
1597 // group. The corresponding code can be hard to analyse and adds
1598 // many additional unnecessary tests for regular tags.
1599 // * the second strategy consists in waiting for trouble, that shall
1600 // appear when we find the first group with big endian encoding. This
1601 // is easy to detect since the length of a "Group Length" tag (the
1602 // ones with zero as element number) has to be of 4 (0x0004). When we
1603 // encounter 1024 (0x0400) chances are the encoding changed and we
1604 // found a group with big endian encoding.
1605 // We shall use this second strategy. In order to make sure that we
1606 // can interpret the presence of an apparently big endian encoded
1607 // length of a "Group Length" without committing a big mistake, we
1608 // add an additional check: we look in the already parsed elements
1609 // for the presence of a "Transfer Syntax" whose value has to be "big
1610 // endian encoding". When this is the case, chances are we have got our
1611 // hands on a big endian encoded file: we switch the swap code to
1612 // big endian and proceed...
1613 if ( (element == 0x0000) && (length16 == 0x0400) )
1615 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1617 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1622 SwitchSwapToBigEndian();
1623 // Restore the unproperly loaded values i.e. the group, the element
1624 // and the dictionary entry depending on them.
1625 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1626 guint16 CorrectElem = SwapShort(Entry->GetElement());
1627 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1631 // This correct tag is not in the dictionary. Create a new one.
1632 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1634 // FIXME this can create a memory leaks on the old entry that be
1635 // left unreferenced.
1636 Entry->SetDictEntry(NewTag);
1639 // Heuristic: well, some files are really ill-formed.
1640 if ( length16 == 0xffff)
1643 // Length16= 0xffff means that we deal with
1644 // 'Unknown Length' Sequence
1646 FixDocEntryFoundLength(Entry, (guint32)length16);
1651 // Either implicit VR or a non DICOM conformal (see note below) explicit
1652 // VR that ommited the VR of (at least) this element. Farts happen.
1653 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1654 // on Data elements "Implicit and Explicit VR Data Elements shall
1655 // not coexist in a Data Set and Data Sets nested within it".]
1656 // Length is on 4 bytes.
1658 FixDocEntryFoundLength(Entry, ReadInt32());
1664 * \brief Find the Value Representation of the current Dicom Element.
1667 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1669 if (Filetype != gdcmExplicitVR)
1674 long PositionOnEntry = ftell(fp);
1675 // Warning: we believe this is explicit VR (Value Representation) because
1676 // we used a heuristic that found "UL" in the first tag. Alas this
1677 // doesn't guarantee that all the tags will be in explicit VR. In some
1678 // cases (see e-film filtered files) one finds implicit VR tags mixed
1679 // within an explicit VR file. Hence we make sure the present tag
1680 // is in explicit VR and try to fix things if it happens not to be
1683 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1685 if(!CheckDocEntryVR(Entry,VR))
1687 fseek(fp, PositionOnEntry, SEEK_SET);
1688 // When this element is known in the dictionary we shall use, e.g. for
1689 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1690 // dictionary entry. Still we have to flag the element as implicit since
1691 // we know now our assumption on expliciteness is not furfilled.
1693 if ( Entry->IsVRUnknown() )
1694 Entry->SetVR("Implicit");
1695 Entry->SetImplicitVR();
1700 * \brief Check the correspondance between the VR of the header entry
1701 * and the taken VR. If they are different, the header entry is
1702 * updated with the new VR.
1703 * @param Entry Header Entry to check
1704 * @param vr Dicom Value Representation
1705 * @return false if the VR is incorrect of if the VR isn't referenced
1706 * otherwise, it returns true
1708 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1710 char msg[100]; // for sprintf
1711 bool RealExplicit = true;
1713 // Assume we are reading a falsely explicit VR file i.e. we reached
1714 // a tag where we expect reading a VR but are in fact we read the
1715 // first to bytes of the length. Then we will interogate (through find)
1716 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1717 // both GCC and VC++ implementations of the STL map. Hence when the
1718 // expected VR read happens to be non-ascii characters we consider
1719 // we hit falsely explicit VR tag.
1721 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1722 RealExplicit = false;
1724 // CLEANME searching the dicom_vr at each occurence is expensive.
1725 // PostPone this test in an optional integrity check at the end
1726 // of parsing or only in debug mode.
1727 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1728 RealExplicit= false;
1730 if ( !RealExplicit )
1732 // We thought this was explicit VR, but we end up with an
1733 // implicit VR tag. Let's backtrack.
1734 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1735 Entry->GetGroup(),Entry->GetElement());
1736 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1737 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1738 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1739 Entry->GetGroup(),Entry->GetElement(),
1740 "UL","FIXME","Group Length");
1741 Entry->SetDictEntry(NewEntry);
1746 if ( Entry->IsVRUnknown() )
1748 // When not a dictionary entry, we can safely overwrite the VR.
1749 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1755 else if ( Entry->GetVR() != vr )
1757 // The VR present in the file and the dictionary disagree. We assume
1758 // the file writer knew best and use the VR of the file. Since it would
1759 // be unwise to overwrite the VR of a dictionary (since it would
1760 // compromise it's next user), we need to clone the actual DictEntry
1761 // and change the VR for the read one.
1762 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1763 Entry->GetGroup(),Entry->GetElement(),
1764 vr,"FIXME",Entry->GetName());
1765 Entry->SetDictEntry(NewEntry);
1771 * \brief Get the transformed value of the header entry. The VR value
1772 * is used to define the transformation to operate on the value
1773 * \warning NOT end user intended method !
1775 * @return Transformed entry value
1777 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1779 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1781 std::string val=((gdcmValEntry *)Entry)->GetValue();
1782 std::string vr=Entry->GetVR();
1783 guint32 length = Entry->GetLength();
1784 std::ostringstream s;
1787 // When short integer(s) are expected, read and convert the following
1788 // n * 2 bytes properly i.e. as a multivaluated strings
1789 // (each single value is separated fromthe next one by '\'
1790 // as usual for standard multivaluated filels
1791 // Elements with Value Multiplicity > 1
1792 // contain a set of short integers (not a single one)
1794 if (vr == "US" || vr == "SS")
1799 for (int i=0; i < nbInt; i++)
1803 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1804 NewInt16 = SwapShort(NewInt16);
1809 // When integer(s) are expected, read and convert the following
1810 // n * 4 bytes properly i.e. as a multivaluated strings
1811 // (each single value is separated fromthe next one by '\'
1812 // as usual for standard multivaluated filels
1813 // Elements with Value Multiplicity > 1
1814 // contain a set of integers (not a single one)
1815 else if (vr == "UL" || vr == "SL")
1820 for (int i=0; i < nbInt; i++)
1824 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1825 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1826 NewInt32=SwapLong(NewInt32);
1830 #ifdef GDCM_NO_ANSI_STRING_STREAM
1831 s << std::ends; // to avoid oddities on Solaris
1832 #endif //GDCM_NO_ANSI_STRING_STREAM
1836 return ((gdcmValEntry *)Entry)->GetValue();
1840 * \brief Get the reverse transformed value of the header entry. The VR
1841 * value is used to define the reverse transformation to operate on
1843 * \warning NOT end user intended method !
1845 * @return Reverse transformed entry value
1847 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1849 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1851 std::string vr=Entry->GetVR();
1852 std::ostringstream s;
1853 std::vector<std::string> tokens;
1855 if (vr == "US" || vr == "SS")
1859 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1860 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1861 for (unsigned int i=0; i<tokens.size();i++)
1863 NewInt16 = atoi(tokens[i].c_str());
1864 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1868 if (vr == "UL" || vr == "SL")
1872 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1873 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1874 for (unsigned int i=0; i<tokens.size();i++)
1876 NewInt32 = atoi(tokens[i].c_str());
1877 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1878 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1883 #ifdef GDCM_NO_ANSI_STRING_STREAM
1884 s << std::ends; // to avoid oddities on Solaris
1885 #endif //GDCM_NO_ANSI_STRING_STREAM
1889 return ((gdcmValEntry *)Entry)->GetValue();
1893 * \brief Skip a given Header Entry
1894 * \warning NOT end user intended method !
1897 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1899 SkipBytes(entry->GetLength());
1903 * \brief Skips to the begining of the next Header Entry
1904 * \warning NOT end user intended method !
1907 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1909 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1910 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1914 * \brief When the length of an element value is obviously wrong (because
1915 * the parser went Jabberwocky) one can hope improving things by
1916 * applying some heuristics.
1918 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1919 guint32 FoundLength)
1921 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1922 if ( FoundLength == 0xffffffff) {
1926 guint16 gr =Entry->GetGroup();
1927 guint16 el =Entry->GetElement();
1929 if (FoundLength%2) {
1930 std::ostringstream s;
1931 s << "Warning : Tag with uneven length "
1933 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1934 dbg.Verbose(0, s.str().c_str());
1937 //////// Fix for some naughty General Electric images.
1938 // Allthough not recent many such GE corrupted images are still present
1939 // on Creatis hard disks. Hence this fix shall remain when such images
1940 // are no longer in user (we are talking a few years, here)...
1941 // Note: XMedCom probably uses such a trick since it is able to read
1942 // those pesky GE images ...
1943 if (FoundLength == 13) { // Only happens for this length !
1944 if ( (Entry->GetGroup() != 0x0008)
1945 || ( (Entry->GetElement() != 0x0070)
1946 && (Entry->GetElement() != 0x0080) ) )
1949 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1953 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1954 // Occurence of such images is quite low (unless one leaves close to a
1955 // 'Leonardo' source. Hence, one might consider commenting out the
1956 // following fix on efficiency reasons.
1958 if ( (Entry->GetGroup() == 0x0009)
1959 && ( (Entry->GetElement() == 0x1113)
1960 || (Entry->GetElement() == 0x1114) ) )
1963 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1966 //////// Deal with sequences, but only on users request:
1968 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1970 FoundLength = 0; // ReadLength is unchanged
1973 //////// We encountered a 'delimiter' element i.e. a tag of the form
1974 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1975 // taken into account.
1977 if(Entry->GetGroup() == 0xfffe)
1979 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1980 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1981 // causes extra troubles...
1982 if( Entry->GetElement() != 0x0000 )
1988 Entry->SetUsableLength(FoundLength);
1992 * \brief Apply some heuristics to predict whether the considered
1993 * element value contains/represents an integer or not.
1994 * @param Entry The element value on which to apply the predicate.
1995 * @return The result of the heuristical predicate.
1997 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1998 guint16 element = Entry->GetElement();
1999 guint16 group = Entry->GetGroup();
2000 std::string vr = Entry->GetVR();
2001 guint32 length = Entry->GetLength();
2003 // When we have some semantics on the element we just read, and if we
2004 // a priori know we are dealing with an integer, then we shall be
2005 // able to swap it's element value properly.
2006 if ( element == 0 ) // This is the group length of the group
2012 // Allthough this should never happen, still some images have a
2013 // corrupted group length [e.g. have a glance at offset x(8336) of
2014 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2015 // Since for dicom compliant and well behaved headers, the present
2016 // test is useless (and might even look a bit paranoid), when we
2017 // encounter such an ill-formed image, we simply display a warning
2018 // message and proceed on parsing (while crossing fingers).
2019 std::ostringstream s;
2020 int filePosition = ftell(fp);
2021 s << "Erroneous Group Length element length on : (" \
2022 << std::hex << group << " , " << element
2023 << ") -before- position x(" << filePosition << ")"
2024 << "lgt : " << length;
2025 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2029 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2036 * \brief Find the Length till the next sequence delimiter
2037 * \warning NOT end user intended method !
2041 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2042 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2045 long PositionOnEntry = ftell(fp);
2046 bool FoundSequenceDelimiter = false;
2047 guint32 TotalLength = 0;
2050 while ( ! FoundSequenceDelimiter)
2056 TotalLength += 4; // We even have to decount the group and element
2058 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2060 char msg[100]; // for sprintf. Sorry
2061 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2062 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2066 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2067 FoundSequenceDelimiter = true;
2068 else if ( n != 0xe000 )
2070 char msg[100]; // for sprintf. Sorry
2071 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2073 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2077 ItemLength = ReadInt32();
2078 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2079 // the ItemLength with ReadInt32
2080 SkipBytes(ItemLength);
2082 fseek(fp, PositionOnEntry, SEEK_SET);
2087 * \brief Reads a supposed to be 16 Bits integer
2088 * (swaps it depending on processor endianity)
2089 * @return read value
2091 guint16 gdcmDocument::ReadInt16() {
2094 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2095 if ( item_read != 1 ) {
2097 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2107 * \brief Reads a supposed to be 32 Bits integer
2108 * (swaps it depending on processor endianity)
2109 * @return read value
2111 guint32 gdcmDocument::ReadInt32() {
2114 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2115 if ( item_read != 1 ) {
2117 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2127 * \brief skips bytes inside the source file
2128 * \warning NOT end user intended method !
2131 void gdcmDocument::SkipBytes(guint32 NBytes) {
2132 //FIXME don't dump the returned value
2133 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2137 * \brief Loads all the needed Dictionaries
2138 * \warning NOT end user intended method !
2140 void gdcmDocument::Initialise(void)
2142 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2147 * \brief Discover what the swap code is (among little endian, big endian,
2148 * bad little endian, bad big endian).
2150 * @return false when we are absolutely sure
2151 * it's neither ACR-NEMA nor DICOM
2152 * true when we hope ours assuptions are OK
2154 bool gdcmDocument::CheckSwap() {
2156 // The only guaranted way of finding the swap code is to find a
2157 // group tag since we know it's length has to be of four bytes i.e.
2158 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2159 // occurs when we can't find such group...
2161 guint32 x=4; // x : for ntohs
2162 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2168 char deb[HEADER_LENGTH_TO_READ];
2170 // First, compare HostByteOrder and NetworkByteOrder in order to
2171 // determine if we shall need to swap bytes (i.e. the Endian type).
2177 // The easiest case is the one of a DICOM header, since it possesses a
2178 // file preamble where it suffice to look for the string "DICM".
2179 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2182 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2183 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2185 // Next, determine the value representation (VR). Let's skip to the
2186 // first element (0002, 0000) and check there if we find "UL"
2187 // - or "OB" if the 1st one is (0002,0001) -,
2188 // in which case we (almost) know it is explicit VR.
2189 // WARNING: if it happens to be implicit VR then what we will read
2190 // is the length of the group. If this ascii representation of this
2191 // length happens to be "UL" then we shall believe it is explicit VR.
2192 // FIXME: in order to fix the above warning, we could read the next
2193 // element value (or a couple of elements values) in order to make
2194 // sure we are not commiting a big mistake.
2195 // We need to skip :
2196 // * the 128 bytes of File Preamble (often padded with zeroes),
2197 // * the 4 bytes of "DICM" string,
2198 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2199 // i.e. a total of 136 bytes.
2203 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2204 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2205 // *Implicit* VR. -and it is !-
2207 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2208 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2209 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2210 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2211 // when Write DCM *adds*
2213 // Use gdcmDocument::dicom_vr to test all the possibilities
2214 // instead of just checking for UL, OB and UI !? group 0000
2216 Filetype = gdcmExplicitVR;
2217 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2218 "explicit Value Representation");
2222 Filetype = gdcmImplicitVR;
2223 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2224 "not an explicit Value Representation");
2230 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2231 "HostByteOrder != NetworkByteOrder");
2236 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2237 "HostByteOrder = NetworkByteOrder");
2240 // Position the file position indicator at first tag (i.e.
2241 // after the file preamble and the "DICM" string).
2243 fseek (fp, 132L, SEEK_SET);
2247 // Alas, this is not a DicomV3 file and whatever happens there is no file
2248 // preamble. We can reset the file position indicator to where the data
2249 // is (i.e. the beginning of the file).
2250 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2253 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2254 // By clean we mean that the length of the first tag is written down.
2255 // If this is the case and since the length of the first group HAS to be
2256 // four (bytes), then determining the proper swap code is straightforward.
2259 // We assume the array of char we are considering contains the binary
2260 // representation of a 32 bits integer. Hence the following dirty
2262 s32 = *((guint32 *)(entCur));
2283 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2284 // It is time for despaired wild guesses.
2285 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2286 // i.e. the 'group length' element is not present :
2288 // check the supposed to be 'group number'
2289 // 0x0002 or 0x0004 or 0x0008
2290 // to determine ' sw' value .
2291 // Only 0 or 4321 will be possible
2292 // (no oportunity to check for the formerly well known
2293 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2294 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2295 // the file IS NOT ACR-NEMA nor DICOM V3
2296 // Find a trick to tell it the caller...
2298 s16 = *((guint16 *)(deb));
2314 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2315 "ACR/NEMA unfound swap info (Really hopeless !)");
2316 Filetype = gdcmUnknown;
2320 // Then the only info we have is the net2host one.
2330 * \brief Restore the unproperly loaded values i.e. the group, the element
2331 * and the dictionary entry depending on them.
2333 void gdcmDocument::SwitchSwapToBigEndian(void)
2335 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2336 "Switching to BigEndian mode.");
2357 * \brief during parsing, Header Elements too long are not loaded in memory
2360 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2364 if ((guint32)NewSize >= (guint32)0xffffffff)
2366 MaxSizeLoadEntry = 0xffffffff;
2369 MaxSizeLoadEntry = NewSize;
2374 * \brief Header Elements too long will not be printed
2375 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2378 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2382 if ((guint32)NewSize >= (guint32)0xffffffff)
2384 MaxSizePrintEntry = 0xffffffff;
2387 MaxSizePrintEntry = NewSize;
2393 * \brief Read the next tag but WITHOUT loading it's value
2394 * (read the 'Group Number', the 'Element Number',
2395 * gets the Dict Entry
2396 * gets the VR, gets the length, gets the offset value)
2397 * @return On succes the newly created DocEntry, NULL on failure.
2399 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2401 gdcmDocEntry *NewEntry;
2406 // We reached the EOF (or an error occured) therefore
2407 // header parsing has to be considered as finished.
2408 return (gdcmDocEntry *)0;
2410 NewEntry = NewDocEntryByNumber(g, n);
2411 FindDocEntryVR(NewEntry);
2412 FindDocEntryLength(NewEntry);
2419 NewEntry->SetOffset(ftell(fp));
2425 * \brief Generate a free TagKey i.e. a TagKey that is not present
2426 * in the TagHt dictionary.
2427 * @param group The generated tag must belong to this group.
2428 * @return The element of tag with given group which is fee.
2430 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2432 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2434 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2435 if (tagHT.count(key) == 0)
2443 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2444 * is placed at the beginning of a tag (TestGroup, TestElement),
2445 * read the length associated to the Tag.
2446 * \warning On success the internal file pointer \ref gdcmDocument::fp
2447 * is modified to point after the tag and it's length.
2448 * On failure (i.e. when the tag wasn't the expected tag
2449 * (TestGroup, TestElement) the internal file pointer
2450 * \ref gdcmDocument::fp is restored to it's original position.
2451 * @param TestGroup The expected group of the tag.
2452 * @param TestElement The expected Element of the tag.
2453 * @return On success returns the length associated to the tag. On failure
2456 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2458 guint16 ItemTagGroup;
2459 guint16 ItemTagElement;
2460 long PositionOnEntry = ftell(fp);
2461 long CurrentPosition = ftell(fp); // On debugging purposes
2463 //// Read the Item Tag group and element, and make
2464 // sure they are respectively 0xfffe and 0xe000:
2465 ItemTagGroup = ReadInt16();
2466 ItemTagElement = ReadInt16();
2467 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2469 std::ostringstream s;
2470 s << " We should have found tag (";
2471 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2472 s << " but instead we encountered tag (";
2473 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2475 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2476 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2477 dbg.Verbose(0, s.str().c_str());
2478 fseek(fp, PositionOnEntry, SEEK_SET);
2482 //// Then read the associated Item Length
2483 CurrentPosition=ftell(fp);
2485 ItemLength = ReadInt32();
2487 std::ostringstream s;
2488 s << "Basic Item Length is: "
2489 << ItemLength << std::endl;
2490 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2491 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2497 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2498 * \sa \ref gdcmDocument::ReadTagLength
2499 * \warning See warning of \ref gdcmDocument::ReadTagLength
2500 * @return On success returns the length associated to the item tag.
2501 * On failure returns 0.
2503 guint32 gdcmDocument::ReadItemTagLength(void)
2505 return ReadTagLength(0xfffe, 0xe000);
2509 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2511 * \sa \ref gdcmDocument::ReadTagLength
2512 * \warning See warning of \ref gdcmDocument::ReadTagLength
2513 * @return On success returns the length associated to the Sequence
2514 * Delimiter tag. On failure returns 0.
2516 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2518 return ReadTagLength(0xfffe, 0xe0dd);
2523 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2524 * No other way so 'skip' the Data
2528 void gdcmDocument::Parse7FE0 (void)
2530 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2534 if ( IsImplicitVRLittleEndianTransferSyntax()
2535 || IsExplicitVRLittleEndianTransferSyntax()
2536 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2537 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2540 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2542 //// Read the Basic Offset Table Item Tag length...
2543 guint32 ItemLength = ReadItemTagLength();
2545 //// ... and then read length[s] itself[themselves]. We don't use
2546 // the values read (BTW what is the purpous of those lengths ?)
2547 if (ItemLength != 0) {
2548 // BTW, what is the purpous of those length anyhow !?
2549 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2550 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2551 for (unsigned int i=0; i < ItemLength; i += 4){
2552 guint32 IndividualLength;
2553 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2554 std::ostringstream s;
2555 s << " Read one length: ";
2556 s << std::hex << IndividualLength << std::endl;
2557 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2561 if ( ! IsRLELossLessTransferSyntax() )
2565 //// We then skip (not reading them) all the fragments of images:
2566 while ( (ItemLength = ReadItemTagLength()) )
2568 SkipBytes(ItemLength);
2576 long RleSegmentLength[15], fragmentLength;
2578 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2579 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2581 // Parse fragments of the current Fragment (Frame)
2582 //------------------ scanning (not reading) fragment pixels
2583 guint32 nbRleSegments = ReadInt32();
2584 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2586 //// Reading RLE Segments Offset Table
2587 guint32 RleSegmentOffsetTable[15];
2588 for(int k=1; k<=15; k++) {
2590 RleSegmentOffsetTable[k] = ReadInt32();
2591 printf(" at : %x Offset Segment %d : %d (%x)\n",
2592 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2593 RleSegmentOffsetTable[k]);
2596 // skipping (not reading) RLE Segments
2597 if (nbRleSegments>1) {
2598 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2599 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2600 - RleSegmentOffsetTable[k];
2602 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2603 k,(unsigned)RleSegmentLength[k],
2604 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2605 SkipBytes(RleSegmentLength[k]);
2609 RleSegmentLength[nbRleSegments]= fragmentLength
2610 - RleSegmentOffsetTable[nbRleSegments];
2612 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2613 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2614 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2615 SkipBytes(RleSegmentLength[nbRleSegments]);
2623 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2624 * \warning Does NOT work with ACR-NEMA files
2625 * \todo Find a trick to solve the pb (use RET fields ?)
2627 * @return true if 'smaller'
2629 bool gdcmDocument::operator<(gdcmDocument &document)
2634 s1=this->GetEntryByNumber(0x0010,0x0010);
2635 s2=document.GetEntryByNumber(0x0010,0x0010);
2643 s1=this->GetEntryByNumber(0x0010,0x0020);
2644 s2=document.GetEntryByNumber(0x0010,0x0020);
2651 // Study Instance UID
2652 s1=this->GetEntryByNumber(0x0020,0x000d);
2653 s2=document.GetEntryByNumber(0x0020,0x000d);
2660 // Serie Instance UID
2661 s1=this->GetEntryByNumber(0x0020,0x000e);
2662 s2=document.GetEntryByNumber(0x0020,0x000e);
2674 //-----------------------------------------------------------------------------