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 int status = pa_stream_connect_record(m_stream.get(), m_audioDevice.id().data(), &attr, flags);
161 if (status != 0) {
162 qCWarning(qLcPulseAudioOut) << "pa_stream_connect_record() failed!";
163 m_stream = {};
164 return false;
165 }
166 return true;
167}
168
169void QPulseAudioSourceStream::installCallbacks(StreamType streamType)
170{
171 switch (streamType) {
172 case StreamType::Ringbuffer: {
173 pa_stream_set_read_callback(m_stream.get(),
174 [](pa_stream *stream, size_t nbytes, void *data) {
175 auto *self = reinterpret_cast<QPulseAudioSourceStream *>(data);
176 Q_ASSERT(stream == self->m_stream.get());
177 self->readCallbackRingbuffer(nbytes);
178 }, this);
179 break;
180 }
181 case StreamType::Callback: {
182 pa_stream_set_read_callback(m_stream.get(),
183 [](pa_stream *stream, size_t nbytes, void *data) {
184 auto *self = reinterpret_cast<QPulseAudioSourceStream *>(data);
185 Q_ASSERT(stream == self->m_stream.get());
186 self->readCallbackAudioCallback(nbytes);
187 }, this);
188 break;
189 }
190 }
191}
192
193void QPulseAudioSourceStream::uninstallCallbacks()
194{
195 pa_stream_set_read_callback(m_stream.get(), nullptr, nullptr);
196}
197
198void QPulseAudioSourceStream::readCallbackRingbuffer([[maybe_unused]] size_t bytesToRead)
199{
200 const void *data{};
201 size_t nBytes{};
202 int status = pa_stream_peek(m_stream.get(), &data, &nBytes);
203 if (status < 0) {
204 invokeOnAppThread([this] {
205 handleIOError(m_parent);
206 });
207 return;
208 }
209
210 QSpan<const std::byte> hostBuffer{
211 reinterpret_cast<const std::byte *>(data),
212 qsizetype(nBytes),
213 };
214
215 uint32_t numberOfFrames = m_format.framesForBytes(nBytes);
216
217 [[maybe_unused]] uint64_t framesWritten =
218 QPlatformAudioSourceStream::process(hostBuffer, numberOfFrames);
219 status = pa_stream_drop(m_stream.get());
220 if (status < 0) {
221 if (!isStopRequested()) {
222 invokeOnAppThread([this] {
223 handleIOError(m_parent);
224 });
225 }
226 }
227}
228
229void QPulseAudioSourceStream::readCallbackAudioCallback([[maybe_unused]] size_t bytesToRead)
230{
231 const void *data{};
232 size_t nBytes{};
233 int status = pa_stream_peek(m_stream.get(), &data, &nBytes);
234 if (status < 0) {
235 QMetaObject::invokeMethod(m_parent, [this] {
236 handleIOError(m_parent);
237 });
238 return;
239 }
240
241 QSpan<const std::byte> hostBuffer{
242 reinterpret_cast<const std::byte *>(data),
243 qsizetype(nBytes),
244 };
245
246 runAudioCallback(*m_audioCallback, hostBuffer, m_format, volume());
247
248 status = pa_stream_drop(m_stream.get());
249 if (status < 0) {
250 if (!isStopRequested()) {
251 QMetaObject::invokeMethod(m_parent, [this] {
252 handleIOError(m_parent);
253 });
254 }
255 }
256}
257
258////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
259
260QPulseAudioSource::QPulseAudioSource(QAudioDevice device, const QAudioFormat &format,
261 QObject *parent)
263{
264}
265
266QPulseAudioSource::~QPulseAudioSource()
267 = default;
268
269bool QPulseAudioSource::validatePulseaudio()
270{
271 QPulseAudioContextManager *pulseEngine = QPulseAudioContextManager::instance();
272 if (!pulseEngine->contextIsGood()) {
273 qWarning() << "Invalid PulseAudio context:" << pulseEngine->getContextState();
274 setError(QtAudio::Error::FatalError);
275 return false;
276 }
277 return true;
278}
279
280void QPulseAudioSource::start(QIODevice *device)
281{
282 if (!validatePulseaudio())
283 return;
284 return BaseClass::start(device);
285}
286
287void QPulseAudioSource::start(AudioCallback &&cb)
288{
289 if (!validatePulseaudio())
290 return;
291 return BaseClass::start(std::move(cb));
292}
293
294QIODevice *QPulseAudioSource::start()
295{
296 if (!validatePulseaudio())
297 return nullptr;
298 return BaseClass::start();
299}
300
301} // namespace QPulseAudioInternal
302
303QT_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)