Debian Codegraph @

modules/module-mpris.c

raw
1 /* WirePlumber
2 *
3 -- Copyright © 2025 Pauli Virtanen
4 -- @author Pauli Virtanen <[email protected]>
5 *
6 * SPDX-License-Identifier: MIT
7 */
8
9 #include <unistd.h>
10
11 #include <glib.h>
12 #include <glib-unix.h>
13
14 #include <wp/wp.h>
15
16 #include "dbus-connection-state.h"
17 #include "flatpak-utils.h"
18
19
20 WP_DEFINE_LOCAL_LOG_TOPIC ("m-mpris")
21
22 #define NAME "mpris"
23
24 #define PLAYER_TIMEOUT_MSEC 3000
25
26 struct _Item
27 {
28 gchar *desktop_entry;
29 guint32 pid;
30 gchar *flatpak_app_id;
31 gchar *flatpak_instance_id;
32 };
33 typedef struct _Item Item;
34
35 struct _Players
36 {
37 grefcount rc;
38 GMutex lock;
39 GHashTable *items;
40 GCancellable *cancellable;
41 GDBusConnection *conn;
42 };
43 typedef struct _Players Players;
44
45 struct _ItemUpdate {
46 Players *players;
47 gchar *bus_name;
48 };
49 typedef struct _ItemUpdate ItemUpdate;
50
51 struct _WpMprisPlugin
52 {
53 WpPlugin parent;
54 WpPlugin *dbus;
55 GDBusConnection *conn;
56 guint name_signal;
57 Players *players;
58 };
59
60 struct _WpMprisPluginOperation
61 {
62 GObject parent;
63 GDBusConnection *conn;
64 const char *name;
65 gint result;
66 };
67
68 enum {
69 ACTION_GET_PLAYERS,
70 ACTION_PAUSE,
71 ACTION_MATCH_PID,
72 N_SIGNALS
73 };
74
75 enum {
76 PROP_0,
77 PROP_RESULT
78 };
79
80 static guint signals[N_SIGNALS] = {0};
81
82 G_DECLARE_FINAL_TYPE (WpMprisPlugin, wp_mpris_plugin, WP, MPRIS_PLUGIN, WpPlugin)
83 G_DEFINE_TYPE (WpMprisPlugin, wp_mpris_plugin, WP_TYPE_PLUGIN)
84
85 #define WP_TYPE_MPRIS_PLUGIN_OPERATION wp_mpris_plugin_operation_get_type ()
86 G_DECLARE_FINAL_TYPE (WpMprisPluginOperation, wp_mpris_plugin_operation, WP, MPRIS_PLUGIN_OPERATION, GObject)
87 G_DEFINE_TYPE (WpMprisPluginOperation, wp_mpris_plugin_operation, G_TYPE_OBJECT)
88
89
90 /*
91 * Media Player items
92 *
93 * Since GDBus callbacks may be issued "late", use separate refcounted object.
94 * Although everything likely runs from main context, add locking to be sure.
95 */
96
97 static void item_free (gpointer data)
98 {
99 Item *item = data;
100
101 g_clear_pointer (&item->desktop_entry, g_free);
102 g_clear_pointer (&item->flatpak_app_id, g_free);
103 g_clear_pointer (&item->flatpak_instance_id, g_free);
104 g_free (item);
105 }
106
107 static Players *players_new (GDBusConnection *conn)
108 {
109 Players *players;
110
111 players = g_new0 (Players, 1);
112 g_ref_count_init(&players->rc);
113 g_mutex_init(&players->lock);
114 players->items = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, item_free);
115 players->cancellable = g_cancellable_new();
116 players->conn = g_object_ref (conn);
117
118 return players;
119 }
120
121 static Players *players_ref (Players *players)
122 {
123 g_ref_count_inc(&players->rc);
124 return players;
125 }
126
127 static void players_unref (Players *players)
128 {
129 if (!g_ref_count_dec(&players->rc))
130 return;
131
132 g_mutex_clear (&players->lock);
133 g_clear_pointer (&players->items, g_hash_table_unref);
134 g_clear_object (&players->conn);
135 g_clear_object (&players->cancellable);
136 g_free (players);
137 }
138
139 G_DEFINE_AUTOPTR_CLEANUP_FUNC (Players, players_unref)
140
141 static Item *players_ensure_item (Players *players, const gchar *bus_name)
142 {
143 Item *item;
144
145 item = g_hash_table_lookup (players->items, bus_name);
146 if (!item) {
147 item = g_new0 (Item, 1);
148 g_hash_table_insert (players->items, g_strdup (bus_name), item);
149 }
150
151 return item;
152 }
153
154 static ItemUpdate *item_update_new (Players *players, const gchar *bus_name)
155 {
156 ItemUpdate *update;
157
158 update = g_new0 (ItemUpdate, 1);
159 update->players = players_ref (players);
160 update->bus_name = g_strdup (bus_name);
161 return update;
162 }
163
164 static void item_update_free (ItemUpdate *update)
165 {
166 players_unref (update->players);
167 g_free (update->bus_name);
168 g_free (update);
169 }
170
171 G_DEFINE_AUTOPTR_CLEANUP_FUNC (ItemUpdate, item_update_free)
172
173 static void item_get_flatpak_app_id (ItemUpdate *update, Item *item)
174 {
175 spa_autofree char *app_id = NULL;
176 spa_autofree char *instance_id = NULL;
177 int res;
178
179 g_clear_pointer (&item->flatpak_app_id, g_free);
180 g_clear_pointer (&item->flatpak_instance_id, g_free);
181
182 if (!item->pid)
183 return;
184
185 res = pw_check_flatpak (item->pid, &app_id, &instance_id, NULL);
186 if (res < 0) {
187 wp_info ("%p: failed to get Flatpak status for '%s': %d (%s)", update->players, update->bus_name,
188 -res, spa_strerror (res));
189 return;
190 }
191
192 if (app_id)
193 item->flatpak_app_id = g_strdup (app_id);
194
195 if (instance_id)
196 item->flatpak_instance_id = g_strdup (instance_id);
197
198 wp_debug ("%p: player '%s' Flatpak App Id = %s, Instance Id = %s", update->players, update->bus_name,
199 item->flatpak_app_id ? item->flatpak_app_id : "-",
200 item->flatpak_instance_id ? item->flatpak_instance_id : "-");
201 }
202
203 static void item_pid_cb (GObject *source_object, GAsyncResult* res, gpointer data)
204 {
205 g_autoptr (ItemUpdate) update = data;
206 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&update->players->lock);
207 Item *item;
208 g_autoptr (GVariant) result = NULL;
209 g_autoptr (GError) error = NULL;
210
211 result = g_dbus_connection_call_finish (update->players->conn, res, &error);
212 if (!result) {
213 wp_info ("%p: failed to get PID for '%s': %s", update->players, update->bus_name, error->message);
214 return;
215 }
216
217 item = players_ensure_item (update->players, update->bus_name);
218 g_variant_get (result, "(u)", &item->pid);
219
220 wp_debug ("%p: player '%s' PID = %u", update->players, update->bus_name, item->pid);
221
222 item_get_flatpak_app_id (update, item);
223 }
224
225 static void item_desktop_entry_cb (GObject *source_object, GAsyncResult* res, gpointer data)
226 {
227 g_autoptr (ItemUpdate) update = data;
228 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&update->players->lock);
229 Item *item;
230 g_autoptr (GVariant) result = NULL;
231 g_autoptr (GVariant) value = NULL;
232 g_autoptr (GError) error = NULL;
233
234 result = g_dbus_connection_call_finish (update->players->conn, res, &error);
235 if (!result) {
236 wp_info ("%p: failed to get DesktopEntry for '%s': %s", update->players, update->bus_name, error->message);
237 return;
238 }
239
240 g_variant_get (result, "(v)", &value);
241 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_STRING)) {
242 wp_info ("%p: bad value for DesktopEntry for '%s'", update->players, update->bus_name);
243 return;
244 }
245
246 item = players_ensure_item (update->players, update->bus_name);
247 g_clear_pointer (&item->desktop_entry, g_free);
248 g_variant_get (value, "s", &item->desktop_entry);
249
250 wp_debug ("%p: player '%s' DesktopEntry = %s", update->players, update->bus_name, item->desktop_entry);
251 }
252
253 static void players_add (Players *players, const gchar *bus_name)
254 {
255 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&players->lock);
256 Item *item;
257
258 if (g_cancellable_is_cancelled (players->cancellable))
259 return;
260
261 wp_debug ("%p: add player '%s'", players, bus_name);
262
263 item = players_ensure_item (players, bus_name);
264 g_clear_pointer (&item->desktop_entry, g_free);
265 item->pid = 0;
266
267 g_dbus_connection_call (players->conn,
268 "org.freedesktop.DBus", "/org/freedesktop/DBus",
269 "org.freedesktop.DBus", "GetConnectionUnixProcessID",
270 g_variant_new ("(s)", bus_name), G_VARIANT_TYPE ("(u)"),
271 G_DBUS_CALL_FLAGS_NO_AUTO_START, PLAYER_TIMEOUT_MSEC,
272 players->cancellable, item_pid_cb, item_update_new (players, bus_name));
273
274 g_dbus_connection_call (players->conn,
275 bus_name, "/org/mpris/MediaPlayer2",
276 "org.freedesktop.DBus.Properties", "Get",
277 g_variant_new ("(ss)", "org.mpris.MediaPlayer2", "DesktopEntry"), G_VARIANT_TYPE ("(v)"),
278 G_DBUS_CALL_FLAGS_NO_AUTO_START, PLAYER_TIMEOUT_MSEC,
279 players->cancellable, item_desktop_entry_cb, item_update_new (players, bus_name));
280 }
281
282 static void players_remove (Players *players, const gchar *bus_name)
283 {
284 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&players->lock);
285
286 wp_debug ("%p: remove player '%s'", players, bus_name);
287 g_hash_table_remove (players->items, bus_name);
288 }
289
290
291 /*
292 * Media Player monitoring
293 */
294
295 static void on_name_owner_changed(GDBusConnection* connection,
296 const gchar* sender_name,
297 const gchar* object_path,
298 const gchar* interface_name,
299 const gchar* signal_name,
300 GVariant* parameters,
301 gpointer user_data)
302 {
303 Players *players = user_data;
304 const gchar *bus_name;
305 const gchar *old_owner;
306 const gchar *new_owner;
307
308 g_variant_get (parameters, "(&s&s&s)", &bus_name, &old_owner, &new_owner);
309
310 if (!g_str_has_prefix (bus_name, "org.mpris.MediaPlayer2."))
311 return;
312
313 if (strlen (new_owner) == 0)
314 players_remove (players, bus_name);
315 else
316 players_add (players, bus_name);
317 }
318
319 static void list_names_cb (GObject *source_object, GAsyncResult* res, gpointer data)
320 {
321 g_autoptr (Players) players = data;
322 g_autoptr (GVariant) result = NULL;
323 g_autoptr (GError) error = NULL;
324 GVariantIter *iter;
325 const gchar *bus_name;
326
327 result = g_dbus_connection_call_finish (players->conn, res, &error);
328 if (!result) {
329 wp_info ("%p: failed to ListNames: %s", players, error->message);
330 return;
331 }
332
333 g_variant_get (result, "(as)", &iter);
334 while (g_variant_iter_loop (iter, "&s", &bus_name)) {
335 if (!g_str_has_prefix (bus_name, "org.mpris.MediaPlayer2."))
336 continue;
337
338 players_add (players, bus_name);
339 }
340 g_variant_iter_free (iter);
341 }
342
343 static void do_list_names (Players *players)
344 {
345 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&players->lock);
346
347 if (g_cancellable_is_cancelled (players->cancellable))
348 return;
349
350 g_dbus_connection_call (players->conn,
351 "org.freedesktop.DBus", "/org/freedesktop/DBus",
352 "org.freedesktop.DBus", "ListNames",
353 NULL, G_VARIANT_TYPE ("(as)"),
354 G_DBUS_CALL_FLAGS_NO_AUTO_START, -1,
355 players->cancellable, list_names_cb, players_ref (players));
356 }
357
358 static void clear_state (WpMprisPlugin *self)
359 {
360 if (self->conn) {
361 if (self->name_signal) {
362 g_dbus_connection_signal_unsubscribe (self->conn, self->name_signal);
363 self->name_signal = 0;
364 }
365 g_clear_object (&self->conn);
366 }
367
368 if (self->players) {
369 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&self->players->lock);
370
371 g_cancellable_cancel (self->players->cancellable);
372 }
373 g_clear_pointer (&self->players, players_unref);
374 }
375
376 static void
377 on_dbus_state_changed (GObject * dbus, GParamSpec * spec,
378 WpMprisPlugin *self)
379 {
380 WpDBusConnectionState state = -1;
381 g_object_get (dbus, "state", &state, NULL);
382
383 switch (state) {
384 case WP_DBUS_CONNECTION_STATE_CONNECTED: {
385 g_autoptr (GDBusConnection) conn = NULL;
386
387 g_object_get (dbus, "connection", &conn, NULL);
388 g_return_if_fail (conn);
389 g_return_if_fail (!self->conn);
390 g_return_if_fail (!self->players);
391 g_return_if_fail (!self->name_signal);
392
393 self->players = players_new (conn);
394 self->conn = g_object_ref (conn);
395 self->name_signal = g_dbus_connection_signal_subscribe (conn,
396 "org.freedesktop.DBus", "org.freedesktop.DBus", "NameOwnerChanged",
397 "/org/freedesktop/DBus", "org.mpris.MediaPlayer2",
398 G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE, on_name_owner_changed,
399 players_ref (self->players), (GDestroyNotify) players_unref);
400
401 do_list_names (self->players);
402 break;
403 }
404
405 case WP_DBUS_CONNECTION_STATE_CONNECTING:
406 case WP_DBUS_CONNECTION_STATE_CLOSED:
407 clear_state (self);
408 break;
409
410 default:
411 g_assert_not_reached ();
412 }
413 }
414
415
416 /*
417 * WpMprisPluginOperation
418 */
419
420 static void
421 wp_mpris_plugin_operation_init (WpMprisPluginOperation * self)
422 {
423 }
424
425 static void
426 wp_mpris_plugin_operation_finalize (GObject *object)
427 {
428 WpMprisPluginOperation *self = WP_MPRIS_PLUGIN_OPERATION (object);
429
430 g_clear_object (&self->conn);
431
432 G_OBJECT_CLASS (wp_mpris_plugin_operation_parent_class)->finalize (object);
433 }
434
435 static void
436 wp_mpris_plugin_operation_get_property (GObject * object, guint property_id,
437 GValue * value, GParamSpec * pspec)
438 {
439 WpMprisPluginOperation *self = WP_MPRIS_PLUGIN_OPERATION (object);
440
441 switch (property_id) {
442 case PROP_RESULT:
443 g_value_set_int (value, self->result);
444 break;
445 default:
446 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
447 break;
448 }
449 }
450
451 static void
452 wp_mpris_plugin_operation_class_init (WpMprisPluginOperationClass * klass)
453 {
454 GObjectClass *object_class = (GObjectClass *) klass;
455
456 object_class->finalize = wp_mpris_plugin_operation_finalize;
457 object_class->get_property = wp_mpris_plugin_operation_get_property;
458
459 g_object_class_install_property (object_class, PROP_RESULT,
460 g_param_spec_int ("result", "result",
461 "Result from the operation (0 if not completed)", G_MININT, G_MAXINT, 0,
462 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
463 }
464
465 static WpMprisPluginOperation *
466 wp_mpris_plugin_operation_new (GDBusConnection *conn, const gchar *name)
467 {
468 WpMprisPluginOperation * self;
469
470 self = g_object_new (WP_TYPE_MPRIS_PLUGIN_OPERATION, NULL);
471 self->name = name;
472 if (conn)
473 self->conn = g_object_ref (conn);
474
475 return self;
476 }
477
478 static void
479 wp_mpris_plugin_operation_complete (WpMprisPluginOperation * self, gint result)
480 {
481 g_return_if_fail(result);
482 g_return_if_fail(!self->result);
483 self->result = result;
484 g_object_notify (G_OBJECT (self), "result");
485 }
486
487
488 /*
489 * WpMprisPlugin
490 */
491
492 static void
493 wp_mpris_plugin_init (WpMprisPlugin * self)
494 {
495 }
496
497 static void
498 wp_mpris_plugin_enable (WpPlugin * plugin, WpTransition * transition)
499 {
500 WpMprisPlugin *self = WP_MPRIS_PLUGIN (plugin);
501 g_autoptr (WpCore) core = wp_object_get_core (WP_OBJECT (self));
502
503 g_return_if_fail(!self->dbus);
504
505 self->dbus = wp_plugin_find (core, "dbus-connection");
506 if (!self->dbus) {
507 wp_transition_return_error (transition, g_error_new (WP_DOMAIN_LIBRARY,
508 WP_LIBRARY_ERROR_INVARIANT,
509 "dbus-connection module must be loaded before mpris"));
510 return;
511 }
512
513 g_signal_connect_object (self->dbus, "notify::state",
514 G_CALLBACK (on_dbus_state_changed), self, 0);
515 on_dbus_state_changed (G_OBJECT (self->dbus), NULL, self);
516
517 wp_object_update_features (WP_OBJECT (self), WP_PLUGIN_FEATURE_ENABLED, 0);
518 }
519
520 static void
521 wp_mpris_plugin_disable (WpPlugin * plugin)
522 {
523 WpMprisPlugin *self = WP_MPRIS_PLUGIN (plugin);
524
525 clear_state(self);
526 if (self->dbus)
527 g_signal_handlers_disconnect_by_data (self->dbus, self);
528 g_clear_object(&self->dbus);
529
530 wp_object_update_features (WP_OBJECT (self), 0, WP_PLUGIN_FEATURE_ENABLED);
531 }
532
533 static gpointer
534 wp_mpris_plugin_get_players (WpMprisPlugin *self)
535 {
536 g_auto (GVariantBuilder) b = G_VARIANT_BUILDER_INIT (G_VARIANT_TYPE ("av"));
537
538 if (self->players) {
539 g_autoptr (GMutexLocker) locker = g_mutex_locker_new (&self->players->lock);
540 GHashTableIter iter;
541 gpointer key, value;
542
543 g_hash_table_iter_init (&iter, self->players->items);
544 while (g_hash_table_iter_next (&iter, &key, &value)) {
545 const gchar *bus_name = key;
546 const Item *item = value;
547 g_auto (GVariantDict) dict = G_VARIANT_DICT_INIT (NULL);
548
549 g_variant_dict_insert (&dict, "name", "s", bus_name);
550 if (item->pid)
551 g_variant_dict_insert (&dict, "pid", "u", item->pid);
552 if (item->desktop_entry)
553 g_variant_dict_insert (&dict, "desktop-entry", "s", item->desktop_entry);
554 if (item->flatpak_app_id)
555 g_variant_dict_insert (&dict, "flatpak-app-id", "s", item->flatpak_app_id);
556 if (item->flatpak_instance_id)
557 g_variant_dict_insert (&dict, "flatpak-instance-id", "s", item->flatpak_instance_id);
558
559 g_variant_builder_add (&b, "v", g_variant_dict_end (&dict));
560 }
561 }
562
563 return g_variant_builder_end (&b);
564 }
565
566 static void operation_complete (GObject *source_object, GAsyncResult* res, gpointer data)
567 {
568 g_autoptr (WpMprisPluginOperation) op = data;
569 g_autoptr (GVariant) result = NULL;
570 g_autoptr (GError) error = NULL;
571
572 result = g_dbus_connection_call_finish (op->conn, res, &error);
573 if (!result) {
574 wp_info ("operation %s failed: %s", op->name ? op->name : "<?>", error->message);
575 wp_mpris_plugin_operation_complete (op, -EIO);
576 return;
577 }
578
579 wp_mpris_plugin_operation_complete (op, 1);
580 }
581
582 static WpMprisPluginOperation *
583 wp_mpris_plugin_pause (WpMprisPlugin *self, const gchar *bus_name)
584 {
585 g_autoptr (GVariant) result = NULL;
586 WpMprisPluginOperation *op;
587
588 op = wp_mpris_plugin_operation_new (self->conn, "Pause");
589
590 if (!self->conn) {
591 wp_mpris_plugin_operation_complete (op, -EIO);
592 return op;
593 }
594
595 g_dbus_connection_call (self->conn,
596 bus_name, "/org/mpris/MediaPlayer2",
597 "org.mpris.MediaPlayer2.Player", "Pause",
598 NULL, NULL, G_DBUS_CALL_FLAGS_NONE, PLAYER_TIMEOUT_MSEC,
599 NULL, operation_complete, g_object_ref (op));
600
601 return op;
602 }
603
604 static pid_t get_parent_pid(pid_t pid)
605 {
606 g_autofree gchar *path = NULL;
607 g_autofree gchar *stat = NULL;
608 int ppid;
609
610 path = g_strdup_printf ("/proc/%d/stat", (int)pid);
611 if (!g_file_get_contents (path, &stat, NULL, NULL))
612 return 0;
613
614 if (sscanf (stat, "%*d %*s %*s %d", &ppid) == 1)
615 return ppid;
616
617 return 0;
618 }
619
620 static gboolean
621 match_pid(pid_t parent, pid_t child)
622 {
623 pid_t p = child;
624 int j;
625
626 for (j = 0; j < 100 && p > 1; ++j, p = get_parent_pid(p)) {
627 if (parent == p) {
628 wp_trace ("matched pid: %d is %d-child of %d", (int)child, j, (int)parent);
629 return TRUE;
630 }
631 }
632 return FALSE;
633 }
634
635 static gboolean
636 wp_mpris_plugin_match_pid (WpMprisPlugin *self, gint parent, gint child)
637 {
638 return match_pid(parent, child);
639 }
640
641 static void
642 wp_mpris_plugin_class_init (WpMprisPluginClass * klass)
643 {
644 WpPluginClass *plugin_class = (WpPluginClass *) klass;
645
646 plugin_class->enable = wp_mpris_plugin_enable;
647 plugin_class->disable = wp_mpris_plugin_disable;
648
649 signals[ACTION_GET_PLAYERS] = g_signal_new_class_handler (
650 "get-players", G_TYPE_FROM_CLASS (klass),
651 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
652 (GCallback) wp_mpris_plugin_get_players,
653 NULL, NULL, NULL, G_TYPE_VARIANT, 0);
654 signals[ACTION_PAUSE] = g_signal_new_class_handler (
655 "pause", G_TYPE_FROM_CLASS (klass),
656 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
657 (GCallback) wp_mpris_plugin_pause,
658 NULL, NULL, NULL, WP_TYPE_MPRIS_PLUGIN_OPERATION, 1, G_TYPE_STRING);
659 signals[ACTION_MATCH_PID] = g_signal_new_class_handler (
660 "match-pid", G_TYPE_FROM_CLASS (klass),
661 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
662 (GCallback) wp_mpris_plugin_match_pid,
663 NULL, NULL, NULL, G_TYPE_BOOLEAN, 2, G_TYPE_INT, G_TYPE_INT);
664 }
665
666
667 /*
668 * Module
669 */
670
671 WP_PLUGIN_EXPORT GObject *
672 wireplumber__module_init (WpCore * core, WpSpaJson * args, GError ** error)
673 {
674 return G_OBJECT (g_object_new (wp_mpris_plugin_get_type (),
675 "name", NAME,
676 "core", core,
677 NULL));
678 }