summaryrefslogtreecommitdiffstats
path: root/src/main.cpp
blob: b1736cca35f06dc8cadb009e06bb56581a0db9d8 (plain) (blame)
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#include "main.h"
#include "mainwindow.h"
#include "slxoutput.h"
#include "setdefault.h"

#include <cstdio>
#include <cstring>
#include <cstddef>
#include <QVector>
#include <QGuiApplication>
#include <QTimer>
#include <PulseAudioQt/Context>
#include <PulseAudioQt/Server>
#include <PulseAudioQt/Profile>
#include <PulseAudioQt/PulseObject>
#include <PulseAudioQt/SinkInput>
#include <PulseAudioQt/Sink>
#include <PulseAudioQt/Card>
#include <PulseAudioQt/Port>
#include <QList>
#include <QSet>
#include <QTimer>
#include <QCommandLineParser>
// libkf5pulseaudioqt-dev

// Public

/** Ignore any signals from GUI elements when this is true. Set when we're updating the GUI */
bool g_IgnoreGui;

// Private

/** If not empty, on profile change, if profile belongs to this card, make its sink default */
static QString _pendingCardDefaultId;
/** If not empty, on sink appearance, if port belongs to this sink, make it sink's default */
static QString _pendingCardDefaultPort;

/** While running, we want to set each port's volume to 100% the first time we see it. Unfortunately
 *  a port only startes to exist once its according profile is selected, so there is no way to have
 *  a simple "set everything to 100%" method run on startup, at least not without switching through
 *  all profiles on all cards, which sounds like it could be annoying and buggy. So do it this way
 *  for now.
 */
static QSet<QString> _donePorts;

/** Whe something changes, (re)start a short timeout first before actually updating the GUI, to
 *  avoid multiple updates in rapid succession, for example when changing the active profile.
 */
static QTimer _updateDelay;

static MainWindow *_mainWindow;

/**
 * Queue a GUI update. By default, delay it by 50ms. If the timer is already active but hasn't
 * expired yet, it will be restarted with the given timeout.
 */
static void queueGuiUpdate(int ms = 50)
{
	_updateDelay.start(ms);
}

static void addDevicePortToWindow(PulseAudioQt::Card *card, PulseAudioQt::Device *device, PulseAudioQt::Port *port, int portIndex, bool isOutput)
{
	//if (port->availability() == PulseAudioQt::Port::Unavailable)
	//	continue;
	bool portIsActive = portIndex == device->activePortIndex();
	bool defaultSinkAndPort = (device->isDefault() && portIsActive);
	qint64 volume = device->volume();
	printf("[%c] Output: '%s %s', volume: %d, mute: %d\n",
		   defaultSinkAndPort ? 'x' : ' ',
		   device->description().toLocal8Bit().constData(), port->description().toLocal8Bit().constData(),
		   (int)volume, (int)device->isMuted());
	QString id = device->name() + port->name();
	// Only once, update port volume to be 100% if it's low
	if (defaultSinkAndPort && !_donePorts.contains(id)) {
		_donePorts.insert(id);
		if (volume < 60000) {
			volume = 65535;
			device->setVolume(volume);
		}
		device->setMuted(false);
	}
	//knownCardPortCombos.insert(card->name() + ":" + port->name());
	_mainWindow->getDevice(card, device, port, isOutput)->updateDeviceAndPort(defaultSinkAndPort, device->isMuted(),
			(portIsActive && device->isVolumeWritable()) ? device->volume() : -1);
}

/**
 * The actual GUI update logic. Iterate over all sinks and their ports, and add them to the GUI.
 * Then iterate over all non-selected profiles, and add them to the GUI too, so we have a simple, flat
 * list of "outputs" to select, which should be a bit more easy to grasp for a non-technical person
 * trying to make the computer go beep. (Hopefully)
 */
