public virtual void SimpleImageCaptureLoop() { using (var consumer = new CircularBuffer(name: "MySharedMemory", nodeCount: 4, nodeBufferSize: ((8294400 + FastStructure <MetaDataStruct> .Size)) * 2)) // Should be large enough to store 2 full hd raw image data + 4 Size of Struct { Stopwatch stopwatch = new Stopwatch(); do { stopwatch.Reset(); stopwatch.Start(); try { consumer.Read(intPtr => { MetaDataStruct metaData = FastStructure.PtrToStructure <MetaDataStruct>(intPtr); if (metaData.length > 0) { byte[] byteArray = new byte[metaData.length]; FastStructure.ReadArray <byte>(byteArray, intPtr, 0, byteArray.Length); using (var bm = byteArray.ToBitmap(metaData.width, metaData.height, metaData.pitch, metaData.format)) { byte[] compressedJpgByteArray = bm.ToByteCompessedArray(); Bitmap bitmap = compressedJpgByteArray.ToBitmap(); pictureBox1.Invoke(new MethodInvoker(delegate() { if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } pictureBox1.Image = bitmap; })); } } return(0); }, timeout: MAX_SLEEP_TIME); } catch (TimeoutException exception) { Console.WriteLine(exception); } catch (Exception ex) { Console.WriteLine(ex); } int timeout = (int)(MAX_SLEEP_TIME - stopwatch.ElapsedMilliseconds); Thread.Sleep(timeout >= 0 ? timeout : 0); } while (true); } }
protected void ProcessFrame(int width, int height, int pitch, PixelFormat format, IntPtr pBits) { if (format == PixelFormat.Undefined) { DebugMessage("Unsupported render target format"); return; } if (pBits == IntPtr.Zero) { DebugMessage("No image data"); return; } // Copy the image data from the buffer int size = height * pitch; var data = new byte[size]; try { try { Marshal.Copy(pBits, data, 0, size); producer.Write(intPtr => { MetaDataStruct metaData = new MetaDataStruct(data.Length, width, height, pitch, format); FastStructure.StructureToPtr(ref metaData, intPtr); intPtr += FastStructure <MetaDataStruct> .Size; FastStructure.WriteArray <byte>(intPtr, data, 0, data.Length); return(0); }, 0); // skip frame if we cannot write to circular buffer immediately } catch (TimeoutException) { // If we could not acquire write lock skip frame } catch (AccessViolationException) { // In this specifc case we are ignoring CSE (corrupted state exception) // It could happen during Window resizing. // If someone knows are better way please feel free to contribute // Because there is a timout in the resizing hook this exception should never be thrown } } catch (ObjectDisposedException) { // swallow exception to not crash hooked process } }