public void Retrieve() { if (!_alreadyRetrieved) { //construct this object before the lock so there's no chance of deadlocking //with the parent data source (because we are accessing it's tags at the //same time as it's trying to get the pixel data). FramePixelDataRetriever retriever = new FramePixelDataRetriever(this, Parent.binaryStream, Parent.useBulkLoading); lock (_syncLock) { if (!_alreadyRetrieved) { DateTime start = DateTime.Now; _retrieveResult = retriever.Retrieve(); DateTime end = DateTime.Now; _lastRetrievePerformanceInfo = new StreamingPerformanceInfo(start, end, _retrieveResult.MetaData.ContentLength); _alreadyRetrieved = true; } } } }
public void Unload() { lock (_syncLock) { _alreadyRetrieved = false; _retrieveResult = null; } }
public RetrievePixelDataResult Retrieve() { Exception retrieveException; RetrievePixelDataResult result = TryClientRetrievePixelData(out retrieveException); if (result != null) { return(result); } // if no result was returned, then the throw an exception with an appropriate, user-friendly message throw TranslateStreamingException(retrieveException); }
public void Retrieve() { if (!_alreadyRetrieved) { //construct this object before the lock so there's no chance of deadlocking //with the parent data source (because we are accessing it's tags at the //same time as it's trying to get the pixel data). FramePixelDataRetriever retriever = new FramePixelDataRetriever(this); lock (_syncLock) { if (!_alreadyRetrieved) { AbortAttemptIfNecessary(); try { ResetAttemptData(); _retrievesAttempted++; var start = DateTime.Now; _retrieveResult = retriever.Retrieve(); var end = DateTime.Now; _lastRetrievePerformanceInfo = new StreamingPerformanceInfo(start, end, _retrieveResult.MetaData.ContentLength); _alreadyRetrieved = true; } catch (Exception ex) { _lastError = ex; throw; } } } } }
private RetrievePixelDataResult TryClientRetrievePixelData(out Exception lastRetrieveException) { // retry parameters const int maxRetryCount = 10; const int retryTimeout = 1500; int retryDelay = 50; int retryCounter = 0; StreamingClient client = new StreamingClient(this.BaseUrl); RetrievePixelDataResult result = null; lastRetrieveException = null; CodeClock timeoutClock = new CodeClock(); timeoutClock.Start(); while (true) { try { if (retryCounter > 0) { Platform.Log(LogLevel.Info, "Retrying retrieve pixel data for Sop '{0}' (Attempt #{1})", this.SopInstanceUid, retryCounter); } CodeClock statsClock = new CodeClock(); statsClock.Start(); result = client.RetrievePixelData(this.AETitle, this.StudyInstanceUid, this.SeriesInstanceUid, this.SopInstanceUid, this.FrameNumber - 1); statsClock.Stop(); Platform.Log(LogLevel.Debug, "[Retrieve Info] Sop/Frame: {0}/{1}, Transfer Syntax: {2}, Bytes transferred: {3}, Elapsed (s): {4}, Retries: {5}", this.SopInstanceUid, this.FrameNumber, this.TransferSyntaxUid, result.MetaData.ContentLength, statsClock.Seconds, retryCounter); break; } catch (Exception ex) { lastRetrieveException = ex; timeoutClock.Stop(); if (timeoutClock.Seconds * 1000 >= retryTimeout || retryCounter >= maxRetryCount) { // log an alert that we are aborting (exception trace at debug level only) int elapsed = (int)(1000 * timeoutClock.Seconds); Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Aborting after {1} attempts in {2} ms", this.SopInstanceUid, retryCounter, elapsed); Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Abort] Sop/Frame: {0}/{1}, Retry Attempts: {2}, Elapsed: {3} ms", this.SopInstanceUid, this.FrameNumber - 1, retryCounter, elapsed); break; } timeoutClock.Start(); retryCounter++; // log the retry (exception trace at debug level only) Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Retrying in {1} ms", this.SopInstanceUid, retryDelay); Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Retry] Sop/Frame: {0}/{1}, Retry in: {2} ms", this.SopInstanceUid, this.FrameNumber - 1, retryDelay); MemoryManager.Collect(retryDelay); retryDelay *= 2; if (retryDelay > MaxRetryDelay) { retryDelay = MaxRetryDelay; // cap it to avoid overflow, which will cause exception when calling MemoryManager.Collect() } } } return(result); }
private static void RetrieveImages(string serverAE, string studyPath) { Console.WriteLine("server={0}", serverAE); string baseUri = String.Format("http://{0}:{1}", serverHost, serverPort); StreamingClient client = new StreamingClient(new Uri(baseUri)); int totalFrameCount = 0; DirectoryInfo directoryInfo = new DirectoryInfo(studyPath); string studyUid = directoryInfo.Name; RateStatistics frameRate = new RateStatistics("Speed", "frame"); RateStatistics speed = new RateStatistics("Speed", RateType.BYTES); AverageRateStatistics averageSpeed = new AverageRateStatistics(RateType.BYTES); ByteCountStatistics totalSize = new ByteCountStatistics("Size"); frameRate.Start(); speed.Start(); Console.WriteLine("\n------------------------------------------------------------------------------------------------------------------------"); string[] seriesDirs = Directory.GetDirectories(studyPath); foreach (string seriesPath in seriesDirs) { DirectoryInfo dirInfo = new DirectoryInfo(seriesPath); string seriesUid = dirInfo.Name; string[] objectUidPath = Directory.GetFiles(seriesPath, "*.dcm"); foreach (string uidPath in objectUidPath) { FileInfo fileInfo = new FileInfo(uidPath); string uid = fileInfo.Name.Replace(".dcm", ""); Console.Write("{0,-64}... ", uid); try { Stream imageStream; StreamingResultMetaData imageMetaData; FrameStreamingResultMetaData frameMetaData; switch (type) { case ContentTypes.Dicom: imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData); totalFrameCount++; averageSpeed.AddSample(imageMetaData.Speed); totalSize.Value += (ulong)imageMetaData.ContentLength; Console.WriteLine("1 dicom sop [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType); break; case ContentTypes.RawPixel: TimeSpanStatistics elapsedTime = new TimeSpanStatistics(); elapsedTime.Start(); ulong instanceSize = 0; int frameCount = 0; do { RetrievePixelDataResult result = client.RetrievePixelData(serverAE, studyUid, seriesUid, uid, frameCount); frameMetaData = result.MetaData; totalFrameCount++; frameCount++; averageSpeed.AddSample(frameMetaData.Speed); totalSize.Value += (ulong)frameMetaData.ContentLength; instanceSize += (ulong)frameMetaData.ContentLength; } while (!frameMetaData.IsLast); elapsedTime.End(); Console.WriteLine("{0,3} frame(s) [{1,10}] in {2,12}\t[mime={3}]", frameCount, ByteCountFormatter.Format(instanceSize), elapsedTime.FormattedValue, frameMetaData.ResponseMimeType); break; default: imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData); totalFrameCount++; averageSpeed.AddSample(imageMetaData.Speed); totalSize.Value += (ulong)imageMetaData.ContentLength; Console.WriteLine("1 object [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType); break; } } catch (Exception ex) { if (ex is WebException) { HttpWebResponse rsp = ((ex as WebException).Response as HttpWebResponse); string msg = String.Format("Error: {0} : {1}", rsp.StatusCode, HttpUtility.HtmlDecode(rsp.StatusDescription) ); Console.WriteLine(msg); } else { Console.WriteLine(ex.Message); } } } } frameRate.SetData(totalFrameCount); frameRate.End(); speed.SetData(totalSize.Value); speed.End(); Console.WriteLine("\nTotal {0,3} image(s)/frame(s) [{1,10}] in {2,12} ==> [ Speed: {3,12} or {4,12}]", totalFrameCount, totalSize.FormattedValue, TimeSpanFormatter.Format(frameRate.ElapsedTime), frameRate.FormattedValue, speed.FormattedValue ); }
public RetrievePixelDataResult RetrievePixelData() { try { if (_useBulkLoading) { //FrameStreamingResultMetaData result = new FrameStreamingResultMetaData(); string[] uriSplit = Regex.Split(_baseUri.ToString(), "/"); //Console.WriteLine("URI: " + _baseUri); //Console.WriteLine("binary item no: " + uriSplit[uriSplit.Length - 1]); //byte[] binaryData = new byte[1000000]; //_binaryItems.TryGetValue(1, out binaryData); int binaryItemNumber = Int32.Parse(uriSplit[uriSplit.Length - 1]); //byte[] binaryData = _binaryStream.GetBinaryData(binaryItemNumber); //result = _binaryStream.GetMetadata(binaryItemNumber); RetrievePixelDataResult pixelDataResult = new RetrievePixelDataResult(_binaryStream.GetBinaryData(binaryItemNumber), _binaryStream.GetMetadata(binaryItemNumber)); return(pixelDataResult); } else { CodeClock clock = new CodeClock(); clock.Start(); FrameStreamingResultMetaData result = new FrameStreamingResultMetaData(); result.Speed.Start(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_baseUri); request.Timeout = 30000; request.KeepAlive = false; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new StreamingClientException(response.StatusCode, HttpUtility.HtmlDecode(response.StatusDescription)); } Stream responseStream = response.GetResponseStream(); BinaryReader reader = new BinaryReader(responseStream); byte[] buffer = reader.ReadBytes((int)response.ContentLength); reader.Close(); responseStream.Close(); response.Close(); result.Speed.SetData(buffer.Length); result.Speed.End(); result.ResponseMimeType = response.ContentType; result.Status = response.StatusCode; result.StatusDescription = response.StatusDescription; result.Uri = response.ResponseUri; result.ContentLength = buffer.Length; result.IsLast = (response.Headers["IsLast"] != null && bool.Parse(response.Headers["IsLast"])); clock.Stop(); PerformanceReportBroker.PublishReport("MINT", "RetrievePixelData", clock.Seconds); RetrievePixelDataResult pixelDataResult; if (response.Headers["Compressed"] != null && bool.Parse(response.Headers["Compressed"])) { pixelDataResult = new RetrievePixelDataResult(CreateCompressedPixelData(response, buffer), result); } else { pixelDataResult = new RetrievePixelDataResult(buffer, result); } return(pixelDataResult); } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response is HttpWebResponse) { HttpWebResponse response = (HttpWebResponse)ex.Response; throw new StreamingClientException(response.StatusCode, HttpUtility.HtmlDecode(response.StatusDescription)); } throw new StreamingClientException(StreamingClientExceptionType.Network, ex); } }
private RetrievePixelDataResult TryClientRetrievePixelData(out Exception lastRetrieveException) { // retry parameters const int retryTimeout = 1500; int retryDelay = 50; int retryCounter = 0; //Second parameter true to use bulk loading, false to load images one by one MINTStreamingClient client = new MINTStreamingClient(this.BaseUrl, UseBulkLoading, BinaryStream); RetrievePixelDataResult result = null; lastRetrieveException = null; CodeClock timeoutClock = new CodeClock(); timeoutClock.Start(); while (true) { try { if (retryCounter > 0) { Platform.Log(LogLevel.Info, "Retrying retrieve pixel data for Sop '{0}' (Attempt #{1})", this.SopInstanceUid, retryCounter); } CodeClock statsClock = new CodeClock(); statsClock.Start(); result = client.RetrievePixelData(); statsClock.Stop(); Platform.Log(LogLevel.Debug, "[Retrieve Info] Sop/Frame: {0}/{1}, Transfer Syntax: {2}, Bytes transferred: {3}, Elapsed (s): {4}, Retries: {5}", this.SopInstanceUid, this.FrameNumber, this.TransferSyntaxUid, result.MetaData.ContentLength, statsClock.Seconds, retryCounter); break; } catch (Exception ex) { lastRetrieveException = ex; timeoutClock.Stop(); if (timeoutClock.Seconds * 1000 >= retryTimeout) { // log an alert that we are aborting (exception trace at debug level only) int elapsed = (int)(1000 * timeoutClock.Seconds); Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Aborting after {1} attempts in {2} ms", this.SopInstanceUid, retryCounter, elapsed); Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Abort] Sop/Frame: {0}/{1}, Retry Attempts: {2}, Elapsed: {3} ms", this.SopInstanceUid, this.FrameNumber - 1, retryCounter, elapsed); break; } timeoutClock.Start(); retryCounter++; // log the retry (exception trace at debug level only) Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Retrying in {1} ms", this.SopInstanceUid, retryDelay); Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Retry] Sop/Frame: {0}/{1}, Retry in: {2} ms", this.SopInstanceUid, this.FrameNumber - 1, retryDelay); MemoryManager.Collect(retryDelay); retryDelay *= 2; } } return(result); }