1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2004/10/22 03:05:40 $
7 Version: $Revision: 1.74 $
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 #include "gdcmDicomDir.h"
20 #include "gdcmDicomDirStudy.h"
21 #include "gdcmDicomDirSerie.h"
22 #include "gdcmDicomDirImage.h"
23 #include "gdcmDirList.h"
25 #include "gdcmDebug.h"
26 #include "gdcmGlobal.h"
27 #include "gdcmHeader.h"
28 #include "gdcmSeqEntry.h"
29 #include "gdcmSQItem.h"
30 #include "gdcmValEntry.h"
35 #include <sys/types.h>
45 //-----------------------------------------------------------------------------
46 // For full DICOMDIR description, see:
47 // PS 3.3-2003, pages 731-750
48 //-----------------------------------------------------------------------------
49 // Constructor / Destructor
53 * \brief Constructor : creates an empty DicomDir
58 Initialize(); // sets all private fields to NULL
59 std::string pathBidon = "Bidon"; // Sorry, NULL not allowed ...
60 MetaElems = NewMeta();
64 * \brief Constructor Parses recursively the directory and creates the DicomDir
65 * or uses an already built DICOMDIR, depending on 'parseDir' value.
66 * @param fileName name
67 * - of the root directory (parseDir = true)
68 * - of the DICOMDIR (parseDir = false)
69 * @param parseDir boolean
70 * - true if user passed an entry point
71 * and wants to explore recursively the directories
72 * - false if user passed an already built DICOMDIR file
75 DicomDir::DicomDir(std::string const & fileName, bool parseDir ):
78 // Whatever user passed (a root directory or a DICOMDIR)
79 // and whatever the value of parseDir was,
80 // Document is already executed
81 Initialize(); // sets all private fields to NULL
83 // if user passed a root directory, sure we didn't get anything
85 if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
87 dbg.Verbose(0, "DicomDir::DicomDir : entry HT empty");
89 if ( fileName.size() == 1 && fileName[0] == '.' )
91 // user passed '.' as Name
92 // we get current directory name
94 getcwd(dummy, (size_t)1000);
95 SetFileName( dummy ); // will be converted into a string
98 if ( parseDir ) // user asked for a recursive parsing of a root directory
100 MetaElems = NewMeta();
102 dbg.Verbose(0, "DicomDir::DicomDir : Parse directory"
103 " and create the DicomDir");
108 /// \todo if parseDir == false, it should be tagged as an error
109 // NON ! il suffit d'appeler ParseDirectory()
110 // apres le constructeur
113 else // Only if user passed a DICOMDIR
115 // Directory record sequence
116 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
119 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
120 " sequence (0x0004,0x1220)");
121 /// \todo FIXME : what do we do when the parsed file IS NOT a
129 * \brief Canonical destructor
131 DicomDir::~DicomDir()
133 SetStartMethod(NULL);
134 SetProgressMethod(NULL);
136 for(ListDicomDirPatient::iterator cc = Patients.begin();
148 //-----------------------------------------------------------------------------
151 * \brief Canonical Printer
153 void DicomDir::Print(std::ostream &os)
157 MetaElems->SetPrintLevel(PrintLevel);
158 MetaElems->Print(os);
160 for(ListDicomDirPatient::iterator cc = Patients.begin();
161 cc != Patients.end();
164 (*cc)->SetPrintLevel( PrintLevel );
169 //-----------------------------------------------------------------------------
172 * \brief This predicate, based on hopefully reasonable heuristics,
173 * decides whether or not the current header was properly parsed
174 * and contains the mandatory information for being considered as
175 * a well formed and usable DicomDir.
176 * @return true when Document is the one of a reasonable DicomDir,
179 bool DicomDir::IsReadable()
181 if( !Document::IsReadable() )
189 if( Patients.size() <= 0 )
198 * \brief Sets all fields to NULL
201 void DicomDir::Initialize()
204 ProgressMethod = NULL;
206 StartMethodArgDelete = NULL;
207 ProgressMethodArgDelete = NULL;
208 EndMethodArgDelete = NULL;
222 * \brief fills the whole structure, starting from a root Directory
224 void DicomDir::ParseDirectory()
226 CreateDicomDirChainedList( GetFileName() );
232 * \brief Set the start method to call when the parsing of the directory starts
233 * @param method Method to call
234 * @param arg Argument to pass to the method
235 * @param argDelete Argument
236 * \warning In python : the arg parameter isn't considered
238 void DicomDir::SetStartMethod(Method* method, void* arg,
241 if( StartArg && StartMethodArgDelete )
243 StartMethodArgDelete( StartArg );
246 StartMethod = method;
248 StartMethodArgDelete = argDelete;
253 * \brief Set the method to delete the argument
254 * The argument is destroyed when the method is changed or when the
256 * @param method Method to call to delete the argument
258 void DicomDir::SetStartMethodArgDelete(Method* method)
260 StartMethodArgDelete = method;
265 * \brief Set the progress method to call when the parsing of the directory progress
266 * @param method Method to call
267 * @param arg Argument to pass to the method
268 * @param argDelete Argument
269 * \warning In python : the arg parameter isn't considered
271 void DicomDir::SetProgressMethod(Method* method, void* arg,
274 if( ProgressArg && ProgressMethodArgDelete )
276 ProgressMethodArgDelete( ProgressArg );
279 ProgressMethod = method;
281 ProgressMethodArgDelete = argDelete;
286 * \brief Set the method to delete the argument
287 * The argument is destroyed when the method is changed or when the
289 * @param method Method to call to delete the argument
291 void DicomDir::SetProgressMethodArgDelete(Method* method)
293 ProgressMethodArgDelete = method;
298 * \brief Set the end method to call when the parsing of the directory ends
299 * @param method Method to call
300 * @param arg Argument to pass to the method
301 * @param argDelete Argument
302 * \warning In python : the arg parameter isn't considered
304 void DicomDir::SetEndMethod(Method* method, void* arg,
307 if( EndArg && EndMethodArgDelete )
309 EndMethodArgDelete( EndArg );
314 EndMethodArgDelete = argDelete;
319 * \brief Set the method to delete the argument
320 * The argument is destroyed when the method is changed or when the class
322 * @param method Method to call to delete the argument
324 void DicomDir::SetEndMethodArgDelete(Method* method)
326 EndMethodArgDelete = method;
331 * \brief writes on disc a DICOMDIR
332 * \ warning does NOT add the missing elements in the header :
333 * it's up to the user doing it !
334 * \todo : to be re-written using the DICOMDIR tree-like structure
335 * *not* the chained list
336 * (does NOT exist if the DICOMDIR is user-forged !)
337 * @param fileName file to be written to
338 * @return false only when fail to open
341 bool DicomDir::WriteDicomDir(std::string const& fileName)
343 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
344 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
346 std::ofstream* fp = new std::ofstream(fileName.c_str(),
347 std::ios::out | std::ios::binary);
350 printf("Failed to open(write) File [%s] \n", fileName.c_str());
354 uint8_t filePreamble[128];
355 memset(filePreamble, 0, 128);
356 fp->write((char*)filePreamble, 128);
359 DicomDirMeta *ptrMeta = GetDicomDirMeta();
360 ptrMeta->Write(fp, ExplicitVR);
362 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
363 fp->write((char*)&sq[0],8);
365 for(ListDicomDirPatient::iterator cc = Patients.begin();
366 cc != Patients.end();
369 (*cc)->Write( fp, ExplicitVR );
372 // force writing Sequence Delimitation Item
373 fp->write((char*)&sqt[0],8); // fffe e0dd ffff ffff
379 //-----------------------------------------------------------------------------
384 * \brief create a Document-like chained list from a root Directory
385 * @param path entry point of the tree-like structure
387 void DicomDir::CreateDicomDirChainedList(std::string const & path)
390 DirList fileList(path,1); // gets recursively the file list
391 unsigned int count = 0;
398 for( DirList::iterator it = fileList.begin();
399 it != fileList.end();
402 Progress = (float)(count+1)/(float)fileList.size();
403 CallProgressMethod();
409 header = new Header( it->c_str() );
413 "DicomDir::CreateDicomDirChainedList: "
414 "failure in new Header ",
418 if( header->IsReadable() )
420 // Add the file header to the chained list:
421 list.push_back(header);
423 "DicomDir::CreateDicomDirChainedList: readable ",
433 // sorts Patient/Study/Serie/
434 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
436 std::string tmp = fileList.GetDirName();
437 //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
438 SetElements(tmp, list);
444 * \brief adds *the* Meta to a partially created DICOMDIR
447 DicomDirMeta * DicomDir::NewMeta()
449 DicomDirMeta *m = new DicomDirMeta( &TagHT );
451 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
453 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
454 lastOneButSequence --;
455 // ALL the 'out of Sequence' Tags belong to Meta Elems
456 // (we skip 0004|1220 [Directory record sequence] )
457 for ( TagDocEntryHT::iterator cc = TagHT.begin();
458 cc != lastOneButSequence;
461 m->AddDocEntry( cc->second );
464 else // after root directory parsing
466 std::list<Element> elemList;
467 elemList=Global::GetDicomDirElements()->GetDicomDirMetaElements();
468 m->FillObject(elemList);
470 m->SetSQItemNumber(0); // To avoid further missprinting
475 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
477 DicomDirPatient * DicomDir::NewPatient()
479 std::list<Element>::iterator it;
480 uint16_t tmpGr,tmpEl;
481 DictEntry *dictEntry;
484 std::list<Element> elemList;
485 elemList=Global::GetDicomDirElements()->GetDicomDirPatientElements();
486 SQItem *s = new SQItem(0);
488 // for all the DicomDirPatient Elements
489 for( it = elemList.begin(); it != elemList.end(); ++it )
493 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
494 entry = new ValEntry( dictEntry );
495 entry->SetOffset(0); // just to avoid further missprinting
496 entry->SetValue( it->Value );
498 // dealing with value length ...
500 if( dictEntry->GetGroup() == 0xfffe)
502 entry->SetLength(entry->GetValue().length());
504 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
506 entry->SetLength( 4 );
508 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
512 else if( dictEntry->GetVR() == "SQ" )
514 entry->SetLength( 0xffffffff );
518 entry->SetLength( entry->GetValue().length() );
520 s->AddDocEntry( entry );
523 DicomDirPatient *p = new DicomDirPatient(s, &TagHT);
524 Patients.push_front( p );
530 * \brief adds to the HTable
531 * the Entries (Dicom Elements) corresponding to the given type
532 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
533 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
534 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
535 * @param header Header of the current file
537 void DicomDir::SetElement(std::string &path,DicomDirType type,
540 std::list<Element> elemList;
541 std::list<Element>::iterator it;
542 uint16_t tmpGr, tmpEl;
543 DictEntry *dictEntry;
546 SQItem *si = new SQItem(0); // all the items will be at level 1
549 case GDCM_DICOMDIR_IMAGE:
550 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
553 case GDCM_DICOMDIR_SERIE:
554 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
557 case GDCM_DICOMDIR_STUDY:
558 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
561 case GDCM_DICOMDIR_PATIENT:
562 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
565 case GDCM_DICOMDIR_META:
566 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
572 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
573 // to avoid further troubles
574 // imageElem 0008 1140 "" // Referenced Image Sequence
575 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
576 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
577 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
578 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
579 // for all the relevant elements found in their own spot of the DicomDir.dic
580 // FIXME : troubles found when it's a SeqEntry
582 for( it = elemList.begin(); it != elemList.end(); ++it)
586 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
588 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
590 entry->SetOffset(0); // just to avoid further missprinting
591 entry->SetLength(0); // just to avoid further missprinting
595 // NULL when we Build Up (ex nihilo) a DICOMDIR
596 // or when we add the META elems
597 val = header->GetEntryByNumber(tmpGr, tmpEl);
604 if( val == GDCM_UNFOUND)
606 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
608 // force to the *end* File Name
609 val = Util::GetName( path );
611 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
613 if( header->GetFileName().substr(0, path.length()) != path )
615 dbg.Verbose(0, "DicomDir::SetElement : the base path"
616 " of file name is incorrect");
617 val = header->GetFileName();
621 val = &(header->GetFileName().c_str()[path.length()]);
631 if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
635 // GDCM_UNFOUND or not !
637 entry->SetValue( val ); // troubles expected when vr=SQ ...
641 if( dictEntry->GetGroup() == 0xfffe )
643 entry->SetLength( entry->GetValue().length() ); // FIXME
645 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
649 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
653 else if( dictEntry->GetVR() == "SQ" )
655 entry->SetLength( 0xffffffff );
659 entry->SetLength( entry->GetValue().length() );
663 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
665 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
672 case GDCM_DICOMDIR_IMAGE:
673 AddDicomDirImageToEnd(si);
676 case GDCM_DICOMDIR_SERIE:
677 AddDicomDirSerieToEnd(si);
680 case GDCM_DICOMDIR_STUDY:
681 AddDicomDirStudyToEnd(si);
684 case GDCM_DICOMDIR_PATIENT:
685 AddDicomDirPatientToEnd(si);
691 //int count=1; // find a trick to increment
692 //s->AddEntry(si, count); // Seg Faults
697 * \brief CallStartMethod
699 void DicomDir::CallStartMethod()
705 StartMethod( StartArg );
711 * \brief CallProgressMethod
713 void DicomDir::CallProgressMethod()
717 ProgressMethod( ProgressArg );
723 * \brief CallEndMethod
725 void DicomDir::CallEndMethod()
734 //-----------------------------------------------------------------------------
738 * \brief create a 'DicomDir' from a DICOMDIR Header
740 void DicomDir::CreateDicomDir()
742 // The list is parsed.
743 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
744 // 1 - we save the beginning iterator
745 // 2 - we continue to parse
746 // 3 - we find an other tag
747 // + we create the object for the precedent tag
750 // Directory record sequence
751 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
754 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
755 " sequence (0x0004,0x1220)");
756 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
760 SeqEntry* s = dynamic_cast<SeqEntry*>(e);
763 dbg.Verbose(0, "DicomDir::CreateDicomDir: no SeqEntry present");
764 // useless : (0x0004,0x1220) IS a Sequence !
768 DicomDirType type = DicomDir::GDCM_DICOMDIR_META;
769 MetaElems = NewMeta();
771 ListSQItem listItems = s->GetSQItems();
775 for( ListSQItem::iterator i = listItems.begin();
776 i !=listItems.end(); ++i )
778 d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
779 if ( ValEntry* valEntry = dynamic_cast< ValEntry* >(d) )
781 v = valEntry->GetValue();
785 dbg.Verbose(0, "DicomDir::CreateDicomDir: not a ValEntry.");
789 if( v == "PATIENT " )
791 AddDicomDirPatientToEnd( *i );
792 type = DicomDir::GDCM_DICOMDIR_PATIENT;
794 else if( v == "STUDY " )
796 AddDicomDirStudyToEnd( *i );
797 type = DicomDir::GDCM_DICOMDIR_STUDY;
799 else if( v == "SERIES" )
801 AddDicomDirSerieToEnd( *i );
802 type = DicomDir::GDCM_DICOMDIR_SERIE;
804 else if( v == "IMAGE " )
806 AddDicomDirImageToEnd( *i );
807 type = DicomDir::GDCM_DICOMDIR_IMAGE;
811 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
812 // neither an 'IMAGE' SQItem. Skip to next item.
820 * \brief Well ... there is only one occurence
822 void DicomDir::AddDicomDirMeta()
828 MetaElems = new DicomDirMeta( &TagHT );
833 * \brief AddDicomDirPatientToEnd
834 * @param s SQ Item to enqueue to the DicomPatient chained List
836 void DicomDir::AddDicomDirPatientToEnd(SQItem *s)
838 Patients.push_back(new DicomDirPatient(s, &TagHT));
843 * \brief AddDicomDirStudyToEnd
844 * @param s SQ Item to enqueue to the DicomDirStudy chained List
846 void DicomDir::AddDicomDirStudyToEnd(SQItem *s)
848 if( Patients.size() > 0 )
850 ListDicomDirPatient::iterator itp = Patients.end();
852 (*itp)->AddDicomDirStudy(new DicomDirStudy(s, &TagHT));
858 * \brief AddDicomDirSerieToEnd
859 * @param s SQ Item to enqueue to the DicomDirSerie chained List
861 void DicomDir::AddDicomDirSerieToEnd(SQItem *s)
863 if( Patients.size() > 0 )
865 ListDicomDirPatient::iterator itp = Patients.end();
868 if( (*itp)->GetDicomDirStudies().size() > 0 )
870 ListDicomDirStudy::iterator itst=(*itp)->GetDicomDirStudies().end();
872 (*itst)->AddDicomDirSerie(new DicomDirSerie(s, &TagHT));
879 * \brief AddDicomDirImageToEnd
880 * @param s SQ Item to enqueue to the DicomDirImage chained List
882 void DicomDir::AddDicomDirImageToEnd(SQItem *s)
884 if( Patients.size() > 0 )
886 ListDicomDirPatient::iterator itp = Patients.end();
889 if( (*itp)->GetDicomDirStudies().size() > 0 )
891 ListDicomDirStudy::iterator itst = (*itp)->GetDicomDirStudies().end();
894 if( (*itst)->GetDicomDirSeries().size() > 0 )
896 ListDicomDirSerie::iterator its = (*itst)->GetDicomDirSeries().end();
898 (*its)->AddDicomDirImage(new DicomDirImage(s, &TagHT));
906 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
907 * @param path path of the root directory
908 * @param list chained list of Headers
910 void DicomDir::SetElements(std::string &path, VectDocument &list)
912 std::string patPrevName = "", patPrevID = "";
913 std::string studPrevInstanceUID = "", studPrevID = "";
914 std::string serPrevInstanceUID = "", serPrevID = "";
916 std::string patCurName, patCurID;
917 std::string studCurInstanceUID, studCurID;
918 std::string serCurInstanceUID, serCurID;
920 for( VectDocument::iterator it = list.begin();
921 it != list.end(); ++it )
923 // get the current file characteristics
924 patCurName = (*it)->GetEntryByNumber(0x0010,0x0010);
925 patCurID = (*it)->GetEntryByNumber(0x0010,0x0011);
926 studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
927 studCurID = (*it)->GetEntryByNumber(0x0020,0x0010);
928 serCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000e);
929 serCurID = (*it)->GetEntryByNumber(0x0020,0x0011);
931 if( patCurName != patPrevName || patCurID != patPrevID)
933 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
936 // if new Study Deal with 'STUDY' Elements
937 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID )
939 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
942 // if new Serie Deal with 'SERIE' Elements
943 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID )
945 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
948 // Always Deal with 'IMAGE' Elements
949 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
951 patPrevName = patCurName;
952 patPrevID = patCurID;
953 studPrevInstanceUID = studCurInstanceUID;
954 studPrevID = studCurID;
955 serPrevInstanceUID = serCurInstanceUID;
956 serPrevID = serCurID;
962 * \brief compares two dgcmHeaders
964 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
966 return *header1 < *header2;
968 } // end namespace gdcm
970 //-----------------------------------------------------------------------------