1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/12/13 16:32:20 $
7 Version: $Revision: 1.181 $
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"
40 #include "gdcmCommandManager.h"
45 #include <sys/types.h>
48 # define getcwd _getcwd
51 #if defined(_MSC_VER) || defined(__BORLANDC__)
56 // ----------------------------------------------------------------------------
57 // Note for future developpers
58 // ----------------------------------------------------------------------------
60 // Dicom PS 3.3 describes the relationship between Directory Records, as follow
61 // (see also PS 4.3, 2004, page 50 for Entity-Relationship model)
63 // Directory Record Type Directory Record Types which may be included
64 // in the next lower-level directory Entity
66 // (Root directory Entity) PATIENT, TOPIC, PRIVATE
68 // PATIENT STUDY, PRIVATE
70 // STUDY SERIES, VISIT, RESULTS, STUDY COMPONENT, PRIVATE
72 // SERIES IMAGE, OVERLAYS, MODALITY LUT, VOI LUT,
73 // CURVE, STORED PRINT, RT DOSE, RT STRUCTURE SET
74 // RT PLAN, RT TREAT RECORD, PRESENTATION, WAVEFORM,
75 // SR DOCUMENT, KEY OBJECT DOC, SPECTROSCOPY,
76 // RAW DATA, REGISTRATION, FIDUCIAL, PRIVATE,
99 // ----------------------
100 // The current gdcm version only deals with :
102 // (Root directory Entity) PATIENT
109 // DicomDir::CreateDicomDir will have to be completed
110 // Treelike structure management will have to be upgraded
111 // ----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 // Constructor / Destructor
118 * \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, 0x0000, 0x0000 };
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 0000 0000
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
439 * \brief Copies all the attributes from an other DocEntrySet
440 * @param set entry to copy from
441 * @remarks The contained DocEntries are not copied, only referenced
443 void DicomDir::Copy(DocEntrySet *set)
445 // Remove all previous childs
450 DicomDir *dd = dynamic_cast<DicomDir *>(set);
454 MetaElems->Unregister();
455 MetaElems = dd->MetaElems;
457 MetaElems->Register();
459 Patients = dd->Patients;
460 for(ItPatient = Patients.begin();ItPatient != Patients.end();++ItPatient)
461 (*ItPatient)->Register();
465 //-----------------------------------------------------------------------------
468 * \brief create a Document-like chained list from a root Directory
469 * @param path entry point of the tree-like structure
471 void DicomDir::CreateDicomDirChainedList(std::string const &path)
474 DirList dirList(path,1); // gets recursively the file list
475 unsigned int count = 0;
479 DirListType fileList = dirList.GetFilenames();
480 unsigned int nbFile = fileList.size();
481 for( DirListType::iterator it = fileList.begin();
482 it != fileList.end();
485 Progress = (float)(count+1)/(float)nbFile;
486 CallProgressMethod();
493 f->SetLoadMode(LoadMode); // we allow user not to load Sequences,
494 // or Shadow groups, or ......
495 f->SetFileName( it->c_str() );
498 if ( f->IsReadable() )
500 // Add the file to the chained list:
502 gdcmDebugMacro( "Readable " << it->c_str() );
510 // sorts Patient/Study/Serie/
511 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
513 std::string tmp = dirList.GetDirName();
514 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
515 SetElements(tmp, list);
518 for(VectDocument::iterator itDoc=list.begin();
522 dynamic_cast<File *>(*itDoc)->Delete();
527 //-----------------------------------------------------------------------------
530 * \brief Sets all fields to NULL
532 void DicomDir::Initialize()
541 * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header
543 void DicomDir::CreateDicomDir()
545 // The SeqEntries of "Directory Record Sequence" are parsed.
546 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
547 // 1 - we save the beginning iterator
548 // 2 - we continue to parse
549 // 3 - we find an other tag
550 // + we create the object for the precedent tag
552 gdcmDebugMacro("Create DicomDir");
554 // Directory record sequence
555 DocEntry *e = GetDocEntry(0x0004, 0x1220);
558 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
562 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
565 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
575 SQItem *tmpSI=s->GetFirstSQItem();
578 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
579 if ( DataEntry *dataEntry = dynamic_cast<DataEntry *>(d) )
581 v = dataEntry->GetString();
585 gdcmWarningMacro( "(0004,1430) not a DataEntry ?!?");
589 // A decent DICOMDIR has much more images than series,
590 // more series than studies, and so on.
591 // This is the right order to preform the tests
595 si = DicomDirImage::New(true);
596 if ( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
600 gdcmErrorMacro( "Add AddImageToEnd failed");
603 else if ( v == "SERIES" )
605 si = DicomDirSerie::New(true);
606 if ( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
610 gdcmErrorMacro( "Add AddSerieToEnd failed");
613 else if ( v == "VISIT " )
615 si = DicomDirVisit::New(true);
616 if ( !AddVisitToEnd( static_cast<DicomDirVisit *>(si)) )
620 gdcmErrorMacro( "Add AddVisitToEnd failed");
623 else if ( v == "STUDY " )
625 si = DicomDirStudy::New(true);
626 if ( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
630 gdcmErrorMacro( "Add AddStudyToEnd failed");
633 else if ( v == "PATIENT " )
635 si = DicomDirPatient::New(true);
636 if ( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
640 gdcmErrorMacro( "Add PatientToEnd failed");
645 // It was neither a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
646 // nor an 'IMAGE' SQItem. Skip to next item.
647 gdcmDebugMacro( " -------------------------------------------"
648 << "a non PATIENT/STUDY/SERIE/IMAGE SQItem was found : "
651 // FIXME : deal with other item types !
652 tmpSI=s->GetNextSQItem(); // To avoid infinite loop
658 tmpSI=s->GetNextSQItem();
664 * \brief AddPatientToEnd
665 * @param dd SQ Item to enqueue to the DicomPatient chained List
667 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
669 Patients.push_back(dd);
674 * \brief AddStudyToEnd
675 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
677 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
679 if ( Patients.size() > 0 )
681 ListDicomDirPatient::iterator itp = Patients.end();
683 (*itp)->AddStudy(dd);
690 * \brief AddSerieToEnd
691 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
693 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
695 if ( Patients.size() > 0 )
697 ListDicomDirPatient::iterator itp = Patients.end();
700 DicomDirStudy *study = (*itp)->GetLastStudy();
711 * \brief AddVisitToEnd
712 * @param dd SQ Item to enqueue to the DicomDirVisit chained List
714 bool DicomDir::AddVisitToEnd(DicomDirVisit *dd)
716 if ( Patients.size() > 0 )
718 ListDicomDirPatient::iterator itp = Patients.end();
721 DicomDirStudy *study = (*itp)->GetLastStudy();
731 * \brief AddImageToEnd
732 * @param dd SQ Item to enqueue to the DicomDirImage chained List
734 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
736 if ( Patients.size() > 0 )
738 ListDicomDirPatient::iterator itp = Patients.end();
741 DicomDirStudy *study = (*itp)->GetLastStudy();
744 DicomDirSerie *serie = study->GetLastSerie();
756 * \brief for each Header of the chained list,
757 * add/update the Patient/Study/Serie/Image info
758 * @param path path of the root directory
759 * @param list chained list of Headers
761 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
766 std::string patPrevName = "", patPrevID = "";
767 std::string studPrevInstanceUID = "", studPrevID = "";
768 std::string serPrevInstanceUID = "", serPrevID = "";
770 std::string patCurName, patCurID;
771 std::string studCurInstanceUID, studCurID;
772 std::string serCurInstanceUID, serCurID;
775 for( VectDocument::const_iterator it = list.begin();
779 // get the current file characteristics
780 patCurName = (*it)->GetEntryString(0x0010,0x0010);
781 patCurID = (*it)->GetEntryString(0x0010,0x0011);
782 studCurInstanceUID = (*it)->GetEntryString(0x0020,0x000d);
783 studCurID = (*it)->GetEntryString(0x0020,0x0010);
784 serCurInstanceUID = (*it)->GetEntryString(0x0020,0x000e);
785 serCurID = (*it)->GetEntryString(0x0020,0x0011);
787 if ( patCurName != patPrevName || patCurID != patPrevID || first )
789 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
793 // if new Study, deal with 'STUDY' Elements
794 if ( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
797 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
801 // if new Serie, deal with 'SERIE' Elements
802 if ( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
805 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
808 // Always Deal with 'IMAGE' Elements
809 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
811 patPrevName = patCurName;
812 patPrevID = patCurID;
813 studPrevInstanceUID = studCurInstanceUID;
814 studPrevID = studCurID;
815 serPrevInstanceUID = serCurInstanceUID;
816 serPrevID = serCurID;
822 * \brief adds to the HTable
823 * the Entries (Dicom Elements) corresponding to the given type
824 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
825 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
826 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
827 * @param header Header of the current file
829 void DicomDir::SetElement(std::string const &path, DicomDirType type,
832 ListDicomDirElem elemList;
833 ListDicomDirElem::const_iterator it;
834 uint16_t tmpGr, tmpEl;
835 DictEntry *dictEntry;
842 case GDCM_DICOMDIR_IMAGE:
843 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
844 si = DicomDirImage::New(true);
845 if ( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
848 gdcmErrorMacro( "Add ImageToEnd failed");
851 case GDCM_DICOMDIR_SERIE:
852 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
853 si = DicomDirSerie::New(true);
854 if ( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
857 gdcmErrorMacro( "Add SerieToEnd failed");
860 case GDCM_DICOMDIR_STUDY:
861 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
862 si = DicomDirStudy::New(true);
863 if ( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
866 gdcmErrorMacro( "Add StudyToEnd failed");
869 case GDCM_DICOMDIR_PATIENT:
870 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
871 si = DicomDirPatient::New(true);
872 if ( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
875 gdcmErrorMacro( "Add PatientToEnd failed");
878 case GDCM_DICOMDIR_META:
882 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
884 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
885 MetaElems = DicomDirMeta::New(true);
892 // FIXME : troubles found when it's a SeqEntry
894 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
895 // to avoid further troubles
896 // imageElem 0008 1140 "" // Referenced Image Sequence
897 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
898 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
899 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
900 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
902 std::string referencedVal;
903 // for all the relevant elements found in their own spot of the DicomDir.dic
904 for( it = elemList.begin(); it != elemList.end(); ++it)
908 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
910 entry = DataEntry::New( dictEntry );
911 entry->SetOffset(0); // just to avoid further missprinting
915 // NULL when we Build Up (ex nihilo) a DICOMDIR
916 // or when we add the META elems
918 val = header->GetEntryString(tmpGr, tmpEl);
925 if ( val == GDCM_UNFOUND)
927 if ( tmpGr == 0x0004 ) // never present in File !
931 case 0x1130: // File-set ID
932 // force to the *end* File Name
933 val = Util::GetName( path );
936 case 0x1500: // Only used for image
937 if ( header->GetFileName().substr(0, path.length()) != path )
939 gdcmWarningMacro( "The base path of file name is incorrect");
940 val = header->GetFileName();
944 //val = &(header->GetFileName().c_str()[path.length()+1]);
945 val = &(header->GetFileName().c_str()[path.length()]);
949 case 0x1510: // Referenced SOP Class UID in File
950 referencedVal = header->GetEntryString(0x0008, 0x0016);
951 // FIXME : probabely something to check
955 case 0x1511: // Referenced SOP Instance UID in File
956 referencedVal = header->GetEntryString(0x0008, 0x0018);
957 // FIXME : probabely something to check
961 case 0x1512: // Referenced Transfer Syntax UID in File
962 referencedVal = header->GetEntryString(0x0002, 0x0010);
963 // FIXME : probabely something to check
974 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
978 /* FIX later the pb of creating the 'Implementation Version Name'!
980 if (val == GDCM_UNFOUND)
983 if ( tmpGr == 0x0002 && tmpEl == 0x0013)
985 // 'Implementation Version Name'
986 std::string val = "GDCM ";
987 val += Util::GetVersion();
990 entry->SetString( val ); // troubles expected when vr=SQ ...
992 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
994 gdcmDebugMacro("GDCM_DICOMDIR_META ?!? should never print that");
1002 * \brief Move the content of the source SQItem to the destination SQItem
1003 * Only DocEntry's are moved
1004 * @param dst destination SQItem
1005 * @param src source SQItem
1007 void DicomDir::MoveSQItem(DocEntrySet *dst, DocEntrySet *src)
1010 // todo : rewrite the whole stuff, without using RemoveEntry an AddEntry,
1012 entry = src->GetFirstEntry();
1015 dst->AddEntry(entry); // use it, *before* removing it!
1016 src->RemoveEntry(entry);
1017 // we destroyed -> the current iterator is not longer valid
1018 entry = src->GetFirstEntry();
1023 * \brief compares two files
1025 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1027 return *header1 < *header2;
1030 //-----------------------------------------------------------------------------
1033 * \brief Canonical Printer
1034 * @param os ostream we want to print in
1035 * @param indent Indentation string to be prepended during printing
1037 void DicomDir::Print(std::ostream &os, std::string const & )
1041 MetaElems->SetPrintLevel(PrintLevel);
1042 MetaElems->Print(os);
1044 for(ListDicomDirPatient::iterator cc = Patients.begin();
1045 cc != Patients.end();
1048 (*cc)->SetPrintLevel(PrintLevel);
1053 //-----------------------------------------------------------------------------
1054 } // end namespace gdcm