-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathmediacontroller.cpp
More file actions
419 lines (356 loc) · 11.6 KB
/
mediacontroller.cpp
File metadata and controls
419 lines (356 loc) · 11.6 KB
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
#include "mediacontroller.h"
#include "logger.h"
#include "eardetection.hpp"
#include "playerstatuswatcher.h"
#include "pulseaudiocontroller.h"
#include <QDebug>
#include <QProcess>
#include <QThread>
#include <QRegularExpression>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
MediaController::MediaController(QObject *parent) : QObject(parent) {
m_pulseAudio = new PulseAudioController(this);
if (!m_pulseAudio->initialize())
{
LOG_ERROR("Failed to initialize PulseAudio controller");
}
}
void MediaController::handleEarDetection(EarDetection *earDetection)
{
if (earDetectionBehavior == Disabled)
{
LOG_DEBUG("Ear detection is disabled, ignoring status");
return;
}
bool primaryInEar = earDetection->isPrimaryInEar();
bool secondaryInEar = earDetection->isSecondaryInEar();
LOG_DEBUG("Ear detection status: primaryInEar="
<< primaryInEar << ", secondaryInEar=" << secondaryInEar
<< ", isAirPodsActive=" << isActiveOutputDeviceAirPods());
// First handle playback pausing based on selected behavior
bool shouldPause = false;
bool shouldResume = false;
if (earDetectionBehavior == PauseWhenOneRemoved)
{
shouldPause = !primaryInEar || !secondaryInEar;
shouldResume = primaryInEar && secondaryInEar;
}
else if (earDetectionBehavior == PauseWhenBothRemoved)
{
shouldPause = !primaryInEar && !secondaryInEar;
shouldResume = primaryInEar || secondaryInEar;
}
if (shouldPause && isActiveOutputDeviceAirPods())
{
if (getCurrentMediaState() == Playing)
{
LOG_DEBUG("Pausing playback for ear detection");
pause();
}
}
// Then handle device profile switching
if (primaryInEar || secondaryInEar)
{
LOG_INFO("At least one AirPod is in ear");
activateA2dpProfile();
// Resume if conditions are met and we previously paused
if (shouldResume && !pausedByAppServices.isEmpty() && isActiveOutputDeviceAirPods())
{
play();
}
}
else
{
LOG_INFO("Both AirPods are out of ear");
removeAudioOutputDevice();
}
}
void MediaController::setEarDetectionBehavior(EarDetectionBehavior behavior)
{
earDetectionBehavior = behavior;
LOG_INFO("Set ear detection behavior to: " << behavior);
}
void MediaController::followMediaChanges() {
playerStatusWatcher = new PlayerStatusWatcher("", this);
connect(playerStatusWatcher, &PlayerStatusWatcher::playbackStatusChanged,
this, [this](const QString &status)
{
LOG_DEBUG("Playback status changed: " << status);
MediaState state = mediaStateFromPlayerctlOutput(status);
emit mediaStateChanged(state);
});
}
bool MediaController::isActiveOutputDeviceAirPods() {
QString defaultSinkMacAddress = m_pulseAudio->getDefaultSinkMacAddress();
LOG_DEBUG("Default sink MAC address: " << defaultSinkMacAddress);
return defaultSinkMacAddress == connectedDeviceMacAddress;
}
void MediaController::handleConversationalAwareness(const QByteArray &data) {
if (data.size() < 10) {
LOG_ERROR("Invalid conversational awareness packet");
return;
}
uint8_t flag = (uint8_t)data[9];
switch (flag) {
case 0x01:
LOG_INFO("Conversational awareness event: voice detected");
if (initialVolume == -1 && isActiveOutputDeviceAirPods()) {
QString sink = m_pulseAudio->getDefaultSink();
initialVolume = m_pulseAudio->getSinkVolume(sink);
LOG_DEBUG("Initial volume saved: " << initialVolume << "%");
}
if (initialVolume != -1) {
QString sink = m_pulseAudio->getDefaultSink();
int target = initialVolume * 0.20;
m_pulseAudio->setSinkVolume(sink, target);
LOG_INFO("Volume lowered to " << target << "%");
}
break;
case 0x08:
LOG_INFO("Conversational awareness disabled");
initialVolume = -1;
break;
case 0x09:
LOG_INFO("Conversational awareness enabled");
break;
default:
LOG_INFO("Conversational awareness event: voice ended");
if (initialVolume != -1 && isActiveOutputDeviceAirPods()) {
QString sink = m_pulseAudio->getDefaultSink();
m_pulseAudio->setSinkVolume(sink, initialVolume);
LOG_INFO("Volume restored to " << initialVolume << "%");
initialVolume = -1;
}
break;
}
}
bool MediaController::isA2dpProfileAvailable() {
if (m_deviceOutputName.isEmpty()) {
return false;
}
return m_pulseAudio->isProfileAvailable(m_deviceOutputName, "a2dp-sink-sbc_xq") ||
m_pulseAudio->isProfileAvailable(m_deviceOutputName, "a2dp-sink-sbc") ||
m_pulseAudio->isProfileAvailable(m_deviceOutputName, "a2dp-sink");
}
QString MediaController::getPreferredA2dpProfile() {
if (m_deviceOutputName.isEmpty()) {
return QString();
}
if (!m_cachedA2dpProfile.isEmpty() &&
m_pulseAudio->isProfileAvailable(m_deviceOutputName, m_cachedA2dpProfile)) {
return m_cachedA2dpProfile;
}
QStringList profiles = {"a2dp-sink-sbc_xq", "a2dp-sink-sbc", "a2dp-sink"};
for (const QString &profile : profiles) {
if (m_pulseAudio->isProfileAvailable(m_deviceOutputName, profile)) {
LOG_INFO("Selected best available A2DP profile: " << profile);
m_cachedA2dpProfile = profile;
return profile;
}
}
m_cachedA2dpProfile.clear();
return QString();
}
bool MediaController::restartWirePlumber() {
LOG_INFO("Restarting WirePlumber to rediscover A2DP profiles");
int result = QProcess::execute("systemctl", QStringList() << "--user" << "restart" << "wireplumber");
if (result == 0) {
LOG_INFO("WirePlumber restarted successfully");
QThread::sleep(2);
return true;
} else {
LOG_ERROR("Failed to restart WirePlumber. Do you use wireplumber?");
return false;
}
}
void MediaController::activateA2dpProfile() {
if (connectedDeviceMacAddress.isEmpty() || m_deviceOutputName.isEmpty()) {
LOG_WARN("Connected device MAC address or output name is empty, cannot activate A2DP profile");
return;
}
if (!isA2dpProfileAvailable()) {
LOG_WARN("A2DP profile not available, attempting to restart WirePlumber");
if (restartWirePlumber()) {
m_deviceOutputName = getAudioDeviceName();
if (!isA2dpProfileAvailable()) {
LOG_ERROR("A2DP profile still not available after WirePlumber restart");
return;
}
} else {
LOG_ERROR("Could not restart WirePlumber, A2DP profile unavailable");
return;
}
}
QString preferredProfile = getPreferredA2dpProfile();
if (preferredProfile.isEmpty()) {
LOG_ERROR("No suitable A2DP profile found");
return;
}
LOG_INFO("Activating A2DP profile for AirPods: " << preferredProfile);
if (!m_pulseAudio->setCardProfile(m_deviceOutputName, preferredProfile)) {
LOG_ERROR("Failed to activate A2DP profile: " << preferredProfile);
}
LOG_INFO("A2DP profile activated successfully");
}
void MediaController::removeAudioOutputDevice() {
if (connectedDeviceMacAddress.isEmpty() || m_deviceOutputName.isEmpty()) {
LOG_WARN("Connected device MAC address or output name is empty, cannot remove audio output device");
return;
}
LOG_INFO("Removing AirPods as audio output device");
if (!m_pulseAudio->setCardProfile(m_deviceOutputName, "off")) {
LOG_ERROR("Failed to remove AirPods as audio output device");
}
}
void MediaController::setConnectedDeviceMacAddress(const QString &macAddress) {
connectedDeviceMacAddress = macAddress;
m_deviceOutputName = getAudioDeviceName();
m_cachedA2dpProfile.clear();
LOG_INFO("Device output name set to: " << m_deviceOutputName);
}
MediaController::MediaState MediaController::mediaStateFromPlayerctlOutput(
const QString &output) const {
if (output == "Playing") {
return MediaState::Playing;
} else if (output == "Paused") {
return MediaState::Paused;
} else {
return MediaState::Stopped;
}
}
MediaController::MediaState MediaController::getCurrentMediaState() const
{
return mediaStateFromPlayerctlOutput(PlayerStatusWatcher::getCurrentPlaybackStatus(""));
}
QStringList MediaController::getPlayingMediaPlayers()
{
QStringList playingServices;
QDBusConnection bus = QDBusConnection::sessionBus();
QStringList services = bus.interface()->registeredServiceNames().value();
for (const QString &service : services)
{
if (!service.startsWith("org.mpris.MediaPlayer2."))
{
continue;
}
QDBusInterface playerInterface(
service,
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
bus);
if (!playerInterface.isValid())
{
continue;
}
QVariant playbackStatus = playerInterface.property("PlaybackStatus");
if (playbackStatus.isValid() && playbackStatus.toString() == "Playing")
{
playingServices << service;
LOG_DEBUG("Found playing service: " << service);
}
}
return playingServices;
}
void MediaController::play()
{
if (pausedByAppServices.isEmpty())
{
LOG_INFO("No services to resume");
return;
}
QDBusConnection bus = QDBusConnection::sessionBus();
int resumedCount = 0;
for (const QString &service : pausedByAppServices)
{
QDBusInterface playerInterface(
service,
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
bus);
if (!playerInterface.isValid())
{
LOG_WARN("Service no longer available: " << service);
continue;
}
QDBusReply<void> reply = playerInterface.call("Play");
if (reply.isValid())
{
LOG_INFO("Resumed playback for: " << service);
resumedCount++;
}
else
{
LOG_ERROR("Failed to resume " << service << ": " << reply.error().message());
}
}
if (resumedCount > 0)
{
LOG_INFO("Resumed " << resumedCount << " media player(s) via DBus");
pausedByAppServices.clear();
}
else
{
LOG_ERROR("Failed to resume any media players via DBus");
}
}
void MediaController::pause()
{
QDBusConnection bus = QDBusConnection::sessionBus();
QStringList services = bus.interface()->registeredServiceNames().value();
pausedByAppServices.clear();
int pausedCount = 0;
for (const QString &service : services)
{
if (!service.startsWith("org.mpris.MediaPlayer2."))
{
continue;
}
QDBusInterface playerInterface(
service,
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
bus);
if (!playerInterface.isValid())
{
continue;
}
QVariant playbackStatus = playerInterface.property("PlaybackStatus");
LOG_DEBUG("PlaybackStatus for " << service << ": " << playbackStatus.toString());
if (!playbackStatus.isValid() || playbackStatus.toString() != "Playing")
{
continue;
}
QDBusReply<void> reply = playerInterface.call("Pause");
LOG_DEBUG("Pausing service: " << service);
if (reply.isValid())
{
LOG_INFO("Paused playback for: " << service);
pausedByAppServices << service;
pausedCount++;
}
else
{
LOG_ERROR("Failed to pause " << service << ": " << reply.error().message());
}
}
if (pausedCount > 0)
{
LOG_INFO("Paused " << pausedCount << " media player(s) via DBus");
}
else
{
LOG_INFO("No playing media players found to pause");
}
}
MediaController::~MediaController() {
}
QString MediaController::getAudioDeviceName()
{
if (connectedDeviceMacAddress.isEmpty()) { return QString(); }
QString cardName = m_pulseAudio->getCardNameForDevice(connectedDeviceMacAddress);
if (cardName.isEmpty()) {
LOG_ERROR("No matching Bluetooth card found for MAC address: " << connectedDeviceMacAddress);
}
return cardName;
}