1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/03/02 17:16:48 $
7 Version: $Revision: 1.134 $
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)
140 Initialize(); // sets all private fields to NULL
142 // if user passed a root directory, sure we didn't get anything
144 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
147 gdcmWarningMacro( "Entry HT empty for file: "<<fileName);
149 // Only if user passed a root directory
150 // ------------------------------------
151 if ( fileName == "." )
153 // user passed '.' as Name
154 // we get current directory name
156 getcwd(dummy, (size_t)1000);
157 SetFileName( dummy ); // will be converted into a string
160 if ( parseDir ) // user asked for a recursive parsing of a root directory
164 gdcmWarningMacro( "Parse directory and create the DicomDir");
169 // user may just call ParseDirectory() *after* constructor
172 // Only if user passed a DICOMDIR
173 // ------------------------------
176 // Directory record sequence
177 DocEntry *e = GetDocEntry(0x0004, 0x1220);
180 gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
181 << " in file " << fileName);
189 * \brief Canonical destructor
191 DicomDir::~DicomDir()
193 SetStartMethod(NULL);
194 SetProgressMethod(NULL);
204 //-----------------------------------------------------------------------------
207 * \brief This predicate, based on hopefully reasonable heuristics,
208 * decides whether or not the current document was properly parsed
209 * and contains the mandatory information for being considered as
210 * a well formed and usable DicomDir.
211 * @return true when Document is the one of a reasonable DicomDir,
214 bool DicomDir::IsReadable()
216 if( Filetype == Unknown)
218 gdcmWarningMacro( "Wrong filetype");
223 gdcmWarningMacro( "Meta Elements missing in DicomDir");
226 if( Patients.size() <= 0 )
228 gdcmWarningMacro( "NO Patient in DicomDir");
236 * \brief adds *the* Meta to a partially created DICOMDIR
238 DicomDirMeta *DicomDir::NewMeta()
243 DocEntry *entry = GetFirstEntry();
246 MetaElems = new DicomDirMeta(true);
248 entry = GetFirstEntry();
251 if( dynamic_cast<SeqEntry *>(entry) )
254 RemoveEntryNoDestroy(entry);
255 MetaElems->AddEntry(entry);
257 entry = GetFirstEntry();
260 else // after root directory parsing
262 MetaElems = new DicomDirMeta(false);
264 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
269 * \brief adds a new Patient (with the basic elements) to a partially created
272 DicomDirPatient *DicomDir::NewPatient()
274 DicomDirPatient *p = new DicomDirPatient();
275 AddPatientToEnd( p );
280 * \brief Remove all Patients
282 void DicomDir::ClearPatient()
284 for(ListDicomDirPatient::iterator cc = Patients.begin();
294 * \brief Get the first entry while visiting the DicomDirPatients
295 * \return The first DicomDirPatient if found, otherwhise NULL
297 DicomDirPatient *DicomDir::GetFirstPatient()
299 ItPatient = Patients.begin();
300 if ( ItPatient != Patients.end() )
306 * \brief Get the next entry while visiting the DicomDirPatients
307 * \note : meaningfull only if GetFirstEntry already called
308 * \return The next DicomDirPatient if found, otherwhise NULL
310 DicomDirPatient *DicomDir::GetNextPatient()
312 gdcmAssertMacro (ItPatient != Patients.end());
315 if ( ItPatient != Patients.end() )
321 * \brief fills the whole structure, starting from a root Directory
323 void DicomDir::ParseDirectory()
325 CreateDicomDirChainedList( GetFileName() );
330 * \brief Set the start method to call when the parsing of the
332 * @param method Method to call
333 * @param arg Argument to pass to the method
334 * @param argDelete Argument
335 * \warning In python : the arg parameter isn't considered
337 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
338 DicomDir::Method *argDelete )
340 if( StartArg && StartMethodArgDelete )
342 StartMethodArgDelete( StartArg );
345 StartMethod = method;
347 StartMethodArgDelete = argDelete;
351 * \brief Set the progress method to call when the parsing of the
353 * @param method Method to call
354 * @param arg Argument to pass to the method
355 * @param argDelete Argument
356 * \warning In python : the arg parameter isn't considered
358 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
359 DicomDir::Method *argDelete )
361 if( ProgressArg && ProgressMethodArgDelete )
363 ProgressMethodArgDelete( ProgressArg );
366 ProgressMethod = method;
368 ProgressMethodArgDelete = argDelete;
372 * \brief Set the end method to call when the parsing of the directory ends
373 * @param method Method to call
374 * @param arg Argument to pass to the method
375 * @param argDelete Argument
376 * \warning In python : the arg parameter isn't considered
378 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
379 DicomDir::Method *argDelete )
381 if( EndArg && EndMethodArgDelete )
383 EndMethodArgDelete( EndArg );
388 EndMethodArgDelete = argDelete;
392 * \brief Set the method to delete the argument
393 * The argument is destroyed when the method is changed or when the
395 * @param method Method to call to delete the argument
397 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
399 StartMethodArgDelete = method;
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::SetProgressMethodArgDelete( DicomDir::Method *method )
410 ProgressMethodArgDelete = method;
414 * \brief Set the method to delete the argument
415 * The argument is destroyed when the method is changed or when
416 * the class is destroyed
417 * @param method Method to call to delete the argument
419 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
421 EndMethodArgDelete = method;
425 * \brief writes on disc a DICOMDIR
426 * \ warning does NOT add the missing elements in the header :
427 * it's up to the user doing it !
428 * @param fileName file to be written to
429 * @return false only when fail to open
432 bool DicomDir::WriteDicomDir(std::string const &fileName)
435 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
436 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
438 std::ofstream *fp = new std::ofstream(fileName.c_str(),
439 std::ios::out | std::ios::binary);
442 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
446 char filePreamble[128];
447 memset(filePreamble, 0, 128);
448 fp->write(filePreamble, 128);
449 binary_write( *fp, "DICM");
451 DicomDirMeta *ptrMeta = GetMeta();
452 ptrMeta->WriteContent(fp, ExplicitVR);
454 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
457 binary_write(*fp, sq[i]);
460 for(ListDicomDirPatient::iterator cc = Patients.begin();
461 cc != Patients.end();
464 (*cc)->WriteContent( fp, ExplicitVR );
467 // force writing Sequence Delimitation Item
470 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
479 //-----------------------------------------------------------------------------
482 * \brief create a Document-like chained list from a root Directory
483 * @param path entry point of the tree-like structure
485 void DicomDir::CreateDicomDirChainedList(std::string const &path)
488 DirList dirList(path,1); // gets recursively the file list
489 unsigned int count = 0;
493 DirListType fileList = dirList.GetFilenames();
495 for( DirListType::iterator it = fileList.begin();
496 it != fileList.end();
499 Progress = (float)(count+1)/(float)fileList.size();
500 CallProgressMethod();
506 header = new File( it->c_str() );
509 gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
513 if( header->IsReadable() )
515 // Add the file to the chained list:
516 list.push_back(header);
517 gdcmWarningMacro( "Readable " << it->c_str() );
525 // sorts Patient/Study/Serie/
526 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
528 std::string tmp = dirList.GetDirName();
529 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
530 SetElements(tmp, list);
533 for(VectDocument::iterator itDoc=list.begin();
537 delete dynamic_cast<File *>(*itDoc);
542 * \brief CallStartMethod
544 void DicomDir::CallStartMethod()
550 StartMethod( StartArg );
555 * \brief CallProgressMethod
557 void DicomDir::CallProgressMethod()
561 ProgressMethod( ProgressArg );
566 * \brief CallEndMethod
568 void DicomDir::CallEndMethod()
577 //-----------------------------------------------------------------------------
580 * \brief Sets all fields to NULL
582 void DicomDir::Initialize()
585 ProgressMethod = NULL;
587 StartMethodArgDelete = NULL;
588 ProgressMethodArgDelete = NULL;
589 EndMethodArgDelete = NULL;
601 * \brief create a 'DicomDir' from a DICOMDIR Header
603 void DicomDir::CreateDicomDir()
605 // The SeqEntries of "Directory Record Sequence" are parsed.
606 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
607 // 1 - we save the beginning iterator
608 // 2 - we continue to parse
609 // 3 - we find an other tag
610 // + we create the object for the precedent tag
613 // Directory record sequence
614 DocEntry *e = GetDocEntry(0x0004, 0x1220);
617 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
621 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
624 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
634 SQItem *tmpSI=s->GetFirstSQItem();
637 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
638 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
640 v = valEntry->GetValue();
644 gdcmWarningMacro( "Not a ValEntry.");
648 if( v == "PATIENT " )
650 si = new DicomDirPatient(true);
651 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
655 gdcmErrorMacro( "Add PatientToEnd failed");
658 else if( v == "STUDY " )
660 si = new DicomDirStudy(true);
661 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
665 gdcmErrorMacro( "Add AddStudyToEnd failed");
668 else if( v == "SERIES" )
670 si = new DicomDirSerie(true);
671 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
675 gdcmErrorMacro( "Add AddSerieToEnd failed");
678 else if( v == "IMAGE " )
680 si = new DicomDirImage(true);
681 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
685 gdcmErrorMacro( "Add AddImageToEnd failed");
690 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
691 // neither an 'IMAGE' SQItem. Skip to next item.
695 MoveSQItem(si,tmpSI);
697 tmpSI=s->GetNextSQItem();
703 * \brief AddPatientToEnd
704 * @param dd SQ Item to enqueue to the DicomPatient chained List
706 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
708 Patients.push_back(dd);
713 * \brief AddStudyToEnd
714 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
716 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
718 if( Patients.size() > 0 )
720 ListDicomDirPatient::iterator itp = Patients.end();
722 (*itp)->AddStudy(dd);
729 * \brief AddSerieToEnd
730 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
732 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
734 if( Patients.size() > 0 )
736 ListDicomDirPatient::iterator itp = Patients.end();
739 DicomDirStudy *study = (*itp)->GetLastStudy();
750 * \brief AddImageToEnd
751 * @param dd SQ Item to enqueue to the DicomDirImage chained List
753 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
755 if( Patients.size() > 0 )
757 ListDicomDirPatient::iterator itp = Patients.end();
760 DicomDirStudy *study = (*itp)->GetLastStudy();
763 DicomDirSerie *serie = study->GetLastSerie();
775 * \brief for each Header of the chained list,
776 * add/update the Patient/Study/Serie/Image info
777 * @param path path of the root directory
778 * @param list chained list of Headers
780 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
785 std::string patPrevName = "", patPrevID = "";
786 std::string studPrevInstanceUID = "", studPrevID = "";
787 std::string serPrevInstanceUID = "", serPrevID = "";
789 std::string patCurName, patCurID;
790 std::string studCurInstanceUID, studCurID;
791 std::string serCurInstanceUID, serCurID;
794 for( VectDocument::const_iterator it = list.begin();
798 // get the current file characteristics
799 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
800 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
801 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
802 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
803 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
804 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
806 if( patCurName != patPrevName || patCurID != patPrevID || first )
808 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
812 // if new Study Deal with 'STUDY' Elements
813 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
816 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
820 // if new Serie Deal with 'SERIE' Elements
821 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
824 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
827 // Always Deal with 'IMAGE' Elements
828 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
830 patPrevName = patCurName;
831 patPrevID = patCurID;
832 studPrevInstanceUID = studCurInstanceUID;
833 studPrevID = studCurID;
834 serPrevInstanceUID = serCurInstanceUID;
835 serPrevID = serCurID;
841 * \brief adds to the HTable
842 * the Entries (Dicom Elements) corresponding to the given type
843 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
844 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
845 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
846 * @param header Header of the current file
848 void DicomDir::SetElement(std::string const &path, DicomDirType type,
851 ListDicomDirElem elemList;
852 ListDicomDirElem::const_iterator it;
853 uint16_t tmpGr, tmpEl;
854 DictEntry *dictEntry;
861 case GDCM_DICOMDIR_IMAGE:
862 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
863 si = new DicomDirImage(true);
864 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
867 gdcmErrorMacro( "Add ImageToEnd failed");
870 case GDCM_DICOMDIR_SERIE:
871 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
872 si = new DicomDirSerie(true);
873 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
876 gdcmErrorMacro( "Add SerieToEnd failed");
879 case GDCM_DICOMDIR_STUDY:
880 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
881 si = new DicomDirStudy(true);
882 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
885 gdcmErrorMacro( "Add StudyToEnd failed");
888 case GDCM_DICOMDIR_PATIENT:
889 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
890 si = new DicomDirPatient(true);
891 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
894 gdcmErrorMacro( "Add PatientToEnd failed");
897 case GDCM_DICOMDIR_META:
898 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
899 si = new DicomDirMeta(true);
903 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
905 MetaElems = static_cast<DicomDirMeta *>(si);
910 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
911 // to avoid further troubles
912 // imageElem 0008 1140 "" // Referenced Image Sequence
913 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
914 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
915 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
916 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
918 // FIXME : troubles found when it's a SeqEntry
920 // for all the relevant elements found in their own spot of the DicomDir.dic
921 for( it = elemList.begin(); it != elemList.end(); ++it)
925 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
927 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
929 entry->SetOffset(0); // just to avoid further missprinting
933 // NULL when we Build Up (ex nihilo) a DICOMDIR
934 // or when we add the META elems
935 val = header->GetEntryValue(tmpGr, tmpEl);
942 if( val == GDCM_UNFOUND)
944 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
946 // force to the *end* File Name
947 val = Util::GetName( path );
949 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
951 if( header->GetFileName().substr(0, path.length()) != path )
953 gdcmWarningMacro( "The base path of file name is incorrect");
954 val = header->GetFileName();
958 val = &(header->GetFileName().c_str()[path.length()]);
968 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
972 entry->SetValue( val ); // troubles expected when vr=SQ ...
974 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
976 gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
983 * \brief Move the content of the source SQItem to the destination SQItem
984 * Only DocEntry's are moved
985 * @param dst destination SQItem
986 * @param src source SQItem
988 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
992 entry = src->GetFirstEntry();
995 src->RemoveEntryNoDestroy(entry);
996 dst->AddEntry(entry);
997 // we destroyed -> the current iterator is not longer valid
998 entry = src->GetFirstEntry();
1003 * \brief compares two files
1005 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1007 return *header1 < *header2;
1010 //-----------------------------------------------------------------------------
1013 * \brief Canonical Printer
1014 * @param os ostream we want to print in
1015 * @param indent Indentation string to be prepended during printing
1017 void DicomDir::Print(std::ostream &os, std::string const & )
1021 MetaElems->SetPrintLevel(PrintLevel);
1022 MetaElems->Print(os);
1024 for(ListDicomDirPatient::iterator cc = Patients.begin();
1025 cc != Patients.end();
1028 (*cc)->SetPrintLevel(PrintLevel);
1033 //-----------------------------------------------------------------------------
1034 } // end namespace gdcm