static void updateActiveOutput()
{
	g_IgnoreGui = true; // Block GUI updates
	_mainWindow->mark(); // Mark all items in the lists as unused
	auto *i = PulseAudioQt::Context::instance();
	auto cards = i->cards();

	printf(".--------------------------------------------.\n");
	//QSet<QString> knownCardPortCombos;
	for (auto *sink : i->sinks()) {
		PulseAudioQt::Card *card = nullptr;
		if (sink->cardIndex() < cards.size()) {
			card = cards.at(sink->cardIndex());
		}
		int portIndex = -1;
		for (auto *port : sink->ports()) {
			portIndex++;
			addDevicePortToWindow(card, sink, port, portIndex, true);
		}
	}
	for (auto *source : i->sources()) {
		PulseAudioQt::Card *card = nullptr;
		if (source->cardIndex() < cards.size()) {
			card = cards.at(source->cardIndex());
		}
		int portIndex = -1;
		for (auto *port : source->ports()) {
			portIndex++;
			addDevicePortToWindow(card, source, port, portIndex, false);
		}
	}
	// Now find all the profiles from all cards that are not active and add an entry to the list for each one
	for (auto *card : cards) {
		/*
		 * Don't do this for now - even though we know now that there might be another port for a card that currently
		 * doesn't exist for any of its sinks, we don't know what profile we need to switch to to get a sink with that port.
		 * Rather refactor the UI a little bit to have a card switcher.
		int portIndex = -1;
		for (auto *port : card->ports()) {
			portIndex++;
			if (knownCardPortCombos.contains(card->name() + ":" + port->name()))
				continue;
			_mainWindow->getCardPort(card, port)->updateCardAndProfile();
		}
		*/
		int profIndex = -1;
		for (auto *profile : card->profiles()) {
			profIndex++;
			// Ignore the active profile, and profiles that are unavailable
			if (profIndex == card->activeProfileIndex() || profile->availability() == PulseAudioQt::Profile::Unavailable)
				continue;
			// No point in selecting something that doesn't have any way to output sound
			if (profile->sinks() == 0 && profile->sources() == 0)
				continue;
			printf("[ ] Output: '%s', sinks: %d\n",
				   profile->description().toLocal8Bit().constData(), profile->sinks());
			_mainWindow->getCardProfile(card, profile)->updateCardAndProfile();
		}
	}
	printf("`--------------------------------------------´\n");
	_mainWindow->sweep(); // Removes all items from the list that are still marked unused, i.e. updateOutput() was not called on those
	g_IgnoreGui = false; // Allow GUI updates again
}

/**
 * Called some time after the user changed to a profile/port that was not enabled at the time of clicking, so
 * wait for PA state to update and then set the port as default port.
 */
static void checkShouldSetDefaultPort(PulseAudioQt::Device *sink)
{
    if (_pendingCardDefaultPort.isEmpty())
        return;
    int portIdx = -1;
    for (auto *port : sink->ports()) {
        portIdx++;
        if (port->name() == _pendingCardDefaultPort) {
            _pendingCardDefaultPort.clear();
            sink->setActivePortIndex(portIdx);
        }
    }
}

/**
 * Called after the user set a GUI entry as default that represents a profile, after the active profile
 * or the list of available ports changed. Only after this happened can we actually set as default the sink/port
 * that was created from selecting that profile as the default sink.
 */
static void checkShouldSetDefaultSink()
{
	if (_pendingCardDefaultId.isEmpty()) // No switch actually pending
		return;
	// Otherwise, it's the ID of the card that the profile belongs to that the user wants to set as default
	printf("Pending card default to %s\n", _pendingCardDefaultId.toLocal8Bit().constData());
	auto *i = PulseAudioQt::Context::instance();
	int cardIdx = -1;
	// Find the current index of that card
	for (auto *card : i->cards()) {
		cardIdx++;
		if (card->name() == _pendingCardDefaultId && !card->ports().isEmpty())
			break;
	}
	// Then iterate over all sinks until we find one that belongs to the card
	for (auto *sink : i->sinks()) {
		if (sink->cardIndex() == cardIdx) {
			printf("MATCH SET!\n");
			// Set as default, unmute, and clear the pending switch
			sink->setDefault(true);
			sink->setMuted(false);
			_pendingCardDefaultId.clear();
			checkShouldSetDefaultPort(sink);
		}
	}
}

/**
 * Called when PA tells us about a new card; start listening to signals we're interesed in.
 */
static void newCardAppeared(PulseAudioQt::Card *card)
{
	//if (_doneCards.contains(card->name()))
	//	return;
	auto *i = PulseAudioQt::Context::instance();
	QCoreApplication::connect(card, &PulseAudioQt::Card::profilesChanged, [=]() {
		printf("Card %p profiles changed\n", card);
	});
	QCoreApplication::connect(card, &PulseAudioQt::Card::activeProfileIndexChanged, [=]() {
		printf("Card %p active profile index changed\n", card);
		checkShouldSetDefaultSink();
		queueGuiUpdate();
	});
	QCoreApplication::connect(card, &PulseAudioQt::Card::portsChanged, [=]() {
		printf("Card %p ports changed\n", card);
		checkShouldSetDefaultSink();
		queueGuiUpdate();
	});
	/*
	QCoreApplication::connect(card, &PulseAudioQt::Card::sinksChanged, [=]() {
		printf("Card %p sinks changed\n", card);
	});
	*/
}

