private DicomFile TryClientRetrieveImageHeader(out Exception lastRetrieveException)
        {
            // retry parameters
            const int retryTimeout = 1500;
            int       retryDelay   = 50;
            int       retryCounter = 0;

            var timeoutClock = new CodeClock();

            timeoutClock.Start();

            lastRetrieveException = null;

            while (true)
            {
                try
                {
                    if (retryCounter > 0)
                    {
                        Platform.Log(LogLevel.Info, "Retrying retrieve headers for Sop '{0}' (Attempt #{1})", SopInstanceUid, retryCounter);
                    }

                    return(_loader.LoadDicomFile(new LoadDicomFileArgs(StudyInstanceUid, SeriesInstanceUid, SopInstanceUid, true, false)));
                }
                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)
                        var elapsed = (int)(1000 * timeoutClock.Seconds);
                        Platform.Log(LogLevel.Warn, "Failed to retrieve headers for Sop '{0}'; Aborting after {1} attempts in {2} ms", SopInstanceUid, retryCounter, elapsed);
                        Platform.Log(LogLevel.Debug, ex, "[GetHeaders Fail-Abort] Sop: {0}, Retry Attempts: {1}, Elapsed: {2} ms", SopInstanceUid, retryCounter, elapsed);
                        break;
                    }
                    timeoutClock.Start();

                    retryCounter++;

                    // log the retry (exception trace at debug level only)
                    Platform.Log(LogLevel.Warn, "Failed to retrieve headers for Sop '{0}'; Retrying in {1} ms", SopInstanceUid, retryDelay);
                    Platform.Log(LogLevel.Debug, ex, "[GetHeaders Fail-Retry] Sop: {0}, Retry in: {1} ms", SopInstanceUid, retryDelay);

                    MemoryManager.Collect(retryDelay);
                    retryDelay *= 2;
                }
            }

            return(null);
        }
Пример #2
0
        /// <summary>
        /// Draws the Text Overlay.
        /// </summary>
        protected virtual void DrawTextOverlay(TPresentationImage presentationImage)
        {
#if DEBUG
            var clock = new CodeClock();
            clock.Start();
#endif
            var annotationLayoutProvider = presentationImage as IAnnotationLayoutProvider;
            if (annotationLayoutProvider == null)
            {
                return;
            }

            var layout = annotationLayoutProvider.AnnotationLayout;
            if (layout == null || !layout.Visible)
            {
                return;
            }

            foreach (var annotationBox in layout.AnnotationBoxes)
            {
                if (annotationBox.Visible)
                {
                    var annotationText = annotationBox.GetAnnotationText(presentationImage);
                    if (!string.IsNullOrEmpty(annotationText))
                    {
                        DrawAnnotationBox(annotationText, annotationBox);
                    }
                }
            }
#if DEBUG
            clock.Stop();
            PerformanceReportBroker.PublishReport(_rendererTypeId, "DrawTextOverlay", clock.Seconds);
#endif
        }
