[libcamera-devel] [PATCH] android: camera_device: Hold reference to self when open
Laurent Pinchart
laurent.pinchart at ideasonboard.com
Sun Aug 23 20:29:00 CEST 2020
CameraDevice instances are managed through shared pointers to support
hptplug. No reference is however taken on the device when opened by the
camera service, which could cause an open device to be deleted if
unplugged, leading to a crash when the device is next accessed.
Fix this by taking a reference when opening a device, and releasing it
at close time. The reference is stored in the CameraDevice instance
itself, which is more efficient than storing it in a container in the
CameraHalManager as that would require lookup operations.
Signed-off-by: Laurent Pinchart <laurent.pinchart at ideasonboard.com>
---
src/android/camera_device.cpp | 12 ++++++++++++
src/android/camera_device.h | 4 +++-
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/src/android/camera_device.cpp b/src/android/camera_device.cpp
index de6f86f7cb9b..52468be70781 100644
--- a/src/android/camera_device.cpp
+++ b/src/android/camera_device.cpp
@@ -459,6 +459,12 @@ int CameraDevice::open(const hw_module_t *hardwareModule)
camera3Device_.ops = &hal_dev_ops;
camera3Device_.priv = this;
+ /*
+ * Hold a reference to ourselves, to protect against deletion if the
+ * camera is unplugged before being closed.
+ */
+ self_ = shared_from_this();
+
return 0;
}
@@ -468,6 +474,12 @@ void CameraDevice::close()
camera_->release();
running_ = false;
+
+ /*
+ * Drop our self reference. From this point the CameraDevice may get
+ * deleted at any time.
+ */
+ self_.reset();
}
void CameraDevice::setCallbacks(const camera3_callback_ops_t *callbacks)
diff --git a/src/android/camera_device.h b/src/android/camera_device.h
index 3934f194f1b5..fd991c76b90d 100644
--- a/src/android/camera_device.h
+++ b/src/android/camera_device.h
@@ -44,7 +44,8 @@ struct CameraStream {
Encoder *jpeg;
};
-class CameraDevice : protected libcamera::Loggable
+class CameraDevice : public std::enable_shared_from_this<CameraDevice>,
+ protected libcamera::Loggable
{
public:
static std::shared_ptr<CameraDevice> create(unsigned int id,
@@ -104,6 +105,7 @@ private:
unsigned int id_;
camera3_device_t camera3Device_;
+ std::shared_ptr<CameraDevice> self_;
bool running_;
std::shared_ptr<libcamera::Camera> camera_;
--
Regards,
Laurent Pinchart
More information about the libcamera-devel
mailing list