/**
 * Called when PA tells us about a new device; start listening to signals we're interested in.
 */
static void newDeviceAppeared(PulseAudioQt::Device *device)
{
	QCoreApplication::connect(device, &PulseAudioQt::Sink::activePortIndexChanged, [device]() {
		printf("Sink %p changed active port\n", device);
		queueGuiUpdate();
	});
	QCoreApplication::connect(device, &PulseAudioQt::Sink::defaultChanged, [device]() {
		printf("Sink %p changed default\n", device);
		queueGuiUpdate();
	});
	QCoreApplication::connect(device, &PulseAudioQt::Sink::portsChanged, [device]() {
		printf("Sink %p ports changed\n", device);
		checkShouldSetDefaultPort(device);
		queueGuiUpdate();
	});
	QCoreApplication::connect(device, &PulseAudioQt::Sink::volumeChanged, [device]() {
		queueGuiUpdate(250);
	});
	QCoreApplication::connect(device, &PulseAudioQt::Sink::isVolumeWritableChanged, [device]() {
		queueGuiUpdate();
	});
	checkShouldSetDefaultPort(device);
	queueGuiUpdate();
}

/**
 * Mute/unmute device by its string identifier.
 */
void setMuted(const QString &deviceId, bool muted)
{
	auto *i = PulseAudioQt::Context::instance();

	for (auto *sp : i->sinks()) {
		if (sp->name() == deviceId) {
			sp->setMuted(muted);
		}
	}
	for (auto *sp : i->sources()) {
		if (sp->name() == deviceId) {
			sp->setMuted(muted);
		}
	}
	queueGuiUpdate();
}

/**
 * Set a device's volume, by its string identifier.
 */
void setSinkVolume(const QString &deviceId, int volume)
{
	auto *i = PulseAudioQt::Context::instance();

	for (auto *sp : i->sinks()) {
		if (sp->name() == deviceId) {
			sp->setVolume(volume);
			queueGuiUpdate(250);
		}
	}
	for (auto *sp : i->sources()) {
		if (sp->name() == deviceId) {
			sp->setVolume(volume);
			queueGuiUpdate(250);
		}
	}
}

/**
 * Set the given card as default, preferably enabling the given profile
 * on it. If this card doesn't have a profile with the given ID, try
 * to use a profile that contains the string "Duplex" in its name,
 * otherwise, just use the first profile available.
 */
void enableCard(const QString &card, const QString &profile, const QString &port)
{
	auto *i = PulseAudioQt::Context::instance();
	PulseAudioQt::Card *matchingCard = nullptr;
	int profileIdx = -1;
	int cardIdx = -1;

	_pendingCardDefaultId.clear();
	_pendingCardDefaultPort.clear();
	for (auto *cp : i->cards()) {
		cardIdx++;
		if (cp->name() != card)
			continue;
		int i = -1;
		int exactProfileIdx = -1;
		for (auto *pp : cp->profiles()) {
			i++;
			if (pp->availability() == PulseAudioQt::Profile::Unavailable)
				continue;
			if (pp->description().contains(QLatin1String("Duplex"))) {
				// Prefer Duplex mode for analog outputs, it's usually listed after output only
				profileIdx = i;
			}
			if (profileIdx == -1) {
				// Otherwise default to first one in list
				profileIdx = i;
			}
			if (pp->name() == profile) {
				exactProfileIdx = i;
			}
		}
		if (exactProfileIdx != -1) {
			profileIdx = exactProfileIdx;
		}
		if (profileIdx != -1) {
			matchingCard = cp;
			break;
		}
	}
	if (matchingCard != nullptr && profileIdx < matchingCard->profiles().size()) {
		if (matchingCard->activeProfileIndex() == profileIdx) {
			// Profile already active, just unmute sink
			for (auto *sink : i->sinks()) {
				if (sink->cardIndex() == cardIdx) {
					sink->setMuted(false);
					sink->setDefault(true);
					_pendingCardDefaultPort = port;
					checkShouldSetDefaultPort(sink);
				}
			}
			for (auto *source : i->sources()) {
				if (source->cardIndex() == cardIdx) {
					source->setMuted(false);
					source->setDefault(true);
				}
			}
		} else {
			// Remember the ID of the card we switched to; we need this as only after PA is done
			// switching to the desired profile will we see any sink belonging to it, so we can only
			// set the according sink as fallback after that happens. See checkShouldSetDefault().
			_pendingCardDefaultId = matchingCard->name();
			_pendingCardDefaultPort = port;
			matchingCard->setActiveProfileIndex(profileIdx);
		}
	}
	queueGuiUpdate();
}