Пример #3
0
        /// <summary>
        /// Draws an <see cref="ImageGraphic"/>.
        /// </summary>
        protected override void DrawImageGraphic(ImageGraphic imageGraphic)
        {
            CodeClock clock = new CodeClock();

            clock.Start();

            const int bytesPerPixel = 4;

            Surface.ImageBuffer.Graphics.Clear(Color.FromArgb(0x0, 0xFF, 0xFF, 0xFF));

            BitmapData bitmapData = Surface.ImageBuffer.Bitmap.LockBits(
                new Rectangle(0, 0, Surface.ImageBuffer.Bitmap.Width, Surface.ImageBuffer.Bitmap.Height),
                ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            try
            {
                ImageRenderer.Render(imageGraphic, bitmapData.Scan0, bitmapData.Width, bytesPerPixel, Surface.ClientRectangle);
            }
            finally
            {
                Surface.ImageBuffer.Bitmap.UnlockBits(bitmapData);
            }

            Surface.FinalBuffer.RenderImage(Surface.ImageBuffer);

            clock.Stop();
            PerformanceReportBroker.PublishReport("GDIRenderer", "DrawImageGraphic", clock.Seconds);
        }
Пример #4
0
        /// <summary>
        /// Draws the Text Overlay.
        /// </summary>
        protected void DrawTextOverlay(IPresentationImage presentationImage)
        {
            CodeClock clock = new CodeClock();

            clock.Start();

            if (presentationImage == null || !(presentationImage is IAnnotationLayoutProvider))
            {
                return;
            }

            IAnnotationLayout layout = ((IAnnotationLayoutProvider)presentationImage).AnnotationLayout;

            if (layout == null || !layout.Visible)
            {
                return;
            }

            foreach (AnnotationBox annotationBox in layout.AnnotationBoxes)
            {
                if (annotationBox.Visible)
                {
                    string annotationText = annotationBox.GetAnnotationText(presentationImage);
                    if (!String.IsNullOrEmpty(annotationText))
                    {
                        DrawAnnotationBox(annotationText, annotationBox);
                    }
                }
            }

            clock.Stop();
            PerformanceReportBroker.PublishReport("RendererBase", "DrawTextOverlay", clock.Seconds);
        }
Пример #5
0
        private void DoDraw()
        {
            EventsHelper.Fire(_drawing, this, EventArgs.Empty);

            CodeClock clock = new CodeClock();

            clock.Start();

            if (this.Surface != null)
            {
                System.Drawing.Graphics graphics = this.CreateGraphics();

                this.Surface.WindowID        = this.Handle;
                this.Surface.ContextID       = graphics.GetHdc();
                this.Surface.ClientRectangle = this.ClientRectangle;
                this.Surface.ClipRectangle   = this.ClientRectangle;

                DrawArgs args = new DrawArgs(this.Surface,
                                             new WinFormsScreenProxy(Screen.FromControl(this)),
                                             DrawMode.Render)
                {
                    Dpi = Dpi
                };

                _isDrawing = true;

                try
                {
                    _tile.Draw(args);

                    _lastRenderExceptionMessage = null;
                }
                catch (Exception ex)
                {
                    Platform.Log(LogLevel.Error, ex, "An error has occured while rendering the contents of a tile.");

                    _lastRenderExceptionMessage = ex is RenderingException ? ((RenderingException)ex).UserMessage : ex.Message;

                    // we cannot simply pass the existing Graphics because we haven't released its hDC yet
                    // if we do, we'll get a "Object is currently in use elsewhere" exception
                    DrawErrorMessage(_lastRenderExceptionMessage, Surface.ContextID, ClientRectangle);
                }
                finally
                {
                    graphics.ReleaseHdc(this.Surface.ContextID);
                    graphics.Dispose();

                    _isDrawing = false;
                }
            }

            //Cause the tile to paint/refresh.
            Invalidate();
            Update();

            clock.Stop();
            string str = String.Format("TileControl.Draw: {0}, {1}\n", clock.ToString(), this.Size.ToString());

            Trace.Write(str);
        }
Пример #6
0
        /// <summary>
        /// Computes the area of the polygon.
        /// </summary>
        /// <returns>The area of the polygon in square units.</returns>
        public double ComputeArea()
        {
            CodeClock clock = new CodeClock();

            clock.Start();
            try
            {
                unsafe
                {
                    fixed(PointF *vertices = _vertexArray)
                    {
                        if (!_isComplex)
                        {
                            return(ComputeSimpleArea(vertices, _vertexArray.Length));
                        }
                        else
                        {
                            return(ComputeComplexArea(new RectangleF(_boundingRect.Location - _normalizingOffset, _boundingRect.Size), vertices, _vertexArray.Length));
                        }
                    }
                }
            }
            finally
            {
                clock.Stop();
                //Trace.WriteLine(string.Format("{1} Polygon area calculation took {0:f4} ms", clock.Seconds*1000, _isComplex ? "Complex" : "Simple"), "Math.Polygons");
            }
        }
            public void Refresh()
            {
                var clock = new CodeClock();

                clock.Start();

                var currentProcess = Process.GetCurrentProcess();

                currentProcess.Refresh();

                ProcessVirtualMemoryBytes = currentProcess.VirtualMemorySize64;
                ProcessPrivateBytes       = currentProcess.PrivateMemorySize64;
                ProcessWorkingSetBytes    = currentProcess.WorkingSet64;
                GCTotalBytesAllocated     = GC.GetTotalMemory(false);
                SystemFreeMemoryBytes     = SystemResources.GetAvailableMemory(SizeUnits.Bytes);

                HighWaterMarkBytes         = MemoryManagementSettings.Default.HighWatermarkMegaBytes * OneMegabyte;
                LowWaterMarkBytes          = MemoryManagementSettings.Default.LowWatermarkMegaBytes * OneMegabyte;
                HeldMemoryToCollectPercent = MemoryManagementSettings.Default.HeldMemoryToCollectPercent / 100.0;

                x64MinimumFreeSystemMemoryBytes = MemoryManagementSettings.Default.x64MinimumFreeSystemMemoryMegabytes * OneMegabyte;
                x64MaxMemoryUsagePercent        = MemoryManagementSettings.Default.x64MaxMemoryUsagePercent / 100.0;
                x64MaxMemoryToCollectBytes      = MemoryManagementSettings.Default.x64MaxMemoryToCollectMegabytes * OneMegabyte;

                MemoryManagerLargeObjectBytesCount = MemoryManager.LargeObjectBytesCount;

                clock.Stop();

                PerformanceReportBroker.PublishReport("Memory", "UpdateMemoryInfo", clock.Seconds);
            }
Пример #8
0
        //readBinaryData Reads a binary stream of given length into a byte array
        public void readBinaryData(ref BinaryReader reader, ref int contentLength, ref byte[] binaryData)
        {
            CodeClock clockBinary = new CodeClock();

            //Try to read contentLength many bytes
            int readBytes = reader.Read(binaryData, 0, contentLength);

            //If the bytes read in were not as many as needed
            clockBinary.Start();
            initialMetadata.Speed.Start();
            while (readBytes < contentLength)
            {
                //Try to read contentLength - (the # of bytes already read in) bytes
                int moreReadBytes = reader.Read(binaryData, readBytes, contentLength - readBytes);
                if (moreReadBytes == 0)
                {
                    break;
                }
                readBytes += moreReadBytes;
            }

            initialMetadata.Speed.End();
            clockBinary.Stop();
            binaryClock += clockBinary.Seconds;
        }
Пример #9
0
            /// <summary>
            /// Called by <see cref="StandardSopFrameData.GetNormalizedOverlayData"/> to create a new byte buffer containing normalized
            /// overlay pixel data for a particular overlay plane.
            /// </summary>
            /// <remarks>
            /// See <see cref="StandardSopFrameData.GetNormalizedOverlayData"/> for details on the expected format of the byte buffer.
            /// </remarks>
            /// <param name="overlayNumber">The 1-based overlay plane number.</param>
            /// <returns>A new byte buffer containing the normalized overlay pixel data.</returns>
            protected override byte[] CreateNormalizedOverlayData(int overlayNumber)
            {
                //TODO (CR December 2010): make this a helper method somewhere, since it's now identical to the one in StreamingSopFrameData?

                var overlayIndex = overlayNumber - 1;

                byte[] overlayData = null;

                var clock = new CodeClock();

                clock.Start();

                // check whether or not the overlay plane exists before attempting to ascertain
                // whether or not the overlay is embedded in the pixel data
                var overlayPlaneModuleIod = new OverlayPlaneModuleIod(Parent);

                if (overlayPlaneModuleIod.HasOverlayPlane(overlayIndex))
                {
                    if (_overlayCache[overlayIndex] == null)
                    {
                        var overlayPlane = overlayPlaneModuleIod[overlayIndex];
                        if (!overlayPlane.HasOverlayData)
                        {
                            // if the overlay is embedded, trigger retrieval of pixel data which will populate the cache for us
                            GetNormalizedPixelData();
                        }
                        else
                        {
                            // try to compute the offset in the OverlayData bit stream where we can find the overlay frame that applies to this image frame
                            int overlayFrame;
                            int bitOffset;
                            if (overlayPlane.TryGetRelevantOverlayFrame(FrameNumber, Parent.NumberOfFrames, out overlayFrame) &&
                                overlayPlane.TryComputeOverlayDataBitOffset(overlayFrame, out bitOffset))
                            {
                                // offset found - unpack only that overlay frame
                                var od = new OverlayData(bitOffset,
                                                         overlayPlane.OverlayRows,
                                                         overlayPlane.OverlayColumns,
                                                         overlayPlane.IsBigEndianOW,
                                                         overlayPlane.OverlayData);
                                _overlayCache[overlayIndex] = od.Unpack();
                            }
                            else
                            {
                                // no relevant overlay frame found - i.e. the overlay for this image frame is blank
                                _overlayCache[overlayIndex] = new byte[0];
                            }
                        }
                    }

                    overlayData = _overlayCache[overlayIndex];
                }

                clock.Stop();
                PerformanceReportBroker.PublishReport("DicomMessageSopDataSource", "CreateNormalizedOverlayData", clock.Seconds);

                return(overlayData);
            }
Пример #10
0
        public static void Render(
            ImageGraphic imageGraphic,
            IntPtr pDstPixelData,
            int dstWidth,
            int dstBytesPerPixel,
            Rectangle clientRectangle)
        {
            if (clientRectangle.Width <= 0 || clientRectangle.Height <= 0)
            {
                return;
            }

            if (imageGraphic.SizeInBytes != imageGraphic.PixelData.Raw.Length)
            {
                throw new InvalidOperationException(String.Format(SR.ExceptionIncorrectPixelDataSize, imageGraphic.SizeInBytes, imageGraphic.PixelData.Raw.Length));
            }

#if DEBUG
            CodeClock clock = new CodeClock();
            clock.Start();
#endif
            RectangleF srcViewableRectangle;
            Rectangle  dstViewableRectangle;

            CalculateVisibleRectangles(imageGraphic, clientRectangle, out dstViewableRectangle, out srcViewableRectangle);

            var grayGraphic = imageGraphic as GrayscaleImageGraphic;
            ColorImageGraphic colorGraphic;
            if (grayGraphic != null)
            {
                RenderGrayscale(
                    grayGraphic,
                    srcViewableRectangle,
                    dstViewableRectangle,
                    pDstPixelData,
                    dstWidth,
                    dstBytesPerPixel);
            }
            else if (null != (colorGraphic = imageGraphic as ColorImageGraphic))
            {
                RenderColor(
                    colorGraphic,
                    srcViewableRectangle,
                    dstViewableRectangle,
                    pDstPixelData,
                    dstWidth,
                    dstBytesPerPixel);
            }
            else
            {
                throw new Exception("Unknown ImageGraphic.");
            }
#if DEBUG
            clock.Stop();
            PerformanceReportBroker.PublishReport("ImageRenderer", "Render", clock.Seconds);
#endif
        }
Пример #11
0
        public void CopyTo(byte[] buffer, int srcOffset, int dstOffset, int count)
        {
            var cc = new CodeClock();

            cc.Start();
            _bb.CopyTo(buffer, srcOffset, dstOffset, count);
            cc.Stop();
            Report(cc, "CopyTo(byte[],int,int,int)", count);
        }
Пример #12
0
        public void CopyTo(Stream s, int offset, int count)
        {
            var cc = new CodeClock();

            cc.Start();
            _bb.CopyTo(s, offset, count);
            cc.Stop();
            Report(cc, "CopyTo(Stream,int,int)", count);
        }
Пример #13
0
        public void Swap(int bytesToSwap)
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            _bb.Swap(bytesToSwap);
            cc.Stop();
            Report(cc, "Swap", length);
        }
