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
qwindowscamera.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 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
5#include "qsemaphore.h"
6#include "qmutex.h"
7
8#include <private/qcameradevice_p.h>
9#include <private/qmemoryvideobuffer_p.h>
10#include <private/qwindowsmultimediautils_p.h>
11#include <private/qvideoframe_p.h>
12#include <private/qcomobject_p.h>
13#include <private/qwmf_support_p.h>
14#include <private/qwindowsmediafoundation_p.h>
15
16#include <QtCore/private/qsystemerror_p.h>
17
18#include <mfapi.h>
19#include <mfidl.h>
20#include <mferror.h>
21#include <mfreadwrite.h>
22
23#include <system_error>
24#include <utility>
25
26QT_BEGIN_NAMESPACE
27
28namespace QFFmpeg {
29
30qsizetype indexOfClosestCameraFormat(QSpan<const QCameraFormat> candidates,
31 const QCameraFormat &requested)
32{
33 qsizetype closest = -1;
34 std::pair<float, float> closestDistance{};
35
36 for (qsizetype i = 0; i != candidates.size(); ++i) {
37 const QCameraFormat &candidate = candidates[i];
38 if (candidate.pixelFormat() != requested.pixelFormat()
39 || candidate.resolution() != requested.resolution()) {
40 continue;
41 }
42
43 const std::pair distance{ qAbs(candidate.maxFrameRate() - requested.maxFrameRate()),
44 qAbs(candidate.minFrameRate() - requested.minFrameRate()) };
45 if (closest < 0 || distance < closestDistance) {
46 closest = i;
47 closestDistance = distance;
48 }
49 }
50
51 return closest;
52}
53
54namespace {
55
56class CameraReaderCallback : public QComObject<IMFSourceReaderCallback>
57{
58public:
59 //from IMFSourceReaderCallback
60 STDMETHODIMP OnReadSample(HRESULT status, DWORD, DWORD, LONGLONG timestamp, IMFSample *sample) override;
61 STDMETHODIMP OnFlush(DWORD) override;
62 STDMETHODIMP OnEvent(DWORD, IMFMediaEvent *) override { return S_OK; }
63
64 void setActiveCamera(ActiveCamera *activeCamera)
65 {
66 QMutexLocker locker(&m_mutex);
67 m_activeCamera = activeCamera;
68 }
69private:
70 // Destructor is not public. Caller should call Release.
71 ~CameraReaderCallback() override = default;
72
73 ActiveCamera *m_activeCamera = nullptr;
74 QMutex m_mutex;
75};
76
77ComPtr<IMFSourceReader> createCameraReader(const QWindowsMediaFoundation &wmf,
78 IMFMediaSource *mediaSource,
79 const ComPtr<CameraReaderCallback> &callback)
80{
81 ComPtr<IMFSourceReader> sourceReader;
82 ComPtr<IMFAttributes> readerAttributes;
83
84 HRESULT hr = wmf.mfCreateAttributes(readerAttributes.GetAddressOf(), 1);
85 if (SUCCEEDED(hr)) {
86 hr = readerAttributes->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, callback.Get());
87 if (SUCCEEDED(hr)) {
88 hr = wmf.mfCreateSourceReaderFromMediaSource(mediaSource, readerAttributes.Get(),
89 sourceReader.GetAddressOf());
90 if (SUCCEEDED(hr))
91 return sourceReader;
92 }
93 }
94
95 qWarning() << "Failed to create camera IMFSourceReader" << hr;
96 return sourceReader;
97}
98
99ComPtr<IMFMediaSource> createCameraSource(const QWindowsMediaFoundation &wmf,
100 const QString &deviceId)
101{
102 ComPtr<IMFMediaSource> mediaSource;
103 ComPtr<IMFAttributes> sourceAttributes;
104 HRESULT hr = wmf.mfCreateAttributes(sourceAttributes.GetAddressOf(), 2);
105 if (SUCCEEDED(hr)) {
106 hr = sourceAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
107 MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
108 if (SUCCEEDED(hr)) {
109 hr = sourceAttributes->SetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
110 reinterpret_cast<LPCWSTR>(deviceId.utf16()));
111 if (SUCCEEDED(hr)) {
112 hr = wmf.mfCreateDeviceSource(sourceAttributes.Get(), mediaSource.GetAddressOf());
113 if (SUCCEEDED(hr))
114 return mediaSource;
115 }
116 }
117 }
118 qWarning() << "Failed to create camera IMFMediaSource" << hr;
119 return mediaSource;
120}
121
122int calculateVideoFrameStride(const QWindowsMediaFoundation &wmf, IMFMediaType *videoType,
123 int width)
124{
125 Q_ASSERT(videoType);
126
127 GUID subtype = GUID_NULL;
128 HRESULT hr = videoType->GetGUID(MF_MT_SUBTYPE, &subtype);
129 if (SUCCEEDED(hr)) {
130 LONG stride = 0;
131 hr = wmf.mfGetStrideForBitmapInfoHeader(subtype.Data1, width, &stride);
132 if (SUCCEEDED(hr))
133 return int(qAbs(stride));
134 }
135
136 qWarning() << "Failed to calculate video stride" << QSystemError::windowsComString(hr);
137 return 0;
138}
139
140bool setCameraReaderFormat(IMFSourceReader *sourceReader, IMFMediaType *videoType)
141{
142 Q_ASSERT(sourceReader);
143 Q_ASSERT(videoType);
144
145 HRESULT hr = sourceReader->SetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, nullptr,
146 videoType);
147 if (FAILED(hr))
148 qWarning() << "Failed to set video format" << QSystemError::windowsComString(hr);
149
150 return SUCCEEDED(hr);
151}
152
153ComPtr<IMFMediaType> findVideoType(IMFSourceReader *reader, const QCameraFormat &format)
154{
155 std::vector<ComPtr<IMFMediaType>> mediaTypes;
156 std::vector<QCameraFormat> candidates;
157
158 for (DWORD i = 0;; ++i) {
159 ComPtr<IMFMediaType> mediaType;
160 HRESULT hr = reader->GetNativeMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, i,
161 mediaType.GetAddressOf());
162 if (FAILED(hr))
163 break;
164
165 const std::optional<QCameraFormat> candidate =
166 QWMF::cameraFormatFromMediaType(mediaType.Get());
167 if (!candidate)
168 continue;
169
170 mediaTypes.push_back(std::move(mediaType));
171 candidates.push_back(std::move(*candidate));
172 }
173
174 const qsizetype index = indexOfClosestCameraFormat(candidates, format);
175 if (index < 0)
176 return {};
177
178 return mediaTypes.at(index);
179}
180
181} // namespace
182
184{
185public:
186 static std::unique_ptr<ActiveCamera> create(QWindowsCamera &wc, const QCameraDevice &device, const QCameraFormat &format)
187 {
188 QWindowsMediaFoundation *wmf = QWindowsMediaFoundation::instance();
189 Q_ASSERT(wmf);
190
191 auto ac = std::unique_ptr<ActiveCamera>(new ActiveCamera(wc, *wmf));
192 ac->m_source = createCameraSource(*wmf, QString::fromUtf8(device.id()));
193 if (!ac->m_source)
194 return {};
195
196 ac->m_readerCallback = makeComObject<CameraReaderCallback>();
197 ac->m_readerCallback->setActiveCamera(ac.get());
198 ac->m_reader = createCameraReader(*wmf, ac->m_source.Get(), ac->m_readerCallback);
199 if (!ac->m_reader)
200 return {};
201
202 if (!ac->setFormat(format))
203 return {};
204
205 return ac;
206 }
207
208 bool setFormat(const QCameraFormat &format)
209 {
210 flush();
211
212 auto videoType = findVideoType(m_reader.Get(), format);
213 if (videoType) {
214 if (setCameraReaderFormat(m_reader.Get(), videoType.Get())) {
215 m_frameFormat = { format.resolution(), format.pixelFormat() };
216 m_frameFormat.setColorRange(QCameraFormatPrivate::getColorRange(format));
217 m_frameFormat.setColorSpace(QCameraFormatPrivate::getColorSpace(format));
218 m_videoFrameStride =
219 calculateVideoFrameStride(m_wmf, videoType.Get(), format.resolution().width());
220 }
221 }
222
223 m_reader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, nullptr, nullptr, nullptr,
224 nullptr);
225 return true;
226 }
227
228 void onReadSample(HRESULT status, LONGLONG timestamp, IMFSample *sample)
229 {
230 if (FAILED(status)) {
231 const std::string msg{ std::system_category().message(status) };
232 m_windowsCamera.updateError(QCamera::CameraError, QString::fromStdString(msg));
233 return;
234 }
235
236 if (sample) {
237 ComPtr<IMFMediaBuffer> mediaBuffer;
238 if (SUCCEEDED(sample->ConvertToContiguousBuffer(mediaBuffer.GetAddressOf()))) {
239
240 auto result = QWMF::withLockedBuffer(mediaBuffer,
241 [&](QSpan<BYTE> data, QSpan<BYTE> /*max*/) {
242 QByteArray bytes(data);
243 auto buffer = std::make_unique<QMemoryVideoBuffer>(std::move(bytes),
244 m_videoFrameStride);
245 QVideoFrame frame =
246 QVideoFramePrivate::createFrame(std::move(buffer), m_frameFormat);
247
248 // WMF uses 100-nanosecond units, Qt uses microseconds
249 frame.setStartTime(timestamp / 10);
250
251 LONGLONG duration = -1;
252 if (SUCCEEDED(sample->GetSampleDuration(&duration)))
253 frame.setEndTime((timestamp + duration) / 10);
254
255 return frame;
256 });
257
258 if (result)
259 Q_EMIT m_windowsCamera.newVideoFrame(result.value());
260 }
261 }
262
263 m_reader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, nullptr,
264 nullptr, nullptr, nullptr);
265 }
266
267 void onFlush()
268 {
269 m_flushWait.release();
270 }
271
273 {
274 flush();
275 if (m_readerCallback)
276 m_readerCallback->setActiveCamera(nullptr);
277 }
278
279private:
280 ActiveCamera(QWindowsCamera &wc, const QWindowsMediaFoundation &wmf)
281 : m_windowsCamera(wc), m_wmf(wmf), m_flushWait(0)
282 {
283 }
284
285 void flush()
286 {
287 if (m_reader && SUCCEEDED(m_reader->Flush(MF_SOURCE_READER_FIRST_VIDEO_STREAM))) {
288 m_flushWait.acquire();
289 }
290 }
291
292 QWindowsCamera &m_windowsCamera;
293 const QWindowsMediaFoundation &m_wmf;
294
295 QSemaphore m_flushWait;
296
297 ComPtr<IMFMediaSource> m_source;
298 ComPtr<IMFSourceReader> m_reader;
299 ComPtr<CameraReaderCallback> m_readerCallback;
300
301 QVideoFrameFormat m_frameFormat;
302 int m_videoFrameStride = 0;
303};
304
305STDMETHODIMP CameraReaderCallback::OnReadSample(HRESULT status, DWORD, DWORD, LONGLONG timestamp, IMFSample *sample)
306{
307 QMutexLocker locker(&m_mutex);
308 if (m_activeCamera)
309 m_activeCamera->onReadSample(status, timestamp, sample);
310
311 return S_OK;
312}
313
314STDMETHODIMP CameraReaderCallback::OnFlush(DWORD)
315{
316 QMutexLocker locker(&m_mutex);
317 if (m_activeCamera)
318 m_activeCamera->onFlush();
319 return S_OK;
320}
321
324{
325 m_cameraDevice = camera ? camera->cameraDevice() : QCameraDevice{};
326}
327
332
333void QWindowsCamera::setActive(bool active)
334{
335 if (bool(m_active) == active)
336 return;
337
338 if (active) {
339 if (m_cameraDevice.isNull())
340 return;
341
342 if (m_cameraFormat.isNull())
343 m_cameraFormat = findBestCameraFormat(m_cameraDevice);
344
345 m_active = ActiveCamera::create(*this, m_cameraDevice, m_cameraFormat);
346 if (m_active)
347 Q_EMIT activeChanged(true);
348
349 } else {
350 m_active.reset();
351 Q_EMIT activeChanged(false);
352 }
353}
354
355void QWindowsCamera::setCamera(const QCameraDevice &camera)
356{
357 bool active = bool(m_active);
358 if (active)
359 setActive(false);
360 m_cameraDevice = camera;
361 m_cameraFormat = {};
362 if (active)
363 setActive(true);
364}
365
366bool QWindowsCamera::setCameraFormat(const QCameraFormat &format)
367{
368 if (format.isNull())
369 return false;
370
371 bool ok = m_active ? m_active->setFormat(format) : true;
372 if (ok)
373 m_cameraFormat = format;
374
375 return ok;
376}
377
378} // namespace QFFmpeg
379
380QT_END_NAMESPACE
void onReadSample(HRESULT status, LONGLONG timestamp, IMFSample *sample)
bool setFormat(const QCameraFormat &format)
static std::unique_ptr< ActiveCamera > create(QWindowsCamera &wc, const QCameraDevice &device, const QCameraFormat &format)
bool setCameraFormat(const QCameraFormat &) override
void setCamera(const QCameraDevice &camera) override
QWindowsCamera(QCamera *parent)
void setActive(bool active) override
\inmodule QtCore
Definition qmutex.h:347
qsizetype indexOfClosestCameraFormat(QSpan< const QCameraFormat > candidates, const QCameraFormat &requested)