1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2006/01/27 10:01:33 $
7 Version: $Revision: 1.185 $
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.html 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 //-----------------------------------------------------------------------------
20 // For full DICOMDIR description, see:
21 // PS 3.3-2003, pages 731-750
22 //-----------------------------------------------------------------------------
23 #include "gdcmDicomDir.h"
24 #include "gdcmDicomDirObject.h"
25 #include "gdcmDicomDirStudy.h"
26 #include "gdcmDicomDirSerie.h"
27 #include "gdcmDicomDirVisit.h"
28 #include "gdcmDicomDirImage.h"
29 #include "gdcmDicomDirPatient.h"
30 #include "gdcmDicomDirMeta.h"
31 #include "gdcmDicomDirElement.h"
32 #include "gdcmDirList.h"
34 #include "gdcmDebug.h"
35 #include "gdcmGlobal.h"
37 #include "gdcmSeqEntry.h"
38 #include "gdcmSQItem.h"
39 #include "gdcmDataEntry.h"
40 #include "gdcmCommandManager.h"
45 #include <sys/types.h>
48 # define getcwd _getcwd
51 #if defined(_MSC_VER) || defined(__BORLANDC__)
57 #if defined(__BORLANDC__)
58 #include <mem.h> // for memset
61 // ----------------------------------------------------------------------------
62 // Note for future developpers
63 // ----------------------------------------------------------------------------
65 // Dicom PS 3.3 describes the relationship between Directory Records, as follow
66 // (see also PS 4.3, 2004, page 50 for Entity-Relationship model)
68 // Directory Record Type Directory Record Types which may be included
69 // in the next lower-level directory Entity
71 // (Root directory Entity) PATIENT, TOPIC, PRIVATE
73 // PATIENT STUDY, PRIVATE
75 // STUDY SERIES, VISIT, RESULTS, STUDY COMPONENT, PRIVATE
77 // SERIES IMAGE, OVERLAYS, MODALITY LUT, VOI LUT,
78 // CURVE, STORED PRINT, RT DOSE, RT STRUCTURE SET
79 // RT PLAN, RT TREAT RECORD, PRESENTATION, WAVEFORM,
80 // SR DOCUMENT, KEY OBJECT DOC, SPECTROSCOPY,
81 // RAW DATA, REGISTRATION, FIDUCIAL, PRIVATE,
104 // ----------------------
105 // The current gdcm version only deals with :
107 // (Root directory Entity) PATIENT
114 // DicomDir::CreateDicomDir will have to be completed
115 // Treelike structure management will have to be upgraded
116 // ----------------------------------------------------------------------------
120 //-----------------------------------------------------------------------------
121 // Constructor / Destructor
123 * \brief Constructor : creates an empty DicomDir
127 Initialize(); // sets all private fields to NULL
133 * \brief Canonical destructor
135 DicomDir::~DicomDir()
144 //-----------------------------------------------------------------------------
148 * \brief Loader. use SetFileName(fn)
149 * or SetLoadMode(lm) + SetDirectoryName(dn) before !
150 * @return false if file cannot be open or no swap info was found,
151 * or no tag was found.
153 bool DicomDir::Load( )
157 if ( ! this->Document::Load( ) )
160 return DoTheLoadingJob( );
164 * \brief Does the Loading Job (internal use only)
165 * @return false if file cannot be open or no swap info was found,
166 * or no tag was found.
168 bool DicomDir::DoTheLoadingJob( )
175 // Only if user passed a DICOMDIR
176 // ------------------------------
178 if (!Document::Load() )
183 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
185 gdcmWarningMacro( "Entry HT empty for file: "<< GetFileName());
188 // Directory record sequence
189 DocEntry *e = GetDocEntry(0x0004, 0x1220);
192 gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
193 << " in file " << GetFileName());
201 // Only if user passed a root directory
202 // ------------------------------------
203 if ( GetFileName() == "." )
205 // user passed '.' as Name
206 // we get current directory name
208 const char *cwd = getcwd(buf, 2048);
211 SetFileName( buf ); // will be converted into a string
215 gdcmErrorMacro( "Path was too long to fit on 2048 bytes" );
219 gdcmDebugMacro( "Parse directory and create the DicomDir : "
227 * \brief This predicate, based on hopefully reasonable heuristics,
228 * decides whether or not the current document was properly parsed
229 * and contains the mandatory information for being considered as
230 * a well formed and usable DicomDir.
231 * @return true when Document is the one of a reasonable DicomDir,
234 bool DicomDir::IsReadable()
236 if ( Filetype == Unknown )
238 gdcmErrorMacro( "Wrong filetype for " << GetFileName());
243 gdcmWarningMacro( "Meta Elements missing in DicomDir");
246 if ( Patients.size() <= 0 )
248 gdcmWarningMacro( "NO Patient in DicomDir");
256 * \brief adds *the* Meta to a partially created DICOMDIR
258 DicomDirMeta *DicomDir::NewMeta()
263 DocEntry *entry = GetFirstEntry();
266 MetaElems = DicomDirMeta::New(true); // true = empty
268 entry = GetFirstEntry();
271 if ( dynamic_cast<SeqEntry *>(entry) )
274 MetaElems->AddEntry(entry);
277 entry = GetFirstEntry();
280 else // after root directory parsing
282 MetaElems = DicomDirMeta::New(false); // false = not empty
284 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
289 * \brief adds a new Patient (with the basic elements) to a partially created
292 DicomDirPatient *DicomDir::NewPatient()
294 DicomDirPatient *dd = DicomDirPatient::New();
295 AddPatientToEnd( dd );
300 * \brief Remove all Patients
302 void DicomDir::ClearPatient()
304 for(ListDicomDirPatient::iterator cc = Patients.begin();
314 * \brief Get the first entry while visiting the DicomDirPatients
315 * \return The first DicomDirPatient if found, otherwhise NULL
317 DicomDirPatient *DicomDir::GetFirstPatient()
319 ItPatient = Patients.begin();
320 if ( ItPatient != Patients.end() )
326 * \brief Get the next entry while visiting the DicomDirPatients
327 * \note : meaningfull only if GetFirstEntry already called
328 * \return The next DicomDirPatient if found, otherwhise NULL
330 DicomDirPatient *DicomDir::GetNextPatient()
332 gdcmAssertMacro (ItPatient != Patients.end());
335 if ( ItPatient != Patients.end() )
341 * \brief fills the whole structure, starting from a root Directory
343 void DicomDir::ParseDirectory()
345 CreateDicomDirChainedList( GetFileName() );
350 * \brief writes on disc a DICOMDIR
351 * \ warning does NOT add the missing elements in the header :
352 * it's up to the user doing it !
353 * @param fileName file to be written to
354 * @return false only when fail to open
357 bool DicomDir::Write(std::string const &fileName)
360 uint16_t sq[6] = { 0x0004, 0x1220, 0x5153, 0x0000, 0xffff, 0xffff };
361 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0x0000, 0x0000 };
363 std::ofstream *fp = new std::ofstream(fileName.c_str(),
364 std::ios::out | std::ios::binary);
367 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
371 char filePreamble[128];
372 memset(filePreamble, 0, 128);
373 fp->write(filePreamble, 128);
374 binary_write( *fp, "DICM");
376 DicomDirMeta *ptrMeta = GetMeta();
377 ptrMeta->WriteContent(fp, ExplicitVR);
379 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
382 binary_write(*fp, sq[i]);
385 for(ListDicomDirPatient::iterator cc = Patients.begin();
386 cc != Patients.end();
389 (*cc)->WriteContent( fp, ExplicitVR );
392 // force writing Sequence Delimitation Item
395 binary_write(*fp, sqt[i]); // fffe e0dd 0000 0000
405 * \brief Anonymize a DICOMDIR
409 bool DicomDir::Anonymize()
412 // Something clever to be found to forge the Patient names
413 std::ostringstream s;
415 for(ListDicomDirPatient::iterator cc = Patients.begin();
420 v = (*cc)->GetDataEntry(0x0010, 0x0010) ; // Patient's Name
423 v->SetString(s.str());
426 v = (*cc)->GetDataEntry(0x0010, 0x0020) ; // Patient ID
432 v = (*cc)->GetDataEntry(0x0010, 0x0030) ; // Patient's BirthDate
444 * \brief Copies all the attributes from an other DocEntrySet
445 * @param set entry to copy from
446 * @remarks The contained DocEntries are not copied, only referenced
448 void DicomDir::Copy(DocEntrySet *set)
450 // Remove all previous childs
455 DicomDir *dd = dynamic_cast<DicomDir *>(set);
459 MetaElems->Unregister();
460 MetaElems = dd->MetaElems;
462 MetaElems->Register();
464 Patients = dd->Patients;
465 for(ItPatient = Patients.begin();ItPatient != Patients.end();++ItPatient)
466 (*ItPatient)->Register();
470 //-----------------------------------------------------------------------------
473 * \brief create a Document-like chained list from a root Directory
474 * @param path entry point of the tree-like structure
476 void DicomDir::CreateDicomDirChainedList(std::string const &path)
479 DirList dirList(path,1); // gets recursively the file list
480 unsigned int count = 0;
484 DirListType fileList = dirList.GetFilenames();
485 unsigned int nbFile = fileList.size();
486 for( DirListType::iterator it = fileList.begin();
487 it != fileList.end();
490 Progress = (float)(count+1)/(float)nbFile;
491 CallProgressMethod();
498 f->SetLoadMode(LoadMode); // we allow user not to load Sequences,
499 // or Shadow groups, or ......
500 f->SetFileName( it->c_str() );
503 if ( f->IsReadable() )
505 // Add the file to the chained list:
507 gdcmDebugMacro( "Readable " << it->c_str() );
515 // sorts Patient/Study/Serie/
516 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
518 std::string tmp = dirList.GetDirName();
519 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
520 SetElements(tmp, list);
523 for(VectDocument::iterator itDoc=list.begin();
527 dynamic_cast<File *>(*itDoc)->Delete();
532 //-----------------------------------------------------------------------------
535 * \brief Sets all fields to NULL
537 void DicomDir::Initialize()
546 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
548 void DicomDir::CreateDicomDir()
550 // The SeqEntries of "Directory Record Sequence" are parsed.
551 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
552 // 1 - we save the beginning iterator
553 // 2 - we continue to parse
554 // 3 - we find an other tag
555 // + we create the object for the precedent tag
557 gdcmDebugMacro("Create DicomDir");
559 // Directory record sequence
560 DocEntry *e = GetDocEntry(0x0004, 0x1220);
563 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
567 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
570 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
580 SQItem *tmpSI=s->GetFirstSQItem();
583 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
584 if ( DataEntry *dataEntry = dynamic_cast<DataEntry *>(d) )
586 v = dataEntry->GetString();
590 gdcmWarningMacro( "(0004,1430) not a DataEntry ?!?");
594 // A decent DICOMDIR has much more images than series,
595 // more series than studies, and so on.
596 // This is the right order to perform the tests
600 si = DicomDirImage::New(true);
601 if ( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
605 gdcmErrorMacro( "Add AddImageToEnd failed");
608 else if ( v == "SERIES" )
610 si = DicomDirSerie::New(true);
611 if ( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
615 gdcmErrorMacro( "Add AddSerieToEnd failed");
618 else if ( v == "VISIT " )
620 si = DicomDirVisit::New(true);
621 if ( !AddVisitToEnd( static_cast<DicomDirVisit *>(si)) )
625 gdcmErrorMacro( "Add AddVisitToEnd failed");
628 else if ( v == "STUDY " )
630 si = DicomDirStudy::New(true);
631 if ( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
635 gdcmErrorMacro( "Add AddStudyToEnd failed");
638 else if ( v == "PATIENT " )
640 si = DicomDirPatient::New(true);
641 if ( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
645 gdcmErrorMacro( "Add PatientToEnd failed");
650 // It was neither a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
651 // nor an 'IMAGE' SQItem. Skip to next item.
652 gdcmDebugMacro( " -------------------------------------------"
653 << "a non PATIENT/STUDY/SERIE/IMAGE SQItem was found : "
656 // FIXME : deal with other item types !
657 tmpSI=s->GetNextSQItem(); // To avoid infinite loop
663 tmpSI=s->GetNextSQItem();
669 * \brief AddPatientToEnd
670 * @param dd SQ Item to enqueue to the DicomPatient chained List
672 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
674 Patients.push_back(dd);
679 * \brief AddStudyToEnd
680 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
682 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
684 if ( Patients.size() > 0 )
686 ListDicomDirPatient::iterator itp = Patients.end();
688 (*itp)->AddStudy(dd);
695 * \brief AddSerieToEnd
696 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
698 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
700 if ( Patients.size() > 0 )
702 ListDicomDirPatient::iterator itp = Patients.end();
705 DicomDirStudy *study = (*itp)->GetLastStudy();
716 * \brief AddVisitToEnd
717 * @param dd SQ Item to enqueue to the DicomDirVisit chained List
719 bool DicomDir::AddVisitToEnd(DicomDirVisit *dd)
721 if ( Patients.size() > 0 )
723 ListDicomDirPatient::iterator itp = Patients.end();
726 DicomDirStudy *study = (*itp)->GetLastStudy();
736 * \brief AddImageToEnd
737 * @param dd SQ Item to enqueue to the DicomDirImage chained List
739 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
741 if ( Patients.size() > 0 )
743 ListDicomDirPatient::iterator itp = Patients.end();
746 DicomDirStudy *study = (*itp)->GetLastStudy();
749 DicomDirSerie *serie = study->GetLastSerie();
761 * \brief for each Header of the chained list,
762 * add/update the Patient/Study/Serie/Image info
763 * @param path path of the root directory
764 * @param list chained list of Headers
766 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
771 std::string patPrevName = "", patPrevID = "";
772 std::string studPrevInstanceUID = "", studPrevID = "";
773 std::string serPrevInstanceUID = "", serPrevID = "";
775 std::string patCurName, patCurID;
776 std::string studCurInstanceUID, studCurID;
777 std::string serCurInstanceUID, serCurID;
780 for( VectDocument::const_iterator it = list.begin();
784 // get the current file characteristics
785 patCurName = (*it)->GetEntryString(0x0010,0x0010);
786 patCurID = (*it)->GetEntryString(0x0010,0x0011);
787 studCurInstanceUID = (*it)->GetEntryString(0x0020,0x000d);
788 studCurID = (*it)->GetEntryString(0x0020,0x0010);
789 serCurInstanceUID = (*it)->GetEntryString(0x0020,0x000e);
790 serCurID = (*it)->GetEntryString(0x0020,0x0011);
792 if ( patCurName != patPrevName || patCurID != patPrevID || first )
794 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
798 // if new Study, deal with 'STUDY' Elements
799 if ( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
802 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
806 // if new Serie, deal with 'SERIE' Elements
807 if ( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
810 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
813 // Always Deal with 'IMAGE' Elements
814 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
816 patPrevName = patCurName;
817 patPrevID = patCurID;
818 studPrevInstanceUID = studCurInstanceUID;
819 studPrevID = studCurID;
820 serPrevInstanceUID = serCurInstanceUID;
821 serPrevID = serCurID;
827 * \brief adds to the HTable
828 * the Entries (Dicom Elements) corresponding to the given type
829 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
830 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
831 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
832 * @param header Header of the current file
834 void DicomDir::SetElement(std::string const &path, DicomDirType type,
837 ListDicomDirElem elemList;
838 ListDicomDirElem::const_iterator it;
839 uint16_t tmpGr, tmpEl;
840 DictEntry *dictEntry;
847 case GDCM_DICOMDIR_IMAGE:
848 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
849 si = DicomDirImage::New(true);
850 if ( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
853 gdcmErrorMacro( "Add ImageToEnd failed");
856 case GDCM_DICOMDIR_SERIE:
857 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
858 si = DicomDirSerie::New(true);
859 if ( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
862 gdcmErrorMacro( "Add SerieToEnd failed");
865 case GDCM_DICOMDIR_STUDY:
866 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
867 si = DicomDirStudy::New(true);
868 if ( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
871 gdcmErrorMacro( "Add StudyToEnd failed");
874 case GDCM_DICOMDIR_PATIENT:
875 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
876 si = DicomDirPatient::New(true);
877 if ( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
880 gdcmErrorMacro( "Add PatientToEnd failed");
883 case GDCM_DICOMDIR_META:
887 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
889 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
890 MetaElems = DicomDirMeta::New(true);
897 // FIXME : troubles found when it's a SeqEntry
899 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
900 // to avoid further troubles
901 // imageElem 0008 1140 "" // Referenced Image Sequence
902 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
903 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
904 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
905 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
907 std::string referencedVal;
908 // for all the relevant elements found in their own spot of the DicomDir.dic
909 for( it = elemList.begin(); it != elemList.end(); ++it)
913 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
915 entry = DataEntry::New( dictEntry );
916 entry->SetOffset(0); // just to avoid further missprinting
920 // NULL when we Build Up (ex nihilo) a DICOMDIR
921 // or when we add the META elems
923 val = header->GetEntryString(tmpGr, tmpEl);
930 if ( val == GDCM_UNFOUND)
932 if ( tmpGr == 0x0004 ) // never present in File !
936 case 0x1130: // File-set ID
937 // force to the *end* File Name
938 val = Util::GetName( path );
941 case 0x1500: // Only used for image
942 if ( header->GetFileName().substr(0, path.length()) != path )
944 gdcmWarningMacro( "The base path of file name is incorrect");
945 val = header->GetFileName();
949 // avoid the first '/' in File name !
950 if ( header->GetFileName().c_str()[path.length()]
951 == GDCM_FILESEPARATOR )
952 val = &(header->GetFileName().c_str()[path.length()+1]);
954 val = &(header->GetFileName().c_str()[path.length()]);
958 case 0x1510: // Referenced SOP Class UID in File
959 referencedVal = header->GetEntryString(0x0008, 0x0016);
960 // FIXME : probabely something to check
964 case 0x1511: // Referenced SOP Instance UID in File
965 referencedVal = header->GetEntryString(0x0008, 0x0018);
966 // FIXME : probabely something to check
970 case 0x1512: // Referenced Transfer Syntax UID in File
971 referencedVal = header->GetEntryString(0x0002, 0x0010);
972 // FIXME : probabely something to check
982 // If the entry is not found in the Header, don't write its 'value' in the DICOMDIR !
989 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
992 // Don't polute the DICOMDIR with empty fields
1001 /* FIX later the pb of creating the 'Implementation Version Name'!
1003 if (val == GDCM_UNFOUND)
1006 if ( tmpGr == 0x0002 && tmpEl == 0x0013)
1008 // 'Implementation Version Name'
1009 std::string val = "GDCM ";
1010 val += Util::GetVersion();
1014 entry->SetString( val ); // troubles expected when vr=SQ ...
1016 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1018 gdcmDebugMacro("GDCM_DICOMDIR_META ?!? should never print that");
1021 si->AddEntry(entry);
1027 * \brief Move the content of the source SQItem to the destination SQItem
1028 * Only DocEntry's are moved
1029 * @param dst destination SQItem
1030 * @param src source SQItem
1032 void DicomDir::MoveSQItem(DocEntrySet *dst, DocEntrySet *src)
1035 // todo : rewrite the whole stuff, without using RemoveEntry an AddEntry,
1037 entry = src->GetFirstEntry();
1040 dst->AddEntry(entry); // use it, *before* removing it!
1041 src->RemoveEntry(entry);
1042 // we destroyed -> the current iterator is not longer valid
1043 entry = src->GetFirstEntry();
1048 * \brief compares two files
1050 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1052 return *header1 < *header2;
1055 //-----------------------------------------------------------------------------
1058 * \brief Canonical Printer
1059 * @param os ostream we want to print in
1060 * @param indent Indentation string to be prepended during printing
1062 void DicomDir::Print(std::ostream &os, std::string const & )
1066 MetaElems->SetPrintLevel(PrintLevel);
1067 MetaElems->Print(os);
1069 for(ListDicomDirPatient::iterator cc = Patients.begin();
1070 cc != Patients.end();
1073 (*cc)->SetPrintLevel(PrintLevel);
1078 //-----------------------------------------------------------------------------
1079 } // end namespace gdcm