Пример #14
0
        public void Swap8()
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            _bb.Swap8();
            cc.Stop();
            Report(cc, "Swap8", length);
        }
Пример #15
0
        public void CopyTo(BinaryWriter bw)
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            _bb.CopyTo(bw);
            cc.Stop();
            Report(cc, "CopyTo(BinaryWriter)", length);
        }
Пример #16
0
        public void Chop(int count)
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            _bb.Chop(count);
            cc.Stop();
            Report(cc, "Chop", length - count);
        }
Пример #17
0
        public void SetString(string stringValue, byte paddingByte)
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            _bb.SetString(stringValue, paddingByte);
            cc.Stop();
            Report(cc, "SetString(string,byte)", length);
        }
Пример #18
0
        public byte[] ToBytes(int offset, int count)
        {
            var cc = new CodeClock();

            cc.Start();
            var result = _bb.ToBytes(offset, count);

            cc.Stop();
            Report(cc, "ToBytes(int,int)", count);
            return(result);
        }
Пример #19
0
        public int CopyFrom(Stream s, int count)
        {
            var cc = new CodeClock();

            cc.Start();
            var result = _bb.CopyFrom(s, count);

            cc.Stop();
            Report(cc, "CopyFrom", count);
            return(result);
        }
Пример #20
0
        public byte[] GetChunk(int offset, int count)
        {
            var cc = new CodeClock();

            cc.Start();
            var result = _bb.GetChunk(offset, count);

            cc.Stop();
            Report(cc, "GetChunk", count);
            return(result);
        }
        private void CollectGarbage()
        {
            CodeClock clock = new CodeClock();

            clock.Start();

            Platform.Log(LogLevel.Debug, "Performing garbage collection.");
            GC.Collect();

            clock.Stop();
            PerformanceReportBroker.PublishReport("Memory", "GarbageCollection", clock.Seconds);
        }
