1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/06/17 12:36:07 $
7 Version: $Revision: 1.141 $
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 );
221 * \brief This predicate, based on hopefully reasonable heuristics,
222 * decides whether or not the current document was properly parsed
223 * and contains the mandatory information for being considered as
224 * a well formed and usable DicomDir.
225 * @return true when Document is the one of a reasonable DicomDir,
228 bool DicomDir::IsReadable()
230 if( Filetype == Unknown)
232 gdcmWarningMacro( "Wrong filetype");
237 gdcmWarningMacro( "Meta Elements missing in DicomDir");
240 if( Patients.size() <= 0 )
242 gdcmWarningMacro( "NO Patient in DicomDir");
250 * \brief adds *the* Meta to a partially created DICOMDIR
252 DicomDirMeta *DicomDir::NewMeta()
257 DocEntry *entry = GetFirstEntry();
260 MetaElems = new DicomDirMeta(true); // true = empty
262 entry = GetFirstEntry();
265 if( dynamic_cast<SeqEntry *>(entry) )
268 RemoveEntryNoDestroy(entry);
269 MetaElems->AddEntry(entry);
271 entry = GetFirstEntry();
274 else // after root directory parsing
276 MetaElems = new DicomDirMeta(false); // false = not empty
278 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
283 * \brief adds a new Patient (with the basic elements) to a partially created
286 DicomDirPatient *DicomDir::NewPatient()
288 DicomDirPatient *p = new DicomDirPatient();
289 AddPatientToEnd( p );
294 * \brief Remove all Patients
296 void DicomDir::ClearPatient()
298 for(ListDicomDirPatient::iterator cc = Patients.begin();
308 * \brief Get the first entry while visiting the DicomDirPatients
309 * \return The first DicomDirPatient if found, otherwhise NULL
311 DicomDirPatient *DicomDir::GetFirstPatient()
313 ItPatient = Patients.begin();
314 if ( ItPatient != Patients.end() )
320 * \brief Get the next entry while visiting the DicomDirPatients
321 * \note : meaningfull only if GetFirstEntry already called
322 * \return The next DicomDirPatient if found, otherwhise NULL
324 DicomDirPatient *DicomDir::GetNextPatient()
326 gdcmAssertMacro (ItPatient != Patients.end());
329 if ( ItPatient != Patients.end() )
335 * \brief fills the whole structure, starting from a root Directory
337 void DicomDir::ParseDirectory()
339 CreateDicomDirChainedList( GetFileName() );
344 * \brief Set the start method to call when the parsing of the
346 * @param method Method to call
347 * @param arg Argument to pass to the method
348 * @param argDelete Argument
349 * \warning In python : the arg parameter isn't considered
351 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
352 DicomDir::Method *argDelete )
354 if( StartArg && StartMethodArgDelete )
356 StartMethodArgDelete( StartArg );
359 StartMethod = method;
361 StartMethodArgDelete = argDelete;
366 * \brief Set the progress method to call when the parsing of the
368 * @param method Method to call
369 * @param arg Argument to pass to the method
370 * @param argDelete Argument
371 * \warning In python : the arg parameter isn't considered
373 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
374 DicomDir::Method *argDelete )
376 if( ProgressArg && ProgressMethodArgDelete )
378 ProgressMethodArgDelete( ProgressArg );
381 ProgressMethod = method;
383 ProgressMethodArgDelete = argDelete;
387 * \brief Set the end method to call when the parsing of the directory ends
388 * @param method Method to call
389 * @param arg Argument to pass to the method
390 * @param argDelete Argument
391 * \warning In python : the arg parameter isn't considered
393 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
394 DicomDir::Method *argDelete )
396 if( EndArg && EndMethodArgDelete )
398 EndMethodArgDelete( EndArg );
403 EndMethodArgDelete = argDelete;
407 * \brief Set the method to delete the argument
408 * The argument is destroyed when the method is changed or when the
410 * @param method Method to call to delete the argument
412 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
414 StartMethodArgDelete = method;
418 * \brief Set the method to delete the argument
419 * The argument is destroyed when the method is changed or when the
421 * @param method Method to call to delete the argument
423 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
425 ProgressMethodArgDelete = method;
429 * \brief Set the method to delete the argument
430 * The argument is destroyed when the method is changed or when
431 * the class is destroyed
432 * @param method Method to call to delete the argument
434 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
436 EndMethodArgDelete = method;
440 * \brief writes on disc a DICOMDIR
441 * \ warning does NOT add the missing elements in the header :
442 * it's up to the user doing it !
443 * @param fileName file to be written to
444 * @return false only when fail to open
447 bool DicomDir::WriteDicomDir(std::string const &fileName)
450 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
451 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
453 std::ofstream *fp = new std::ofstream(fileName.c_str(),
454 std::ios::out | std::ios::binary);
457 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
461 char filePreamble[128];
462 memset(filePreamble, 0, 128);
463 fp->write(filePreamble, 128);
464 binary_write( *fp, "DICM");
466 DicomDirMeta *ptrMeta = GetMeta();
467 ptrMeta->WriteContent(fp, ExplicitVR);
469 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
472 binary_write(*fp, sq[i]);
475 for(ListDicomDirPatient::iterator cc = Patients.begin();
476 cc != Patients.end();
479 (*cc)->WriteContent( fp, ExplicitVR );
482 // force writing Sequence Delimitation Item
485 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
495 * \brief Anonymize a DICOMDIR
499 bool DicomDir::AnonymizeDicomDir()
502 // Something clever to be found to forge the Patient names
503 std::ostringstream s;
505 for(ListDicomDirPatient::iterator cc = Patients.begin();
510 v = (*cc)->GetValEntry(0x0010, 0x0010) ; // Patient's Name
513 v->SetValue(s.str());
516 v = (*cc)->GetValEntry(0x0010, 0x0020) ; // Patient ID
522 v = (*cc)->GetValEntry(0x0010, 0x0030) ; // Patient's BirthDate
533 //-----------------------------------------------------------------------------
536 * \brief create a Document-like chained list from a root Directory
537 * @param path entry point of the tree-like structure
539 void DicomDir::CreateDicomDirChainedList(std::string const &path)
542 DirList dirList(path,1); // gets recursively the file list
543 unsigned int count = 0;
547 DirListType fileList = dirList.GetFilenames();
549 for( DirListType::iterator it = fileList.begin();
550 it != fileList.end();
553 Progress = (float)(count+1)/(float)fileList.size();
554 CallProgressMethod();
561 f->SetLoadMode(LoadMode); // we allow user not to load Sequences...
562 f->Load( it->c_str() );
566 // gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
570 if( f->IsReadable() )
572 // Add the file to the chained list:
574 gdcmWarningMacro( "Readable " << it->c_str() );
582 // sorts Patient/Study/Serie/
583 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
585 std::string tmp = dirList.GetDirName();
586 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
587 SetElements(tmp, list);
590 for(VectDocument::iterator itDoc=list.begin();
594 delete dynamic_cast<File *>(*itDoc);
599 * \brief CallStartMethod
601 void DicomDir::CallStartMethod()
607 StartMethod( StartArg );
612 * \brief CallProgressMethod
614 void DicomDir::CallProgressMethod()
618 ProgressMethod( ProgressArg );
623 * \brief CallEndMethod
625 void DicomDir::CallEndMethod()
634 //-----------------------------------------------------------------------------
637 * \brief Sets all fields to NULL
639 void DicomDir::Initialize()
642 ProgressMethod = NULL;
644 StartMethodArgDelete = NULL;
645 ProgressMethodArgDelete = NULL;
646 EndMethodArgDelete = NULL;
658 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
660 void DicomDir::CreateDicomDir()
662 // The SeqEntries of "Directory Record Sequence" are parsed.
663 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
664 // 1 - we save the beginning iterator
665 // 2 - we continue to parse
666 // 3 - we find an other tag
667 // + we create the object for the precedent tag
670 // Directory record sequence
671 DocEntry *e = GetDocEntry(0x0004, 0x1220);
674 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
678 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
681 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
691 SQItem *tmpSI=s->GetFirstSQItem();
694 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
695 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
697 v = valEntry->GetValue();
701 gdcmWarningMacro( "(0004,1430) not a ValEntry ?!?");
705 if( v == "PATIENT " )
707 si = new DicomDirPatient(true);
708 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
712 gdcmErrorMacro( "Add PatientToEnd failed");
715 else if( v == "STUDY " )
717 si = new DicomDirStudy(true);
718 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
722 gdcmErrorMacro( "Add AddStudyToEnd failed");
725 else if( v == "SERIES" )
727 si = new DicomDirSerie(true);
728 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
732 gdcmErrorMacro( "Add AddSerieToEnd failed");
735 else if( v == "IMAGE " )
737 si = new DicomDirImage(true);
738 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
742 gdcmErrorMacro( "Add AddImageToEnd failed");
747 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
748 // neither an 'IMAGE' SQItem. Skip to next item.
752 MoveSQItem(si,tmpSI);
754 tmpSI=s->GetNextSQItem();
760 * \brief AddPatientToEnd
761 * @param dd SQ Item to enqueue to the DicomPatient chained List
763 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
765 Patients.push_back(dd);
770 * \brief AddStudyToEnd
771 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
773 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
775 if( Patients.size() > 0 )
777 ListDicomDirPatient::iterator itp = Patients.end();
779 (*itp)->AddStudy(dd);
786 * \brief AddSerieToEnd
787 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
789 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
791 if( Patients.size() > 0 )
793 ListDicomDirPatient::iterator itp = Patients.end();
796 DicomDirStudy *study = (*itp)->GetLastStudy();
807 * \brief AddImageToEnd
808 * @param dd SQ Item to enqueue to the DicomDirImage chained List
810 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
812 if( Patients.size() > 0 )
814 ListDicomDirPatient::iterator itp = Patients.end();
817 DicomDirStudy *study = (*itp)->GetLastStudy();
820 DicomDirSerie *serie = study->GetLastSerie();
832 * \brief for each Header of the chained list,
833 * add/update the Patient/Study/Serie/Image info
834 * @param path path of the root directory
835 * @param list chained list of Headers
837 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
842 std::string patPrevName = "", patPrevID = "";
843 std::string studPrevInstanceUID = "", studPrevID = "";
844 std::string serPrevInstanceUID = "", serPrevID = "";
846 std::string patCurName, patCurID;
847 std::string studCurInstanceUID, studCurID;
848 std::string serCurInstanceUID, serCurID;
851 for( VectDocument::const_iterator it = list.begin();
855 // get the current file characteristics
856 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
857 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
858 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
859 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
860 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
861 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
863 if( patCurName != patPrevName || patCurID != patPrevID || first )
865 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
869 // if new Study Deal with 'STUDY' Elements
870 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
873 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
877 // if new Serie Deal with 'SERIE' Elements
878 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
881 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
884 // Always Deal with 'IMAGE' Elements
885 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
887 patPrevName = patCurName;
888 patPrevID = patCurID;
889 studPrevInstanceUID = studCurInstanceUID;
890 studPrevID = studCurID;
891 serPrevInstanceUID = serCurInstanceUID;
892 serPrevID = serCurID;
898 * \brief adds to the HTable
899 * the Entries (Dicom Elements) corresponding to the given type
900 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
901 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
902 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
903 * @param header Header of the current file
905 void DicomDir::SetElement(std::string const &path, DicomDirType type,
908 ListDicomDirElem elemList;
909 ListDicomDirElem::const_iterator it;
910 uint16_t tmpGr, tmpEl;
911 DictEntry *dictEntry;
918 case GDCM_DICOMDIR_IMAGE:
919 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
920 si = new DicomDirImage(true);
921 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
924 gdcmErrorMacro( "Add ImageToEnd failed");
927 case GDCM_DICOMDIR_SERIE:
928 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
929 si = new DicomDirSerie(true);
930 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
933 gdcmErrorMacro( "Add SerieToEnd failed");
936 case GDCM_DICOMDIR_STUDY:
937 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
938 si = new DicomDirStudy(true);
939 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
942 gdcmErrorMacro( "Add StudyToEnd failed");
945 case GDCM_DICOMDIR_PATIENT:
946 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
947 si = new DicomDirPatient(true);
948 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
951 gdcmErrorMacro( "Add PatientToEnd failed");
954 case GDCM_DICOMDIR_META:
955 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
956 si = new DicomDirMeta(true);
960 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
962 MetaElems = static_cast<DicomDirMeta *>(si);
967 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
968 // to avoid further troubles
969 // imageElem 0008 1140 "" // Referenced Image Sequence
970 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
971 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
972 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
973 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
975 // FIXME : troubles found when it's a SeqEntry
977 // for all the relevant elements found in their own spot of the DicomDir.dic
978 for( it = elemList.begin(); it != elemList.end(); ++it)
982 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
984 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
986 entry->SetOffset(0); // just to avoid further missprinting
990 // NULL when we Build Up (ex nihilo) a DICOMDIR
991 // or when we add the META elems
992 val = header->GetEntryValue(tmpGr, tmpEl);
999 if( val == GDCM_UNFOUND)
1001 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1003 // force to the *end* File Name
1004 val = Util::GetName( path );
1006 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1008 if( header->GetFileName().substr(0, path.length()) != path )
1010 gdcmWarningMacro( "The base path of file name is incorrect");
1011 val = header->GetFileName();
1015 val = &(header->GetFileName().c_str()[path.length()]);
1025 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1029 entry->SetValue( val ); // troubles expected when vr=SQ ...
1031 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1033 gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1035 si->AddEntry(entry);
1040 * \brief Move the content of the source SQItem to the destination SQItem
1041 * Only DocEntry's are moved
1042 * @param dst destination SQItem
1043 * @param src source SQItem
1045 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1049 entry = src->GetFirstEntry();
1052 src->RemoveEntryNoDestroy(entry);
1053 dst->AddEntry(entry);
1054 // we destroyed -> the current iterator is not longer valid
1055 entry = src->GetFirstEntry();
1060 * \brief compares two files
1062 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1064 return *header1 < *header2;
1067 //-----------------------------------------------------------------------------
1070 * \brief Canonical Printer
1071 * @param os ostream we want to print in
1072 * @param indent Indentation string to be prepended during printing
1074 void DicomDir::Print(std::ostream &os, std::string const & )
1078 MetaElems->SetPrintLevel(PrintLevel);
1079 MetaElems->Print(os);
1081 for(ListDicomDirPatient::iterator cc = Patients.begin();
1082 cc != Patients.end();
1085 (*cc)->SetPrintLevel(PrintLevel);
1090 //-----------------------------------------------------------------------------
1091 } // end namespace gdcm