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_stream.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
7#if QT_CONFIG(linux_dmabuf)
8# include "qlibcamera_dmabufregistry_p.h"
9#endif
10
11#include <QtMultimedia/private/qmemoryvideobuffer_p.h>
12#include <QtMultimedia/private/qvideoframe_p.h>
13#if QT_CONFIG(linux_dmabuf)
14# include <QtMultimedia/private/qdmabufsource_p.h>
15# include <QtMultimedia/private/qdmabufvideobuffer_p.h>
16# include <QtMultimedia/private/qmaterializingvideobuffer_p.h>
17# include <QtMultimedia/private/qmultimedia_drm_support_p.h>
18#endif
19
20#include <QtCore/qmetaobject.h>
21#include <QtCore/qspan.h>
22#include <QtCore/qvarlengtharray.h>
23#include <QtCore/private/qsystemerror_p.h>
24
25#include <libcamera/base/span.h>
26#include <libcamera/camera.h>
27#include <libcamera/framebuffer.h>
28#include <libcamera/request.h>
29
30#include <sys/mman.h>
31#include <unistd.h>
32
33#include <cerrno>
34#include <chrono>
35#include <cstring>
36
37QT_BEGIN_NAMESPACE
38
39using namespace Qt::StringLiterals;
40
41namespace QLibCamera {
42
43using namespace libcamera;
44
45namespace {
46
47q23::expected<QVideoFrame, QString> createVideoFrameFromLibcameraBuffer(const FrameBuffer &buffer,
48 QVideoFrameFormat format,
49 int bytesPerLine)
50{
51 Span<const FrameBuffer::Plane> planes = buffer.planes();
52 if (planes.empty())
53 return q23::unexpected(u"Captured frame buffer has no planes"_s);
54
55 // All libcamera planes are commonly packed into a single fd with per-plane offsets (see
56 // FrameBuffer::Plane::offset); map that one fd once and copy the whole region.
57 const int fd = planes[0].fd.get();
58 size_t totalLength = 0;
59 for (const FrameBuffer::Plane &plane : planes)
60 totalLength = std::max<size_t>(totalLength, plane.offset + plane.length);
61
62 void *mapped = ::mmap(nullptr, totalLength, PROT_READ, MAP_SHARED, fd, 0);
63 if (mapped == MAP_FAILED) {
64 return q23::unexpected(u"mmap fallback failed for captured frame: %1"_s.arg(
65 QString::fromLocal8Bit(strerror(errno))));
66 }
67
68 QByteArray data(static_cast<const char *>(mapped), qsizetype(totalLength));
69 ::munmap(mapped, totalLength);
70
71 auto videoBuffer = std::make_unique<QMemoryVideoBuffer>(std::move(data), bytesPerLine);
72 return QVideoFramePrivate::createFrame(std::move(videoBuffer), std::move(format));
73}
74
75#if QT_CONFIG(linux_dmabuf)
76
77// The frame wraps the request's DMA-BUF and holds the request as a capture slot.
78q23::expected<QVideoFrame, QString> createZeroCopyFrame(QLibCameraDmaBufRegistry &registry,
79 Request *request, const FrameBuffer &buffer,
80 const QVideoFrameFormat &format,
81 int bytesPerLine)
82{
83 using namespace QtMultimediaPrivate;
84
85 std::shared_ptr<QDmaBuf> dmaBuf = registry.dmaBufFor(request);
86 if (!dmaBuf) {
87 registry.recycleSlot(request);
88 return q23::unexpected(u"Completed request does not belong to the capture registry"_s);
89 }
90
91 std::unique_ptr<QAbstractVideoBuffer> videoBuffer;
92 const std::optional<DmaBufLayout> &layout = registry.layout();
93 if (layout) {
94 // One DmaBufPlane per layout plane, all within the same DMA-BUF.
95 const auto drmFormats = dmaBufFourccFromPixelFormat(format.pixelFormat());
96 QVarLengthArray<DmaBufPlane, 4> planes;
97 for (qsizetype plane = 0; plane < layout->size(); ++plane) {
98 const DmaBufPlaneLayout &planeLayout = (*layout)[plane];
99 planes.push_back({
100 dmaBuf->fd(),
101 planeLayout.offset,
102 planeLayout.pitch,
103 drmFormats[plane],
104 });
105 }
106 const QSpan<const DmaBufPlane> planeSpan(planes.data(), planes.size());
107
108 using Buffer = MaterializingVideoBuffer<DmaBufSource, QLibCameraDmaBufRegistry,
109 QDmaBufVideoBuffer>;
110 videoBuffer =
111 Buffer::wrapOrMaterialize(registry, request, DmaBufSource(dmaBuf, *layout), format,
112 // QDmaBufVideoBuffer args:
113 format, planeSpan, dmaBuf);
114 } else {
115 // Formats without a zero-copy layout (e.g. JPEG) hold only the bytes the driver used.
116 const auto metadataPlanes = buffer.metadata().planes();
117 if (metadataPlanes.empty()) {
118 registry.recycleSlot(request);
119 return q23::unexpected(u"Completed capture buffer has no plane metadata"_s);
120 }
121
122 const DmaBufLayout plainLayout{
123 DmaBufPlaneLayout{
124 0,
125 uint32_t(bytesPerLine),
126 qsizetype(metadataPlanes[0].bytesused),
127 },
128 };
129
130 using Buffer = MaterializingVideoBuffer<DmaBufSource, QLibCameraDmaBufRegistry>;
131 videoBuffer = Buffer::wrapOrMaterialize(registry, request,
132 DmaBufSource(dmaBuf, plainLayout), format);
133 }
134
135 return QVideoFramePrivate::createFrame(std::move(videoBuffer), format);
136}
137
138#endif // QT_CONFIG(linux_dmabuf)
139
140} // namespace
141
142void requeueRequest(Camera &camera, Request *request, QLibCameraPendingControls &pendingControls)
143{
144 request->reuse(Request::ReuseFlag::ReuseBuffers);
145 pendingControls.mergeInto(request->controls());
146
147 const int queueResult = camera.queueRequest(request);
148 switch (queueResult) {
149 case 0:
150 case -EACCES: // the camera is stopping
151 break;
152 case -ENODEV: // the camera has been disconnected
153 qCDebug(lcLibCamera) << "Camera disconnected, not requeueing request";
154 break;
155 default:
156 qCWarning(lcLibCamera) << "Failed to requeue request:"
157 << QSystemError::stdString(-queueResult);
158 break;
159 }
160}
161
162QLibCameraCameraStream::QLibCameraCameraStream(
163 std::shared_ptr<Camera> libcameraCamera, Stream *stream, int bytesPerLine,
164 QVideoFrameFormat frameFormat, double maxFrameRate,
165 std::shared_ptr<QLibCameraPendingControls> pendingControls
166#if QT_CONFIG(linux_dmabuf)
167 ,
168 std::shared_ptr<QLibCameraDmaBufRegistry> dmaBufRegistry
169#endif
170 )
171 : m_libcameraCamera(std::move(libcameraCamera)),
172 m_stream(stream),
173 m_bytesPerLine(bytesPerLine),
174 m_frameFormat(std::move(frameFormat)),
175 m_maxFrameRate(maxFrameRate),
176 m_pendingControls(std::move(pendingControls))
177#if QT_CONFIG(linux_dmabuf)
178 ,
179 m_dmaBufRegistry(std::move(dmaBufRegistry))
180#endif
181{
182}
183
184q23::expected<QVideoFrame, QString> QLibCameraCameraStream::createFrame(Request *request,
185 const FrameBuffer &buffer)
186{
187#if QT_CONFIG(linux_dmabuf)
188 if (m_dmaBufRegistry) {
189 // The frame holds the request as a slot; the request is queued again once it lets go.
190 return createZeroCopyFrame(*m_dmaBufRegistry, request, buffer, m_frameFormat,
191 m_bytesPerLine);
192 }
193#endif
194
195 q23::expected<QVideoFrame, QString> frame =
196 createVideoFrameFromLibcameraBuffer(buffer, m_frameFormat, m_bytesPerLine);
197
198 // we have created a deep copy, so recycle the buffer now
199 requeueRequest(*m_libcameraCamera, request, *m_pendingControls);
200 return frame;
201}
202
204{
205 // Runs on libcamera's CameraManager thread
206 using namespace std::chrono;
207
208 switch (request->status()) {
209 case Request::RequestComplete:
210 break;
211 case Request::RequestCancelled:
212 return; // e.g. during stop()
213 case Request::RequestPending:
214 qCWarning(lcLibCamera) << "Completed request is still pending";
215 return;
216 }
217
218 FrameBuffer *buffer = request->findBuffer(m_stream);
219 if (!buffer) {
220 qCWarning(lcLibCamera) << "Completed request has no buffer for our stream";
221 return;
222 }
223
224 const auto timestamp = nanoseconds(int64_t(buffer->metadata().timestamp));
225 if (!m_firstFrameTimestamp)
226 m_firstFrameTimestamp = timestamp;
227
228 q23::expected<QVideoFrame, QString> frame = createFrame(request, *buffer);
229 if (!frame) {
230 qCWarning(lcLibCamera) << "Failed to build video frame:" << frame.error();
231 return;
232 }
233
234 const auto elapsed = duration_cast<microseconds>(timestamp - *m_firstFrameTimestamp);
235 frame->setStartTime(elapsed.count());
236 if (m_maxFrameRate > 0) {
237 const auto frameDuration =
238 duration_cast<microseconds>(duration<double>(1.0 / m_maxFrameRate));
239 frame->setEndTime((elapsed + frameDuration).count());
240 }
241
242 QMetaObject::invokeMethod(this, [this, frame = std::move(*frame)] {
243 // emit on app thread: destructor will cancel in-flight events
244 Q_EMIT newVideoFrame(frame);
245 }, Qt::QueuedConnection);
246}
247
248} // namespace QLibCamera
249
250QT_END_NAMESPACE
251
252#include "moc_qlibcamera_stream_p.cpp"
QLibCameraCameraStream(std::shared_ptr< libcamera::Camera >, libcamera::Stream *, int bytesPerLine, QVideoFrameFormat, double maxFrameRate, std::shared_ptr< QLibCameraPendingControls >)
void handleRequestCompleted(libcamera::Request *)
void requeueRequest(libcamera::Camera &camera, libcamera::Request *request, QLibCameraPendingControls &pendingControls)
#define MAP_FAILED