10#if QT_CONFIG(linux_dmabuf)
11# include "qlibcamera_dmabufregistry_p.h"
14#include <QtMultimedia/private/qcameradevice_p.h>
15#include <QtMultimedia/private/qmultimedia_ranges_p.h>
16#include <QtMultimedia/qcameradevice.h>
18#include <QtCore/qscopeguard.h>
19#include <QtCore/private/qsystemerror_p.h>
21#include <libcamera/camera.h>
22#include <libcamera/control_ids.h>
23#include <libcamera/controls.h>
24#include <libcamera/framebuffer.h>
25#include <libcamera/framebuffer_allocator.h>
26#include <libcamera/geometry.h>
27#include <libcamera/pixel_format.h>
28#include <libcamera/request.h>
29#include <libcamera/stream.h>
37using namespace Qt::StringLiterals;
45auto makeCameraError(
const QString &errorString)
47 return q23::unexpected(std::tuple{
56 : QPlatformCamera(parent), m_instance(std::move(instance))
69 case QVideoFrameFormat::Format_NV12:
70 case QVideoFrameFormat::Format_YUV420P:
72 case QVideoFrameFormat::Format_YUYV:
73 case QVideoFrameFormat::Format_UYVY:
75 case QVideoFrameFormat::Format_Jpeg:
84 if (m_active == active)
86 if (m_cameraDevice.isNull() && active)
88 if (active && !m_camera) {
89 updateError(QCamera::CameraError, u"Camera device is not available"_s);
93 if (m_resolvedFormat.isNull())
94 m_resolvedFormat = resolveCameraFormat();
97 m_lastFrameStart.reset();
98 m_lastFrameEnd.reset();
99 if (StartCapturingResult result = startCapturing(); !result) {
100 auto [error, string] = result.error();
101 updateError(error, string);
108 emitEndOfStreamFrame(m_lastFrameStart.value_or(std::chrono::microseconds{}),
112 Q_EMIT activeChanged(active);
115void QLibCameraCamera::
setCamera(
const QCameraDevice &camera)
117 if (m_cameraDevice == camera)
120 const bool wasActive = m_active;
123 m_cameraDevice = camera;
125 m_resolvedFormat = {};
128 if (!camera.isNull() && m_instance)
129 m_camera = m_instance->get(QString::fromUtf8(camera.id()));
132 supportedFeaturesChanged(QLibCameraControls::detectSupportedFeatures(m_camera->controls()));
134 supportedFeaturesChanged({});
139 m_resolvedFormat = resolveCameraFormat();
142 emitEndOfStreamFrame(m_lastFrameStart.value_or(std::chrono::microseconds{}),
144 updateError(QCamera::CameraError, u"Camera device is not available"_s);
145 Q_EMIT activeChanged(
false);
149 if (StartCapturingResult result = startCapturing(); !result) {
151 emitEndOfStreamFrame(m_lastFrameStart.value_or(std::chrono::microseconds{}),
153 auto [error, string] = result.error();
154 updateError(error, string);
155 Q_EMIT activeChanged(
false);
161 if (!format.isNull() && !m_cameraDevice.videoFormats().contains(format))
164 m_cameraFormat = format;
166 QCameraFormat resolvedFormat = resolveCameraFormat();
167 if (resolvedFormat == m_resolvedFormat)
170 m_resolvedFormat = resolvedFormat;
174 startCapturingReportingErrors();
179QCameraFormat QLibCameraCamera::resolveCameraFormat()
const
181 return m_cameraFormat.isNull() ? findBestCameraFormat(m_cameraDevice) : m_cameraFormat;
184QLibCameraCamera::StartCapturingResult QLibCameraCamera::startCapturing()
187 namespace ranges = QtMultimediaPrivate::ranges;
189 if (!m_camera || m_resolvedFormat.isNull())
192 auto abortGuard = qScopeGuard([
this] {
196 const int acquireResult = m_camera->acquire();
197 switch (acquireResult) {
201 return makeCameraError(u"Camera is in use"_s);
203 return makeCameraError(u"Camera has been disconnected"_s);
205 return makeCameraError(u"Failed to acquire camera: "_s
206 + QSystemError::stdString(-acquireResult));
209 m_streamState = StreamState::Acquired;
211 m_config = m_camera->generateConfiguration({ StreamRole::VideoRecording });
212 if (!m_config || m_config->empty())
213 return makeCameraError(u"Camera does not support video capture"_s);
215 StreamConfiguration &streamConfig = m_config->at(0);
218 const std::vector<PixelFormat> pixelFormats = streamConfig.formats().pixelformats();
219 const auto pixelFormatIt = ranges::find_if(pixelFormats, [&](
const PixelFormat &pf) {
220 return pixelFormatFromLibcamera(pf) == m_resolvedFormat.pixelFormat();
222 if (pixelFormatIt != pixelFormats.end())
223 streamConfig.pixelFormat = *pixelFormatIt;
225 streamConfig.size = toSize(m_resolvedFormat.resolution());
228 switch (m_config->validate()) {
229 case CameraConfiguration::Valid:
230 case CameraConfiguration::Adjusted:
232 case CameraConfiguration::Invalid:
233 return makeCameraError(u"Invalid camera configuration"_s);
236 const int configureResult = m_camera->configure(m_config.get());
237 switch (configureResult) {
241 return makeCameraError(u"Camera has been disconnected"_s);
243 return makeCameraError(u"Camera is not in a state where it can be configured"_s);
245 return makeCameraError(u"Invalid camera configuration"_s);
247 return makeCameraError(u"Failed to configure camera: "_s
248 + QSystemError::stdString(-configureResult));
253 const StreamConfiguration &adjusted = m_config->at(0);
254 m_stride =
int(adjusted.stride);
255 std::tie(m_colorSpace, m_colorRange) = colorSpaceFromLibcamera(adjusted.colorSpace);
256 if (
const std::optional adjustedFormat = pixelFormatFromLibcamera(adjusted.pixelFormat))
257 m_framePixelFormat = *adjustedFormat;
259 Stream *stream = adjusted.stream();
261 m_allocator = std::make_unique<FrameBufferAllocator>(m_camera);
262 if (
const int allocated = m_allocator->allocate(stream); allocated < 0) {
265 return makeCameraError(u"Camera is not in a state where buffers can be allocated"_s);
267 return makeCameraError(u"Camera stream is not part of the active configuration"_s);
269 return makeCameraError(u"Capture buffers are already allocated"_s);
271 return makeCameraError(u"Failed to allocate capture buffers: "_s
272 + QSystemError::stdString(-allocated));
277 for (
const std::unique_ptr<FrameBuffer> &buffer : m_allocator->buffers(stream)) {
278 std::unique_ptr<Request> request = m_camera->createRequest();
280 return makeCameraError(u"Failed to create capture request"_s);
282 const int addBufferResult = request->addBuffer(stream, buffer.get());
283 switch (addBufferResult) {
287 return makeCameraError(u"Capture request already has a buffer for the stream"_s);
289 return makeCameraError(u"Frame buffer does not reference a valid stream"_s);
291 return makeCameraError(u"Failed to add buffer to capture request: "_s
292 + QSystemError::stdString(-addBufferResult));
294 m_requests.push_back(std::move(request));
297 m_pendingControls = std::make_shared<QLibCameraPendingControls>();
298#if QT_CONFIG(linux_dmabuf)
299 m_dmaBufRegistry = QLibCameraDmaBufRegistry::create(m_camera, m_pendingControls, m_requests,
300 stream, frameFormat(), m_stride);
303 m_stream = std::make_unique<QLibCameraCameraStream>(m_camera, stream, m_stride, frameFormat(),
304 m_resolvedFormat.maxFrameRate(),
306#if QT_CONFIG(linux_dmabuf)
312 connect(m_stream.get(), &QLibCameraCameraStream::newVideoFrame,
this,
313 [
this](
const QVideoFrame &frame) {
314 m_lastFrameStart = std::chrono::microseconds{ frame.startTime() };
315 m_lastFrameEnd = std::chrono::microseconds{ frame.endTime() };
316 Q_EMIT newVideoFrame(frame);
319 m_camera->requestCompleted.connect(
this, [stream = m_stream.get()](Request *request) {
321 stream->handleRequestCompleted(request);
324 using namespace std::chrono;
325 ControlList startControls(m_camera->controls());
326 if (m_resolvedFormat.maxFrameRate() > 0) {
327 const auto frameDuration = duration_cast<microseconds>(
328 duration<
double>(1.0 / m_resolvedFormat.maxFrameRate()));
329 startControls.set(libcamera::controls::FrameDurationLimits,
330 { frameDuration.count(), frameDuration.count() });
333 const int startResult = m_camera->start(&startControls);
334 switch (startResult) {
338 return makeCameraError(u"Camera has been disconnected"_s);
340 return makeCameraError(u"Camera is not in a state where it can be started"_s);
342 return makeCameraError(u"Failed to start camera: "_s
343 + QSystemError::stdString(-startResult));
345 m_streamState = StreamState::Running;
347 for (
const std::unique_ptr<Request> &request : m_requests) {
348 const int queueResult = m_camera->queueRequest(request.get());
349 switch (queueResult) {
353 return makeCameraError(u"Camera has been disconnected"_s);
355 return makeCameraError(u"Camera is not running so requests can't be queued"_s);
357 return makeCameraError(u"Capture request does not belong to this camera"_s);
359 return makeCameraError(u"Capture request is invalid"_s);
361 return makeCameraError(u"No buffer memory available to queue capture request"_s);
363 return makeCameraError(u"Failed to queue capture request: "_s
364 + QSystemError::stdString(-queueResult));
368 abortGuard.dismiss();
372void QLibCameraCamera::startCapturingReportingErrors()
374 if (StartCapturingResult result = startCapturing(); !result)
375 updateError(
std::get<0>(result.error()),
std::get<1>(result.error()));
378void QLibCameraCamera::stopCapturing()
381 m_camera->requestCompleted.disconnect(
this);
382#if QT_CONFIG(linux_dmabuf)
384 if (m_dmaBufRegistry)
385 m_dmaBufRegistry->stop();
387 if (m_streamState == StreamState::Running) {
388 const int stopResult = m_camera->stop();
389 switch (stopResult) {
394 qCDebug(lcLibCamera) <<
"Camera disconnected while stopping capture";
397 qCWarning(lcLibCamera)
398 <<
"Failed to stop camera:" << QSystemError::stdString(-stopResult);
404 Stream *stream = m_stream ? m_stream->stream() :
nullptr;
408#if QT_CONFIG(linux_dmabuf)
409 m_dmaBufRegistry.reset();
411 m_pendingControls.reset();
412 if (m_allocator && stream) {
413 const int freeResult = m_allocator->free(stream);
414 switch (freeResult) {
420 qCWarning(lcLibCamera)
421 <<
"Failed to free capture buffers:" << QSystemError::stdString(-freeResult);
428 if (m_camera && m_streamState != StreamState::Idle) {
429 const int releaseResult = m_camera->release();
430 switch (releaseResult) {
434 qCWarning(lcLibCamera) <<
"Camera still running while releasing it";
437 qCWarning(lcLibCamera)
438 <<
"Failed to release camera:" << QSystemError::stdString(-releaseResult);
442 m_streamState = StreamState::Idle;
447 if (mode != QCamera::ExposureAuto && mode != QCamera::ExposureManual)
449 withPendingControls([&](ControlList &pending) {
452 exposureModeChanged(mode);
457 return mode == QCamera::ExposureAuto || mode == QCamera::ExposureManual;
462 withPendingControls([&](ControlList &pending) {
465 exposureCompensationChanged(compensation);
470 withPendingControls([&](ControlList &pending) {
473 isoSensitivityChanged(iso);
478 withPendingControls([&](ControlList &pending) {
481 exposureTimeChanged(seconds);
486 withPendingControls([&](ControlList &pending) {
489 if (mode != QCamera::WhiteBalanceAuto)
491 whiteBalanceModeChanged(mode);
496 withPendingControls([&](ControlList &pending) {
499 colorTemperatureChanged(temperature);
502void QLibCameraCamera::
zoomTo(
float newZoomFactor,
float )
506 newZoomFactor =
std::clamp(newZoomFactor, minZoomFactor(), maxZoomFactor());
507 withPendingControls([&](ControlList &pending) {
510 zoomFactorChanged(newZoomFactor);
515 QVideoFrameFormat result(m_resolvedFormat.resolution(),
516 m_framePixelFormat == QVideoFrameFormat::Format_Invalid
517 ? m_resolvedFormat.pixelFormat()
518 : m_framePixelFormat);
519 result.setStreamFrameRate(m_resolvedFormat.maxFrameRate());
520 result.setColorSpace(m_colorSpace);
521 result.setColorRange(m_colorRange);
529#include "moc_qlibcamera_camera_p.cpp"
void setExposureCompensation(float compensation) override
void setManualIsoSensitivity(int iso) override
void setActive(bool active) override
void setCamera(const QCameraDevice &) override
void setManualExposureTime(float seconds) override
bool setCameraFormat(const QCameraFormat &) override
void zoomTo(float newZoomFactor, float rate=-1.) override
~QLibCameraCamera() override
void setExposureMode(QCamera::ExposureMode) override
QVideoFrameFormat frameFormat() const override
int cameraPixelFormatScore(QVideoFrameFormat::PixelFormat, QVideoFrameFormat::ColorRange) const override
void setColorTemperature(int temperature) override
void setWhiteBalanceMode(QCamera::WhiteBalanceMode) override
bool isExposureModeSupported(QCamera::ExposureMode mode) const override
void setExposureCompensation(ControlList &pending, float stops)
void setAnalogueGainForIso(ControlList &pending, int iso)
void setAwbEnable(ControlList &pending, bool enable)
void setZoomFactor(ControlList &pending, const ControlInfoMap &controls, float zoomFactor)
void setColorTemperature(ControlList &pending, int kelvin)
void setManualExposureTime(ControlList &pending, float seconds)
void setAeEnable(ControlList &pending, bool enable)
constexpr unsigned kCaptureBufferCount