Пример #22
0
        /// <summary>
        /// Traverses and renders the scene graph.
        /// </summary>
        protected override void Render()
        {
            CodeClock clock = new CodeClock();

            clock.Start();

            Surface.FinalBuffer.Graphics.Clear(Color.Black);
            base.Render();

            clock.Stop();
            PerformanceReportBroker.PublishReport("GDIRenderer", "Render", clock.Seconds);
        }
Пример #23
0
        public void Append(byte[] buffer, int offset, int count)
        {
            // always copy the buffer to ensure isolation of the input data from the object under test
            buffer = CopyBytes(buffer);

            var cc = new CodeClock();

            cc.Start();
            _bb.Append(buffer, offset, count);
            cc.Stop();
            Report(cc, "Append", count);
        }
Пример #24
0
            public byte[] GetUncompressedPixelData(out string photometricInterpretation)
            {
                try
                {
                    //construct this object before the lock so there's no chance of deadlocking
                    //with the parent data source (because we are accessing its tags at the
                    //same time as it's trying to get the pixel data).
                    var retriever = new FramePixelDataRetriever(this);

                    lock (_syncLock)
                    {
                        IFramePixelData framePixelData;

                        if (_framePixelData == null)
                        {
                            AbortAttemptIfNecessary();

                            ResetAttemptData();
                            _retrievesAttempted++;

                            framePixelData = retriever.Retrieve();
                        }
                        else
                        {
                            framePixelData = _framePixelData;
                        }

                        //free this memory up in case it's holding a compressed buffer.
                        _framePixelData = null;

                        var clock = new CodeClock();
                        clock.Start();

                        //synchronize the call to decompress; it's really already synchronized by
                        //the parent b/c it's only called from CreateFrameNormalizedPixelData, but it doesn't hurt.
                        byte[] pixelData = framePixelData.GetPixelData(out photometricInterpretation);

                        clock.Stop();

                        Platform.Log(LogLevel.Debug,
                                     "[Decompress Info] Sop/Frame: {0}/{1}, Transfer Syntax: {2}, Uncompressed bytes: {3}, Elapsed (s): {4}",
                                     retriever.SopInstanceUid, FrameNumber, retriever.TransferSyntaxUid,
                                     pixelData.Length, clock.Seconds);

                        return(pixelData);
                    }
                }
                catch (Exception ex)
                {
                    _lastError = ex;
                    throw;
                }
            }
