ctkDICOMRetrieve.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. #include <stdexcept>
  15. // Qt includes
  16. #include <QSqlQuery>
  17. #include <QSqlRecord>
  18. #include <QVariant>
  19. #include <QDate>
  20. #include <QStringList>
  21. #include <QSet>
  22. #include <QFile>
  23. #include <QDirIterator>
  24. #include <QFileInfo>
  25. #include <QDebug>
  26. // ctkDICOMCore includes
  27. #include "ctkDICOMRetrieve.h"
  28. #include "ctkLogger.h"
  29. // DCMTK includes
  30. #include "dcmtk/dcmnet/dimse.h"
  31. #include "dcmtk/dcmnet/diutil.h"
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcfilefo.h>
  34. #include <dcmtk/dcmdata/dcdeftag.h>
  35. #include <dcmtk/dcmdata/dcdatset.h>
  36. #include <dcmtk/ofstd/ofcond.h>
  37. #include <dcmtk/ofstd/ofstring.h>
  38. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  39. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  40. #include <dcmtk/dcmjpeg/djdecode.h> /* for dcmjpeg decoders */
  41. #include <dcmtk/dcmjpeg/djencode.h> /* for dcmjpeg encoders */
  42. #include <dcmtk/dcmdata/dcrledrg.h> /* for DcmRLEDecoderRegistration */
  43. #include <dcmtk/dcmdata/dcrleerg.h> /* for DcmRLEEncoderRegistration */
  44. #include <dcmtk/dcmnet/scu.h>
  45. #include "dcmtk/oflog/oflog.h"
  46. static ctkLogger logger("org.commontk.dicom.DICOMRetrieve");
  47. //------------------------------------------------------------------------------
  48. class ctkDICOMRetrievePrivate
  49. {
  50. public:
  51. ctkDICOMRetrievePrivate();
  52. ~ctkDICOMRetrievePrivate();
  53. bool KeepAssociationOpen;
  54. bool ConnectionParamsChanged;
  55. QSharedPointer<ctkDICOMDatabase> RetrieveDatabase;
  56. DcmSCU scu;
  57. QString MoveDestinationAETitle;
  58. // do the retrieve, handling both series and study retrieves
  59. enum RetrieveType { RetrieveSeries, RetrieveStudy };
  60. bool retrieve ( const QString& studyInstanceUID,
  61. const QString& seriesInstanceUID,
  62. const RetrieveType rType );
  63. };
  64. //------------------------------------------------------------------------------
  65. // ctkDICOMRetrievePrivate methods
  66. //------------------------------------------------------------------------------
  67. ctkDICOMRetrievePrivate::ctkDICOMRetrievePrivate()
  68. {
  69. this->RetrieveDatabase = QSharedPointer<ctkDICOMDatabase> (0);
  70. KeepAssociationOpen = true;
  71. ConnectionParamsChanged = false;
  72. logger.info ( "Setting Transfer Syntaxes" );
  73. OFList<OFString> transferSyntaxes;
  74. transferSyntaxes.push_back ( UID_LittleEndianExplicitTransferSyntax );
  75. transferSyntaxes.push_back ( UID_BigEndianExplicitTransferSyntax );
  76. transferSyntaxes.push_back ( UID_LittleEndianImplicitTransferSyntax );
  77. scu.addPresentationContext ( UID_MOVEStudyRootQueryRetrieveInformationModel, transferSyntaxes );
  78. }
  79. //------------------------------------------------------------------------------
  80. ctkDICOMRetrievePrivate::~ctkDICOMRetrievePrivate()
  81. {
  82. // At least now be kind to the server and release association
  83. scu.closeAssociation(DCMSCU_RELEASE_ASSOCIATION);
  84. }
  85. //------------------------------------------------------------------------------
  86. bool ctkDICOMRetrievePrivate::retrieve ( const QString& studyInstanceUID,
  87. const QString& seriesInstanceUID,
  88. const RetrieveType rType )
  89. {
  90. if ( !this->RetrieveDatabase )
  91. {
  92. logger.error ( "No RetrieveDatabase for retrieve transaction" );
  93. return false;
  94. }
  95. // Register the JPEG libraries in case we need them
  96. // (registration only happens once, so it's okay to call repeatedly)
  97. // register global JPEG decompression codecs
  98. DJDecoderRegistration::registerCodecs();
  99. // register global JPEG compression codecs
  100. DJEncoderRegistration::registerCodecs();
  101. // register RLE compression codec
  102. DcmRLEEncoderRegistration::registerCodecs();
  103. // register RLE decompression codec
  104. DcmRLEDecoderRegistration::registerCodecs();
  105. // If we like to query another server than before, be sure to disconnect first
  106. if (scu.isConnected() && ConnectionParamsChanged)
  107. {
  108. scu.closeAssociation(DCMSCU_RELEASE_ASSOCIATION);
  109. }
  110. // Connect to server if not already connected
  111. if (!scu.isConnected())
  112. {
  113. // Check and initialize networking parameters in DCMTK
  114. if ( !scu.initNetwork().good() )
  115. {
  116. logger.error ( "Error initializing the network" );
  117. return false;
  118. }
  119. // Negotiate (i.e. start the) association
  120. logger.debug ( "Negotiating Association" );
  121. if ( !scu.negotiateAssociation().good() )
  122. {
  123. logger.error ( "Error negotiating association" );
  124. return false;;
  125. }
  126. }
  127. ConnectionParamsChanged = false;
  128. // Setup query about what to be received from the PACS
  129. logger.debug ( "Setting Retrieve Parameters" );
  130. DcmDataset *retrieveParameters = new DcmDataset();
  131. if ( rType == RetrieveSeries )
  132. {
  133. retrieveParameters->putAndInsertString ( DCM_QueryRetrieveLevel, "SERIES" );
  134. retrieveParameters->putAndInsertString ( DCM_SeriesInstanceUID, seriesInstanceUID.toStdString().c_str() );
  135. // Always required to send all highler level unique keys, so add study here (we are in Study Root)
  136. retrieveParameters->putAndInsertString ( DCM_StudyInstanceUID, studyInstanceUID.toStdString().c_str() ); //TODO
  137. }
  138. else
  139. {
  140. retrieveParameters->putAndInsertString ( DCM_QueryRetrieveLevel, "STUDY" );
  141. retrieveParameters->putAndInsertString ( DCM_StudyInstanceUID, studyInstanceUID.toStdString().c_str() );
  142. }
  143. // Issue request
  144. logger.debug ( "Sending Move Request" );
  145. MOVEResponses responses;
  146. T_ASC_PresentationContextID presID = scu.findPresentationContextID(UID_MOVEStudyRootQueryRetrieveInformationModel, "" /* don't care about transfer syntax */ );
  147. if (presID == 0)
  148. {
  149. logger.error ( "MOVE Request failed: No valid Study Root MOVE Presentation Context available" );
  150. if (!KeepAssociationOpen)
  151. {
  152. scu.closeAssociation(DCMSCU_RELEASE_ASSOCIATION);
  153. }
  154. return false;
  155. }
  156. OFCondition status = scu.sendMOVERequest ( presID, this->MoveDestinationAETitle.toStdString().c_str(), retrieveParameters, &responses );
  157. // Close association if we do not want to explicitly keep it open
  158. if (!KeepAssociationOpen)
  159. {
  160. scu.closeAssociation(DCMSCU_RELEASE_ASSOCIATION);
  161. }
  162. // Free some (little) memory
  163. delete retrieveParameters;
  164. // If we do not receive a single response, something is fishy
  165. if ( responses.begin() == responses.end() )
  166. {
  167. logger.error ( "No responses received at all! (at least one empty response always expected)" );
  168. throw std::runtime_error( std::string("No responses received from server!") );
  169. }
  170. /* The server is permitted to acknowledge every image that was received, or
  171. * to send a single move response.
  172. * If there is only a single response, this can mean the following:
  173. * 1) No images to transfer (Status Success and Number of Completed Subops = 0)
  174. * 2) All images transferred (Status Success and Number of Completed Subops > 0)
  175. * 3) Error code, i.e. no images transferred
  176. * 4) Warning (one or more failures, i.e. some images transferred)
  177. */
  178. if ( responses.numResults() == 1 )
  179. {
  180. MOVEResponse* rsp = *responses.begin();
  181. logger.debug ( "MOVE response receveid with status: " + QString(DU_cmoveStatusString(rsp->m_status)) );
  182. if ((rsp->m_status == STATUS_Success) || (rsp->m_status == STATUS_MOVE_Warning_SubOperationsCompleteOneOrMoreFailures))
  183. {
  184. if (rsp->m_numberOfCompletedSubops == 0)
  185. {
  186. logger.error ( "No images transferred by PACS!" );
  187. throw std::runtime_error( std::string("No images transferred by PACS!") );
  188. }
  189. }
  190. else
  191. {
  192. logger.error("MOVE request failed, server does report error");
  193. QString statusDetail("No details");
  194. if (rsp->m_statusDetail != NULL)
  195. {
  196. std::ostringstream out;
  197. rsp->m_statusDetail->print(out);
  198. statusDetail = "Status Detail: " + statusDetail.fromStdString(out.str());
  199. }
  200. statusDetail.prepend("MOVE request failed: ");
  201. logger.error(statusDetail);
  202. throw std::runtime_error( statusDetail.toStdString() );
  203. }
  204. }
  205. // Select the last MOVE response to output meaningful status information
  206. OFListIterator(MOVEResponse*) it = responses.begin();
  207. Uint32 numResults = responses.numResults();
  208. for (Uint32 i = 1; i < numResults; i++)
  209. {
  210. it++;
  211. }
  212. logger.debug ( "MOVE responses report for study: " + studyInstanceUID +"\n"
  213. + QString::number(static_cast<unsigned int>((*it)->m_numberOfCompletedSubops)) + " images transferred, and\n"
  214. + QString::number(static_cast<unsigned int>((*it)->m_numberOfWarningSubops)) + " images transferred with warning, and\n"
  215. + QString::number(static_cast<unsigned int>((*it)->m_numberOfFailedSubops)) + " images transfers failed");
  216. /* Comment from Michael: The code below does not make sense. Using MOVE you never
  217. * receive the image here but only status information; thus, rsp->m_dataset is _not_
  218. * an image. I leave it inside since it might be moved to a location which makes more
  219. * sense.
  220. */
  221. // for ( OFListIterator(MOVEResponse*) it = responses.begin(); it != responses.end(); it++ )
  222. // {
  223. // DcmDataset *dataset = (*it)->m_dataset;
  224. // if ( dataset != NULL )
  225. // {
  226. // logger.debug ( "Got a valid dataset" );
  227. // // Save in correct directory
  228. // E_TransferSyntax output_transfersyntax = dataset->getOriginalXfer();
  229. // dataset->chooseRepresentation( output_transfersyntax, NULL );
  230. //
  231. // if ( !dataset->canWriteXfer( output_transfersyntax ) )
  232. // {
  233. // // Pick EXS_LittleEndianExplicit as our default
  234. // output_transfersyntax = EXS_LittleEndianExplicit;
  235. // }
  236. //
  237. // DcmXfer opt_oxferSyn( output_transfersyntax );
  238. // if ( !dataset->chooseRepresentation( opt_oxferSyn.getXfer(), NULL ).bad() )
  239. // {
  240. // DcmFileFormat fileformat( dataset );
  241. //
  242. // // Follow dcmdjpeg example
  243. // OFString SOPInstanceUID;
  244. // dataset->findAndGetOFString ( DCM_SOPInstanceUID, SOPInstanceUID );
  245. // QFileInfo fi ( directory, QString ( SOPInstanceUID.c_str() ) );
  246. // logger.debug ( "Saving file: " + fi.absoluteFilePath() );
  247. // status = fileformat.saveFile ( fi.absoluteFilePath().toStdString().c_str(), opt_oxferSyn.getXfer() );
  248. // if ( !status.good() )
  249. // {
  250. // logger.error ( "Error saving file: " + fi.absoluteFilePath() + " Error is " + status.text() );
  251. // }
  252. // // Insert into our local database
  253. // RetrieveDatabase->insert( dataset, true );
  254. // }
  255. // }
  256. // }
  257. return true;
  258. }
  259. //------------------------------------------------------------------------------
  260. // ctkDICOMRetrieve methods
  261. //------------------------------------------------------------------------------
  262. ctkDICOMRetrieve::ctkDICOMRetrieve()
  263. : d_ptr(new ctkDICOMRetrievePrivate)
  264. {
  265. }
  266. //------------------------------------------------------------------------------
  267. ctkDICOMRetrieve::~ctkDICOMRetrieve()
  268. {
  269. }
  270. //------------------------------------------------------------------------------
  271. /// Set methods for connectivity
  272. void ctkDICOMRetrieve::setCallingAETitle( const QString& callingAETitle )
  273. {
  274. Q_D(ctkDICOMRetrieve);
  275. if (strcmp(callingAETitle.toStdString().c_str(), d->scu.getAETitle().c_str()))
  276. {
  277. d->scu.setAETitle(callingAETitle.toStdString().c_str());
  278. d->ConnectionParamsChanged = true;
  279. }
  280. }
  281. //------------------------------------------------------------------------------
  282. QString ctkDICOMRetrieve::callingAETitle() const
  283. {
  284. Q_D(const ctkDICOMRetrieve);
  285. return d->scu.getAETitle().c_str();
  286. }
  287. //------------------------------------------------------------------------------
  288. void ctkDICOMRetrieve::setCalledAETitle( const QString& calledAETitle )
  289. {
  290. Q_D(ctkDICOMRetrieve);
  291. if (strcmp(calledAETitle.toStdString().c_str(),d->scu.getPeerAETitle().c_str()))
  292. {
  293. d->scu.setPeerAETitle(calledAETitle.toStdString().c_str());
  294. d->ConnectionParamsChanged = true;
  295. }
  296. }
  297. //------------------------------------------------------------------------------
  298. QString ctkDICOMRetrieve::calledAETitle()const
  299. {
  300. Q_D(const ctkDICOMRetrieve);
  301. return d->scu.getPeerAETitle().c_str();
  302. }
  303. //------------------------------------------------------------------------------
  304. void ctkDICOMRetrieve::setHost( const QString& host )
  305. {
  306. Q_D(ctkDICOMRetrieve);
  307. if (strcmp(host.toStdString().c_str(), d->scu.getPeerHostName().c_str()))
  308. {
  309. d->scu.setPeerHostName(host.toStdString().c_str());
  310. d->ConnectionParamsChanged = true;
  311. }
  312. }
  313. //------------------------------------------------------------------------------
  314. QString ctkDICOMRetrieve::host()const
  315. {
  316. Q_D(const ctkDICOMRetrieve);
  317. return d->scu.getPeerHostName().c_str();
  318. }
  319. //------------------------------------------------------------------------------
  320. void ctkDICOMRetrieve::setCalledPort( int port )
  321. {
  322. Q_D(ctkDICOMRetrieve);
  323. if (d->scu.getPeerPort() != port)
  324. {
  325. d->scu.setPeerPort(port);
  326. d->ConnectionParamsChanged = true;
  327. }
  328. }
  329. //------------------------------------------------------------------------------
  330. int ctkDICOMRetrieve::calledPort()const
  331. {
  332. Q_D(const ctkDICOMRetrieve);
  333. return d->scu.getPeerPort();
  334. }
  335. //------------------------------------------------------------------------------
  336. void ctkDICOMRetrieve::setMoveDestinationAETitle( const QString& moveDestinationAETitle )
  337. {
  338. Q_D(ctkDICOMRetrieve);
  339. if (moveDestinationAETitle != d->MoveDestinationAETitle)
  340. {
  341. d->MoveDestinationAETitle = moveDestinationAETitle;
  342. d->ConnectionParamsChanged = true;
  343. }
  344. }
  345. //------------------------------------------------------------------------------
  346. QString ctkDICOMRetrieve::moveDestinationAETitle()const
  347. {
  348. Q_D(const ctkDICOMRetrieve);
  349. return d->MoveDestinationAETitle;
  350. }
  351. //------------------------------------------------------------------------------
  352. void ctkDICOMRetrieve::setRetrieveDatabase(QSharedPointer<ctkDICOMDatabase> dicomDatabase)
  353. {
  354. Q_D(ctkDICOMRetrieve);
  355. d->RetrieveDatabase = dicomDatabase;
  356. // (server parameters do not have to be changed)
  357. }
  358. //------------------------------------------------------------------------------
  359. QSharedPointer<ctkDICOMDatabase> ctkDICOMRetrieve::retrieveDatabase()const
  360. {
  361. Q_D(const ctkDICOMRetrieve);
  362. return d->RetrieveDatabase;
  363. }
  364. //------------------------------------------------------------------------------
  365. void ctkDICOMRetrieve::setKeepAssociationOpen(const bool keepOpen)
  366. {
  367. Q_D(ctkDICOMRetrieve);
  368. d->KeepAssociationOpen = keepOpen;
  369. }
  370. //------------------------------------------------------------------------------
  371. bool ctkDICOMRetrieve::keepAssociationOpen()
  372. {
  373. Q_D(const ctkDICOMRetrieve);
  374. return d->KeepAssociationOpen;
  375. }
  376. //------------------------------------------------------------------------------
  377. bool ctkDICOMRetrieve::retrieveSeries(const QString& studyInstanceUID,
  378. const QString& seriesInstanceUID)
  379. {
  380. if (studyInstanceUID.isEmpty() || seriesInstanceUID.isEmpty())
  381. {
  382. logger.error("Cannot receive series: Either Study or Series Instance UID empty.");
  383. return false;
  384. }
  385. Q_D(ctkDICOMRetrieve);
  386. logger.info ( "Starting retrieveSeries" );
  387. return d->retrieve ( studyInstanceUID, seriesInstanceUID, ctkDICOMRetrievePrivate::RetrieveSeries );
  388. }
  389. //------------------------------------------------------------------------------
  390. bool ctkDICOMRetrieve::retrieveStudy( const QString& studyInstanceUID )
  391. {
  392. if (studyInstanceUID.isEmpty())
  393. {
  394. logger.error("Cannot receive series: Either Study or Series Instance UID empty.");
  395. return false;
  396. }
  397. Q_D(ctkDICOMRetrieve);
  398. logger.info ( "Starting retrieveStudy" );
  399. return d->retrieve ( studyInstanceUID, "", ctkDICOMRetrievePrivate::RetrieveStudy );
  400. }