Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PAAudio.cpp « mumble « src - github.com/mumble-voip/mumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f04a3756ac2086e454e4f9e055af69380ee59b87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// Copyright 2007-2021 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

#include "PAAudio.h"
#include "Global.h"

#ifdef Q_CC_GNU
#	define RESOLVE(var)                                                          \
		{                                                                         \
			var = reinterpret_cast< __typeof__(var) >(qlPortAudio.resolve(#var)); \
			if (!var)                                                             \
				return;                                                           \
		}
#else
#	define RESOLVE(var)                                                                           \
		{                                                                                          \
			*reinterpret_cast< void ** >(&var) = static_cast< void * >(qlPortAudio.resolve(#var)); \
			if (!var)                                                                              \
				return;                                                                            \
		}
#endif

static std::unique_ptr< PortAudioSystem > pas;

class PortAudioInputRegistrar : public AudioInputRegistrar {
private:
	AudioInput *create() Q_DECL_OVERRIDE;
	const QList< audioDevice > getDeviceChoices() Q_DECL_OVERRIDE;
	void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE;
	bool canEcho(EchoCancelOptionID echoCancelID, const QString &outputSystem) const Q_DECL_OVERRIDE;
	bool isMicrophoneAccessDeniedByOS() Q_DECL_OVERRIDE { return false; };

public:
	PortAudioInputRegistrar();
};

class PortAudioOutputRegistrar : public AudioOutputRegistrar {
private:
	AudioOutput *create() Q_DECL_OVERRIDE;
	const QList< audioDevice > getDeviceChoices() Q_DECL_OVERRIDE;
	void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE;

public:
	PortAudioOutputRegistrar();
};

class PortAudioInit : public DeferInit {
private:
	std::unique_ptr< PortAudioInputRegistrar > airPortAudio;
	std::unique_ptr< PortAudioOutputRegistrar > aorPortAudio;
	void initialize();
	void destroy();
};

PortAudioInputRegistrar::PortAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("PortAudio")) {
}

AudioInput *PortAudioInputRegistrar::create() {
	return new PortAudioInput();
}

const QList< audioDevice > PortAudioInputRegistrar::getDeviceChoices() {
	return pas->enumerateDevices(true, Global::get().s.iPortAudioInput);
}

void PortAudioInputRegistrar::setDeviceChoice(const QVariant &choice, Settings &s) {
	s.iPortAudioInput = choice.toInt();
}

bool PortAudioInputRegistrar::canEcho(EchoCancelOptionID, const QString &) const {
	return false;
}

PortAudioOutputRegistrar::PortAudioOutputRegistrar() : AudioOutputRegistrar(QLatin1String("PortAudio")) {
}

AudioOutput *PortAudioOutputRegistrar::create() {
	return new PortAudioOutput();
}

const QList< audioDevice > PortAudioOutputRegistrar::getDeviceChoices() {
	return pas->enumerateDevices(false, Global::get().s.iPortAudioOutput);
}

void PortAudioOutputRegistrar::setDeviceChoice(const QVariant &choice, Settings &s) {
	s.iPortAudioOutput = choice.toInt();
}

void PortAudioInit::initialize() {
	pas.reset(new PortAudioSystem());

	pas->qmWait.lock();
	pas->qwcWait.wait(&pas->qmWait, 1000);
	pas->qmWait.unlock();

	if (pas->bOk) {
		airPortAudio.reset(new PortAudioInputRegistrar());
		aorPortAudio.reset(new PortAudioOutputRegistrar());
	} else {
		pas.reset();
	}
}

void PortAudioInit::destroy() {
	airPortAudio.reset();
	aorPortAudio.reset();
	pas.reset();
}

// Instantiate PortAudioSystem, PortAudioInputRegistrar and PortAudioOutputRegistrar
static PortAudioInit pai;

PortAudioSystem::PortAudioSystem() : bOk(false) {
	QStringList alternatives;
#ifdef Q_OS_WIN
	alternatives << QLatin1String("portaudio_x64.dll");
	alternatives << QLatin1String("portaudio_x86.dll");
#elif defined(Q_OS_MAC)
	alternatives << QLatin1String("libportaudio.dylib");
	alternatives << QLatin1String("libportaudio.2.dylib");
#else
	alternatives << QLatin1String("libportaudio.so");
	alternatives << QLatin1String("libportaudio.so.2");
#endif
	for (const auto &lib : alternatives) {
		qlPortAudio.setFileName(lib);
		if (qlPortAudio.load()) {
			break;
		}
	}

	if (!qlPortAudio.isLoaded()) {
		return;
	}

	RESOLVE(Pa_GetVersionText)
	RESOLVE(Pa_GetErrorText)
	RESOLVE(Pa_Initialize)
	RESOLVE(Pa_Terminate)
	RESOLVE(Pa_OpenStream)
	RESOLVE(Pa_CloseStream)
	RESOLVE(Pa_StartStream)
	RESOLVE(Pa_StopStream)
	RESOLVE(Pa_IsStreamActive)
	RESOLVE(Pa_GetDefaultInputDevice)
	RESOLVE(Pa_GetDefaultOutputDevice)
	RESOLVE(Pa_HostApiDeviceIndexToDeviceIndex)
	RESOLVE(Pa_GetHostApiCount)
	RESOLVE(Pa_GetHostApiInfo)
	RESOLVE(Pa_GetDeviceInfo)

	const auto ret = Pa_Initialize();
	if (ret != paNoError) {
		qWarning("PortAudioSystem: failed to initialize library - Pa_Initialize() returned: %s", Pa_GetErrorText(ret));
		return;
	}

	bOk = true;

	qDebug("%s from %s", Pa_GetVersionText(), qPrintable(qlPortAudio.fileName()));
}

PortAudioSystem::~PortAudioSystem() {
	if (bOk) {
		const auto ret = Pa_Terminate();
		if (ret != paNoError) {
			qWarning("PortAudioSystem: failed to terminate library - Pa_Terminate() returned: %s",
					 Pa_GetErrorText(ret));
		}
	}
}

const QList< audioDevice > PortAudioSystem::enumerateDevices(const bool input, const PaDeviceIndex current) {
	QList< audioDevice > audioDevices;

	if (!bOk) {
		return audioDevices;
	}

	audioDevices << audioDevice(tr("Default device"), -1);

	for (PaHostApiIndex apiIndex = 0; apiIndex < Pa_GetHostApiCount(); ++apiIndex) {
		const auto *apiInfo = Pa_GetHostApiInfo(apiIndex);
		if (!apiInfo) {
			continue;
		}

		for (PaDeviceIndex apiDeviceIndex = 0; apiDeviceIndex < apiInfo->deviceCount; ++apiDeviceIndex) {
			const auto deviceIndex = Pa_HostApiDeviceIndexToDeviceIndex(apiIndex, apiDeviceIndex);
			const auto *deviceInfo = Pa_GetDeviceInfo(deviceIndex);
			if (!deviceInfo) {
				continue;
			}

			if ((input && (deviceInfo->maxInputChannels > 0)) || (!input && (deviceInfo->maxOutputChannels > 0))) {
				audioDevices << audioDevice(
					QLatin1String(apiInfo->name) + QLatin1String(": ") + QLatin1String(deviceInfo->name), deviceIndex);
			}
		}
	}

	for (auto i = 0; i < audioDevices.count(); ++i) {
		if (audioDevices.at(i).second == current) {
			// We want the current device to appear at the top of the list
			audioDevice audioDevice = audioDevices.takeAt(i);
			audioDevices.prepend(audioDevice);
			break;
		}
	}

	return audioDevices;
}

bool PortAudioSystem::isStreamRunning(PaStream *stream) {
	if (!bOk || !stream) {
		return false;
	}

	const auto ret = Pa_IsStreamActive(stream);
	if (ret == 1) {
		return true;
	} else if (ret != 0) {
		qWarning("PortAudioSystem: failed to determine stream status - Pa_IsStreamActive() returned: %s",
				 Pa_GetErrorText(ret));
	}

	return false;
}

int PortAudioSystem::openStream(PaStream **stream, PaDeviceIndex device, const uint32_t frameSize, const bool isInput) {
	if (!bOk || !stream) {
		return 0;
	}

	QMutexLocker lock(&qmWait);

	// -1 is the default device
	if (device == -1) {
		device = (isInput ? Pa_GetDefaultInputDevice() : Pa_GetDefaultOutputDevice());
	}

	const auto *devInfo = Pa_GetDeviceInfo(device);
	if (!devInfo) {
		qWarning("PortAudioSystem: failed to retrieve info about device %d - Pa_GetDeviceInfo() returned: nullptr",
				 device);
		return 0;
	}

	const auto *apiInfo = Pa_GetHostApiInfo(devInfo->hostApi);
	if (!apiInfo) {
		qWarning(
			"PortAudioSystem: failed to retrieve info about API %d (device %d) - Pa_GetHostApiInfo() returned: nullptr",
			devInfo->hostApi, device);
		return 0;
	}

	qDebug("PortAudioSystem: using %s %s", apiInfo->name, devInfo->name);

	PaStreamParameters streamPar;
	streamPar.channelCount = 1;

	if (!isInput && devInfo->maxOutputChannels > 1) {
		// TODO: add support for more than 2 channels
		streamPar.channelCount = 2;
	}

	streamPar.device           = device;
	streamPar.sampleFormat     = paFloat32;
	streamPar.suggestedLatency = (isInput ? devInfo->defaultLowInputLatency : devInfo->defaultLowOutputLatency);
	streamPar.hostApiSpecificStreamInfo = nullptr;

	const auto ret =
		Pa_OpenStream(stream, isInput ? &streamPar : nullptr, isInput ? nullptr : &streamPar, SAMPLE_RATE, frameSize,
					  paClipOff | paDitherOff, &streamCallback, reinterpret_cast< void * >(isInput));
	if (ret != paNoError) {
		qWarning("PortAudioSystem: failed to open stream - Pa_OpenStream() returned: %s", Pa_GetErrorText(ret));
		*stream = nullptr;
		return 0;
	}

	return streamPar.channelCount;
}

bool PortAudioSystem::closeStream(PaStream *stream) {
	if (!bOk || !stream) {
		return false;
	}

	QMutexLocker lock(&qmWait);

	const auto ret = Pa_CloseStream(stream);
	if (ret != paNoError) {
		qWarning("PortAudioSystem: failed to close stream - Pa_CloseStream() returned: %s", Pa_GetErrorText(ret));
		return false;
	}

	return true;
}

bool PortAudioSystem::startStream(PaStream *stream) {
	if (!bOk) {
		return false;
	}

	if (isStreamRunning(stream)) {
		return true;
	}

	const auto ret = Pa_StartStream(stream);
	if (ret != paNoError) {
		qWarning("PortAudioSystem: failed to start stream - Pa_StartStream() returned: %s", Pa_GetErrorText(ret));
		return false;
	}

	return true;
}

bool PortAudioSystem::stopStream(PaStream *stream) {
	if (!bOk) {
		return false;
	}

	if (!isStreamRunning(stream)) {
		return true;
	}

	const auto ret = Pa_StopStream(stream);
	if (ret != paNoError) {
		qWarning("PortAudioSystem: failed to stop stream - Pa_StopStream() returned: %s", Pa_GetErrorText(ret));
		return false;
	}

	return true;
}

int PortAudioSystem::streamCallback(const void *input, void *output, unsigned long frames,
									const PaStreamCallbackTimeInfo *, PaStreamCallbackFlags, void *isInput) {
	if (isInput) {
		auto const pai = dynamic_cast< PortAudioInput * >(Global::get().ai.get());
		if (!pai) {
			return paAbort;
		}

		pai->process(frames, input);
	} else {
		auto const pao = dynamic_cast< PortAudioOutput * >(Global::get().ao.get());
		if (!pao) {
			return paAbort;
		}

		pao->process(frames, output);
	}

	return paContinue;
}

PortAudioInput::PortAudioInput() : stream(nullptr) {
	iMicChannels = pas->openStream(&stream, Global::get().s.iPortAudioInput, iFrameSize, true);
	if (!iMicChannels) {
		qWarning("PortAudioInput: failed to open stream");
		return;
	}

	iMicFreq   = SAMPLE_RATE;
	eMicFormat = SampleFloat;
	initializeMixer();

	if (!pas->startStream(stream)) {
		qWarning("PortAudioInput: failed to start stream");
	}
}

PortAudioInput::~PortAudioInput() {
	// Request interruption
	qmWait.lock();

	if (!pas->stopStream(stream)) {
		qWarning("PortAudioInput: failed to stop stream");
	}

	qwcSleep.wakeAll();
	qmWait.unlock();

	// Wait for thread to exit
	wait();

	// Cleanup
	if (!pas->closeStream(stream)) {
		qWarning("PortAudioInput: failed to close stream");
	}
}

void PortAudioInput::process(const uint32_t frames, const void *buffer) {
	addMic(buffer, frames);
}

void PortAudioInput::run() {
	if (!pas->isStreamRunning(stream)) {
		return;
	}

	// Pause thread until interruption is requested by the destructor
	qmWait.lock();
	qwcSleep.wait(&qmWait);
	qmWait.unlock();
}

PortAudioOutput::PortAudioOutput() : stream(nullptr) {
	iChannels = pas->openStream(&stream, Global::get().s.iPortAudioOutput, iFrameSize, false);
	if (!iChannels) {
		qWarning("PortAudioOutput: failed to open stream");
		return;
	}

	iMixerFreq    = SAMPLE_RATE;
	eSampleFormat = SampleFloat;

	const uint32_t channelsMask[]{ SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT };

	initializeMixer(channelsMask);

	if (!pas->startStream(stream)) {
		qWarning("PortAudioOutput: failed to start stream");
	}
}

PortAudioOutput::~PortAudioOutput() {
	// Request interruption
	qmWait.lock();

	if (!pas->stopStream(stream)) {
		qWarning("PortAudioOutput: failed to stop stream");
	}

	qwcSleep.wakeAll();
	qmWait.unlock();

	// Wait for thread to exit
	wait();

	// Cleanup
	if (!pas->closeStream(stream)) {
		qWarning("PortAudioOutput: failed to close stream");
	}
}

void PortAudioOutput::process(const uint32_t frames, void *buffer) {
	if (!mix(buffer, frames)) {
		memset(buffer, 0, sizeof(float) * frames * iChannels);
	}
}

void PortAudioOutput::run() {
	if (!pas->isStreamRunning(stream)) {
		return;
	}

	// Pause thread until interruption is requested by the destructor
	qmWait.lock();
	qwcSleep.wait(&qmWait);
	qmWait.unlock();
}

#undef RESOLVE