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 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
26 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
27 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
28 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
29 #define UI1_1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
31 #define str2num(str, typeNum) *((typeNum *)(str))
33 //-----------------------------------------------------------------------------
34 // Refer to gdcmDocument::CheckSwap()
35 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
37 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
38 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
40 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
47 * @param inFilename file to be opened for parsing
48 * @param exception_on_error whether we throw an exception or not
49 * @param enable_sequences = true to allow the header
50 * to be parsed *inside* the SeQuences,
51 * when they have an actual length
52 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
53 * @param ignore_shadow to allow skipping the shadow elements,
54 * to save memory space.
55 * \warning The TRUE value for this param has to be used
56 * with a FALSE value for the 'enable_sequence' param.
57 * ('public elements' may be embedded in 'shadow Sequences')
59 gdcmDocument::gdcmDocument(const char *inFilename,
60 bool exception_on_error,
61 bool enable_sequences,
63 : gdcmElementSet(-1) {
64 enableSequences=enable_sequences;
65 ignoreShadow =ignore_shadow;
67 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
68 filename = inFilename;
71 if ( !OpenFile(exception_on_error))
76 // return false; // to go on compiling
78 fseek(fp,0L,SEEK_END);
88 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
91 // --------------------------------------------------------------
92 // Special Patch to allow gdcm to read ACR-LibIDO formated images
94 // if recognition code tells us we deal with a LibIDO image
95 // we switch lineNumber and columnNumber
98 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
99 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
100 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
101 // with "little-endian strings"
103 filetype = gdcmACR_LIBIDO;
104 std::string rows = GetEntryByNumber(0x0028, 0x0010);
105 std::string columns = GetEntryByNumber(0x0028, 0x0011);
106 SetEntryByNumber(columns, 0x0028, 0x0010);
107 SetEntryByNumber(rows , 0x0028, 0x0011);
109 // ----------------- End of Special Patch ----------------
111 printLevel = 1; // 'Medium' print level by default
116 * @param exception_on_error
118 gdcmDocument::gdcmDocument(bool exception_on_error)
119 :gdcmElementSet(-1) {
120 (void)exception_on_error;
123 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
126 printLevel = 1; // 'Medium' print level by default
130 * \brief Canonical destructor.
132 gdcmDocument::~gdcmDocument (void) {
137 //-----------------------------------------------------------------------------
143 * \brief Prints The Dict Entries of THE public Dicom Dictionary
146 void gdcmDocument::PrintPubDict(std::ostream & os) {
147 RefPubDict->Print(os);
151 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
154 void gdcmDocument::PrintShaDict(std::ostream & os) {
155 RefShaDict->Print(os);
158 //-----------------------------------------------------------------------------
161 * \brief Get the public dictionary used
163 gdcmDict *gdcmDocument::GetPubDict(void) {
168 * \brief Get the shadow dictionary used
170 gdcmDict *gdcmDocument::GetShaDict(void) {
175 * \brief Set the shadow dictionary used
176 * \param dict dictionary to use in shadow
178 bool gdcmDocument::SetShaDict(gdcmDict *dict){
184 * \brief Set the shadow dictionary used
185 * \param dictName name of the dictionary to use in shadow
187 bool gdcmDocument::SetShaDict(DictKey dictName){
188 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
193 * \brief This predicate, based on hopefully reasonable heuristics,
194 * decides whether or not the current gdcmDocument was properly parsed
195 * and contains the mandatory information for being considered as
196 * a well formed and usable Dicom/Acr File.
197 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
200 bool gdcmDocument::IsReadable(void) {
201 if(filetype==gdcmUnknown) {
202 std::cout << "wrong filetype" <<std::endl;
205 if(!tagHT.empty()<=0) {
206 std::cout << "wrong tagHT size "<< tagHT.size() <<std::endl;
214 * \brief Determines if the Transfer Syntax was already encountered
215 * and if it corresponds to a ImplicitVRLittleEndian one.
216 * @return True when ImplicitVRLittleEndian found. False in all other cases.
218 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
219 gdcmDocEntry *Element = GetDocEntryByNumber(0x0002, 0x0010);
222 LoadDocEntrySafe(Element);
224 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
225 if ( Transfer == UI1_2_840_10008_1_2 )
231 * \brief Determines if the Transfer Syntax was already encountered
232 * and if it corresponds to a ExplicitVRLittleEndian one.
233 * @return True when ExplicitVRLittleEndian found. False in all other cases.
235 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
236 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
239 LoadDocEntrySafe(Element);
241 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
242 if ( Transfer == UI1_2_840_10008_1_2_1 )
248 * \brief Determines if the Transfer Syntax was already encountered
249 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
250 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
252 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
253 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
256 LoadDocEntrySafe(Element);
258 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
259 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
265 * \brief Determines if the Transfer Syntax was already encountered
266 * and if it corresponds to a Explicit VR Big Endian one.
267 * @return True when big endian found. False in all other cases.
269 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
270 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
273 LoadDocEntrySafe(Element);
275 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
276 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
282 * \brief returns the File Type
283 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
284 * @return the FileType code
286 FileType gdcmDocument::GetFileType(void) {
291 * \brief opens the file
292 * @param exception_on_error
295 FILE *gdcmDocument::OpenFile(bool exception_on_error)
298 fp=fopen(filename.c_str(),"rb");
299 if(exception_on_error)
302 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
308 fread(&zero, (size_t)2, (size_t)1, fp);
310 //ACR -- or DICOM with no Preamble --
311 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
315 fseek(fp, 126L, SEEK_CUR);
317 fread(dicm, (size_t)4, (size_t)1, fp);
318 if( memcmp(dicm, "DICM", 4) == 0 )
322 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
325 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
331 * \brief closes the file
332 * @return TRUE if the close was successfull
334 bool gdcmDocument::CloseFile(void) {
335 int closed = fclose(fp);
343 * \brief Writes in a file all the Header Entries (Dicom Elements)
344 * of the Chained List
345 * @param fp file pointer on an already open file
346 * @param type Type of the File to be written
347 * (ACR-NEMA, ExplicitVR, ImplicitVR)
348 * \return Always true.
350 bool gdcmDocument::Write(FILE *fp, FileType type) {
353 /// The stuff will have to be rewritten using the SeQuence based
354 /// tree-like stucture instead of the chained list .
355 /// (so we shall remove the Group*HT from the gdcmDocument)
359 /// \todo move the following lines (and a lot of others, to be written)
360 /// to a future function CheckAndCorrectHeader
364 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
365 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
366 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
368 /// a moins de se livrer a un tres complique ajout des champs manquants.
369 /// faire un CheckAndCorrectHeader (?)
371 if (type == gdcmImplicitVR)
373 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
374 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
376 /// \todo Refer to standards on page 21, chapter 6.2
377 /// "Value representation": values with a VR of UI shall be
378 /// padded with a single trailing null
379 /// Dans le cas suivant on doit pader manuellement avec un 0
381 SetEntryLengthByNumber(18, 0x0002, 0x0010);
384 if (type == gdcmExplicitVR)
386 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
387 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
389 /// \todo Refer to standards on page 21, chapter 6.2
390 /// "Value representation": values with a VR of UI shall be
391 /// padded with a single trailing null
392 /// Dans le cas suivant on doit pader manuellement avec un 0
394 SetEntryLengthByNumber(20, 0x0002, 0x0010);
398 * \todo rewrite later, if really usefull
400 * --> Warning : un-updated odd groups lengths can causes pb
401 * --> (xmedcon breaks)
402 * --> to be re- written with future org.
404 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
405 * UpdateGroupLength(false,type);
407 * UpdateGroupLength(true,ACR);
410 WriteEntries(fp,type);
415 * \brief Modifies the value of a given Header Entry (Dicom Element)
416 * when it exists. Create it with the given value when unexistant.
417 * @param Value Value to be set
418 * @param Group Group number of the Entry
419 * @param Elem Element number of the Entry
420 * \return pointer to the modified/created Header Entry (NULL when creation
425 gdcmDocEntry * gdcmDocument::ReplaceOrCreateByNumber(
430 a = GetDocEntryByNumber( Group, Elem);
432 a =NewDocEntryByNumber(Group, Elem);
437 SetEntryByNumber(Value, Group, Elem);
438 //a->SetValue(Value);
443 * \brief Set a new value if the invoked element exists
444 * Seems to be useless !!!
445 * @param Value new element value
446 * @param Group group number of the Entry
447 * @param Elem element number of the Entry
450 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
452 std::string v = Value;
453 SetEntryByNumber(v, Group, Elem);
457 //-----------------------------------------------------------------------------
461 * \brief Checks if a given Dicom Element exists within the H table
462 * @param group Group number of the searched Dicom Element
463 * @param element Element number of the searched Dicom Element
464 * @return number of occurences
466 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
467 std::string key = gdcmDictEntry::TranslateToKey(group, element );
468 return (tagHT.count(key));
472 * \brief Searches within Header Entries (Dicom Elements) parsed with
473 * the public and private dictionaries
474 * for the element value of a given tag.
475 * \warning Don't use any longer : use GetPubEntryByName
476 * @param tagName name of the searched element.
477 * @return Corresponding element value when it exists,
478 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
480 std::string gdcmDocument::GetEntryByName(std::string tagName) {
481 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
482 if( dictEntry == NULL)
485 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
489 * \brief Searches within Header Entries (Dicom Elements) parsed with
490 * the public and private dictionaries
491 * for the element value representation of a given tag.
493 * Obtaining the VR (Value Representation) might be needed by caller
494 * to convert the string typed content to caller's native type
495 * (think of C++ vs Python). The VR is actually of a higher level
496 * of semantics than just the native C++ type.
497 * @param tagName name of the searched element.
498 * @return Corresponding element value representation when it exists,
499 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
501 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
502 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
503 if( dictEntry == NULL)
506 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
507 dictEntry->GetElement());
508 return elem->GetVR();
513 * \brief Searches within Header Entries (Dicom Elements) parsed with
514 * the public and private dictionaries
515 * for the element value representation of a given tag.
516 * @param group Group number of the searched tag.
517 * @param element Element number of the searched tag.
518 * @return Corresponding element value representation when it exists,
519 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
521 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
522 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
523 if ( ! tagHT.count(key))
525 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
529 * \brief Searches within Header Entries (Dicom Elements) parsed with
530 * the public and private dictionaries
531 * for the element value representation of a given tag..
533 * Obtaining the VR (Value Representation) might be needed by caller
534 * to convert the string typed content to caller's native type
535 * (think of C++ vs Python). The VR is actually of a higher level
536 * of semantics than just the native C++ type.
537 * @param group Group number of the searched tag.
538 * @param element Element number of the searched tag.
539 * @return Corresponding element value representation when it exists,
540 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
542 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
543 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
546 return elem->GetVR();
550 * \brief Searches within Header Entries (Dicom Elements) parsed with
551 * the public and private dictionaries
552 * for the value length of a given tag..
553 * @param group Group number of the searched tag.
554 * @param element Element number of the searched tag.
555 * @return Corresponding element length; -2 if not found
557 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
558 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
561 return elem->GetLength();
564 * \brief Sets the value (string) of the Header Entry (Dicom Element)
565 * @param content string value of the Dicom Element
566 * @param tagName name of the searched Dicom Element.
567 * @return true when found
569 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
570 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
571 if( dictEntry == NULL)
574 return(SetEntryByNumber(content,dictEntry->GetGroup(),
575 dictEntry->GetElement()));
579 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
580 * through it's (group, element) and modifies it's content with
582 * @param content new value to substitute with
583 * @param group group number of the Dicom Element to modify
584 * @param element element number of the Dicom Element to modify
586 bool gdcmDocument::SetEntryByNumber(std::string content,
590 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
591 if ( ! tagHT.count(key))
593 int l = content.length();
594 if(l%2) // Non even length are padded with a space (020H).
597 content = content + '\0';
603 ((gdcmValEntry*)a)->SetValue(content);
605 std::string vr = a->GetVR();
608 if( (vr == "US") || (vr == "SS") )
610 else if( (vr == "UL") || (vr == "SL") )
620 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
621 * in the PubDocEntrySet of this instance
622 * through it's (group, element) and modifies it's length with
624 * \warning Use with extreme caution.
625 * @param l new length to substitute with
626 * @param group group number of the Entry to modify
627 * @param element element number of the Entry to modify
628 * @return true on success, false otherwise.
630 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
634 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
635 if ( ! tagHT.count(key))
637 if (l%2) l++; // length must be even
638 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
644 * \brief Gets (from Header) the offset of a 'non string' element value
645 * (LoadElementValues has already be executed)
646 * @param Group group number of the Entry
647 * @param Elem element number of the Entry
648 * @return File Offset of the Element Value
650 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
652 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
655 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
656 "failed to Locate gdcmDocEntry");
659 return Entry->GetOffset();
663 * \brief Gets (from Header) a 'non string' element value
664 * (LoadElementValues has already be executed)
665 * @param Group group number of the Entry
666 * @param Elem element number of the Entry
667 * @return Pointer to the 'non string' area
669 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
671 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
674 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
675 "failed to Locate gdcmDocEntry");
678 return ((gdcmBinEntry *)Entry)->GetVoidArea();
682 * \brief Loads (from disk) the element content
683 * when a string is not suitable
684 * @param Group group number of the Entry
685 * @param Elem element number of the Entry
687 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
689 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
692 size_t o =(size_t)Element->GetOffset();
693 fseek(fp, o, SEEK_SET);
694 size_t l=Element->GetLength();
695 char* a = new char[l];
699 SetEntryVoidAreaByNumber(a, Group, Elem);
700 /// \todo check the result
701 size_t l2 = fread(a, 1, l ,fp);
712 * \brief Sets a 'non string' value to a given Dicom Element
714 * @param group Group number of the searched Dicom Element
715 * @param element Element number of the searched Dicom Element
718 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
722 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
723 if ( ! tagHT.count(key))
725 // This was for multimap ?
726 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
732 * \brief Update the entries with the shadow dictionary.
733 * Only non even entries are analyzed
735 void gdcmDocument::UpdateShaEntries(void) {
736 gdcmDictEntry *entry;
739 // TODO : if still any use (?) explore recursively the whole structure
741 for(ListTag::iterator it=listEntries.begin();
742 it!=listEntries.end();
745 // Odd group => from public dictionary
746 if((*it)->GetGroup()%2==0)
749 // Peer group => search the corresponding dict entry
751 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
755 if((*it)->IsImplicitVR())
760 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
762 // Set the new entry and the new value
763 (*it)->SetDictEntry(entry);
764 CheckDocEntryVR(*it,vr);
766 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
771 // Remove precedent value transformation
772 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
779 * \brief Searches within the Header Entries for a Dicom Element of
781 * @param tagName name of the searched Dicom Element.
782 * @return Corresponding Dicom Element when it exists, and NULL
785 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
786 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
787 if( dictEntry == NULL)
790 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
794 * \brief retrieves a Dicom Element (the first one) using (group, element)
795 * \warning (group, element) IS NOT an identifier inside the Dicom Header
796 * if you think it's NOT UNIQUE, check the count number
797 * and use iterators to retrieve ALL the Dicoms Elements within
798 * a given couple (group, element)
799 * @param group Group number of the searched Dicom Element
800 * @param element Element number of the searched Dicom Element
803 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
805 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
806 if ( ! tagHT.count(key))
808 return tagHT.find(key)->second;
812 * \brief Loads the element while preserving the current
813 * underlying file position indicator as opposed to
814 * to LoadDocEntry that modifies it.
815 * @param entry Header Entry whose value shall be loaded.
818 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
819 long PositionOnEntry = ftell(fp);
821 fseek(fp, PositionOnEntry, SEEK_SET);
826 * \brief Writes in a file (according to the requested format)
827 * the group, the element, the value representation and the length
828 * of a single gdcmDocEntry passed as argument.
829 * @param tag pointer on the gdcmDocEntry to be written
830 * @param _fp already open file pointer
831 * @param type type of the File to be written
833 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
837 guint16 group = tag->GetGroup();
838 std::string vr = tag->GetVR();
839 guint16 el = tag->GetElement();
840 guint32 lgr = tag->GetReadLength();
842 if ( (group == 0xfffe) && (el == 0x0000) )
843 // Fix in order to make some MR PHILIPS images e-film readable
844 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
845 // we just *always* ignore spurious fffe|0000 tag !
848 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
849 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
851 if ( type == gdcmExplicitVR ) {
853 // Special case of delimiters:
854 if (group == 0xfffe) {
855 // Delimiters have NO Value Representation and have NO length.
856 // Hence we skip writing the VR and length and we pad by writing
860 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
865 guint16 shortLgr = lgr;
866 if (vr == "unkn") { // Unknown was 'written'
867 // deal with Little Endian
868 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
869 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
871 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
872 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
874 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
875 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
877 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
883 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
888 * \brief Writes in a file (according to the requested format)
889 * the value of a single gdcmDocEntry passed as argument.
890 * @param tag Pointer on the gdcmDocEntry to be written
891 * @param _fp Already open file pointer
892 * @param type type of the File to be written
895 // TODO : to be re -written recursively !
897 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
900 guint16 group = tag->GetGroup();
901 std::string vr = tag->GetVR();
902 guint32 lgr = tag->GetReadLength();
905 // SeQuences have no value:
908 // Delimiters have no associated value:
911 //--------------------------------
915 // -------------------------------
918 /* // to go on compiling
920 voidArea = tag->GetVoidArea(); // to go on compiling
921 if (voidArea != NULL)
922 { // there is a 'non string' LUT, overlay, etc
923 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
927 if (vr == "US" || vr == "SS")
929 // some 'Short integer' fields may be mulivaluated
930 // each single value is separated from the next one by '\'
931 // we split the string and write each value as a short int
932 std::vector<std::string> tokens;
933 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
934 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
935 for (unsigned int i=0; i<tokens.size();i++)
937 guint16 val_uint16 = atoi(tokens[i].c_str());
938 void *ptr = &val_uint16;
939 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
944 // some 'Integer' fields may be mulivaluated
945 // each single value is separated from the next one by '\'
946 // we split the string and write each value as an int
947 if (vr == "UL" || vr == "SL")
949 std::vector<std::string> tokens;
950 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
951 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
952 for (unsigned int i=0; i<tokens.size();i++)
954 guint32 val_uint32 = atoi(tokens[i].c_str());
955 void *ptr = &val_uint32;
956 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
961 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
965 * \brief Writes in a file (according to the requested format)
966 * a single gdcmDocEntry passed as argument.
967 * \sa WriteEntryValue, WriteEntryTagVRLength.
968 * @param tag Pointer on the gdcmDocEntry to be written
969 * @param _fp Already open file pointer
970 * @param type type of the File to be written
973 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
975 guint32 length = tag->GetLength();
976 gdcmValEntry * Vtag = (gdcmValEntry *) tag;
977 std::cout << "gdcmDocument::WriteEntry Vtag->GetValue() " << Vtag->GetValue() << std::endl;
978 // The value of a tag MUST (see the DICOM norm) be an odd number of
979 // bytes. When this is not the case, pad with an additional byte:
982 Vtag->SetValue(Vtag->GetValue()+"\0");
983 Vtag->SetLength(Vtag->GetReadLength()+1);
986 WriteEntryTagVRLength(Vtag, _fp, type);
987 std::cout << "after WriteEntryTagVRLength " << std::endl;
988 WriteEntryValue(Vtag, _fp, type);
989 std::cout << "after WriteEntryValue " << std::endl;
994 * \brief writes on disc according to the requested format
995 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
996 * using the Chained List
997 * \warning does NOT add the missing elements in the header :
998 * it's up to the user doing it !
999 * (function CheckHeaderCoherence to be written)
1000 * \warning DON'T try, right now, to write a DICOM image
1001 * from an ACR Header (meta elements will be missing!)
1002 * @param type type of the File to be written
1003 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1004 * @param _fp already open file pointer
1007 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1010 // FIXME : explore recursively the whole structure...
1012 /// \todo (?) check write failures (after *each* fwrite)
1014 std::cout << "--------------------- gdcmDocument::WriteEntries " << std::endl;
1015 for (TagDocEntryHT::iterator tag2=tagHT.begin();
1016 tag2 != tagHT.end();
1020 (*tag2).second->Print();
1022 if ( type == gdcmACR ){
1023 if ((*tag2).second->GetGroup() < 0x0008)
1024 // Ignore pure DICOM V3 groups
1026 if ((*tag2).second->GetGroup() %2)
1027 // Ignore the "shadow" groups
1029 if ((*tag2).second->GetVR() == "SQ" ) // ignore Sequences
1031 //if ((*tag2).second->GetDepthLevel() != 0) // Not only ignore the SQ element
1034 if (! WriteEntry((*tag2).second,_fp,type) ) {
1035 std::cout << "Write Failure " << std::endl;
1046 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1048 * @return The properly swaped 32 bits integer.
1050 guint32 gdcmDocument::SwapLong(guint32 a) {
1055 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1056 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1060 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1064 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1067 std::cout << "swapCode= " << sw << std::endl;
1068 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1075 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1077 * @return The properly unswaped 32 bits integer.
1079 guint32 gdcmDocument::UnswapLong(guint32 a) {
1080 return (SwapLong(a));
1084 * \brief Swaps the bytes so they agree with the processor order
1085 * @return The properly swaped 16 bits integer.
1087 guint16 gdcmDocument::SwapShort(guint16 a) {
1088 if ( (sw==4321) || (sw==2143) )
1089 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1094 * \brief Unswaps the bytes so they agree with the processor order
1095 * @return The properly unswaped 16 bits integer.
1097 guint16 gdcmDocument::UnswapShort(guint16 a) {
1098 return (SwapShort(a));
1101 //-----------------------------------------------------------------------------
1105 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1106 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1109 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1111 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1119 depth = set->GetDepthLevel();
1122 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1125 NewDocEntry = ReadNextDocEntry( );
1129 vr = NewDocEntry->GetVR();
1132 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1135 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1136 vl->Copy(NewDocEntry);
1137 vl->SetDepthLevel(depth);
1140 if (/*!delim_mode && */vl->isItemDelimitor())
1142 if ( !delim_mode && ftell(fp)-offset >= l_max)
1149 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1151 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1152 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1153 "nor BinEntry. Probably unknown VR.");
1156 ////// BinEntry or UNKOWN VR:
1157 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1158 bn->Copy(NewDocEntry);
1163 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1164 NewDocEntry->GetElement() == 0x0010 )
1166 if (NewDocEntry->GetLength()==0xffffffff)
1167 // Broken US.3405.1.dcm
1168 Parse7FE0(); // to skip the pixels
1169 // (multipart JPEG/RLE are trouble makers)
1173 // to be sure we are at the beginning
1174 SkipToNextDocEntry(NewDocEntry);
1175 l = NewDocEntry->GetFullLength();
1177 } else { // VR = "SQ"
1179 l=NewDocEntry->GetReadLength();
1180 if (l != 0) // don't mess the delim_mode for zero-length sequence
1181 if (l == 0xffffffff)
1185 // no other way to create it ...
1186 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1187 set->GetDepthLevel());
1188 sq->Copy(NewDocEntry);
1189 sq->SetDelimitorMode(delim_mode);
1190 sq->SetDepthLevel(depth);
1193 { // Don't try to parse zero-length sequences
1194 long lgt = ParseSQ( sq,
1195 NewDocEntry->GetOffset(),
1198 // FIXME : on en fait quoi, de lgt ?
1200 if ( !delim_mode && ftell(fp)-offset >= l_max)
1211 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1212 * @return parsed length for this level
1214 long gdcmDocument::ParseSQ(gdcmSeqEntry *set, long offset, long l_max, bool delim_mode) {
1215 int SQItemNumber = 0;
1216 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1220 int depth = set->GetDepthLevel();
1223 NewDocEntry = ReadNextDocEntry();
1225 if (NewDocEntry->isSequenceDelimitor()) {
1226 //add the Sequence Delimitor // TODO : find the trick to put it properly !
1227 set->SetSequenceDelimitationItem(NewDocEntry);
1231 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1234 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1235 itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1236 l= NewDocEntry->GetReadLength();
1243 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1245 set->AddEntry(itemSQ);
1246 SQItemNumber ++; // a voir
1247 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1251 lgth = ftell(fp) - offset;
1256 * \brief Loads the element content if its length doesn't exceed
1257 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1258 * @param Entry Header Entry (Dicom Element) to be dealt with
1260 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1262 guint16 group = Entry->GetGroup();
1263 std::string vr= Entry->GetVR();
1264 guint32 length = Entry->GetLength();
1266 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1268 // A SeQuence "contains" a set of Elements.
1269 // (fffe e000) tells us an Element is beginning
1270 // (fffe e00d) tells us an Element just ended
1271 // (fffe e0dd) tells us the current SeQuence just ended
1272 if( group == 0xfffe ) {
1273 // NO more value field for SQ !
1274 //Entry->SetValue("gdcm::Skipped");
1275 // appel recursif de Load Value
1276 // (meme pb que pour le parsing)
1280 // When the length is zero things are easy:
1281 if ( length == 0 ) {
1282 ((gdcmValEntry *)Entry)->SetValue("");
1286 // The elements whose length is bigger than the specified upper bound
1287 // are not loaded. Instead we leave a short notice of the offset of
1288 // the element content and it's length.
1289 if (length > MaxSizeLoadEntry) {
1290 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1292 std::ostringstream s;
1293 s << "gdcm::NotLoaded.";
1294 s << " Address:" << (long)Entry->GetOffset();
1295 s << " Length:" << Entry->GetLength();
1296 s << " x(" << std::hex << Entry->GetLength() << ")";
1297 ValEntryPtr->SetValue(s.str());
1299 // to be sure we are at the end of the value ...
1300 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1305 // Any compacter code suggested (?)
1306 if ( IsDocEntryAnInteger(Entry) ) {
1308 std::ostringstream s;
1310 // When short integer(s) are expected, read and convert the following
1311 // n *two characters properly i.e. as short integers as opposed to strings.
1312 // Elements with Value Multiplicity > 1
1313 // contain a set of integers (not a single one)
1314 if (vr == "US" || vr == "SS") {
1316 NewInt = ReadInt16();
1319 for (int i=1; i < nbInt; i++) {
1321 NewInt = ReadInt16();
1326 // When integer(s) are expected, read and convert the following
1327 // n * four characters properly i.e. as integers as opposed to strings.
1328 // Elements with Value Multiplicity > 1
1329 // contain a set of integers (not a single one)
1330 else if (vr == "UL" || vr == "SL") {
1332 NewInt = ReadInt32();
1335 for (int i=1; i < nbInt; i++) {
1337 NewInt = ReadInt32();
1342 #ifdef GDCM_NO_ANSI_STRING_STREAM
1343 s << std::ends; // to avoid oddities on Solaris
1344 #endif //GDCM_NO_ANSI_STRING_STREAM
1346 ((gdcmValEntry *)Entry)->SetValue(s.str());
1350 // We need an additional byte for storing \0 that is not on disk
1351 std::string NewValue(length,0);
1352 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1353 if ( item_read != 1 ) {
1354 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1355 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1359 if( (vr == "UI") ) // Because of correspondance with the VR dic
1360 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1362 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1367 * \brief Find the value Length of the passed Header Entry
1368 * @param Entry Header Entry whose length of the value shall be loaded.
1370 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1371 guint16 element = Entry->GetElement();
1372 //guint16 group = Entry->GetGroup(); //FIXME
1373 std::string vr = Entry->GetVR();
1377 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1379 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1381 // The following reserved two bytes (see PS 3.5-2001, section
1382 // 7.1.2 Data element structure with explicit vr p27) must be
1383 // skipped before proceeding on reading the length on 4 bytes.
1384 fseek(fp, 2L, SEEK_CUR);
1385 guint32 length32 = ReadInt32();
1387 if ( (vr == "OB") && (length32 == 0xffffffff) )
1389 Entry->SetLength(FindDocEntryLengthOB());
1392 FixDocEntryFoundLength(Entry, length32);
1396 // Length is encoded on 2 bytes.
1397 length16 = ReadInt16();
1399 // We can tell the current file is encoded in big endian (like
1400 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1401 // and it's value is the one of the encoding of a big endian file.
1402 // In order to deal with such big endian encoded files, we have
1403 // (at least) two strategies:
1404 // * when we load the "Transfer Syntax" tag with value of big endian
1405 // encoding, we raise the proper flags. Then we wait for the end
1406 // of the META group (0x0002) among which is "Transfer Syntax",
1407 // before switching the swap code to big endian. We have to postpone
1408 // the switching of the swap code since the META group is fully encoded
1409 // in little endian, and big endian coding only starts at the next
1410 // group. The corresponding code can be hard to analyse and adds
1411 // many additional unnecessary tests for regular tags.
1412 // * the second strategy consists in waiting for trouble, that shall
1413 // appear when we find the first group with big endian encoding. This
1414 // is easy to detect since the length of a "Group Length" tag (the
1415 // ones with zero as element number) has to be of 4 (0x0004). When we
1416 // encounter 1024 (0x0400) chances are the encoding changed and we
1417 // found a group with big endian encoding.
1418 // We shall use this second strategy. In order to make sure that we
1419 // can interpret the presence of an apparently big endian encoded
1420 // length of a "Group Length" without committing a big mistake, we
1421 // add an additional check: we look in the already parsed elements
1422 // for the presence of a "Transfer Syntax" whose value has to be "big
1423 // endian encoding". When this is the case, chances are we have got our
1424 // hands on a big endian encoded file: we switch the swap code to
1425 // big endian and proceed...
1426 if ( (element == 0x0000) && (length16 == 0x0400) )
1428 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1430 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1435 SwitchSwapToBigEndian();
1436 // Restore the unproperly loaded values i.e. the group, the element
1437 // and the dictionary entry depending on them.
1438 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1439 guint16 CorrectElem = SwapShort(Entry->GetElement());
1440 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1444 // This correct tag is not in the dictionary. Create a new one.
1445 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1447 // FIXME this can create a memory leaks on the old entry that be
1448 // left unreferenced.
1449 Entry->SetDictEntry(NewTag);
1452 // Heuristic: well some files are really ill-formed.
1453 if ( length16 == 0xffff)
1456 //dbg.Verbose(0, "gdcmDocument::FindLength",
1457 // "Erroneous element length fixed.");
1458 // Actually, length= 0xffff means that we deal with
1459 // Unknown Sequence Length
1461 FixDocEntryFoundLength(Entry, (guint32)length16);
1466 // Either implicit VR or a non DICOM conformal (see note below) explicit
1467 // VR that ommited the VR of (at least) this element. Farts happen.
1468 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1469 // on Data elements "Implicit and Explicit VR Data Elements shall
1470 // not coexist in a Data Set and Data Sets nested within it".]
1471 // Length is on 4 bytes.
1473 FixDocEntryFoundLength(Entry, ReadInt32());
1479 * \brief Find the Value Representation of the current Dicom Element.
1482 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1484 if (filetype != gdcmExplicitVR)
1489 long PositionOnEntry = ftell(fp);
1490 // Warning: we believe this is explicit VR (Value Representation) because
1491 // we used a heuristic that found "UL" in the first tag. Alas this
1492 // doesn't guarantee that all the tags will be in explicit VR. In some
1493 // cases (see e-film filtered files) one finds implicit VR tags mixed
1494 // within an explicit VR file. Hence we make sure the present tag
1495 // is in explicit VR and try to fix things if it happens not to be
1498 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1500 if(!CheckDocEntryVR(Entry,VR))
1502 fseek(fp, PositionOnEntry, SEEK_SET);
1503 // When this element is known in the dictionary we shall use, e.g. for
1504 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1505 // dictionary entry. Still we have to flag the element as implicit since
1506 // we know now our assumption on expliciteness is not furfilled.
1508 if ( Entry->IsVRUnknown() )
1509 Entry->SetVR("Implicit");
1510 Entry->SetImplicitVR();
1515 * \brief Check the correspondance between the VR of the header entry
1516 * and the taken VR. If they are different, the header entry is
1517 * updated with the new VR.
1518 * @param Entry Header Entry to check
1519 * @param vr Dicom Value Representation
1520 * @return false if the VR is incorrect of if the VR isn't referenced
1521 * otherwise, it returns true
1523 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1525 char msg[100]; // for sprintf
1526 bool RealExplicit = true;
1528 // Assume we are reading a falsely explicit VR file i.e. we reached
1529 // a tag where we expect reading a VR but are in fact we read the
1530 // first to bytes of the length. Then we will interogate (through find)
1531 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1532 // both GCC and VC++ implementations of the STL map. Hence when the
1533 // expected VR read happens to be non-ascii characters we consider
1534 // we hit falsely explicit VR tag.
1536 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1537 RealExplicit = false;
1539 // CLEANME searching the dicom_vr at each occurence is expensive.
1540 // PostPone this test in an optional integrity check at the end
1541 // of parsing or only in debug mode.
1542 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1543 RealExplicit= false;
1545 if ( !RealExplicit )
1547 // We thought this was explicit VR, but we end up with an
1548 // implicit VR tag. Let's backtrack.
1549 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1550 Entry->GetGroup(),Entry->GetElement());
1551 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1552 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1553 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1554 Entry->GetGroup(),Entry->GetElement(),
1555 "UL","FIXME","Group Length");
1556 Entry->SetDictEntry(NewEntry);
1561 if ( Entry->IsVRUnknown() )
1563 // When not a dictionary entry, we can safely overwrite the VR.
1564 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1570 else if ( Entry->GetVR() != vr )
1572 // The VR present in the file and the dictionary disagree. We assume
1573 // the file writer knew best and use the VR of the file. Since it would
1574 // be unwise to overwrite the VR of a dictionary (since it would
1575 // compromise it's next user), we need to clone the actual DictEntry
1576 // and change the VR for the read one.
1577 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1578 Entry->GetGroup(),Entry->GetElement(),
1579 vr,"FIXME",Entry->GetName());
1580 Entry->SetDictEntry(NewEntry);
1586 * \brief Get the transformed value of the header entry. The VR value
1587 * is used to define the transformation to operate on the value
1588 * \warning NOT end user intended method !
1590 * @return Transformed entry value
1592 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1594 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1596 std::string val=((gdcmValEntry *)Entry)->GetValue();
1597 std::string vr=Entry->GetVR();
1598 guint32 length = Entry->GetLength();
1599 std::ostringstream s;
1602 // When short integer(s) are expected, read and convert the following
1603 // n * 2 bytes properly i.e. as a multivaluated strings
1604 // (each single value is separated fromthe next one by '\'
1605 // as usual for standard multivaluated filels
1606 // Elements with Value Multiplicity > 1
1607 // contain a set of short integers (not a single one)
1609 if (vr == "US" || vr == "SS")
1614 for (int i=0; i < nbInt; i++)
1618 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1619 NewInt16 = SwapShort(NewInt16);
1624 // When integer(s) are expected, read and convert the following
1625 // n * 4 bytes properly i.e. as a multivaluated strings
1626 // (each single value is separated fromthe next one by '\'
1627 // as usual for standard multivaluated filels
1628 // Elements with Value Multiplicity > 1
1629 // contain a set of integers (not a single one)
1630 else if (vr == "UL" || vr == "SL")
1635 for (int i=0; i < nbInt; i++)
1639 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1640 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1641 NewInt32=SwapLong(NewInt32);
1645 #ifdef GDCM_NO_ANSI_STRING_STREAM
1646 s << std::ends; // to avoid oddities on Solaris
1647 #endif //GDCM_NO_ANSI_STRING_STREAM
1651 return(((gdcmValEntry *)Entry)->GetValue());
1655 * \brief Get the reverse transformed value of the header entry. The VR
1656 * value is used to define the reverse transformation to operate on
1658 * \warning NOT end user intended method !
1660 * @return Reverse transformed entry value
1662 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1664 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1666 std::string vr=Entry->GetVR();
1667 std::ostringstream s;
1668 std::vector<std::string> tokens;
1670 if (vr == "US" || vr == "SS")
1674 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1675 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1676 for (unsigned int i=0; i<tokens.size();i++)
1678 NewInt16 = atoi(tokens[i].c_str());
1679 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1683 if (vr == "UL" || vr == "SL")
1687 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1688 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1689 for (unsigned int i=0; i<tokens.size();i++)
1691 NewInt32 = atoi(tokens[i].c_str());
1692 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1693 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1698 #ifdef GDCM_NO_ANSI_STRING_STREAM
1699 s << std::ends; // to avoid oddities on Solaris
1700 #endif //GDCM_NO_ANSI_STRING_STREAM
1704 return(((gdcmValEntry *)Entry)->GetValue());
1708 * \brief Skip a given Header Entry
1709 * \warning NOT end user intended method !
1712 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1714 SkipBytes(entry->GetLength());
1718 * \brief Skips to the begining of the next Header Entry
1719 * \warning NOT end user intended method !
1722 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1724 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1725 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1729 * \brief Loads the value for a a given VLEntry
1730 * \warning NOT end user intended method !
1733 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1735 //SkipBytes(entry->GetLength());
1736 LoadDocEntry(entry);
1739 * \brief When the length of an element value is obviously wrong (because
1740 * the parser went Jabberwocky) one can hope improving things by
1741 * applying this heuristic.
1743 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength)
1745 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1746 if ( FoundLength == 0xffffffff) {
1750 guint16 gr =Entry->GetGroup();
1751 guint16 el =Entry->GetElement();
1753 if (FoundLength%2) {
1754 std::ostringstream s;
1755 s << "Warning : Tag with uneven length " << FoundLength
1756 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1757 dbg.Verbose(0,s.str().c_str());
1760 // Sorry for the patch!
1761 // XMedCom did the trick to read some naughty GE images ...
1762 if (FoundLength == 13) {
1763 // The following 'if' will be removed when there is no more
1764 // images on Creatis HDs with a 13 length for Manufacturer...
1765 if ( (Entry->GetGroup() != 0x0008) ||
1766 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1767 // end of remove area
1769 Entry->SetReadLength(10); // a bug is to be fixed
1773 // to fix some garbage 'Leonardo' Siemens images
1774 // May be commented out to avoid overhead
1775 else if ( (Entry->GetGroup() == 0x0009) &&
1776 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1778 Entry->SetReadLength(4); // a bug is to be fixed
1782 // to try to 'go inside' SeQuences (with length), and not to skip them
1783 else if ( Entry->GetVR() == "SQ")
1785 if (enableSequences) // only if the user does want to !
1786 FoundLength =0; // ReadLength is unchanged
1789 // we found a 'delimiter' element
1790 // fffe|xxxx is just a marker, we don't take its length into account
1791 else if(Entry->GetGroup() == 0xfffe)
1793 // *normally, fffe|0000 doesn't exist !
1794 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1795 // causes extra troubles :-(
1799 Entry->SetUsableLength(FoundLength);
1803 * \brief Apply some heuristics to predict whether the considered
1804 * element value contains/represents an integer or not.
1805 * @param Entry The element value on which to apply the predicate.
1806 * @return The result of the heuristical predicate.
1808 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1809 guint16 element = Entry->GetElement();
1810 guint16 group = Entry->GetGroup();
1811 std::string vr = Entry->GetVR();
1812 guint32 length = Entry->GetLength();
1813 // When we have some semantics on the element we just read, and if we
1814 // a priori know we are dealing with an integer, then we shall be
1815 // able to swap it's element value properly.
1816 if ( element == 0 ) // This is the group length of the group
1822 std::ostringstream s;
1823 int filePosition = ftell(fp);
1824 s << "Erroneous Group Length element length on : (" \
1825 << std::hex << group << " , " << element
1826 << ") -before- position x(" << filePosition << ")"
1827 << "lgt : " << length;
1828 // These 2 lines commented out : a *very dirty* patch
1829 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1830 // have a glance at offset x(8336) ...
1831 // For *regular* headers, the test is useless..
1832 // lets's print a warning message and go on,
1833 // instead of giving up with an error message
1835 //std::cout << s.str().c_str() << std::endl;
1836 // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
1837 // s.str().c_str());
1840 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1846 * \brief Find the Length till the next sequence delimiter
1847 * \warning NOT end user intended method !
1851 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1852 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1855 long PositionOnEntry = ftell(fp);
1856 bool FoundSequenceDelimiter = false;
1857 guint32 TotalLength = 0;
1860 while ( ! FoundSequenceDelimiter)
1866 TotalLength += 4; // We even have to decount the group and element
1868 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1870 char msg[100]; // for sprintf. Sorry
1871 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1872 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1876 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1877 FoundSequenceDelimiter = true;
1878 else if ( n != 0xe000 )
1880 char msg[100]; // for sprintf. Sorry
1881 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1883 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1887 ItemLength = ReadInt32();
1888 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1889 // the ItemLength with ReadInt32
1890 SkipBytes(ItemLength);
1892 fseek(fp, PositionOnEntry, SEEK_SET);
1897 * \brief Reads a supposed to be 16 Bits integer
1898 * (swaps it depending on processor endianity)
1899 * @return read value
1901 guint16 gdcmDocument::ReadInt16(void) {
1904 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1905 if ( item_read != 1 ) {
1907 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
1917 * \brief Reads a supposed to be 32 Bits integer
1918 * (swaps it depending on processor endianity)
1919 * @return read value
1921 guint32 gdcmDocument::ReadInt32(void) {
1924 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1925 if ( item_read != 1 ) {
1927 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
1937 * \brief skips bytes inside the source file
1938 * \warning NOT end user intended method !
1941 void gdcmDocument::SkipBytes(guint32 NBytes) {
1942 //FIXME don't dump the returned value
1943 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1947 * \brief Loads all the needed Dictionaries
1948 * \warning NOT end user intended method !
1950 void gdcmDocument::Initialise(void)
1952 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1953 RefShaDict = (gdcmDict*)0;
1957 * \brief Discover what the swap code is (among little endian, big endian,
1958 * bad little endian, bad big endian).
1960 * @return false when we are absolutely sure
1961 * it's neither ACR-NEMA nor DICOM
1962 * true when we hope ours assuptions are OK
1964 bool gdcmDocument::CheckSwap() {
1966 // The only guaranted way of finding the swap code is to find a
1967 // group tag since we know it's length has to be of four bytes i.e.
1968 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1969 // occurs when we can't find such group...
1971 guint32 x=4; // x : for ntohs
1972 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1978 char deb[HEADER_LENGTH_TO_READ];
1980 // First, compare HostByteOrder and NetworkByteOrder in order to
1981 // determine if we shall need to swap bytes (i.e. the Endian type).
1987 // The easiest case is the one of a DICOM header, since it possesses a
1988 // file preamble where it suffice to look for the string "DICM".
1989 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1992 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
1993 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
1995 // Next, determine the value representation (VR). Let's skip to the
1996 // first element (0002, 0000) and check there if we find "UL"
1997 // - or "OB" if the 1st one is (0002,0001) -,
1998 // in which case we (almost) know it is explicit VR.
1999 // WARNING: if it happens to be implicit VR then what we will read
2000 // is the length of the group. If this ascii representation of this
2001 // length happens to be "UL" then we shall believe it is explicit VR.
2002 // FIXME: in order to fix the above warning, we could read the next
2003 // element value (or a couple of elements values) in order to make
2004 // sure we are not commiting a big mistake.
2005 // We need to skip :
2006 // * the 128 bytes of File Preamble (often padded with zeroes),
2007 // * the 4 bytes of "DICM" string,
2008 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2009 // i.e. a total of 136 bytes.
2013 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2014 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2015 // *Implicit* VR. -and it is !-
2017 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2018 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2019 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2020 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2021 // when Write DCM *adds*
2023 // Use gdcmDocument::dicom_vr to test all the possibilities
2024 // instead of just checking for UL, OB and UI !? group 0000
2026 filetype = gdcmExplicitVR;
2027 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2028 "explicit Value Representation");
2032 filetype = gdcmImplicitVR;
2033 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2034 "not an explicit Value Representation");
2040 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2041 "HostByteOrder != NetworkByteOrder");
2046 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2047 "HostByteOrder = NetworkByteOrder");
2050 // Position the file position indicator at first tag (i.e.
2051 // after the file preamble and the "DICM" string).
2053 fseek (fp, 132L, SEEK_SET);
2057 // Alas, this is not a DicomV3 file and whatever happens there is no file
2058 // preamble. We can reset the file position indicator to where the data
2059 // is (i.e. the beginning of the file).
2060 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2063 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2064 // By clean we mean that the length of the first tag is written down.
2065 // If this is the case and since the length of the first group HAS to be
2066 // four (bytes), then determining the proper swap code is straightforward.
2069 // We assume the array of char we are considering contains the binary
2070 // representation of a 32 bits integer. Hence the following dirty
2072 s32 = *((guint32 *)(entCur));
2093 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2094 // It is time for despaired wild guesses.
2095 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2096 // i.e. the 'group length' element is not present :
2098 // check the supposed to be 'group number'
2099 // 0x0002 or 0x0004 or 0x0008
2100 // to determine ' sw' value .
2101 // Only 0 or 4321 will be possible
2102 // (no oportunity to check for the formerly well known
2103 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2104 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2105 // the file IS NOT ACR-NEMA nor DICOM V3
2106 // Find a trick to tell it the caller...
2108 s16 = *((guint16 *)(deb));
2124 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2125 "ACR/NEMA unfound swap info (Really hopeless !)");
2126 filetype = gdcmUnknown;
2130 // Then the only info we have is the net2host one.
2140 * \brief Restore the unproperly loaded values i.e. the group, the element
2141 * and the dictionary entry depending on them.
2143 void gdcmDocument::SwitchSwapToBigEndian(void)
2145 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2146 "Switching to BigEndian mode.");
2167 * \brief during parsing, Header Elements too long are not loaded in memory
2170 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2174 if ((guint32)NewSize >= (guint32)0xffffffff)
2176 MaxSizeLoadEntry = 0xffffffff;
2179 MaxSizeLoadEntry = NewSize;
2184 * \brief Header Elements too long will not be printed
2185 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2188 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2192 if ((guint32)NewSize >= (guint32)0xffffffff)
2194 MaxSizePrintEntry = 0xffffffff;
2197 MaxSizePrintEntry = NewSize;
2203 * \brief Read the next tag but WITHOUT loading it's value
2204 * (read the 'Group Number', the 'Element Number',
2205 * gets the Dict Entry
2206 * gets the VR, gets the length, gets the offset value)
2207 * @return On succes the newly created DocEntry, NULL on failure.
2209 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2211 gdcmDocEntry *NewEntry;
2216 // We reached the EOF (or an error occured) therefore
2217 // header parsing has to be considered as finished.
2218 return (gdcmDocEntry *)0;
2220 // Pb : how to propagate the element length (used in SkipDocEntry)
2221 // direct call to SkipBytes ?
2223 // if (ignoreShadow == 1 && g%2 ==1)
2224 // if user wants to skip shadow groups
2225 // and current element *is* a shadow element
2226 // we don't create anything
2227 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2229 NewEntry = NewDocEntryByNumber(g, n);
2230 FindDocEntryVR(NewEntry);
2231 FindDocEntryLength(NewEntry);
2238 NewEntry->SetOffset(ftell(fp));
2243 * \brief Build a new Element Value from all the low level arguments.
2244 * Check for existence of dictionary entry, and build
2245 * a default one when absent.
2246 * @param Name Name of the underlying DictEntry
2248 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2250 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2252 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2254 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2257 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2258 "failed to allocate gdcmDocEntry");
2259 return (gdcmDocEntry *)0;
2265 * \brief Request a new virtual dict entry to the dict set
2266 * @param group group number of the underlying DictEntry
2267 * @param element element number of the underlying DictEntry
2268 * @param vr VR of the underlying DictEntry
2269 * @param fourth owner group
2270 * @param name english name
2272 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2277 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2281 * \brief Build a new Element Value from all the low level arguments.
2282 * Check for existence of dictionary entry, and build
2283 * a default one when absent.
2284 * @param Group group number of the underlying DictEntry
2285 * @param Elem element number of the underlying DictEntry
2287 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2289 // Find out if the tag we encountered is in the dictionaries:
2290 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2292 DictEntry = NewVirtualDictEntry(Group, Elem);
2294 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2297 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2298 "failed to allocate gdcmDocEntry");
2304 /// \todo Never used; commented out, waiting for removal.
2306 * \brief Small utility function that creates a new manually crafted
2307 * (as opposed as read from the file) gdcmDocEntry with user
2308 * specified name and adds it to the public tag hash table.
2309 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2310 * @param NewTagName The name to be given to this new tag.
2311 * @param VR The Value Representation to be given to this new tag.
2312 * @return The newly hand crafted Element Value.
2314 //gdcmDocEntry *gdcmDocument::NewManualDocEntryToPubDict(std::string NewTagName,
2317 // gdcmDocEntry *NewEntry = NULL;
2318 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2319 // guint32 FreeElem = 0;
2320 // gdcmDictEntry *DictEntry = NULL;
2322 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2323 // if (FreeElem == UINT32_MAX)
2325 // dbg.Verbose(1, "gdcmHeader::NewManualDocEntryToPubDict",
2326 // "Group 0xffff in Public Dict is full");
2330 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2331 // VR, "GDCM", NewTagName);
2332 // NewEntry = new gdcmDocEntry(DictEntry);
2333 // AddEntry(NewEntry);
2338 * \brief Generate a free TagKey i.e. a TagKey that is not present
2339 * in the TagHt dictionary.
2340 * @param group The generated tag must belong to this group.
2341 * @return The element of tag with given group which is fee.
2343 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2345 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2347 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2348 if (tagHT.count(key) == 0)
2356 * \brief Searches both the public and the shadow dictionary (when they
2357 * exist) for the presence of the DictEntry with given name.
2358 * The public dictionary has precedence on the shadow one.
2359 * @param Name name of the searched DictEntry
2360 * @return Corresponding DictEntry when it exists, NULL otherwise.
2362 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2364 gdcmDictEntry *found = (gdcmDictEntry *)0;
2365 if (!RefPubDict && !RefShaDict)
2367 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2368 "we SHOULD have a default dictionary");
2372 found = RefPubDict->GetDictEntryByName(Name);
2378 found = RefShaDict->GetDictEntryByName(Name);
2386 * \brief Searches both the public and the shadow dictionary (when they
2387 * exist) for the presence of the DictEntry with given
2388 * group and element. The public dictionary has precedence on the
2390 * @param group group of the searched DictEntry
2391 * @param element element of the searched DictEntry
2392 * @return Corresponding DictEntry when it exists, NULL otherwise.
2394 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2396 gdcmDictEntry *found = (gdcmDictEntry *)0;
2397 if (!RefPubDict && !RefShaDict)
2399 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2400 "we SHOULD have a default dictionary");
2404 found = RefPubDict->GetDictEntryByNumber(group, element);
2410 found = RefShaDict->GetDictEntryByNumber(group, element);
2419 * \ingroup gdcmDocument
2420 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2421 * \ No other way so 'skip' the Data
2424 void gdcmDocument::Parse7FE0 (void) {
2426 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2430 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
2431 if (Transfer == UI1_2_840_10008_1_2 )
2433 if ( Transfer == UI1_2_840_10008_1_2_1 )
2435 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
2437 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
2441 std::string str_nb=GetEntryByNumber(0x0028,0x0100);
2442 if (str_nb == GDCM_UNFOUND ) {
2445 nb = atoi(str_nb.c_str() );
2446 if (nb == 12) nb =16;
2449 guint16 ItemTagGr,ItemTagEl;
2453 // -------------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2455 if ( Transfer != UI1_1_2_840_10008_1_2_5 ) { // !RLELossLessTransferSyntax
2458 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2459 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2461 ItemTagGr=SwapShort(ItemTagGr);
2462 ItemTagEl=SwapShort(ItemTagEl);
2464 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2465 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2469 ln=SwapLong(ln); // Basic Offset Table Item Length
2470 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2471 (unsigned)ftellRes,ln,ln);
2473 // What is it used for ??
2474 char * BasicOffsetTableItemValue= new char[ln+1];
2475 fread(BasicOffsetTableItemValue,ln,1,fp);
2477 for (int i=0;i<ln;i+=4){
2478 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2479 printf(" x(%08x) %d\n",a,a);
2484 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2485 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2487 ItemTagGr=SwapShort(ItemTagGr);
2488 ItemTagEl=SwapShort(ItemTagEl);
2490 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2491 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2493 while ( ( ItemTagGr==0xfffe) && (ItemTagEl!=0xe0dd) ) { // Parse fragments
2498 ln=SwapLong(ln); // length
2499 printf(" at %x : fragment length %d x(%08x)\n",
2500 (unsigned)ftellRes, ln,ln);
2502 // ------------------------
2503 fseek(fp,ln,SEEK_CUR); // skipping (not reading) fragment pixels
2504 // ------------------------
2507 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2508 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2510 ItemTagGr=SwapShort(ItemTagGr);
2511 ItemTagEl=SwapShort(ItemTagEl);
2513 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2514 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2520 long RleSegmentLength[15],fragmentLength;
2521 guint32 nbRleSegments;
2522 guint32 RleSegmentOffsetTable[15];
2524 // Basic Offset Table with Item Value
2526 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2527 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2529 ItemTagGr=SwapShort(ItemTagGr);
2530 ItemTagEl=SwapShort(ItemTagEl);
2532 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2533 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2538 ln=SwapLong(ln); // Basic Offset Table Item Length
2539 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2540 (unsigned)ftellRes,ln,ln);
2542 // What is it used for ??
2543 char * BasicOffsetTableItemValue= new char[ln+1];
2544 fread(BasicOffsetTableItemValue,ln,1,fp);
2546 for (int i=0;i<ln;i+=4){
2547 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2548 printf(" x(%08x) %d\n",a,a);
2553 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2554 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2556 ItemTagGr=SwapShort(ItemTagGr);
2557 ItemTagEl=SwapShort(ItemTagEl);
2559 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2560 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2562 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2563 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
2564 // Parse fragments of the current Fragment (Frame)
2566 fread(&fragmentLength,4,1,fp);
2568 fragmentLength=SwapLong(fragmentLength); // length
2569 printf(" at %x : 'fragment' length %d x(%08x)\n",
2570 (unsigned)ftellRes, (unsigned)fragmentLength,(unsigned)fragmentLength);
2572 //------------------ scanning (not reading) fragment pixels
2574 fread(&nbRleSegments,4,1,fp); // Reading : Number of RLE Segments
2576 nbRleSegments=SwapLong(nbRleSegments);
2577 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2579 for(int k=1; k<=15; k++) { // Reading RLE Segments Offset Table
2581 fread(&RleSegmentOffsetTable[k],4,1,fp);
2583 RleSegmentOffsetTable[k]=SwapLong(RleSegmentOffsetTable[k]);
2584 printf(" at : %x Offset Segment %d : %d (%x)\n",
2585 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2586 RleSegmentOffsetTable[k]);
2589 if (nbRleSegments>1) { // skipping (not reading) RLE Segments
2590 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2591 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2592 - RleSegmentOffsetTable[k];
2594 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2595 k,(unsigned)RleSegmentLength[k],(unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2596 fseek(fp,RleSegmentLength[k],SEEK_CUR);
2599 RleSegmentLength[nbRleSegments]= fragmentLength
2600 - RleSegmentOffsetTable[nbRleSegments];
2602 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2603 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2604 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2606 fseek(fp,RleSegmentLength[nbRleSegments],SEEK_CUR);
2608 // ------------------ end of scanning fragment pixels
2611 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2612 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2614 ItemTagGr=SwapShort(ItemTagGr);
2615 ItemTagEl=SwapShort(ItemTagEl);
2617 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2618 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2626 //-----------------------------------------------------------------------------