From 3cb4ac93e5fdbc1c7fbef7eec77135ed50f9264e Mon Sep 17 00:00:00 2001 From: Carti Date: Mon, 9 Feb 2026 22:27:06 +0100 Subject: [PATCH] AVFoundationDevice: Modify dispose logic Co-authored-by: Felipe Quintella --- FlashCap.Core/Devices/AVFoundationDevice.cs | 33 +++++++++++++------ .../AVFoundation/AVCaptureVideoDataOutput.cs | 4 +-- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/FlashCap.Core/Devices/AVFoundationDevice.cs b/FlashCap.Core/Devices/AVFoundationDevice.cs index 8724472..19a5b38 100644 --- a/FlashCap.Core/Devices/AVFoundationDevice.cs +++ b/FlashCap.Core/Devices/AVFoundationDevice.cs @@ -42,23 +42,36 @@ public AVFoundationDevice(string uniqueID, string modelID) : } protected override async Task OnDisposeAsync() - { - if (this.session != null) - { - this.session.StopRunning(); - this.session.Dispose(); + { + // Ensure that we stop the session if it's running + if (this.session is not null && IsRunning) + { + this.session.StopRunning(); + IsRunning = false; } - - this.device?.Dispose(); + + this.session?.Dispose(); this.deviceInput?.Dispose(); this.deviceOutput?.Dispose(); + this.device?.Dispose(); this.queue?.Dispose(); - Marshal.FreeHGlobal(this.bitmapHeader); + this.session = null; + this.deviceInput = null; + this.deviceOutput = null; + this.device = null; + this.queue = null; + + if (this.bitmapHeader != IntPtr.Zero) + { + Marshal.FreeHGlobal(this.bitmapHeader); + this.bitmapHeader = IntPtr.Zero; + } - if (frameProcessor is not null) + if (this.frameProcessor is not null) { - await frameProcessor.DisposeAsync().ConfigureAwait(false); + await this.frameProcessor.DisposeAsync().ConfigureAwait(false); + this.frameProcessor = null; } await base.OnDisposeAsync().ConfigureAwait(false); diff --git a/FlashCap.Core/Internal/AVFoundation/AVCaptureVideoDataOutput.cs b/FlashCap.Core/Internal/AVFoundation/AVCaptureVideoDataOutput.cs index 06189e1..534851e 100644 --- a/FlashCap.Core/Internal/AVFoundation/AVCaptureVideoDataOutput.cs +++ b/FlashCap.Core/Internal/AVFoundation/AVCaptureVideoDataOutput.cs @@ -73,7 +73,7 @@ public void SetPixelFormatType(int format) IntPtr pixelFormatTypeKeyPtr = Dlfcn.dlsym(LibCoreVideo.Handle, "kCVPixelBufferPixelFormatTypeKey"); if (pixelFormatTypeKeyPtr == IntPtr.Zero) { - throw new Exception("Error comunicating with the AVCaptureVideoDataOutput"); + throw new Exception("Error communicating with the AVCaptureVideoDataOutput"); } // Get NSString value @@ -107,7 +107,7 @@ public void SetSampleBufferDelegate(AVFoundationDevice.VideoBufferHandler sample IntPtr impCallback = Marshal.GetFunctionPointerForDelegate(callbackDelegate); - // "v@:@@@" this means the methood returns void and receives (self, _cmd, output, sampleBuffer, connection). + // "v@:@@@" this means the method returns void and receives (self, _cmd, output, sampleBuffer, connection). string types = "v@:@@@"; bool added = LibObjC.class_addMethod(delegateClass, selDidOutput, impCallback, types); if (!added)