/**
 * Set given sink as default sink, unmute it, and switch to its
 * port as passed to this function. If the sink doesn't have a
 * port with this ID, nothing happens.
 */
void enableSink(const QString &sink, const QString &port)
{
	auto *i = PulseAudioQt::Context::instance();

	_pendingCardDefaultId.clear();
	_pendingCardDefaultPort.clear();
	for (auto *sp : i->sinks()) {
		if (sp->name() != sink)
			continue;
		int i = -1;
		for (auto *pp : sp->ports()) {
			i++;
			if (pp->name() == port) {
				sp->setDefault(true);
				sp->setMuted(false);
				sp->setActivePortIndex(i);
			}
		}
	}
	queueGuiUpdate();
}

/**
 * Set given source as default source, unmute it, and switch to its
 * port as passed to this function. If the source doesn't have a
 * port with this ID, nothing happens.
 */
void enableSource(const QString &source, const QString &port)
{
	auto *i = PulseAudioQt::Context::instance();

	_pendingCardDefaultId.clear();
	_pendingCardDefaultPort.clear();
	for (auto *sp : i->sources()) {
		if (sp->name() != source)
			continue;
		int i = -1;
		for (auto *pp : sp->ports()) {
			i++;
			if (pp->name() == port) {
				sp->setDefault(true);
				sp->setMuted(false);
				sp->setActivePortIndex(i);
			}
		}
	}
	queueGuiUpdate();
}

int main(int argc, char **argv)
{
	QApplication a(argc, argv);
	auto *i = PulseAudioQt::Context::instance();

	a.setOrganizationName(QStringLiteral("slxmix"));
	a.setApplicationVersion(QLatin1String("1.0.0.0.0"));
	QCommandLineParser parser;
	parser.setApplicationDescription(QObject::tr("SLXmix Volume Control"));
	parser.addHelpOption();
	QCommandLineOption selectOption(QStringList() << QStringLiteral("output") << QStringLiteral("o"),
		QObject::tr("Select a specific output configuration and quit. Will select the Profile/Sink/Port combo that best matches the list of given keywords, e.g. 'HDMI 1 5.1'"),
		QStringLiteral("keywords"));
	parser.addOption(selectOption);
	parser.process(a);
	// Select default output and exit
	if (parser.isSet(selectOption)) {
		QString what = parser.value(selectOption);
		QTimer::singleShot(100, [what]() {
			setDefaultOutput(what);
		});
		return a.exec();
	}

	// There's no signal, or no way to check if we're connected to PA, so
	// just wait a bit and hope for the best.
	QTimer::singleShot(100, [=]() {
		for (auto *card : i->cards()) {
			newCardAppeared(card);
			printf("Card: %s (index: %d)\n", card->name().toLocal8Bit().constData(), (int)card->index());
			for (auto *profile : card->profiles()) {
				printf("  Profile: %s\n", profile->name().toLocal8Bit().constData());
			}
			for (auto *port : card->ports()) {
				printf("  Port: %s -- %s (%i)\n", port->name().toLocal8Bit().constData(), port->description().toLocal8Bit().constData(), (int)port->availability());
			}
		}
		for (auto *sink : i->sinks()) {
			printf("Sink: %s (for card index %d)\n", sink->name().toLocal8Bit().constData(), sink->cardIndex());
			for (auto *port : sink->ports()) {
				printf("  Port: %s -- %s (%i)\n", port->name().toLocal8Bit().constData(), port->description().toLocal8Bit().constData(), (int)port->availability());
			}
			newDeviceAppeared(sink);
		}
		for (auto *source : i->sources()) {
			printf("Source: %s (for card index %d)\n", source->name().toLocal8Bit().constData(), source->cardIndex());
			for (auto *port : source->ports()) {
				printf("  Port: %s -- %s (%i)\n", port->name().toLocal8Bit().constData(), port->description().toLocal8Bit().constData(), (int)port->availability());
			}
			newDeviceAppeared(source);
		}
		QCoreApplication::connect(i, &PulseAudioQt::Context::cardAdded, &newCardAppeared);
		QCoreApplication::connect(i, &PulseAudioQt::Context::sinkAdded, &newDeviceAppeared);
		QCoreApplication::connect(i, &PulseAudioQt::Context::sourceAdded, &newDeviceAppeared);
		printf("Initial output\n");
		queueGuiUpdate();
	});

	QCoreApplication::connect(&_updateDelay, &QTimer::timeout, &updateActiveOutput);
	_updateDelay.setInterval(50);
	_updateDelay.setSingleShot(true);

	_mainWindow = new MainWindow;
	_mainWindow->show();

	return a.exec();
}