Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qlibcamera_camera.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
10#if QT_CONFIG(linux_dmabuf)
11# include "qlibcamera_dmabufregistry_p.h"
12#endif
13
14#include <QtMultimedia/private/qcameradevice_p.h>
15#include <QtMultimedia/private/qmultimedia_ranges_p.h>
16#include <QtMultimedia/qcameradevice.h>
17
18#include <QtCore/qscopeguard.h>
19#include <QtCore/private/qsystemerror_p.h>
20
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>
30
31#include <algorithm>
32#include <cerrno>
33#include <chrono>
34
35QT_BEGIN_NAMESPACE
36
37using namespace Qt::StringLiterals;
38
39namespace QLibCamera {
40
41using namespace libcamera;
42
43namespace {
44
45auto makeCameraError(const QString &errorString)
46{
47 return q23::unexpected(std::tuple{
48 QCamera::CameraError,
49 errorString,
50 });
51}
52
53} // namespace
54
55QLibCameraCamera::QLibCameraCamera(QCamera *parent, std::shared_ptr<QLibCameraInstance> instance)
56 : QPlatformCamera(parent), m_instance(std::move(instance))
57{
58}
59
60QLibCameraCamera::~QLibCameraCamera()
61{
62 stopCapturing();
63}
64
65int QLibCameraCamera::cameraPixelFormatScore(QVideoFrameFormat::PixelFormat format,
66 QVideoFrameFormat::ColorRange /*colorRange*/) const
67{
68 switch (format) {
69 case QVideoFrameFormat::Format_NV12:
70 case QVideoFrameFormat::Format_YUV420P:
71 return 3;
72 case QVideoFrameFormat::Format_YUYV:
73 case QVideoFrameFormat::Format_UYVY:
74 return 2;
75 case QVideoFrameFormat::Format_Jpeg:
76 return 0; // compressed; needs decoding before it can be turned into a QVideoFrame
77 default:
78 return 1;
79 }
80}
81
82void QLibCameraCamera::setActive(bool active)
83{
84 if (m_active == active)
85 return;
86 if (m_cameraDevice.isNull() && active)
87 return;
88 if (active && !m_camera) {
89 updateError(QCamera::CameraError, u"Camera device is not available"_s);
90 return;
91 }
92
93 if (m_resolvedFormat.isNull())
94 m_resolvedFormat = resolveCameraFormat();
95
96 if (active) {
97 m_lastFrameStart.reset();
98 m_lastFrameEnd.reset();
99 if (StartCapturingResult result = startCapturing(); !result) {
100 auto [error, string] = result.error();
101 updateError(error, string);
102 return;
103 }
104 m_active = true;
105 } else {
106 m_active = false;
107 stopCapturing();
108 emitEndOfStreamFrame(m_lastFrameStart.value_or(std::chrono::microseconds{}),
109 m_lastFrameEnd);
110 }
111
112 Q_EMIT activeChanged(active);
113}
114
115void QLibCameraCamera::setCamera(const QCameraDevice &camera)
116{
117 if (m_cameraDevice == camera)
118 return;
119
120 const bool wasActive = m_active;
121 stopCapturing();
122
123 m_cameraDevice = camera;
124 m_cameraFormat = {};
125 m_resolvedFormat = {};
126 m_camera.reset();
127
128 if (!camera.isNull() && m_instance)
129 m_camera = m_instance->get(QString::fromUtf8(camera.id()));
130
131 if (m_camera)
132 supportedFeaturesChanged(QLibCameraControls::detectSupportedFeatures(m_camera->controls()));
133 else
134 supportedFeaturesChanged({});
135
136 if (!wasActive)
137 return;
138
139 m_resolvedFormat = resolveCameraFormat();
140 if (!m_camera) {
141 m_active = false;
142 emitEndOfStreamFrame(m_lastFrameStart.value_or(std::chrono::microseconds{}),
143 m_lastFrameEnd);
144 updateError(QCamera::CameraError, u"Camera device is not available"_s);
145 Q_EMIT activeChanged(false);
146 return;
147 }
148
149 if (StartCapturingResult result = startCapturing(); !result) {
150 m_active = false;
151 emitEndOfStreamFrame(m_lastFrameStart.value_or(std::chrono::microseconds{}),
152 m_lastFrameEnd);
153 auto [error, string] = result.error();
154 updateError(error, string);
155 Q_EMIT activeChanged(false);
156 }
157}
158
159bool QLibCameraCamera::setCameraFormat(const QCameraFormat &format)
160{
161 if (!format.isNull() && !m_cameraDevice.videoFormats().contains(format))
162 return false;
163
164 m_cameraFormat = format;
165
166 QCameraFormat resolvedFormat = resolveCameraFormat();
167 if (resolvedFormat == m_resolvedFormat)
168 return true;
169
170 m_resolvedFormat = resolvedFormat;
171
172 if (m_active) {
173 stopCapturing();
174 startCapturingReportingErrors();
175 }
176 return true;
177}
178
179QCameraFormat QLibCameraCamera::resolveCameraFormat() const
180{
181 return m_cameraFormat.isNull() ? findBestCameraFormat(m_cameraDevice) : m_cameraFormat;
182}
183
184QLibCameraCamera::StartCapturingResult QLibCameraCamera::startCapturing()
185{
186 using namespace QLibCameraFormatSupport;
187 namespace ranges = QtMultimediaPrivate::ranges;
188
189 if (!m_camera || m_resolvedFormat.isNull())
190 return {};
191
192 auto abortGuard = qScopeGuard([this] {
193 stopCapturing();
194 });
195
196 const int acquireResult = m_camera->acquire();
197 switch (acquireResult) {
198 case 0:
199 break;
200 case -EBUSY:
201 return makeCameraError(u"Camera is in use"_s);
202 case -ENODEV:
203 return makeCameraError(u"Camera has been disconnected"_s);
204 default:
205 return makeCameraError(u"Failed to acquire camera: "_s
206 + QSystemError::stdString(-acquireResult));
207 }
208
209 m_streamState = StreamState::Acquired;
210
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);
214
215 StreamConfiguration &streamConfig = m_config->at(0);
216 // Prefer the resolved QCameraFormat's pixel format if libcamera can still produce
217 // it for this size; otherwise fall through to whatever generateConfiguration() proposed.
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();
221 });
222 if (pixelFormatIt != pixelFormats.end())
223 streamConfig.pixelFormat = *pixelFormatIt;
224
225 streamConfig.size = toSize(m_resolvedFormat.resolution());
226 streamConfig.bufferCount = kCaptureBufferCount;
227
228 switch (m_config->validate()) {
229 case CameraConfiguration::Valid:
230 case CameraConfiguration::Adjusted:
231 break;
232 case CameraConfiguration::Invalid:
233 return makeCameraError(u"Invalid camera configuration"_s);
234 }
235
236 const int configureResult = m_camera->configure(m_config.get());
237 switch (configureResult) {
238 case 0:
239 break;
240 case -ENODEV:
241 return makeCameraError(u"Camera has been disconnected"_s);
242 case -EACCES:
243 return makeCameraError(u"Camera is not in a state where it can be configured"_s);
244 case -EINVAL:
245 return makeCameraError(u"Invalid camera configuration"_s);
246 default:
247 return makeCameraError(u"Failed to configure camera: "_s
248 + QSystemError::stdString(-configureResult));
249 }
250
251 // validate()/configure() may adjust the requested configuration; the *adjusted* values are
252 // the ones actually in effect, and frameFormat() must describe those, not what was asked for.
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;
258
259 Stream *stream = adjusted.stream();
260
261 m_allocator = std::make_unique<FrameBufferAllocator>(m_camera);
262 if (const int allocated = m_allocator->allocate(stream); allocated < 0) {
263 switch (allocated) {
264 case -EACCES:
265 return makeCameraError(u"Camera is not in a state where buffers can be allocated"_s);
266 case -EINVAL:
267 return makeCameraError(u"Camera stream is not part of the active configuration"_s);
268 case -EBUSY:
269 return makeCameraError(u"Capture buffers are already allocated"_s);
270 default:
271 return makeCameraError(u"Failed to allocate capture buffers: "_s
272 + QSystemError::stdString(-allocated));
273 }
274 }
275
276 m_requests.clear();
277 for (const std::unique_ptr<FrameBuffer> &buffer : m_allocator->buffers(stream)) {
278 std::unique_ptr<Request> request = m_camera->createRequest();
279 if (!request)
280 return makeCameraError(u"Failed to create capture request"_s);
281
282 const int addBufferResult = request->addBuffer(stream, buffer.get());
283 switch (addBufferResult) {
284 case 0:
285 break;
286 case -EEXIST:
287 return makeCameraError(u"Capture request already has a buffer for the stream"_s);
288 case -EINVAL:
289 return makeCameraError(u"Frame buffer does not reference a valid stream"_s);
290 default:
291 return makeCameraError(u"Failed to add buffer to capture request: "_s
292 + QSystemError::stdString(-addBufferResult));
293 }
294 m_requests.push_back(std::move(request));
295 }
296
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);
301#endif
302
303 m_stream = std::make_unique<QLibCameraCameraStream>(m_camera, stream, m_stride, frameFormat(),
304 m_resolvedFormat.maxFrameRate(),
305 m_pendingControls
306#if QT_CONFIG(linux_dmabuf)
307 ,
308 m_dmaBufRegistry
309#endif
310 );
311
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);
317 });
318
319 m_camera->requestCompleted.connect(this, [stream = m_stream.get()](Request *request) {
320 // libcamera thread
321 stream->handleRequestCompleted(request);
322 });
323
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() });
331 }
332
333 const int startResult = m_camera->start(&startControls);
334 switch (startResult) {
335 case 0:
336 break;
337 case -ENODEV:
338 return makeCameraError(u"Camera has been disconnected"_s);
339 case -EACCES:
340 return makeCameraError(u"Camera is not in a state where it can be started"_s);
341 default:
342 return makeCameraError(u"Failed to start camera: "_s
343 + QSystemError::stdString(-startResult));
344 }
345 m_streamState = StreamState::Running;
346
347 for (const std::unique_ptr<Request> &request : m_requests) {
348 const int queueResult = m_camera->queueRequest(request.get());
349 switch (queueResult) {
350 case 0:
351 break;
352 case -ENODEV:
353 return makeCameraError(u"Camera has been disconnected"_s);
354 case -EACCES:
355 return makeCameraError(u"Camera is not running so requests can't be queued"_s);
356 case -EXDEV:
357 return makeCameraError(u"Capture request does not belong to this camera"_s);
358 case -EINVAL:
359 return makeCameraError(u"Capture request is invalid"_s);
360 case -ENOMEM:
361 return makeCameraError(u"No buffer memory available to queue capture request"_s);
362 default:
363 return makeCameraError(u"Failed to queue capture request: "_s
364 + QSystemError::stdString(-queueResult));
365 }
366 }
367
368 abortGuard.dismiss();
369 return {};
370}
371
372void QLibCameraCamera::startCapturingReportingErrors()
373{
374 if (StartCapturingResult result = startCapturing(); !result)
375 updateError(std::get<0>(result.error()), std::get<1>(result.error()));
376}
377
378void QLibCameraCamera::stopCapturing()
379{
380 if (m_camera) {
381 m_camera->requestCompleted.disconnect(this);
382#if QT_CONFIG(linux_dmabuf)
383 // Frames that outlive this keep their own DMA-BUF fd.
384 if (m_dmaBufRegistry)
385 m_dmaBufRegistry->stop();
386#endif
387 if (m_streamState == StreamState::Running) {
388 const int stopResult = m_camera->stop();
389 switch (stopResult) {
390 case 0:
391 case -EACCES: // the camera is not running
392 break;
393 case -ENODEV: // the camera has been disconnected
394 qCDebug(lcLibCamera) << "Camera disconnected while stopping capture";
395 break;
396 default:
397 qCWarning(lcLibCamera)
398 << "Failed to stop camera:" << QSystemError::stdString(-stopResult);
399 break;
400 }
401 }
402 }
403
404 Stream *stream = m_stream ? m_stream->stream() : nullptr;
405 m_stream.reset();
406
407 m_requests.clear();
408#if QT_CONFIG(linux_dmabuf)
409 m_dmaBufRegistry.reset();
410#endif
411 m_pendingControls.reset();
412 if (m_allocator && stream) {
413 const int freeResult = m_allocator->free(stream);
414 switch (freeResult) {
415 case 0:
416 case -EACCES: // the camera is not in a state where buffers can be freed
417 case -EINVAL: // the allocator does not handle this stream
418 break;
419 default:
420 qCWarning(lcLibCamera)
421 << "Failed to free capture buffers:" << QSystemError::stdString(-freeResult);
422 break;
423 }
424 }
425 m_allocator.reset();
426 m_config.reset();
427
428 if (m_camera && m_streamState != StreamState::Idle) {
429 const int releaseResult = m_camera->release();
430 switch (releaseResult) {
431 case 0:
432 break;
433 case -EBUSY: // the camera is still running
434 qCWarning(lcLibCamera) << "Camera still running while releasing it";
435 break;
436 default:
437 qCWarning(lcLibCamera)
438 << "Failed to release camera:" << QSystemError::stdString(-releaseResult);
439 break;
440 }
441 }
442 m_streamState = StreamState::Idle;
443}
444
445void QLibCameraCamera::setExposureMode(QCamera::ExposureMode mode)
446{
447 if (mode != QCamera::ExposureAuto && mode != QCamera::ExposureManual)
448 return;
449 withPendingControls([&](ControlList &pending) {
450 QLibCameraControls::setAeEnable(pending, mode == QCamera::ExposureAuto);
451 });
452 exposureModeChanged(mode);
453}
454
455bool QLibCameraCamera::isExposureModeSupported(QCamera::ExposureMode mode) const
456{
457 return mode == QCamera::ExposureAuto || mode == QCamera::ExposureManual;
458}
459
460void QLibCameraCamera::setExposureCompensation(float compensation)
461{
462 withPendingControls([&](ControlList &pending) {
464 });
465 exposureCompensationChanged(compensation);
466}
467
468void QLibCameraCamera::setManualIsoSensitivity(int iso)
469{
470 withPendingControls([&](ControlList &pending) {
472 });
473 isoSensitivityChanged(iso);
474}
475
476void QLibCameraCamera::setManualExposureTime(float seconds)
477{
478 withPendingControls([&](ControlList &pending) {
480 });
481 exposureTimeChanged(seconds);
482}
483
484void QLibCameraCamera::setWhiteBalanceMode(QCamera::WhiteBalanceMode mode)
485{
486 withPendingControls([&](ControlList &pending) {
487 QLibCameraControls::setAwbEnable(pending, mode == QCamera::WhiteBalanceAuto);
488 });
489 if (mode != QCamera::WhiteBalanceAuto)
490 setColorTemperature(colorTemperatureForWhiteBalance(mode));
491 whiteBalanceModeChanged(mode);
492}
493
494void QLibCameraCamera::setColorTemperature(int temperature)
495{
496 withPendingControls([&](ControlList &pending) {
498 });
499 colorTemperatureChanged(temperature);
500}
501
502void QLibCameraCamera::zoomTo(float newZoomFactor, float /*rate*/)
503{
504 if (!m_camera)
505 return;
506 newZoomFactor = std::clamp(newZoomFactor, minZoomFactor(), maxZoomFactor());
507 withPendingControls([&](ControlList &pending) {
508 QLibCameraControls::setZoomFactor(pending, m_camera->controls(), newZoomFactor);
509 });
510 zoomFactorChanged(newZoomFactor);
511}
512
513QVideoFrameFormat QLibCameraCamera::frameFormat() const
514{
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);
522 return result;
523}
524
525} // namespace QLibCamera
526
527QT_END_NAMESPACE
528
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
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