1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/11/28 15:20:32 $
7 Version: $Revision: 1.174 $
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 "gdcmDicomDirObject.h"
25 #include "gdcmDicomDirStudy.h"
26 #include "gdcmDicomDirSerie.h"
27 #include "gdcmDicomDirVisit.h"
28 #include "gdcmDicomDirImage.h"
29 #include "gdcmDicomDirPatient.h"
30 #include "gdcmDicomDirMeta.h"
31 #include "gdcmDicomDirElement.h"
32 #include "gdcmDirList.h"
34 #include "gdcmDebug.h"
35 #include "gdcmGlobal.h"
37 #include "gdcmSeqEntry.h"
38 #include "gdcmSQItem.h"
39 #include "gdcmDataEntry.h"
44 #include <sys/types.h>
47 # define getcwd _getcwd
50 #if defined(_MSC_VER) || defined(__BORLANDC__)
55 // ----------------------------------------------------------------------------
56 // Note for future developpers
57 // ----------------------------------------------------------------------------
59 // Dicom PS 3.3 describes the relationship between Directory Records, as follow
60 // (see also PS 4.3, 2004, page 50 for Entity-Relationship model)
62 // Directory Record Type Directory Record Types which may be included
63 // in the next lower-level directory Entity
65 // (Root directory Entity) PATIENT, TOPIC, PRIVATE
67 // PATIENT STUDY, PRIVATE
69 // STUDY SERIES, VISIT, RESULTS, STUDY COMPONENT, PRIVATE
71 // SERIES IMAGE, OVERLAYS, MODALITY LUT, VOI LUT,
72 // CURVE, STORED PRINT, RT DOSE, RT STRUCTURE SET
73 // RT PLAN, RT TREAT RECORD, PRESENTATION, WAVEFORM,
74 // SR DOCUMENT, KEY OBJECT DOC, SPECTROSCOPY,
75 // RAW DATA, REGISTRATION, FIDUCIAL, PRIVATE,
98 // ----------------------
99 // The current gdcm version only deals with :
101 // (Root directory Entity) PATIENT
108 // DicomDir::CreateDicomDir will have to be completed
109 // Treelike structure management will have to be upgraded
110 // ----------------------------------------------------------------------------
114 //-----------------------------------------------------------------------------
115 // Constructor / Destructor
117 * \brief Constructor : creates an empty DicomDir
122 Initialize(); // sets all private fields to NULL
128 * \brief Canonical destructor
130 DicomDir::~DicomDir()
139 //-----------------------------------------------------------------------------
143 * \brief Loader. use SetFileName(fn)
144 * or SetLoadMode(lm) + SetDirectoryName(dn) before !
145 * @return false if file cannot be open or no swap info was found,
146 * or no tag was found.
148 bool DicomDir::Load( )
152 if ( ! this->Document::Load( ) )
155 return DoTheLoadingJob( );
159 * \brief Does the Loading Job (internal use only)
160 * @return false if file cannot be open or no swap info was found,
161 * or no tag was found.
163 bool DicomDir::DoTheLoadingJob( )
170 // Only if user passed a DICOMDIR
171 // ------------------------------
173 if (!Document::Load() )
178 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
180 gdcmWarningMacro( "Entry HT empty for file: "<< GetFileName());
183 // Directory record sequence
184 DocEntry *e = GetDocEntry(0x0004, 0x1220);
187 gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
188 << " in file " << GetFileName());
196 // Only if user passed a root directory
197 // ------------------------------------
198 if ( GetFileName() == "." )
200 // user passed '.' as Name
201 // we get current directory name
203 const char *cwd = getcwd(buf, 2048);
206 SetFileName( buf ); // will be converted into a string
210 gdcmErrorMacro( "Path was too long to fit on 2048 bytes" );
214 gdcmDebugMacro( "Parse directory and create the DicomDir : "
222 * \brief This predicate, based on hopefully reasonable heuristics,
223 * decides whether or not the current document was properly parsed
224 * and contains the mandatory information for being considered as
225 * a well formed and usable DicomDir.
226 * @return true when Document is the one of a reasonable DicomDir,
229 bool DicomDir::IsReadable()
231 if ( Filetype == Unknown )
233 gdcmErrorMacro( "Wrong filetype for " << GetFileName());
238 gdcmWarningMacro( "Meta Elements missing in DicomDir");
241 if ( Patients.size() <= 0 )
243 gdcmWarningMacro( "NO Patient in DicomDir");
251 * \brief adds *the* Meta to a partially created DICOMDIR
253 DicomDirMeta *DicomDir::NewMeta()
258 DocEntry *entry = GetFirstEntry();
261 MetaElems = DicomDirMeta::New(true); // true = empty
263 entry = GetFirstEntry();
266 if ( dynamic_cast<SeqEntry *>(entry) )
269 MetaElems->AddEntry(entry);
272 entry = GetFirstEntry();
275 else // after root directory parsing
277 MetaElems = DicomDirMeta::New(false); // false = not empty
279 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
284 * \brief adds a new Patient (with the basic elements) to a partially created
287 DicomDirPatient *DicomDir::NewPatient()
289 DicomDirPatient *dd = DicomDirPatient::New();
290 AddPatientToEnd( dd );
295 * \brief Remove all Patients
297 void DicomDir::ClearPatient()
299 for(ListDicomDirPatient::iterator cc = Patients.begin();
309 * \brief Get the first entry while visiting the DicomDirPatients
310 * \return The first DicomDirPatient if found, otherwhise NULL
312 DicomDirPatient *DicomDir::GetFirstPatient()
314 ItPatient = Patients.begin();
315 if ( ItPatient != Patients.end() )
321 * \brief Get the next entry while visiting the DicomDirPatients
322 * \note : meaningfull only if GetFirstEntry already called
323 * \return The next DicomDirPatient if found, otherwhise NULL
325 DicomDirPatient *DicomDir::GetNextPatient()
327 gdcmAssertMacro (ItPatient != Patients.end());
330 if ( ItPatient != Patients.end() )
336 * \brief fills the whole structure, starting from a root Directory
338 void DicomDir::ParseDirectory()
340 CreateDicomDirChainedList( GetFileName() );
345 * \brief writes on disc a DICOMDIR
346 * \ warning does NOT add the missing elements in the header :
347 * it's up to the user doing it !
348 * @param fileName file to be written to
349 * @return false only when fail to open
352 bool DicomDir::Write(std::string const &fileName)
355 uint16_t sq[6] = { 0x0004, 0x1220, 0x5153, 0x0000, 0xffff, 0xffff };
356 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
358 std::ofstream *fp = new std::ofstream(fileName.c_str(),
359 std::ios::out | std::ios::binary);
362 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
366 char filePreamble[128];
367 memset(filePreamble, 0, 128);
368 fp->write(filePreamble, 128);
369 binary_write( *fp, "DICM");
371 DicomDirMeta *ptrMeta = GetMeta();
372 ptrMeta->WriteContent(fp, ExplicitVR);
374 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
377 binary_write(*fp, sq[i]);
380 for(ListDicomDirPatient::iterator cc = Patients.begin();
381 cc != Patients.end();
384 (*cc)->WriteContent( fp, ExplicitVR );
387 // force writing Sequence Delimitation Item
390 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
400 * \brief Anonymize a DICOMDIR
404 bool DicomDir::Anonymize()
407 // Something clever to be found to forge the Patient names
408 std::ostringstream s;
410 for(ListDicomDirPatient::iterator cc = Patients.begin();
415 v = (*cc)->GetDataEntry(0x0010, 0x0010) ; // Patient's Name
418 v->SetString(s.str());
421 v = (*cc)->GetDataEntry(0x0010, 0x0020) ; // Patient ID
427 v = (*cc)->GetDataEntry(0x0010, 0x0030) ; // Patient's BirthDate
438 //-----------------------------------------------------------------------------
441 * \brief create a Document-like chained list from a root Directory
442 * @param path entry point of the tree-like structure
444 void DicomDir::CreateDicomDirChainedList(std::string const &path)
447 DirList dirList(path,1); // gets recursively the file list
448 unsigned int count = 0;
452 DirListType fileList = dirList.GetFilenames();
454 for( DirListType::iterator it = fileList.begin();
455 it != fileList.end();
458 Progress = (float)(count+1)/(float)fileList.size();
459 CallProgressMethod();
466 f->SetLoadMode(LoadMode); // we allow user not to load Sequences,
467 // or Shadow groups, or ......
468 f->SetFileName( it->c_str() );
471 if ( f->IsReadable() )
473 // Add the file to the chained list:
475 gdcmDebugMacro( "Readable " << it->c_str() );
483 // sorts Patient/Study/Serie/
484 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
486 std::string tmp = dirList.GetDirName();
487 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
488 SetElements(tmp, list);
491 for(VectDocument::iterator itDoc=list.begin();
495 dynamic_cast<File *>(*itDoc)->Delete();
500 * \brief CallStartMethod
502 void DicomDir::CallStartMethod()
506 ExecuteCommand(CMD_STARTPROGRESS);
510 * \brief CallProgressMethod
512 void DicomDir::CallProgressMethod()
514 ExecuteCommand(CMD_PROGRESS);
518 * \brief CallEndMethod
520 void DicomDir::CallEndMethod()
523 ExecuteCommand(CMD_ENDPROGRESS);
526 //-----------------------------------------------------------------------------
529 * \brief Sets all fields to NULL
531 void DicomDir::Initialize()
540 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
542 void DicomDir::CreateDicomDir()
544 // The SeqEntries of "Directory Record Sequence" are parsed.
545 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
546 // 1 - we save the beginning iterator
547 // 2 - we continue to parse
548 // 3 - we find an other tag
549 // + we create the object for the precedent tag
551 gdcmDebugMacro("Create DicomDir");
553 // Directory record sequence
554 DocEntry *e = GetDocEntry(0x0004, 0x1220);
557 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
561 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
564 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
574 SQItem *tmpSI=s->GetFirstSQItem();
577 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
578 if ( DataEntry *dataEntry = dynamic_cast<DataEntry *>(d) )
580 v = dataEntry->GetString();
584 gdcmWarningMacro( "(0004,1430) not a DataEntry ?!?");
588 // A decent DICOMDIR has much more images than series,
589 // more series than studies, and so on.
590 // This is the right order to preform the tests
594 si = DicomDirImage::New(true);
595 if ( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
599 gdcmErrorMacro( "Add AddImageToEnd failed");
602 else if ( v == "SERIES" )
604 si = DicomDirSerie::New(true);
605 if ( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
609 gdcmErrorMacro( "Add AddSerieToEnd failed");
612 else if ( v == "VISIT " )
614 si = DicomDirVisit::New(true);
615 if ( !AddVisitToEnd( static_cast<DicomDirVisit *>(si)) )
619 gdcmErrorMacro( "Add AddVisitToEnd failed");
622 else if ( v == "STUDY " )
624 si = DicomDirStudy::New(true);
625 if ( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
629 gdcmErrorMacro( "Add AddStudyToEnd failed");
632 else if ( v == "PATIENT " )
634 si = DicomDirPatient::New(true);
635 if ( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
639 gdcmErrorMacro( "Add PatientToEnd failed");
644 // It was neither a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
645 // nor an 'IMAGE' SQItem. Skip to next item.
646 gdcmDebugMacro( " -------------------------------------------"
647 << "a non PATIENT/STUDY/SERIE/IMAGE SQItem was found : "
650 // FIXME : deal with other item types !
651 tmpSI=s->GetNextSQItem(); // To avoid infinite loop
655 si->MoveObject(tmpSI); // New code : Copies the List
657 tmpSI=s->GetNextSQItem();
663 * \brief AddPatientToEnd
664 * @param dd SQ Item to enqueue to the DicomPatient chained List
666 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
668 Patients.push_back(dd);
673 * \brief AddStudyToEnd
674 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
676 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
678 if ( Patients.size() > 0 )
680 ListDicomDirPatient::iterator itp = Patients.end();
682 (*itp)->AddStudy(dd);
689 * \brief AddSerieToEnd
690 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
692 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
694 if ( Patients.size() > 0 )
696 ListDicomDirPatient::iterator itp = Patients.end();
699 DicomDirStudy *study = (*itp)->GetLastStudy();
710 * \brief AddVisitToEnd
711 * @param dd SQ Item to enqueue to the DicomDirVisit chained List
713 bool DicomDir::AddVisitToEnd(DicomDirVisit *dd)
715 if ( Patients.size() > 0 )
717 ListDicomDirPatient::iterator itp = Patients.end();
720 DicomDirStudy *study = (*itp)->GetLastStudy();
730 * \brief AddImageToEnd
731 * @param dd SQ Item to enqueue to the DicomDirImage chained List
733 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
735 if ( Patients.size() > 0 )
737 ListDicomDirPatient::iterator itp = Patients.end();
740 DicomDirStudy *study = (*itp)->GetLastStudy();
743 DicomDirSerie *serie = study->GetLastSerie();
755 * \brief for each Header of the chained list,
756 * add/update the Patient/Study/Serie/Image info
757 * @param path path of the root directory
758 * @param list chained list of Headers
760 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
765 std::string patPrevName = "", patPrevID = "";
766 std::string studPrevInstanceUID = "", studPrevID = "";
767 std::string serPrevInstanceUID = "", serPrevID = "";
769 std::string patCurName, patCurID;
770 std::string studCurInstanceUID, studCurID;
771 std::string serCurInstanceUID, serCurID;
774 for( VectDocument::const_iterator it = list.begin();
778 // get the current file characteristics
779 patCurName = (*it)->GetEntryString(0x0010,0x0010);
780 patCurID = (*it)->GetEntryString(0x0010,0x0011);
781 studCurInstanceUID = (*it)->GetEntryString(0x0020,0x000d);
782 studCurID = (*it)->GetEntryString(0x0020,0x0010);
783 serCurInstanceUID = (*it)->GetEntryString(0x0020,0x000e);
784 serCurID = (*it)->GetEntryString(0x0020,0x0011);
786 if ( patCurName != patPrevName || patCurID != patPrevID || first )
788 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
792 // if new Study, deal with 'STUDY' Elements
793 if ( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
796 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
800 // if new Serie, deal with 'SERIE' Elements
801 if ( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
804 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
807 // Always Deal with 'IMAGE' Elements
808 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
810 patPrevName = patCurName;
811 patPrevID = patCurID;
812 studPrevInstanceUID = studCurInstanceUID;
813 studPrevID = studCurID;
814 serPrevInstanceUID = serCurInstanceUID;
815 serPrevID = serCurID;
821 * \brief adds to the HTable
822 * the Entries (Dicom Elements) corresponding to the given type
823 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
824 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
825 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
826 * @param header Header of the current file
828 void DicomDir::SetElement(std::string const &path, DicomDirType type,
831 ListDicomDirElem elemList;
832 ListDicomDirElem::const_iterator it;
833 uint16_t tmpGr, tmpEl;
834 DictEntry *dictEntry;
841 case GDCM_DICOMDIR_IMAGE:
842 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
843 si = DicomDirImage::New(true);
844 if ( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
847 gdcmErrorMacro( "Add ImageToEnd failed");
850 case GDCM_DICOMDIR_SERIE:
851 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
852 si = DicomDirSerie::New(true);
853 if ( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
856 gdcmErrorMacro( "Add SerieToEnd failed");
859 case GDCM_DICOMDIR_STUDY:
860 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
861 si = DicomDirStudy::New(true);
862 if ( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
865 gdcmErrorMacro( "Add StudyToEnd failed");
868 case GDCM_DICOMDIR_PATIENT:
869 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
870 si = DicomDirPatient::New(true);
871 if ( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
874 gdcmErrorMacro( "Add PatientToEnd failed");
877 case GDCM_DICOMDIR_META:
881 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
883 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
884 MetaElems = DicomDirMeta::New(true);
891 // FIXME : troubles found when it's a SeqEntry
893 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
894 // to avoid further troubles
895 // imageElem 0008 1140 "" // Referenced Image Sequence
896 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
897 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
898 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
899 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
901 std::string referencedVal;
902 // for all the relevant elements found in their own spot of the DicomDir.dic
903 for( it = elemList.begin(); it != elemList.end(); ++it)
907 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
909 entry = DataEntry::New( dictEntry );
910 entry->SetOffset(0); // just to avoid further missprinting
914 // NULL when we Build Up (ex nihilo) a DICOMDIR
915 // or when we add the META elems
917 val = header->GetEntryString(tmpGr, tmpEl);
924 if ( val == GDCM_UNFOUND)
926 if ( tmpGr == 0x0004 ) // never present in File !
930 case 0x1130: // File-set ID
931 // force to the *end* File Name
932 val = Util::GetName( path );
935 case 0x1500: // Only used for image
936 if ( header->GetFileName().substr(0, path.length()) != path )
938 gdcmWarningMacro( "The base path of file name is incorrect");
939 val = header->GetFileName();
943 val = &(header->GetFileName().c_str()[path.length()+1]);
947 case 0x1510: // Referenced SOP Class UID in File
948 referencedVal = header->GetEntryString(0x0008, 0x0016);
949 // FIXME : probabely something to check
953 case 0x1511: // Referenced SOP Instance UID in File
954 referencedVal = header->GetEntryString(0x0008, 0x0018);
955 // FIXME : probabely something to check
959 case 0x1512: // Referenced Transfer Syntax UID in File
960 referencedVal = header->GetEntryString(0x0002, 0x0010);
961 // FIXME : probabely something to check
972 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
976 /* FIX later the pb of creating the 'Implementation Version Name'!
978 if (val == GDCM_UNFOUND)
981 if ( tmpGr == 0x0002 && tmpEl == 0x0013)
983 // 'Implementation Version Name'
984 std::string val = "GDCM ";
985 val += Util::GetVersion();
988 entry->SetString( val ); // troubles expected when vr=SQ ...
990 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
992 gdcmDebugMacro("GDCM_DICOMDIR_META ?!? should never print that");
1000 * \brief Move the content of the source SQItem to the destination SQItem
1001 * Only DocEntry's are moved
1002 * @param dst destination SQItem
1003 * @param src source SQItem
1005 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1009 entry = src->GetFirstEntry();
1012 src->RemoveEntry(entry);
1013 dst->AddEntry(entry);
1014 // we destroyed -> the current iterator is not longer valid
1015 entry = src->GetFirstEntry();
1020 * \brief compares two files
1022 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1024 return *header1 < *header2;
1027 //-----------------------------------------------------------------------------
1030 * \brief Canonical Printer
1031 * @param os ostream we want to print in
1032 * @param indent Indentation string to be prepended during printing
1034 void DicomDir::Print(std::ostream &os, std::string const & )
1038 MetaElems->SetPrintLevel(PrintLevel);
1039 MetaElems->Print(os);
1041 for(ListDicomDirPatient::iterator cc = Patients.begin();
1042 cc != Patients.end();
1045 (*cc)->SetPrintLevel(PrintLevel);
1050 //-----------------------------------------------------------------------------
1051 } // end namespace gdcm