comparison ViewerPlugin/Plugin.cpp @ 0:4a7a53257c7d

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Sat, 22 Oct 2016 21:48:33 +0200
parents
children 77b76c1a213f
comparison
equal deleted inserted replaced
-1:000000000000 0:4a7a53257c7d
1 /**
2 * Orthanc - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
4 * Department, University Hospital of Liege, Belgium
5 *
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU Affero General Public License
8 * as published by the Free Software Foundation, either version 3 of
9 * the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 **/
19
20
21 #include "../Framework/Inputs/DicomPyramid.h"
22 #include "../Framework/Jpeg2000Reader.h"
23 #include "../Framework/Messaging/PluginOrthancConnection.h"
24 #include "../Framework/Orthanc/Core/Images/PngWriter.h"
25 #include "../Framework/Orthanc/Core/MultiThreading/Semaphore.h"
26 #include "../Framework/Orthanc/Core/OrthancException.h"
27 #include "../Framework/Orthanc/Plugins/Samples/Common/OrthancPluginCppWrapper.h"
28
29 #include <EmbeddedResources.h>
30
31 #include <cassert>
32
33
34
35 namespace OrthancWSI
36 {
37 // TODO Add LRU recycling policy
38 class DicomPyramidCache : public boost::noncopyable
39 {
40 private:
41 boost::mutex mutex_;
42 IOrthancConnection& orthanc_;
43 std::auto_ptr<DicomPyramid> pyramid_;
44
45 DicomPyramid& GetPyramid(const std::string& seriesId)
46 {
47 // Mutex is assumed to be locked
48
49 if (pyramid_.get() == NULL ||
50 pyramid_->GetSeriesId() != seriesId)
51 {
52 pyramid_.reset(new DicomPyramid(orthanc_, seriesId));
53 }
54
55 if (pyramid_.get() == NULL)
56 {
57 throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
58 }
59
60 return *pyramid_;
61 }
62
63 public:
64 DicomPyramidCache(IOrthancConnection& orthanc) :
65 orthanc_(orthanc)
66 {
67 }
68
69 void Invalidate(const std::string& seriesId)
70 {
71 boost::mutex::scoped_lock lock(mutex_);
72
73 if (pyramid_.get() != NULL &&
74 pyramid_->GetSeriesId() == seriesId)
75 {
76 pyramid_.reset(NULL);
77 }
78 }
79
80 class Locker : public boost::noncopyable
81 {
82 private:
83 boost::mutex::scoped_lock lock_;
84 DicomPyramid& pyramid_;
85
86 public:
87 Locker(DicomPyramidCache& cache,
88 const std::string& seriesId) :
89 lock_(cache.mutex_),
90 pyramid_(cache.GetPyramid(seriesId))
91 {
92 }
93
94 DicomPyramid& GetPyramid() const
95 {
96 return pyramid_;
97 }
98 };
99 };
100 }
101
102
103 OrthancPluginContext* context_ = NULL;
104
105 std::auto_ptr<OrthancWSI::PluginOrthancConnection> orthanc_;
106 std::auto_ptr<OrthancWSI::DicomPyramidCache> cache_;
107 std::auto_ptr<Orthanc::Semaphore> transcoderSemaphore_;
108
109
110 static bool DisplayPerformanceWarning()
111 {
112 (void) DisplayPerformanceWarning; // Disable warning about unused function
113 OrthancPluginLogWarning(context_, "Performance warning in whole-slide imaging: "
114 "Non-release build, runtime debug assertions are turned on");
115 return true;
116 }
117
118
119 void ServePyramid(OrthancPluginRestOutput* output,
120 const char* url,
121 const OrthancPluginHttpRequest* request)
122 {
123 std::string seriesId(request->groups[0]);
124
125 char tmp[1024];
126 sprintf(tmp, "Accessing whole-slide pyramid of series %s", seriesId.c_str());
127 OrthancPluginLogInfo(context_, tmp);
128
129
130 OrthancWSI::DicomPyramidCache::Locker locker(*cache_, seriesId);
131
132 unsigned int totalWidth = locker.GetPyramid().GetLevelWidth(0);
133 unsigned int totalHeight = locker.GetPyramid().GetLevelHeight(0);
134
135 Json::Value resolutions = Json::arrayValue;
136 for (unsigned int i = 0; i < locker.GetPyramid().GetLevelCount(); i++)
137 {
138 resolutions.append(static_cast<float>(totalWidth) /
139 static_cast<float>(locker.GetPyramid().GetLevelWidth(i)));
140 }
141
142 Json::Value result;
143 result["ID"] = seriesId;
144 result["TotalWidth"] = totalWidth;
145 result["TotalHeight"] = totalHeight;
146 result["TileWidth"] = locker.GetPyramid().GetTileWidth();
147 result["TileHeight"] = locker.GetPyramid().GetTileHeight();
148 result["Resolutions"] = resolutions;
149
150 std::string s = result.toStyledString();
151 OrthancPluginAnswerBuffer(context_, output, s.c_str(), s.size(), "application/json");
152 }
153
154
155 void ServeTile(OrthancPluginRestOutput* output,
156 const char* url,
157 const OrthancPluginHttpRequest* request)
158 {
159 std::string seriesId(request->groups[0]);
160 int level = boost::lexical_cast<int>(request->groups[1]);
161 int tileY = boost::lexical_cast<int>(request->groups[3]);
162 int tileX = boost::lexical_cast<int>(request->groups[2]);
163
164 char tmp[1024];
165 sprintf(tmp, "Accessing tile in series %s: (%d,%d) at level %d", seriesId.c_str(), tileX, tileY, level);
166 OrthancPluginLogInfo(context_, tmp);
167
168 if (level < 0 ||
169 tileX < 0 ||
170 tileY < 0)
171 {
172 throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
173 }
174
175 // Retrieve the raw tile from the WSI pyramid
176 OrthancWSI::ImageCompression compression;
177 Orthanc::PixelFormat format;
178 std::string tile;
179 unsigned int tileWidth, tileHeight;
180
181 {
182 OrthancWSI::DicomPyramidCache::Locker locker(*cache_, seriesId);
183
184 compression = locker.GetPyramid().GetImageCompression();
185 format = locker.GetPyramid().GetPixelFormat();
186 tileWidth = locker.GetPyramid().GetTileWidth();
187 tileHeight = locker.GetPyramid().GetTileHeight();
188
189 if (!locker.GetPyramid().ReadRawTile(tile,
190 static_cast<unsigned int>(level),
191 static_cast<unsigned int>(tileX),
192 static_cast<unsigned int>(tileY)))
193 {
194 throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource);
195 }
196 }
197
198
199 // Test whether the tile is a JPEG image. In such a case, we can
200 // serve it as such, because any Web browser can handle JPEG
201
202 if (compression == OrthancWSI::ImageCompression_Jpeg)
203 {
204 OrthancPluginAnswerBuffer(context_, output, tile.c_str(), tile.size(), "image/jpeg");
205 return; // We're done
206 }
207
208
209 // The tile does not come from a DICOM-JPEG instance, we need to
210 // decompress the raw tile
211 std::auto_ptr<Orthanc::ImageAccessor> decoded;
212
213 Orthanc::Semaphore::Locker locker(*transcoderSemaphore_);
214
215 switch (compression)
216 {
217 case OrthancWSI::ImageCompression_Jpeg2000:
218 decoded.reset(new OrthancWSI::Jpeg2000Reader);
219 dynamic_cast<OrthancWSI::Jpeg2000Reader&>(*decoded).ReadFromMemory(tile);
220 break;
221
222 case OrthancWSI::ImageCompression_None:
223 {
224 unsigned int bpp = Orthanc::GetBytesPerPixel(format);
225 if (bpp * tileWidth * tileHeight != tile.size())
226 {
227 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
228 }
229
230 decoded.reset(new Orthanc::ImageAccessor);
231 decoded->AssignReadOnly(format, tileWidth, tileHeight, bpp * tileWidth, tile.c_str());
232 break;
233 }
234
235 default:
236 throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented);
237 }
238
239
240 // This is a lossless frame (coming from a JPEG2000 or uncompressed
241 // DICOM instance), serve it as a PNG image so as to prevent lossy
242 // compression
243
244 std::string png;
245 Orthanc::PngWriter writer;
246 writer.WriteToMemory(png, *decoded);
247
248 OrthancPluginAnswerBuffer(context_, output, png.c_str(), png.size(), "image/png");
249 }
250
251
252 OrthancPluginErrorCode OnChangeCallback(OrthancPluginChangeType changeType,
253 OrthancPluginResourceType resourceType,
254 const char *resourceId)
255 {
256 if (resourceType == OrthancPluginResourceType_Series &&
257 changeType == OrthancPluginChangeType_NewChildInstance)
258 {
259 char tmp[1024];
260 sprintf(tmp, "New instance has been added to series %s, invalidating it", resourceId);
261 OrthancPluginLogInfo(context_, tmp);
262
263 cache_->Invalidate(resourceId);
264 }
265
266 return OrthancPluginErrorCode_Success;
267 }
268
269
270
271 void ServeFile(OrthancPluginRestOutput* output,
272 const char* url,
273 const OrthancPluginHttpRequest* request)
274 {
275 Orthanc::EmbeddedResources::FileResourceId resource;
276
277 std::string f(request->groups[0]);
278 std::string mime;
279
280 if (f == "viewer.html")
281 {
282 resource = Orthanc::EmbeddedResources::VIEWER_HTML;
283 mime = "text/html";
284 }
285 else if (f == "viewer.js")
286 {
287 resource = Orthanc::EmbeddedResources::VIEWER_JS;
288 mime = "application/javascript";
289 }
290 else if (f == "ol.js")
291 {
292 resource = Orthanc::EmbeddedResources::OPENLAYERS_JS;
293 mime = "application/javascript";
294 }
295 else if (f == "ol.css")
296 {
297 resource = Orthanc::EmbeddedResources::OPENLAYERS_CSS;
298 mime = "text/css";
299 }
300 else
301 {
302 throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource);
303 }
304
305 std::string content;
306 Orthanc::EmbeddedResources::GetFileResource(content, resource);
307
308 OrthancPluginAnswerBuffer(context_, output, content.c_str(), content.size(), mime.c_str());
309 }
310
311
312
313 extern "C"
314 {
315 ORTHANC_PLUGINS_API int32_t OrthancPluginInitialize(OrthancPluginContext* context)
316 {
317 context_ = context;
318 assert(DisplayPerformanceWarning());
319
320 /* Check the version of the Orthanc core */
321 if (OrthancPluginCheckVersion(context_) == 0)
322 {
323 char info[1024];
324 sprintf(info, "Your version of Orthanc (%s) must be above %d.%d.%d to run this plugin",
325 context_->orthancVersion,
326 ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER,
327 ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER,
328 ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER);
329 OrthancPluginLogError(context_, info);
330 return -1;
331 }
332
333 // Limit the number of PNG transcoders to the number of available
334 // hardware threads (e.g. number of CPUs or cores or
335 // hyperthreading units)
336 unsigned int threads = boost::thread::hardware_concurrency();
337
338 if (threads <= 0)
339 {
340 threads = 1;
341 }
342
343 transcoderSemaphore_.reset(new Orthanc::Semaphore(threads));
344
345 char info[1024];
346 sprintf(info, "The whole-slide imaging plugin will use at most %d threads to transcode the tiles", threads);
347 OrthancPluginLogWarning(context_, info);
348
349 OrthancPluginSetDescription(context, "Plugin to serve whole-slide microscopic images from Orthanc.");
350
351 orthanc_.reset(new OrthancWSI::PluginOrthancConnection(context));
352 cache_.reset(new OrthancWSI::DicomPyramidCache(*orthanc_));
353
354 OrthancPluginRegisterOnChangeCallback(context_, OnChangeCallback);
355
356 OrthancPlugins::RegisterRestCallback<ServeFile>(context, "/wsi/app/(ol.css)", true);
357 OrthancPlugins::RegisterRestCallback<ServeFile>(context, "/wsi/app/(ol.js)", true);
358 OrthancPlugins::RegisterRestCallback<ServeFile>(context, "/wsi/app/(viewer.html)", true);
359 OrthancPlugins::RegisterRestCallback<ServeFile>(context, "/wsi/app/(viewer.js)", true);
360 OrthancPlugins::RegisterRestCallback<ServePyramid>(context, "/wsi/pyramids/([0-9a-f-]+)", true);
361 OrthancPlugins::RegisterRestCallback<ServeTile>(context, "/wsi/tiles/([0-9a-f-]+)/([0-9-]+)/([0-9-]+)/([0-9-]+)", true);
362
363 // Extend the default Orthanc Explorer with custom JavaScript for WSI
364 std::string explorer;
365 Orthanc::EmbeddedResources::GetFileResource(explorer, Orthanc::EmbeddedResources::ORTHANC_EXPLORER);
366 OrthancPluginExtendOrthancExplorer(context_, explorer.c_str());
367
368 return 0;
369 }
370
371
372 ORTHANC_PLUGINS_API void OrthancPluginFinalize()
373 {
374 cache_.reset(NULL);
375 orthanc_.reset(NULL);
376 transcoderSemaphore_.reset(NULL);
377 }
378
379
380 ORTHANC_PLUGINS_API const char* OrthancPluginGetName()
381 {
382 return "wsi";
383 }
384
385
386 ORTHANC_PLUGINS_API const char* OrthancPluginGetVersion()
387 {
388 return ORTHANC_WSI_VERSION;
389 }
390 }