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
qpulseaudiosource.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
6#include <QtMultimedia/private/qaudiosystem_platform_stream_support_p.h>
7#include <QtMultimedia/private/qpulseaudio_contextmanager_p.h>
8#include <QtMultimedia/private/qpulsehelpers_p.h>
9
10#include <mutex> // for std::lock_guard
11#include <unistd.h>
12
13QT_BEGIN_NAMESPACE
14
15namespace QPulseAudioInternal {
16
17using namespace QtMultimediaPrivate;
18
19QPulseAudioSourceStream::QPulseAudioSourceStream(QAudioDevice device, const QAudioFormat &format,
20 std::optional<qsizetype> ringbufferSize,
21 QPulseAudioSource *parent,
22 float volume,
23 std::optional<int32_t> hardwareBufferSize)
26 },
27 m_parent(parent)
28{
29 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
30 pa_sample_spec spec = QPulseAudioInternal::audioFormatToSampleSpec(format);
31 pa_channel_map channel_map = QPulseAudioInternal::channelMapForAudioFormat(format);
32
33 if (!pa_sample_spec_valid(&spec))
34 return;
35
36 const QByteArray streamName =
37 QStringLiteral("QtmPulseStream-%1-%2").arg(::getpid()).arg(quintptr(this)).toUtf8();
38
39 if (Q_UNLIKELY(qLcPulseAudioIn().isEnabled(QtDebugMsg))) {
40 qCDebug(qLcPulseAudioIn) << "Format: " << spec.format;
41 qCDebug(qLcPulseAudioIn) << "Rate: " << spec.rate;
42 qCDebug(qLcPulseAudioIn) << "Channels: " << spec.channels;
43 qCDebug(qLcPulseAudioIn) << "Frame size: " << pa_frame_size(&spec);
44 }
45
46 std::lock_guard engineLock{ *pulseEngine };
47
48 m_stream = PAStreamHandle{
49 pa_stream_new(pulseEngine->context(), streamName.constData(), &spec, &channel_map),
50 PAStreamHandle::HasRef,
51 };
52}
53
54QPulseAudioSourceStream::~QPulseAudioSourceStream() = default;
55
56bool QPulseAudioSourceStream::start(QIODevice *device)
57{
58 setQIODevice(device);
59
60 createQIODeviceConnections(device);
61
62 return startStream(StreamType::Ringbuffer);
63}
64
65bool QPulseAudioSourceStream::start(AudioCallback &&audioCallback)
66{
67 m_audioCallback = std::move(audioCallback);
68 return startStream(StreamType::Callback);
69}
70
72{
73 QIODevice *device = createRingbufferReaderDevice();
74 bool started = start(device);
75 if (!started)
76 return nullptr;
77
78 return device;
79}
80
81void QPulseAudioSourceStream::stop(ShutdownPolicy shutdownPolicy)
82{
83 requestStop();
84
85 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
86 std::lock_guard engineLock{ *pulseEngine };
87
88 uninstallCallbacks();
89 disconnectQIODeviceConnections();
90
91 if (shutdownPolicy == ShutdownPolicy::DrainRingbuffer) {
92 size_t bytesToRead = pa_stream_readable_size(m_stream.get());
93 if (bytesToRead != size_t(-1))
94 readCallbackRingbuffer(bytesToRead);
95 }
96
97 // Note: we need to cork the stream before disconnecting to prevent pulseaudio from deadlocking
98 auto op = streamCork(m_stream, true);
99 pulseEngine->waitForAsyncOperation(op);
100
101 pa_stream_disconnect(m_stream.get());
102
103 finalizeQIODevice(shutdownPolicy);
104 if (shutdownPolicy == ShutdownPolicy::DiscardRingbuffer)
105 emptyRingbuffer();
106}
107
109{
110 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
111 std::lock_guard engineLock{ *pulseEngine };
112
113 std::ignore = streamCork(m_stream, true);
114}
115
117{
118 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
119 std::lock_guard engineLock{ *pulseEngine };
120
121 std::ignore = streamCork(m_stream, false);
122}
123
125{
126 return bool(m_stream);
127}
128
130{
131 m_parent->updateStreamIdle(idle);
132}
133
134bool QPulseAudioSourceStream::startStream(StreamType streamType)
135{
136 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
137 static const bool serverIsPipewire = [&] {
138 return pulseEngine->serverName().contains(u"PulseAudio (on PipeWire");
139 }();
140
141 pa_buffer_attr attr{
142 .maxlength = uint32_t(m_format.bytesForFrames(m_hardwareBufferFrames.value_or(1024))),
143 .tlength = uint32_t(-1),
144 .prebuf = uint32_t(-1),
145 .minreq = uint32_t(-1),
146
147 // pulseaudio's vanilla implementation requires us to set a fragment size, otherwise we only
148 // get a single callback every 2-ish seconds.
149 .fragsize = serverIsPipewire
150 ? uint32_t(-1)
151 : uint32_t(m_format.bytesForFrames(m_hardwareBufferFrames.value_or(1024))),
152 };
153
154 constexpr pa_stream_flags flags =
155 pa_stream_flags(PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_ADJUST_LATENCY);
156
157 std::lock_guard engineLock{ *pulseEngine };
158 installCallbacks(streamType);
159
160 const auto id = m_audioDevice.id();
161 int status = pa_stream_connect_record(m_stream.get(), id.data(), &attr, flags);
162 if (status != 0) {
163 qCWarning(qLcPulseAudioOut) << "pa_stream_connect_record() failed!";
164 m_stream = {};
165 return false;
166 }
167 return true;
168}
169
170void QPulseAudioSourceStream::installCallbacks(StreamType streamType)
171{
172 switch (streamType) {
173 case StreamType::Ringbuffer: {
174 pa_stream_set_read_callback(m_stream.get(),
175 [](pa_stream *stream, size_t nbytes, void *data) {
176 auto *self = reinterpret_cast<QPulseAudioSourceStream *>(data);
177 Q_ASSERT(stream == self->m_stream.get());
178 self->readCallbackRingbuffer(nbytes);
179 }, this);
180 break;
181 }
182 case StreamType::Callback: {
183 pa_stream_set_read_callback(m_stream.get(),
184 [](pa_stream *stream, size_t nbytes, void *data) {
185 auto *self = reinterpret_cast<QPulseAudioSourceStream *>(data);
186 Q_ASSERT(stream == self->m_stream.get());
187 self->readCallbackAudioCallback(nbytes);
188 }, this);
189 break;
190 }
191 }
192}
193
194void QPulseAudioSourceStream::uninstallCallbacks()
195{
196 pa_stream_set_read_callback(m_stream.get(), nullptr, nullptr);
197}
198
199void QPulseAudioSourceStream::readCallbackRingbuffer([[maybe_unused]] size_t bytesToRead)
200{
201 const void *data{};
202 size_t nBytes{};
203 int status = pa_stream_peek(m_stream.get(), &data, &nBytes);
204 if (status < 0) {
205 invokeOnAppThread([this] {
206 handleIOError(m_parent);
207 });
208 return;
209 }
210
211 QSpan<const std::byte> hostBuffer{
212 reinterpret_cast<const std::byte *>(data),
213 qsizetype(nBytes),
214 };
215
216 uint32_t numberOfFrames = m_format.framesForBytes(nBytes);
217
218 [[maybe_unused]] uint64_t framesWritten =
219 QPlatformAudioSourceStream::process(hostBuffer, numberOfFrames);
220 status = pa_stream_drop(m_stream.get());
221 if (status < 0) {
222 if (!isStopRequested()) {
223 invokeOnAppThread([this] {
224 handleIOError(m_parent);
225 });
226 }
227 }
228}
229
230void QPulseAudioSourceStream::readCallbackAudioCallback([[maybe_unused]] size_t bytesToRead)
231{
232 const void *data{};
233 size_t nBytes{};
234 int status = pa_stream_peek(m_stream.get(), &data, &nBytes);
235 if (status < 0) {
236 QMetaObject::invokeMethod(m_parent, [this] {
237 handleIOError(m_parent);
238 });
239 return;
240 }
241
242 QSpan<const std::byte> hostBuffer{
243 reinterpret_cast<const std::byte *>(data),
244 qsizetype(nBytes),
245 };
246
247 runAudioCallback(*m_audioCallback, hostBuffer, m_format, volume());
248
249 status = pa_stream_drop(m_stream.get());
250 if (status < 0) {
251 if (!isStopRequested()) {
252 QMetaObject::invokeMethod(m_parent, [this] {
253 handleIOError(m_parent);
254 });
255 }
256 }
257}
258
259////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
260
261QPulseAudioSource::QPulseAudioSource(QAudioDevice device, const QAudioFormat &format,
262 QObject *parent)
264{
265}
266
267QPulseAudioSource::~QPulseAudioSource()
268 = default;
269
270bool QPulseAudioSource::validatePulseaudio()
271{
272 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
273 if (!pulseEngine->contextIsGood()) {
274 qWarning() << "Invalid PulseAudio context:" << pulseEngine->getContextState();
275 setError(QtAudio::Error::FatalError);
276 return false;
277 }
278 return true;
279}
280
281void QPulseAudioSource::start(QIODevice *device)
282{
283 if (!validatePulseaudio())
284 return;
285 return BaseClass::start(device);
286}
287
288void QPulseAudioSource::start(AudioCallback &&cb)
289{
290 if (!validatePulseaudio())
291 return;
292 return BaseClass::start(std::move(cb));
293}
294
295QIODevice *QPulseAudioSource::start()
296{
297 if (!validatePulseaudio())
298 return nullptr;
299 return BaseClass::start();
300}
301
302} // namespace QPulseAudioInternal
303
304QT_END_NAMESPACE
QPulseAudioSource(QAudioDevice, const QAudioFormat &, QObject *parent)
void start(QIODevice *device) override
void start(AudioCallback &&) override
QPulseAudioSourceStream(QAudioDevice, const QAudioFormat &, std::optional< qsizetype > ringbufferSize, QPulseAudioSource *parent, float volume, std::optional< int32_t > hardwareBufferSize)