librealsense icon indicating copy to clipboard operation
librealsense copied to clipboard

System.AccessViolationException using Align with .net Wrapper

Open jb455 opened this issue 8 years ago • 9 comments

Required Info
Camera Model SR300
Firmware Version 3.21.0.0
Operating System & Version Windows 10 build 15063
Kernel Version (Linux Only)
SDK Version 2.9.0

Hi, I've been playing with the C# wrapper. My initial goal is to get the depth image aligned to the colour image and alter pixels in the colour image based on their depth. Starting with the cs-tutorial-2-capture example, I've added an instance of the Align class using: align = new Align(Stream.Color); and then in the while loop added:

var aligned = align.Process(frames);
var colorized_aligned_depth = colorizer.Colorize(aligned.DepthFrame);
UploadImage(imgColor, colorized_aligned_depth);

(replacing the UploadImage call for the raw colour image, just want to see the raw depth next to the aligned depth for now) However, after a few frames I keep getting an System.AccessViolationException ('Attempted to read or write protected memory. This is often an indication that other memory is corrupt.') traced back to Processing.cs line 100 (NativeMethods.rs2_process_frame in Align.Process), and inspecting the FrameSet input for that method under debug I can see that the DepthFrame is null. Adding a null check before calling Process doesn't seem to help, it can often pass the null check immediately before calling then be null by the time it gets to the native call. I figured it may be something to do with not releasing things, as the Readme for the wrapper (https://github.com/IntelRealSense/librealsense/tree/master/wrappers/csharp/readme.md) says you should call release on everything (though the sample doesn't), but after wrapping everything in using blocks so the inside of my while loop looks like this:

using (var frames = pipeline.WaitForFrames())
{
    if (frames.DepthFrame == null || frames.ColorFrame == null)
        continue;

    using (var colorized_depth = colorizer.Colorize(frames.DepthFrame))
    {
        UploadImage(imgDepth, colorized_depth);
    }
                                
    using (var aligned = align.Process(frames))
    using (var colorized_aligned_depth = colorizer.Colorize(aligned.DepthFrame))
    {
        UploadImage(imgColor, colorized_aligned_depth);
    }
}

I still get the same exception after about 10 seconds, but this time in Frame.cs line 54 (the Release method).

Can anyone help resolve this please? Am I using anything incorrectly or is this an issue with the wrapper?

BTW, I also had problems running the sample out of the box before making any changes as the colour image from the SR300 is 16 bits per pixel but the BitmapSource.Create call in UploadImage expects 24 bits so I get System.ArgumentException: 'Value does not fall within the expected range.'.

Thanks!

jb455 avatar Jan 15 '18 13:01 jb455

I'm having the exact same problem

joseluisreyes avatar Jan 15 '18 15:01 joseluisreyes

Hi @jb455 @joseluisreyes We are currently looking into the C# wrapper issues. It seems that the latest code on development branch has broken the wrapper. I have submitted a PR to fix it. In addition, I will look into align question and report back to you.

dorodnic avatar Jan 15 '18 15:01 dorodnic

Thanks dorodnic. My secondary goal is to get the point cloud aligned to the colour image too. I just noticed that the point cloud class isn't available in the wrapper. Is that by design or did you just not get around to it?

jb455 avatar Jan 16 '18 10:01 jb455

I've managed to work around this issue by using unsafe code with the Marshal and Buffer.MemoryCopy to create a copy of the colour data in memory then using that copy going forwards (then releasing it when I'm done). It seems the original image data is being collected too early, causing the exception I was seeing before.

Also, if I set the colour stream to Rgba8 it seems to come out as BGR8 at 24bpp which renders alright as long as you change the PixelFormat in UploadImage to Bgr24.

jb455 avatar Jan 17 '18 09:01 jb455

Hi @jb455 and @joseluisreyes , I've managed to reproduce this issue, and rooted the bug to a missing "add_ref" call for the Align.Process call.

index f43c2e0d..3c032471 100644
--- a/wrappers/csharp/src/Processing.cs
+++ b/wrappers/csharp/src/Processing.cs
@@ -95,6 +95,7 @@ namespace Intel.RealSense
         public FrameSet Process(FrameSet original)
         {
             object error;
+            NativeMethods.rs2_frame_add_ref(original.m_instance.Handle, out error);
             NativeMethods.rs2_process_frame(m_instance.Handle, original.m_instance.Handle, out error);
             return queue.WaitForFrames();
         }

This looks like the right solution, and works fine with no leaks (or at least no frame leaks - tested manually for ~6 minutes and memory remained ~200MB, didn't perform any memory inspection). Will push the changes soon

zivsha avatar Jan 30 '18 12:01 zivsha

@jb455 / @joseluisreyes can you confirm this fixed the issue for you?

zivsha avatar Feb 03 '18 19:02 zivsha

Hi zivsha, I don't get the crash from just streaming and rendering any more, but if I try to access the image data by:

uint* colourData = (uint*)colourFrame.Data.ToPointer();
for(...)
{
    uint colour = colourData[idx];
}

I still get the same exception. The way I got round it before was by taking a copy of the data using:

int colourbpp = colourFrame.BitsPerPixel / 8;

var colourDataPtr = Marshal.AllocHGlobal(colourFrame.Stride * colourFrame.Height * colourbpp); 

var colourData = (uint*)colourDataPtr.ToPointer();
Buffer.MemoryCopy(colourFrame.Data.ToPointer(), colourData, colourFrame.Stride * colourFrame.Height, colourFrame.Stride * colourFrame.Height);
for(...)
{
    uint colour = (uint)Marshal.ReadInt32(colourDataPtr, idx * colourbpp);
}
Marshal.FreeHGlobal(colourDataPtr);

But this has quite a lot of overhead so isn't efficient enough to be used while streaming at a decent frame rate (which is what I need), so I'd like to be able to access the image data directly through the original pointer.

(PS, I wasn't able to build realsense2.dll for x64 from development branch using VS17 - I keep getting linker errors. I ended up using the pre-built x64 realsense2 binary from 2.9.1 with LibrealsenseWrapper built from development branch with your fix so my findings above may be a bit out of sync if changes have been made to the native dll too.)

--Edit-- Just realised that my first snippet always hits the exception when idx gets to 692200, just over 75% of the way through the 1280x720 image. If I increase the image size to 1920x1080 it errors at 1555432, which again is just over 75% of the image. This lead me to realise that my image format was RGB24 whereas uint is 32-bit so it was taking too many bytes from the array and therefore overflowing. Since there's no 24 bit int in C#, changing the image format to RGBA32 allows me to use uint. However it's still a bit slow! I'll see if I can optimise my code.

jb455 avatar Feb 05 '18 11:02 jb455

[Realsense Customer Engineering Team Comment] @jb455 Would like to check with you if the issue fixed?

Yes, I haven't had this exception in a few weeks so it seems fixed!

jb455 avatar Feb 28 '18 09:02 jb455