1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/06/02 09:40:58 $
7 Version: $Revision: 1.139 $
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, TOPIC, PRIVATE
65 // PATIENT STUDY, PRIVATE
67 // STUDY SERIES, VISIT, RESULTS, STUDY COMPONENT, PRIVATE
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, PRIVATE,
96 // ----------------------
97 // The current gdcm version only deals with :
99 // (Root directory Entity) PATIENT
105 // DicomDir::CreateDicomDir will have to be completed
106 // Treelike structure management will have to be upgraded
107 // ----------------------------------------------------------------------------
111 //-----------------------------------------------------------------------------
112 // Constructor / Destructor
114 * \brief Constructor : creates an empty DicomDir
119 Initialize(); // sets all private fields to NULL
124 * \brief Constructor Parses recursively the directory and creates the DicomDir
125 * or uses an already built DICOMDIR, depending on 'parseDir' value.
126 * @param fileName name
127 * - of the root directory (parseDir = true)
128 * - of the DICOMDIR (parseDir = false)
129 * @param parseDir boolean
130 * - true if user passed an entry point
131 * and wants to explore recursively the directories
132 * - false if user passed an already built DICOMDIR file
133 * and wants to use it
135 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
138 // At this step, Document constructor is already executed,
139 // whatever user passed (either a root directory or a DICOMDIR)
140 // and whatever the value of parseDir was.
141 // (nothing is cheked in Document constructor, to avoid overhead)
144 SetLoadMode (0x00000000); // concerns only dicom files
149 * \brief Canonical destructor
151 DicomDir::~DicomDir()
153 SetStartMethod(NULL);
154 SetProgressMethod(NULL);
164 //-----------------------------------------------------------------------------
167 bool DicomDir::Load(std::string const &fileName )
170 // We should clean out anything that already exists.
172 Initialize(); // sets all private fields to NULL
176 // Only if user passed a DICOMDIR
177 // ------------------------------
183 Document::Load(fileName);
184 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
186 gdcmWarningMacro( "Entry HT empty for file: "<< fileName);
189 // Directory record sequence
190 DocEntry *e = GetDocEntry(0x0004, 0x1220);
193 gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
194 << " in file " << fileName);
202 // Only if user passed a root directory
203 // ------------------------------------
204 if ( fileName == "." )
206 // user passed '.' as Name
207 // we get current directory name
209 getcwd(dummy, (size_t)1000);
210 SetFileName( dummy ); // will be converted into a string
213 gdcmWarningMacro( "Parse directory and create the DicomDir : " << Filename );
220 * \brief This predicate, based on hopefully reasonable heuristics,
221 * decides whether or not the current document was properly parsed
222 * and contains the mandatory information for being considered as
223 * a well formed and usable DicomDir.
224 * @return true when Document is the one of a reasonable DicomDir,
227 bool DicomDir::IsReadable()
229 if( Filetype == Unknown)
231 gdcmWarningMacro( "Wrong filetype");
236 gdcmWarningMacro( "Meta Elements missing in DicomDir");
239 if( Patients.size() <= 0 )
241 gdcmWarningMacro( "NO Patient in DicomDir");
249 * \brief adds *the* Meta to a partially created DICOMDIR
251 DicomDirMeta *DicomDir::NewMeta()
256 DocEntry *entry = GetFirstEntry();
259 MetaElems = new DicomDirMeta(true);
261 entry = GetFirstEntry();
264 if( dynamic_cast<SeqEntry *>(entry) )
267 RemoveEntryNoDestroy(entry);
268 MetaElems->AddEntry(entry);
270 entry = GetFirstEntry();
273 else // after root directory parsing
275 MetaElems = new DicomDirMeta(false);
277 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
282 * \brief adds a new Patient (with the basic elements) to a partially created
285 DicomDirPatient *DicomDir::NewPatient()
287 DicomDirPatient *p = new DicomDirPatient();
288 AddPatientToEnd( p );
293 * \brief Remove all Patients
295 void DicomDir::ClearPatient()
297 for(ListDicomDirPatient::iterator cc = Patients.begin();
307 * \brief Get the first entry while visiting the DicomDirPatients
308 * \return The first DicomDirPatient if found, otherwhise NULL
310 DicomDirPatient *DicomDir::GetFirstPatient()
312 ItPatient = Patients.begin();
313 if ( ItPatient != Patients.end() )
319 * \brief Get the next entry while visiting the DicomDirPatients
320 * \note : meaningfull only if GetFirstEntry already called
321 * \return The next DicomDirPatient if found, otherwhise NULL
323 DicomDirPatient *DicomDir::GetNextPatient()
325 gdcmAssertMacro (ItPatient != Patients.end());
328 if ( ItPatient != Patients.end() )
334 * \brief fills the whole structure, starting from a root Directory
336 void DicomDir::ParseDirectory()
338 CreateDicomDirChainedList( GetFileName() );
343 * \brief Set the start method to call when the parsing of the
345 * @param method Method to call
346 * @param arg Argument to pass to the method
347 * @param argDelete Argument
348 * \warning In python : the arg parameter isn't considered
350 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
351 DicomDir::Method *argDelete )
353 if( StartArg && StartMethodArgDelete )
355 StartMethodArgDelete( StartArg );
358 StartMethod = method;
360 StartMethodArgDelete = argDelete;
365 * \brief Set the progress method to call when the parsing of the
367 * @param method Method to call
368 * @param arg Argument to pass to the method
369 * @param argDelete Argument
370 * \warning In python : the arg parameter isn't considered
372 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
373 DicomDir::Method *argDelete )
375 if( ProgressArg && ProgressMethodArgDelete )
377 ProgressMethodArgDelete( ProgressArg );
380 ProgressMethod = method;
382 ProgressMethodArgDelete = argDelete;
386 * \brief Set the end method to call when the parsing of the directory ends
387 * @param method Method to call
388 * @param arg Argument to pass to the method
389 * @param argDelete Argument
390 * \warning In python : the arg parameter isn't considered
392 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
393 DicomDir::Method *argDelete )
395 if( EndArg && EndMethodArgDelete )
397 EndMethodArgDelete( EndArg );
402 EndMethodArgDelete = argDelete;
406 * \brief Set the method to delete the argument
407 * The argument is destroyed when the method is changed or when the
409 * @param method Method to call to delete the argument
411 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
413 StartMethodArgDelete = method;
417 * \brief Set the method to delete the argument
418 * The argument is destroyed when the method is changed or when the
420 * @param method Method to call to delete the argument
422 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
424 ProgressMethodArgDelete = method;
428 * \brief Set the method to delete the argument
429 * The argument is destroyed when the method is changed or when
430 * the class is destroyed
431 * @param method Method to call to delete the argument
433 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
435 EndMethodArgDelete = method;
439 * \brief writes on disc a DICOMDIR
440 * \ warning does NOT add the missing elements in the header :
441 * it's up to the user doing it !
442 * @param fileName file to be written to
443 * @return false only when fail to open
446 bool DicomDir::WriteDicomDir(std::string const &fileName)
449 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
450 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
452 std::ofstream *fp = new std::ofstream(fileName.c_str(),
453 std::ios::out | std::ios::binary);
456 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
460 char filePreamble[128];
461 memset(filePreamble, 0, 128);
462 fp->write(filePreamble, 128);
463 binary_write( *fp, "DICM");
465 DicomDirMeta *ptrMeta = GetMeta();
466 ptrMeta->WriteContent(fp, ExplicitVR);
468 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
471 binary_write(*fp, sq[i]);
474 for(ListDicomDirPatient::iterator cc = Patients.begin();
475 cc != Patients.end();
478 (*cc)->WriteContent( fp, ExplicitVR );
481 // force writing Sequence Delimitation Item
484 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
494 * \brief Anonymize a DICOMDIR
498 bool DicomDir::AnonymizeDicomDir()
501 // Something clever to be found to forge the Patient names
502 std::ostringstream s;
504 for(ListDicomDirPatient::iterator cc = Patients.begin();
509 v = (*cc)->GetValEntry(0x0010, 0x0010) ; // Patient's Name
512 v->SetValue(s.str());
515 v = (*cc)->GetValEntry(0x0010, 0x0020) ; // Patient ID
521 v = (*cc)->GetValEntry(0x0010, 0x0030) ; // Patient's BirthDate
540 //-----------------------------------------------------------------------------
543 * \brief create a Document-like chained list from a root Directory
544 * @param path entry point of the tree-like structure
546 void DicomDir::CreateDicomDirChainedList(std::string const &path)
549 DirList dirList(path,1); // gets recursively the file list
550 unsigned int count = 0;
554 DirListType fileList = dirList.GetFilenames();
556 for( DirListType::iterator it = fileList.begin();
557 it != fileList.end();
560 Progress = (float)(count+1)/(float)fileList.size();
561 CallProgressMethod();
568 f->SetLoadMode(LoadMode); // we allow user not to load Sequences...
569 f->Load( it->c_str() );
573 // gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
577 if( f->IsReadable() )
579 // Add the file to the chained list:
581 gdcmWarningMacro( "Readable " << it->c_str() );
589 // sorts Patient/Study/Serie/
590 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
592 std::string tmp = dirList.GetDirName();
593 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
594 SetElements(tmp, list);
597 for(VectDocument::iterator itDoc=list.begin();
601 delete dynamic_cast<File *>(*itDoc);
606 * \brief CallStartMethod
608 void DicomDir::CallStartMethod()
614 StartMethod( StartArg );
619 * \brief CallProgressMethod
621 void DicomDir::CallProgressMethod()
625 ProgressMethod( ProgressArg );
630 * \brief CallEndMethod
632 void DicomDir::CallEndMethod()
641 //-----------------------------------------------------------------------------
644 * \brief Sets all fields to NULL
646 void DicomDir::Initialize()
649 ProgressMethod = NULL;
651 StartMethodArgDelete = NULL;
652 ProgressMethodArgDelete = NULL;
653 EndMethodArgDelete = NULL;
665 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
667 void DicomDir::CreateDicomDir()
669 // The SeqEntries of "Directory Record Sequence" are parsed.
670 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
671 // 1 - we save the beginning iterator
672 // 2 - we continue to parse
673 // 3 - we find an other tag
674 // + we create the object for the precedent tag
677 // Directory record sequence
678 DocEntry *e = GetDocEntry(0x0004, 0x1220);
681 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
685 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
688 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
698 SQItem *tmpSI=s->GetFirstSQItem();
701 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
702 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
704 v = valEntry->GetValue();
708 gdcmWarningMacro( "(0004,1430) not a ValEntry ?!?");
712 if( v == "PATIENT " )
714 si = new DicomDirPatient(true);
715 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
719 gdcmErrorMacro( "Add PatientToEnd failed");
722 else if( v == "STUDY " )
724 si = new DicomDirStudy(true);
725 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
729 gdcmErrorMacro( "Add AddStudyToEnd failed");
732 else if( v == "SERIES" )
734 si = new DicomDirSerie(true);
735 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
739 gdcmErrorMacro( "Add AddSerieToEnd failed");
742 else if( v == "IMAGE " )
744 si = new DicomDirImage(true);
745 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
749 gdcmErrorMacro( "Add AddImageToEnd failed");
754 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
755 // neither an 'IMAGE' SQItem. Skip to next item.
759 MoveSQItem(si,tmpSI);
761 tmpSI=s->GetNextSQItem();
767 * \brief AddPatientToEnd
768 * @param dd SQ Item to enqueue to the DicomPatient chained List
770 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
772 Patients.push_back(dd);
777 * \brief AddStudyToEnd
778 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
780 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
782 if( Patients.size() > 0 )
784 ListDicomDirPatient::iterator itp = Patients.end();
786 (*itp)->AddStudy(dd);
793 * \brief AddSerieToEnd
794 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
796 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
798 if( Patients.size() > 0 )
800 ListDicomDirPatient::iterator itp = Patients.end();
803 DicomDirStudy *study = (*itp)->GetLastStudy();
814 * \brief AddImageToEnd
815 * @param dd SQ Item to enqueue to the DicomDirImage chained List
817 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
819 if( Patients.size() > 0 )
821 ListDicomDirPatient::iterator itp = Patients.end();
824 DicomDirStudy *study = (*itp)->GetLastStudy();
827 DicomDirSerie *serie = study->GetLastSerie();
839 * \brief for each Header of the chained list,
840 * add/update the Patient/Study/Serie/Image info
841 * @param path path of the root directory
842 * @param list chained list of Headers
844 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
849 std::string patPrevName = "", patPrevID = "";
850 std::string studPrevInstanceUID = "", studPrevID = "";
851 std::string serPrevInstanceUID = "", serPrevID = "";
853 std::string patCurName, patCurID;
854 std::string studCurInstanceUID, studCurID;
855 std::string serCurInstanceUID, serCurID;
858 for( VectDocument::const_iterator it = list.begin();
862 // get the current file characteristics
863 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
864 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
865 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
866 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
867 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
868 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
870 if( patCurName != patPrevName || patCurID != patPrevID || first )
872 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
876 // if new Study Deal with 'STUDY' Elements
877 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
880 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
884 // if new Serie Deal with 'SERIE' Elements
885 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
888 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
891 // Always Deal with 'IMAGE' Elements
892 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
894 patPrevName = patCurName;
895 patPrevID = patCurID;
896 studPrevInstanceUID = studCurInstanceUID;
897 studPrevID = studCurID;
898 serPrevInstanceUID = serCurInstanceUID;
899 serPrevID = serCurID;
905 * \brief adds to the HTable
906 * the Entries (Dicom Elements) corresponding to the given type
907 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
908 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
909 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
910 * @param header Header of the current file
912 void DicomDir::SetElement(std::string const &path, DicomDirType type,
915 ListDicomDirElem elemList;
916 ListDicomDirElem::const_iterator it;
917 uint16_t tmpGr, tmpEl;
918 DictEntry *dictEntry;
925 case GDCM_DICOMDIR_IMAGE:
926 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
927 si = new DicomDirImage(true);
928 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
931 gdcmErrorMacro( "Add ImageToEnd failed");
934 case GDCM_DICOMDIR_SERIE:
935 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
936 si = new DicomDirSerie(true);
937 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
940 gdcmErrorMacro( "Add SerieToEnd failed");
943 case GDCM_DICOMDIR_STUDY:
944 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
945 si = new DicomDirStudy(true);
946 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
949 gdcmErrorMacro( "Add StudyToEnd failed");
952 case GDCM_DICOMDIR_PATIENT:
953 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
954 si = new DicomDirPatient(true);
955 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
958 gdcmErrorMacro( "Add PatientToEnd failed");
961 case GDCM_DICOMDIR_META:
962 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
963 si = new DicomDirMeta(true);
967 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
969 MetaElems = static_cast<DicomDirMeta *>(si);
974 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
975 // to avoid further troubles
976 // imageElem 0008 1140 "" // Referenced Image Sequence
977 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
978 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
979 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
980 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
982 // FIXME : troubles found when it's a SeqEntry
984 // for all the relevant elements found in their own spot of the DicomDir.dic
985 for( it = elemList.begin(); it != elemList.end(); ++it)
989 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
991 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
993 entry->SetOffset(0); // just to avoid further missprinting
997 // NULL when we Build Up (ex nihilo) a DICOMDIR
998 // or when we add the META elems
999 val = header->GetEntryValue(tmpGr, tmpEl);
1006 if( val == GDCM_UNFOUND)
1008 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1010 // force to the *end* File Name
1011 val = Util::GetName( path );
1013 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1015 if( header->GetFileName().substr(0, path.length()) != path )
1017 gdcmWarningMacro( "The base path of file name is incorrect");
1018 val = header->GetFileName();
1022 val = &(header->GetFileName().c_str()[path.length()]);
1032 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1036 entry->SetValue( val ); // troubles expected when vr=SQ ...
1038 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1040 gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1042 si->AddEntry(entry);
1047 * \brief Move the content of the source SQItem to the destination SQItem
1048 * Only DocEntry's are moved
1049 * @param dst destination SQItem
1050 * @param src source SQItem
1052 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1056 entry = src->GetFirstEntry();
1059 src->RemoveEntryNoDestroy(entry);
1060 dst->AddEntry(entry);
1061 // we destroyed -> the current iterator is not longer valid
1062 entry = src->GetFirstEntry();
1067 * \brief compares two files
1069 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1071 return *header1 < *header2;
1074 //-----------------------------------------------------------------------------
1077 * \brief Canonical Printer
1078 * @param os ostream we want to print in
1079 * @param indent Indentation string to be prepended during printing
1081 void DicomDir::Print(std::ostream &os, std::string const & )
1085 MetaElems->SetPrintLevel(PrintLevel);
1086 MetaElems->Print(os);
1088 for(ListDicomDirPatient::iterator cc = Patients.begin();
1089 cc != Patients.end();
1092 (*cc)->SetPrintLevel(PrintLevel);
1097 //-----------------------------------------------------------------------------
1098 } // end namespace gdcm