1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/05/03 09:43:04 $
7 Version: $Revision: 1.138 $
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 "gdcmDicomDirStudy.h"
25 #include "gdcmDicomDirSerie.h"
26 #include "gdcmDicomDirImage.h"
27 #include "gdcmDicomDirPatient.h"
28 #include "gdcmDicomDirMeta.h"
29 #include "gdcmDicomDirElement.h"
30 #include "gdcmDirList.h"
32 #include "gdcmDebug.h"
33 #include "gdcmGlobal.h"
35 #include "gdcmSeqEntry.h"
36 #include "gdcmSQItem.h"
37 #include "gdcmValEntry.h"
42 #include <sys/types.h>
45 # define getcwd _getcwd
48 #if defined(_MSC_VER) || defined(__BORLANDC__)
53 // ----------------------------------------------------------------------------
54 // Note for future developpers
55 // ----------------------------------------------------------------------------
57 // Dicom PS 3.3 describes the relationship between Directory Records, as follow
58 // (see also PS 4.3, 2004, page 50 for Entity-Relationship model)
60 // Directory Record Type Directory Record Types which may be included
61 // in the next lower-level directory Entity
63 // (Root directory Entity) PATIENT
67 // STUDY SERIES, VISIT, RESULTS, STUDY COMPONENT
69 // SERIES IMAGE, OVERLAYS, MODALITY LUT, VOI LUT,
70 // CURVE, STORED PRINT, RT DOSE, RT STRUCTURE SET
71 // RT PLAN, RT TREAT RECORD, PRESENTATION, WAVEFORM,
72 // SR DOCUMENT, KEY OBJECT DOC, SPECTROSCOPY,
73 // RAW DATA, REGISTRATION, FIDUCIAL
93 // ----------------------
94 // The current gdcm version only deals with :
96 // (Root directory Entity) PATIENT
102 // DicomDir::CreateDicomDir will have to be completed
103 // Treelike structure management will have to be upgraded
104 // ----------------------------------------------------------------------------
108 //-----------------------------------------------------------------------------
109 // Constructor / Destructor
111 * \brief Constructor : creates an empty DicomDir
116 Initialize(); // sets all private fields to NULL
121 * \brief Constructor Parses recursively the directory and creates the DicomDir
122 * or uses an already built DICOMDIR, depending on 'parseDir' value.
123 * @param fileName name
124 * - of the root directory (parseDir = true)
125 * - of the DICOMDIR (parseDir = false)
126 * @param parseDir boolean
127 * - true if user passed an entry point
128 * and wants to explore recursively the directories
129 * - false if user passed an already built DICOMDIR file
130 * and wants to use it
132 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
135 // At this step, Document constructor is already executed,
136 // whatever user passed (a root directory or a DICOMDIR)
137 // and whatever the value of parseDir was.
138 // (nothing is cheked in Document constructor, to avoid overhead)
141 SetLoadMode (0x00000000); // concerns only dicom files
146 * \brief Canonical destructor
148 DicomDir::~DicomDir()
150 SetStartMethod(NULL);
151 SetProgressMethod(NULL);
161 //-----------------------------------------------------------------------------
164 bool DicomDir::Load(std::string const &fileName )
167 // We should clean out anything that already exists.
169 Initialize(); // sets all private fields to NULL
173 // Only if user passed a DICOMDIR
174 // ------------------------------
180 Document::Load(fileName);
181 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
183 gdcmWarningMacro( "Entry HT empty for file: "<< fileName);
186 // Directory record sequence
187 DocEntry *e = GetDocEntry(0x0004, 0x1220);
190 gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
191 << " in file " << fileName);
199 // Only if user passed a root directory
200 // ------------------------------------
201 if ( fileName == "." )
203 // user passed '.' as Name
204 // we get current directory name
206 getcwd(dummy, (size_t)1000);
207 SetFileName( dummy ); // will be converted into a string
210 gdcmWarningMacro( "Parse directory and create the DicomDir : " << Filename );
217 * \brief This predicate, based on hopefully reasonable heuristics,
218 * decides whether or not the current document was properly parsed
219 * and contains the mandatory information for being considered as
220 * a well formed and usable DicomDir.
221 * @return true when Document is the one of a reasonable DicomDir,
224 bool DicomDir::IsReadable()
226 if( Filetype == Unknown)
228 gdcmWarningMacro( "Wrong filetype");
233 gdcmWarningMacro( "Meta Elements missing in DicomDir");
236 if( Patients.size() <= 0 )
238 gdcmWarningMacro( "NO Patient in DicomDir");
246 * \brief adds *the* Meta to a partially created DICOMDIR
248 DicomDirMeta *DicomDir::NewMeta()
253 DocEntry *entry = GetFirstEntry();
256 MetaElems = new DicomDirMeta(true);
258 entry = GetFirstEntry();
261 if( dynamic_cast<SeqEntry *>(entry) )
264 RemoveEntryNoDestroy(entry);
265 MetaElems->AddEntry(entry);
267 entry = GetFirstEntry();
270 else // after root directory parsing
272 MetaElems = new DicomDirMeta(false);
274 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
279 * \brief adds a new Patient (with the basic elements) to a partially created
282 DicomDirPatient *DicomDir::NewPatient()
284 DicomDirPatient *p = new DicomDirPatient();
285 AddPatientToEnd( p );
290 * \brief Remove all Patients
292 void DicomDir::ClearPatient()
294 for(ListDicomDirPatient::iterator cc = Patients.begin();
304 * \brief Get the first entry while visiting the DicomDirPatients
305 * \return The first DicomDirPatient if found, otherwhise NULL
307 DicomDirPatient *DicomDir::GetFirstPatient()
309 ItPatient = Patients.begin();
310 if ( ItPatient != Patients.end() )
316 * \brief Get the next entry while visiting the DicomDirPatients
317 * \note : meaningfull only if GetFirstEntry already called
318 * \return The next DicomDirPatient if found, otherwhise NULL
320 DicomDirPatient *DicomDir::GetNextPatient()
322 gdcmAssertMacro (ItPatient != Patients.end());
325 if ( ItPatient != Patients.end() )
331 * \brief fills the whole structure, starting from a root Directory
333 void DicomDir::ParseDirectory()
335 CreateDicomDirChainedList( GetFileName() );
340 * \brief Set the start method to call when the parsing of the
342 * @param method Method to call
343 * @param arg Argument to pass to the method
344 * @param argDelete Argument
345 * \warning In python : the arg parameter isn't considered
347 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
348 DicomDir::Method *argDelete )
350 if( StartArg && StartMethodArgDelete )
352 StartMethodArgDelete( StartArg );
355 StartMethod = method;
357 StartMethodArgDelete = argDelete;
362 * \brief Set the progress method to call when the parsing of the
364 * @param method Method to call
365 * @param arg Argument to pass to the method
366 * @param argDelete Argument
367 * \warning In python : the arg parameter isn't considered
369 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
370 DicomDir::Method *argDelete )
372 if( ProgressArg && ProgressMethodArgDelete )
374 ProgressMethodArgDelete( ProgressArg );
377 ProgressMethod = method;
379 ProgressMethodArgDelete = argDelete;
383 * \brief Set the end method to call when the parsing of the directory ends
384 * @param method Method to call
385 * @param arg Argument to pass to the method
386 * @param argDelete Argument
387 * \warning In python : the arg parameter isn't considered
389 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
390 DicomDir::Method *argDelete )
392 if( EndArg && EndMethodArgDelete )
394 EndMethodArgDelete( EndArg );
399 EndMethodArgDelete = argDelete;
403 * \brief Set the method to delete the argument
404 * The argument is destroyed when the method is changed or when the
406 * @param method Method to call to delete the argument
408 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
410 StartMethodArgDelete = method;
414 * \brief Set the method to delete the argument
415 * The argument is destroyed when the method is changed or when the
417 * @param method Method to call to delete the argument
419 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
421 ProgressMethodArgDelete = method;
425 * \brief Set the method to delete the argument
426 * The argument is destroyed when the method is changed or when
427 * the class is destroyed
428 * @param method Method to call to delete the argument
430 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
432 EndMethodArgDelete = method;
436 * \brief writes on disc a DICOMDIR
437 * \ warning does NOT add the missing elements in the header :
438 * it's up to the user doing it !
439 * @param fileName file to be written to
440 * @return false only when fail to open
443 bool DicomDir::WriteDicomDir(std::string const &fileName)
446 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
447 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
449 std::ofstream *fp = new std::ofstream(fileName.c_str(),
450 std::ios::out | std::ios::binary);
453 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
457 char filePreamble[128];
458 memset(filePreamble, 0, 128);
459 fp->write(filePreamble, 128);
460 binary_write( *fp, "DICM");
462 DicomDirMeta *ptrMeta = GetMeta();
463 ptrMeta->WriteContent(fp, ExplicitVR);
465 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
468 binary_write(*fp, sq[i]);
471 for(ListDicomDirPatient::iterator cc = Patients.begin();
472 cc != Patients.end();
475 (*cc)->WriteContent( fp, ExplicitVR );
478 // force writing Sequence Delimitation Item
481 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
491 * \brief Anonymize a DICOMDIR
495 bool DicomDir::AnonymizeDicomDir()
498 // Something clever to be found to forge the Patient names
499 std::ostringstream s;
501 for(ListDicomDirPatient::iterator cc = Patients.begin();
506 v = (*cc)->GetValEntry(0x0010, 0x0010) ; // Patient's Name
509 v->SetValue(s.str());
512 v = (*cc)->GetValEntry(0x0010, 0x0020) ; // Patient ID
518 v = (*cc)->GetValEntry(0x0010, 0x0030) ; // Patient's BirthDate
537 //-----------------------------------------------------------------------------
540 * \brief create a Document-like chained list from a root Directory
541 * @param path entry point of the tree-like structure
543 void DicomDir::CreateDicomDirChainedList(std::string const &path)
546 DirList dirList(path,1); // gets recursively the file list
547 unsigned int count = 0;
551 DirListType fileList = dirList.GetFilenames();
553 for( DirListType::iterator it = fileList.begin();
554 it != fileList.end();
557 Progress = (float)(count+1)/(float)fileList.size();
558 CallProgressMethod();
565 f->SetLoadMode(LoadMode); // we allow user not to load Sequences...
566 f->Load( it->c_str() );
570 // gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
574 if( f->IsReadable() )
576 // Add the file to the chained list:
578 gdcmWarningMacro( "Readable " << it->c_str() );
586 // sorts Patient/Study/Serie/
587 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
589 std::string tmp = dirList.GetDirName();
590 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
591 SetElements(tmp, list);
594 for(VectDocument::iterator itDoc=list.begin();
598 delete dynamic_cast<File *>(*itDoc);
603 * \brief CallStartMethod
605 void DicomDir::CallStartMethod()
611 StartMethod( StartArg );
616 * \brief CallProgressMethod
618 void DicomDir::CallProgressMethod()
622 ProgressMethod( ProgressArg );
627 * \brief CallEndMethod
629 void DicomDir::CallEndMethod()
638 //-----------------------------------------------------------------------------
641 * \brief Sets all fields to NULL
643 void DicomDir::Initialize()
646 ProgressMethod = NULL;
648 StartMethodArgDelete = NULL;
649 ProgressMethodArgDelete = NULL;
650 EndMethodArgDelete = NULL;
662 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
664 void DicomDir::CreateDicomDir()
666 // The SeqEntries of "Directory Record Sequence" are parsed.
667 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
668 // 1 - we save the beginning iterator
669 // 2 - we continue to parse
670 // 3 - we find an other tag
671 // + we create the object for the precedent tag
674 // Directory record sequence
675 DocEntry *e = GetDocEntry(0x0004, 0x1220);
678 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
682 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
685 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
695 SQItem *tmpSI=s->GetFirstSQItem();
698 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
699 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
701 v = valEntry->GetValue();
705 gdcmWarningMacro( "(0004,1430) not a ValEntry ?!?");
709 if( v == "PATIENT " )
711 si = new DicomDirPatient(true);
712 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
716 gdcmErrorMacro( "Add PatientToEnd failed");
719 else if( v == "STUDY " )
721 si = new DicomDirStudy(true);
722 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
726 gdcmErrorMacro( "Add AddStudyToEnd failed");
729 else if( v == "SERIES" )
731 si = new DicomDirSerie(true);
732 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
736 gdcmErrorMacro( "Add AddSerieToEnd failed");
739 else if( v == "IMAGE " )
741 si = new DicomDirImage(true);
742 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
746 gdcmErrorMacro( "Add AddImageToEnd failed");
751 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
752 // neither an 'IMAGE' SQItem. Skip to next item.
756 MoveSQItem(si,tmpSI);
758 tmpSI=s->GetNextSQItem();
764 * \brief AddPatientToEnd
765 * @param dd SQ Item to enqueue to the DicomPatient chained List
767 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
769 Patients.push_back(dd);
774 * \brief AddStudyToEnd
775 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
777 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
779 if( Patients.size() > 0 )
781 ListDicomDirPatient::iterator itp = Patients.end();
783 (*itp)->AddStudy(dd);
790 * \brief AddSerieToEnd
791 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
793 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
795 if( Patients.size() > 0 )
797 ListDicomDirPatient::iterator itp = Patients.end();
800 DicomDirStudy *study = (*itp)->GetLastStudy();
811 * \brief AddImageToEnd
812 * @param dd SQ Item to enqueue to the DicomDirImage chained List
814 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
816 if( Patients.size() > 0 )
818 ListDicomDirPatient::iterator itp = Patients.end();
821 DicomDirStudy *study = (*itp)->GetLastStudy();
824 DicomDirSerie *serie = study->GetLastSerie();
836 * \brief for each Header of the chained list,
837 * add/update the Patient/Study/Serie/Image info
838 * @param path path of the root directory
839 * @param list chained list of Headers
841 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
846 std::string patPrevName = "", patPrevID = "";
847 std::string studPrevInstanceUID = "", studPrevID = "";
848 std::string serPrevInstanceUID = "", serPrevID = "";
850 std::string patCurName, patCurID;
851 std::string studCurInstanceUID, studCurID;
852 std::string serCurInstanceUID, serCurID;
855 for( VectDocument::const_iterator it = list.begin();
859 // get the current file characteristics
860 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
861 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
862 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
863 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
864 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
865 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
867 if( patCurName != patPrevName || patCurID != patPrevID || first )
869 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
873 // if new Study Deal with 'STUDY' Elements
874 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
877 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
881 // if new Serie Deal with 'SERIE' Elements
882 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
885 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
888 // Always Deal with 'IMAGE' Elements
889 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
891 patPrevName = patCurName;
892 patPrevID = patCurID;
893 studPrevInstanceUID = studCurInstanceUID;
894 studPrevID = studCurID;
895 serPrevInstanceUID = serCurInstanceUID;
896 serPrevID = serCurID;
902 * \brief adds to the HTable
903 * the Entries (Dicom Elements) corresponding to the given type
904 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
905 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
906 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
907 * @param header Header of the current file
909 void DicomDir::SetElement(std::string const &path, DicomDirType type,
912 ListDicomDirElem elemList;
913 ListDicomDirElem::const_iterator it;
914 uint16_t tmpGr, tmpEl;
915 DictEntry *dictEntry;
922 case GDCM_DICOMDIR_IMAGE:
923 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
924 si = new DicomDirImage(true);
925 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
928 gdcmErrorMacro( "Add ImageToEnd failed");
931 case GDCM_DICOMDIR_SERIE:
932 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
933 si = new DicomDirSerie(true);
934 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
937 gdcmErrorMacro( "Add SerieToEnd failed");
940 case GDCM_DICOMDIR_STUDY:
941 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
942 si = new DicomDirStudy(true);
943 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
946 gdcmErrorMacro( "Add StudyToEnd failed");
949 case GDCM_DICOMDIR_PATIENT:
950 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
951 si = new DicomDirPatient(true);
952 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
955 gdcmErrorMacro( "Add PatientToEnd failed");
958 case GDCM_DICOMDIR_META:
959 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
960 si = new DicomDirMeta(true);
964 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
966 MetaElems = static_cast<DicomDirMeta *>(si);
971 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
972 // to avoid further troubles
973 // imageElem 0008 1140 "" // Referenced Image Sequence
974 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
975 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
976 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
977 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
979 // FIXME : troubles found when it's a SeqEntry
981 // for all the relevant elements found in their own spot of the DicomDir.dic
982 for( it = elemList.begin(); it != elemList.end(); ++it)
986 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
988 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
990 entry->SetOffset(0); // just to avoid further missprinting
994 // NULL when we Build Up (ex nihilo) a DICOMDIR
995 // or when we add the META elems
996 val = header->GetEntryValue(tmpGr, tmpEl);
1003 if( val == GDCM_UNFOUND)
1005 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1007 // force to the *end* File Name
1008 val = Util::GetName( path );
1010 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1012 if( header->GetFileName().substr(0, path.length()) != path )
1014 gdcmWarningMacro( "The base path of file name is incorrect");
1015 val = header->GetFileName();
1019 val = &(header->GetFileName().c_str()[path.length()]);
1029 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1033 entry->SetValue( val ); // troubles expected when vr=SQ ...
1035 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1037 gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1039 si->AddEntry(entry);
1044 * \brief Move the content of the source SQItem to the destination SQItem
1045 * Only DocEntry's are moved
1046 * @param dst destination SQItem
1047 * @param src source SQItem
1049 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1053 entry = src->GetFirstEntry();
1056 src->RemoveEntryNoDestroy(entry);
1057 dst->AddEntry(entry);
1058 // we destroyed -> the current iterator is not longer valid
1059 entry = src->GetFirstEntry();
1064 * \brief compares two files
1066 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1068 return *header1 < *header2;
1071 //-----------------------------------------------------------------------------
1074 * \brief Canonical Printer
1075 * @param os ostream we want to print in
1076 * @param indent Indentation string to be prepended during printing
1078 void DicomDir::Print(std::ostream &os, std::string const & )
1082 MetaElems->SetPrintLevel(PrintLevel);
1083 MetaElems->Print(os);
1085 for(ListDicomDirPatient::iterator cc = Patients.begin();
1086 cc != Patients.end();
1089 (*cc)->SetPrintLevel(PrintLevel);
1094 //-----------------------------------------------------------------------------
1095 } // end namespace gdcm