1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/04/14 14:26:19 $
7 Version: $Revision: 1.137 $
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 void 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);
198 // Only if user passed a root directory
199 // ------------------------------------
200 if ( fileName == "." )
202 // user passed '.' as Name
203 // we get current directory name
205 getcwd(dummy, (size_t)1000);
206 SetFileName( dummy ); // will be converted into a string
209 gdcmWarningMacro( "Parse directory and create the DicomDir : " << Filename );
215 * \brief This predicate, based on hopefully reasonable heuristics,
216 * decides whether or not the current document was properly parsed
217 * and contains the mandatory information for being considered as
218 * a well formed and usable DicomDir.
219 * @return true when Document is the one of a reasonable DicomDir,
222 bool DicomDir::IsReadable()
224 if( Filetype == Unknown)
226 gdcmWarningMacro( "Wrong filetype");
231 gdcmWarningMacro( "Meta Elements missing in DicomDir");
234 if( Patients.size() <= 0 )
236 gdcmWarningMacro( "NO Patient in DicomDir");
244 * \brief adds *the* Meta to a partially created DICOMDIR
246 DicomDirMeta *DicomDir::NewMeta()
251 DocEntry *entry = GetFirstEntry();
254 MetaElems = new DicomDirMeta(true);
256 entry = GetFirstEntry();
259 if( dynamic_cast<SeqEntry *>(entry) )
262 RemoveEntryNoDestroy(entry);
263 MetaElems->AddEntry(entry);
265 entry = GetFirstEntry();
268 else // after root directory parsing
270 MetaElems = new DicomDirMeta(false);
272 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
277 * \brief adds a new Patient (with the basic elements) to a partially created
280 DicomDirPatient *DicomDir::NewPatient()
282 DicomDirPatient *p = new DicomDirPatient();
283 AddPatientToEnd( p );
288 * \brief Remove all Patients
290 void DicomDir::ClearPatient()
292 for(ListDicomDirPatient::iterator cc = Patients.begin();
302 * \brief Get the first entry while visiting the DicomDirPatients
303 * \return The first DicomDirPatient if found, otherwhise NULL
305 DicomDirPatient *DicomDir::GetFirstPatient()
307 ItPatient = Patients.begin();
308 if ( ItPatient != Patients.end() )
314 * \brief Get the next entry while visiting the DicomDirPatients
315 * \note : meaningfull only if GetFirstEntry already called
316 * \return The next DicomDirPatient if found, otherwhise NULL
318 DicomDirPatient *DicomDir::GetNextPatient()
320 gdcmAssertMacro (ItPatient != Patients.end());
323 if ( ItPatient != Patients.end() )
329 * \brief fills the whole structure, starting from a root Directory
331 void DicomDir::ParseDirectory()
333 CreateDicomDirChainedList( GetFileName() );
338 * \brief Set the start method to call when the parsing of the
340 * @param method Method to call
341 * @param arg Argument to pass to the method
342 * @param argDelete Argument
343 * \warning In python : the arg parameter isn't considered
345 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
346 DicomDir::Method *argDelete )
348 if( StartArg && StartMethodArgDelete )
350 StartMethodArgDelete( StartArg );
353 StartMethod = method;
355 StartMethodArgDelete = argDelete;
360 * \brief Set the progress method to call when the parsing of the
362 * @param method Method to call
363 * @param arg Argument to pass to the method
364 * @param argDelete Argument
365 * \warning In python : the arg parameter isn't considered
367 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
368 DicomDir::Method *argDelete )
370 if( ProgressArg && ProgressMethodArgDelete )
372 ProgressMethodArgDelete( ProgressArg );
375 ProgressMethod = method;
377 ProgressMethodArgDelete = argDelete;
381 * \brief Set the end method to call when the parsing of the directory ends
382 * @param method Method to call
383 * @param arg Argument to pass to the method
384 * @param argDelete Argument
385 * \warning In python : the arg parameter isn't considered
387 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
388 DicomDir::Method *argDelete )
390 if( EndArg && EndMethodArgDelete )
392 EndMethodArgDelete( EndArg );
397 EndMethodArgDelete = argDelete;
401 * \brief Set the method to delete the argument
402 * The argument is destroyed when the method is changed or when the
404 * @param method Method to call to delete the argument
406 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
408 StartMethodArgDelete = method;
412 * \brief Set the method to delete the argument
413 * The argument is destroyed when the method is changed or when the
415 * @param method Method to call to delete the argument
417 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
419 ProgressMethodArgDelete = method;
423 * \brief Set the method to delete the argument
424 * The argument is destroyed when the method is changed or when
425 * the class is destroyed
426 * @param method Method to call to delete the argument
428 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
430 EndMethodArgDelete = method;
434 * \brief writes on disc a DICOMDIR
435 * \ warning does NOT add the missing elements in the header :
436 * it's up to the user doing it !
437 * @param fileName file to be written to
438 * @return false only when fail to open
441 bool DicomDir::WriteDicomDir(std::string const &fileName)
444 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
445 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
447 std::ofstream *fp = new std::ofstream(fileName.c_str(),
448 std::ios::out | std::ios::binary);
451 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
455 char filePreamble[128];
456 memset(filePreamble, 0, 128);
457 fp->write(filePreamble, 128);
458 binary_write( *fp, "DICM");
460 DicomDirMeta *ptrMeta = GetMeta();
461 ptrMeta->WriteContent(fp, ExplicitVR);
463 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
466 binary_write(*fp, sq[i]);
469 for(ListDicomDirPatient::iterator cc = Patients.begin();
470 cc != Patients.end();
473 (*cc)->WriteContent( fp, ExplicitVR );
476 // force writing Sequence Delimitation Item
479 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
489 * \brief Anonymize a DICOMDIR
493 bool DicomDir::AnonymizeDicomDir()
496 // Something clever to be found to forge the Patient names
497 std::ostringstream s;
499 for(ListDicomDirPatient::iterator cc = Patients.begin();
504 v = (*cc)->GetValEntry(0x0010, 0x0010) ; // Patient's Name
507 v->SetValue(s.str());
510 v = (*cc)->GetValEntry(0x0010, 0x0020) ; // Patient ID
516 v = (*cc)->GetValEntry(0x0010, 0x0030) ; // Patient's BirthDate
535 //-----------------------------------------------------------------------------
538 * \brief create a Document-like chained list from a root Directory
539 * @param path entry point of the tree-like structure
541 void DicomDir::CreateDicomDirChainedList(std::string const &path)
544 DirList dirList(path,1); // gets recursively the file list
545 unsigned int count = 0;
549 DirListType fileList = dirList.GetFilenames();
551 for( DirListType::iterator it = fileList.begin();
552 it != fileList.end();
555 Progress = (float)(count+1)/(float)fileList.size();
556 CallProgressMethod();
563 f->SetLoadMode(LoadMode); // we allow user not to load Sequences...
564 f->Load( it->c_str() );
568 // gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
572 if( f->IsReadable() )
574 // Add the file to the chained list:
576 gdcmWarningMacro( "Readable " << it->c_str() );
584 // sorts Patient/Study/Serie/
585 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
587 std::string tmp = dirList.GetDirName();
588 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
589 SetElements(tmp, list);
592 for(VectDocument::iterator itDoc=list.begin();
596 delete dynamic_cast<File *>(*itDoc);
601 * \brief CallStartMethod
603 void DicomDir::CallStartMethod()
609 StartMethod( StartArg );
614 * \brief CallProgressMethod
616 void DicomDir::CallProgressMethod()
620 ProgressMethod( ProgressArg );
625 * \brief CallEndMethod
627 void DicomDir::CallEndMethod()
636 //-----------------------------------------------------------------------------
639 * \brief Sets all fields to NULL
641 void DicomDir::Initialize()
644 ProgressMethod = NULL;
646 StartMethodArgDelete = NULL;
647 ProgressMethodArgDelete = NULL;
648 EndMethodArgDelete = NULL;
660 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
662 void DicomDir::CreateDicomDir()
664 // The SeqEntries of "Directory Record Sequence" are parsed.
665 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
666 // 1 - we save the beginning iterator
667 // 2 - we continue to parse
668 // 3 - we find an other tag
669 // + we create the object for the precedent tag
672 // Directory record sequence
673 DocEntry *e = GetDocEntry(0x0004, 0x1220);
676 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
680 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
683 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
693 SQItem *tmpSI=s->GetFirstSQItem();
696 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
697 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
699 v = valEntry->GetValue();
703 gdcmWarningMacro( "(0004,1430) not a ValEntry ?!?");
707 if( v == "PATIENT " )
709 si = new DicomDirPatient(true);
710 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
714 gdcmErrorMacro( "Add PatientToEnd failed");
717 else if( v == "STUDY " )
719 si = new DicomDirStudy(true);
720 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
724 gdcmErrorMacro( "Add AddStudyToEnd failed");
727 else if( v == "SERIES" )
729 si = new DicomDirSerie(true);
730 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
734 gdcmErrorMacro( "Add AddSerieToEnd failed");
737 else if( v == "IMAGE " )
739 si = new DicomDirImage(true);
740 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
744 gdcmErrorMacro( "Add AddImageToEnd failed");
749 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
750 // neither an 'IMAGE' SQItem. Skip to next item.
754 MoveSQItem(si,tmpSI);
756 tmpSI=s->GetNextSQItem();
762 * \brief AddPatientToEnd
763 * @param dd SQ Item to enqueue to the DicomPatient chained List
765 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
767 Patients.push_back(dd);
772 * \brief AddStudyToEnd
773 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
775 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
777 if( Patients.size() > 0 )
779 ListDicomDirPatient::iterator itp = Patients.end();
781 (*itp)->AddStudy(dd);
788 * \brief AddSerieToEnd
789 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
791 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
793 if( Patients.size() > 0 )
795 ListDicomDirPatient::iterator itp = Patients.end();
798 DicomDirStudy *study = (*itp)->GetLastStudy();
809 * \brief AddImageToEnd
810 * @param dd SQ Item to enqueue to the DicomDirImage chained List
812 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
814 if( Patients.size() > 0 )
816 ListDicomDirPatient::iterator itp = Patients.end();
819 DicomDirStudy *study = (*itp)->GetLastStudy();
822 DicomDirSerie *serie = study->GetLastSerie();
834 * \brief for each Header of the chained list,
835 * add/update the Patient/Study/Serie/Image info
836 * @param path path of the root directory
837 * @param list chained list of Headers
839 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
844 std::string patPrevName = "", patPrevID = "";
845 std::string studPrevInstanceUID = "", studPrevID = "";
846 std::string serPrevInstanceUID = "", serPrevID = "";
848 std::string patCurName, patCurID;
849 std::string studCurInstanceUID, studCurID;
850 std::string serCurInstanceUID, serCurID;
853 for( VectDocument::const_iterator it = list.begin();
857 // get the current file characteristics
858 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
859 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
860 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
861 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
862 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
863 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
865 if( patCurName != patPrevName || patCurID != patPrevID || first )
867 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
871 // if new Study Deal with 'STUDY' Elements
872 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
875 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
879 // if new Serie Deal with 'SERIE' Elements
880 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
883 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
886 // Always Deal with 'IMAGE' Elements
887 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
889 patPrevName = patCurName;
890 patPrevID = patCurID;
891 studPrevInstanceUID = studCurInstanceUID;
892 studPrevID = studCurID;
893 serPrevInstanceUID = serCurInstanceUID;
894 serPrevID = serCurID;
900 * \brief adds to the HTable
901 * the Entries (Dicom Elements) corresponding to the given type
902 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
903 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
904 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
905 * @param header Header of the current file
907 void DicomDir::SetElement(std::string const &path, DicomDirType type,
910 ListDicomDirElem elemList;
911 ListDicomDirElem::const_iterator it;
912 uint16_t tmpGr, tmpEl;
913 DictEntry *dictEntry;
920 case GDCM_DICOMDIR_IMAGE:
921 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
922 si = new DicomDirImage(true);
923 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
926 gdcmErrorMacro( "Add ImageToEnd failed");
929 case GDCM_DICOMDIR_SERIE:
930 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
931 si = new DicomDirSerie(true);
932 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
935 gdcmErrorMacro( "Add SerieToEnd failed");
938 case GDCM_DICOMDIR_STUDY:
939 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
940 si = new DicomDirStudy(true);
941 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
944 gdcmErrorMacro( "Add StudyToEnd failed");
947 case GDCM_DICOMDIR_PATIENT:
948 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
949 si = new DicomDirPatient(true);
950 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
953 gdcmErrorMacro( "Add PatientToEnd failed");
956 case GDCM_DICOMDIR_META:
957 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
958 si = new DicomDirMeta(true);
962 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
964 MetaElems = static_cast<DicomDirMeta *>(si);
969 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
970 // to avoid further troubles
971 // imageElem 0008 1140 "" // Referenced Image Sequence
972 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
973 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
974 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
975 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
977 // FIXME : troubles found when it's a SeqEntry
979 // for all the relevant elements found in their own spot of the DicomDir.dic
980 for( it = elemList.begin(); it != elemList.end(); ++it)
984 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
986 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
988 entry->SetOffset(0); // just to avoid further missprinting
992 // NULL when we Build Up (ex nihilo) a DICOMDIR
993 // or when we add the META elems
994 val = header->GetEntryValue(tmpGr, tmpEl);
1001 if( val == GDCM_UNFOUND)
1003 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1005 // force to the *end* File Name
1006 val = Util::GetName( path );
1008 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1010 if( header->GetFileName().substr(0, path.length()) != path )
1012 gdcmWarningMacro( "The base path of file name is incorrect");
1013 val = header->GetFileName();
1017 val = &(header->GetFileName().c_str()[path.length()]);
1027 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1031 entry->SetValue( val ); // troubles expected when vr=SQ ...
1033 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1035 gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1037 si->AddEntry(entry);
1042 * \brief Move the content of the source SQItem to the destination SQItem
1043 * Only DocEntry's are moved
1044 * @param dst destination SQItem
1045 * @param src source SQItem
1047 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1051 entry = src->GetFirstEntry();
1054 src->RemoveEntryNoDestroy(entry);
1055 dst->AddEntry(entry);
1056 // we destroyed -> the current iterator is not longer valid
1057 entry = src->GetFirstEntry();
1062 * \brief compares two files
1064 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1066 return *header1 < *header2;
1069 //-----------------------------------------------------------------------------
1072 * \brief Canonical Printer
1073 * @param os ostream we want to print in
1074 * @param indent Indentation string to be prepended during printing
1076 void DicomDir::Print(std::ostream &os, std::string const & )
1080 MetaElems->SetPrintLevel(PrintLevel);
1081 MetaElems->Print(os);
1083 for(ListDicomDirPatient::iterator cc = Patients.begin();
1084 cc != Patients.end();
1087 (*cc)->SetPrintLevel(PrintLevel);
1092 //-----------------------------------------------------------------------------
1093 } // end namespace gdcm