Пример #25
0
        public double[] ToDoubles()
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            var result = _bb.ToDoubles();

            cc.Stop();
            Report(cc, "ToDoubles", length);
            return(result);
        }
Пример #26
0
        public float[] ToFloats()
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            var result = _bb.ToFloats();

            cc.Stop();
            Report(cc, "ToFloats", length);
            return(result);
        }
Пример #27
0
        public uint[] ToUInt32s()
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            var result = _bb.ToUInt32s();

            cc.Stop();
            Report(cc, "ToUInt32s", length);
            return(result);
        }
Пример #28
0
        public void FromBytes(byte[] bytes)
        {
            // always copy the buffer to ensure isolation of the input data from the object under test
            bytes = CopyBytes(bytes);

            var cc = new CodeClock();

            cc.Start();
            _bb.FromBytes(bytes);
            cc.Stop();
            Report(cc, "FromBytes", bytes.Length);
        }
Пример #29
0
        public string GetString()
        {
            var length = Length;
            var cc     = new CodeClock();

            cc.Start();
            var result = _bb.GetString();

            cc.Stop();
            Report(cc, "GetString", length);
            return(result);
        }
Пример #30
0
        private static int[] ConstructFinalLut(IComposedLut outputLut, IColorMap colorMap, bool invert)
        {
            CodeClock clock = new CodeClock();

            clock.Start();

            colorMap.MinInputValue = outputLut.MinOutputValue;
            colorMap.MaxInputValue = outputLut.MaxOutputValue;

            int[] outputLutData = outputLut.Data;
            int[] colorMapData  = colorMap.Data;

            if (_finalLutBuffer == null || _finalLutBuffer.Length != outputLutData.Length)
            {
                _finalLutBuffer = new int[outputLutData.Length];
            }

            int numberOfEntries = _finalLutBuffer.Length;

            fixed(int *pOutputLutData = outputLutData)
            {
                fixed(int *pColorMapData = colorMapData)
                {
                    fixed(int *pFinalLutData = _finalLutBuffer)
                    {
                        int *pFinalLut = pFinalLutData;

                        if (!invert)
                        {
                            int firstColorMappedPixelValue = colorMap.FirstMappedPixelValue;
                            for (int i = 0; i < numberOfEntries; ++i)
                            {
                                *(pFinalLut++) = pColorMapData[*(pOutputLutData + i) - firstColorMappedPixelValue];
                            }
                        }
                        else
                        {
                            int lastColorMappedPixelValue = colorMap.FirstMappedPixelValue + colorMap.Data.Length - 1;
                            for (int i = 0; i < numberOfEntries; ++i)
                            {
                                *(pFinalLut++) = pColorMapData[lastColorMappedPixelValue - *(pOutputLutData + i)];
                            }
                        }
                    }
                }
            }

            clock.Stop();
            PerformanceReportBroker.PublishReport("ImageRenderer", "ConstructFinalLut", clock.Seconds);

            return(_finalLutBuffer);
        }