//- mpris
// NOTE: the player as org.mpris.MediaPlayer2.mp3_player on the session bus, so playerctl, media
// keys bound to it, waybar's mpris module, desktop widgets and bluetooth headset buttons (via
// mpris-proxy) all control it. spec: https://specifications.freedesktop.org/mpris-spec/latest/
//
// same machinery as the control socket: the actions are player_command's, and change detection
// is a PlayerSnapshot compare that turns into PropertiesChanged signals. everything runs on the
// main thread from the poll it already sleeps in.
#define MPRIS_PATH "/org/mpris/MediaPlayer2"
#define MPRIS_ROOT "org.mpris.MediaPlayer2"
#define MPRIS_PLAYER "org.mpris.MediaPlayer2.Player"
#define MPRIS_PROPERTIES "org.freedesktop.DBus.Properties"
#define MPRIS_NO_TRACK "/org/mpris/MediaPlayer2/TrackList/NoTrack"
typedef struct Mpris Mpris;
struct Mpris {
App *app;
DBusConnection bus;
b32 active;
char name[96];
PlayerSnapshot published;
b32 any_published;
s64 last_position_us; // for Seeked: where playback should be by now
u64 last_check_ns;
u32 last_key;
};
global_variable const char mpris_introspection[] =
"\n"
"\n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
"\n";
global_variable const char *mpris_root_properties[] = {"CanQuit", "CanRaise", "HasTrackList", "Identity", "DesktopEntry", "SupportedUriSchemes", "SupportedMimeTypes"};
global_variable const char *mpris_player_properties[] = {"PlaybackStatus", "Rate", "Metadata", "Volume", "Position", "MinimumRate", "MaximumRate",
"CanGoNext", "CanGoPrevious", "CanPlay", "CanPause", "CanSeek", "CanControl"};
internal s64 mpris_position_us(App *app)
{
u32 key = app_current_key(app);
if(key == TRACK_NONE || !(app->position.flags & PLAYBACK_HAS_TRACK) || app->position.track_key != key || !app->position.rate) return 0;
return (s64)(app->position.frame * 1000000ull / app->position.rate);
}
internal void mpris_track_id(char *out, u32 size, u32 key)
{
if(key == TRACK_NONE) snprintf(out, size, MPRIS_NO_TRACK);
else snprintf(out, size, "/org/mp3_player/track/%u", key);
}
//- property values
internal void mpris_dict_entry_begin(DBusWriter *w, const char *key, const char *signature)
{
dbus_w_align(w, 8);
dbus_w_cstring(w, key);
dbus_w_signature(w, signature);
}
internal void mpris_write_metadata(Mpris *mpris, DBusWriter *w, PlayerSnapshot *snapshot)
{
App *app = mpris->app;
u32 array = dbus_w_array_begin(w, 8);
char track_id[64];
mpris_track_id(track_id, sizeof(track_id), snapshot->key);
mpris_dict_entry_begin(w, "mpris:trackid", "o");
dbus_w_cstring(w, track_id);
if(snapshot->key != TRACK_NONE) {
Qari *qari = &app->catalog->qaris[TrackQari(snapshot->key)];
Surah *surah = &app->catalog->surahs[TrackSurah(snapshot->key)];
char title[160];
snprintf(title, sizeof(title), "%u. " Str8Fmt, TrackSurah(snapshot->key) + 1, Str8Arg(surah->name));
mpris_dict_entry_begin(w, "xesam:title", "s");
dbus_w_cstring(w, title);
mpris_dict_entry_begin(w, "xesam:artist", "as");
u32 artists = dbus_w_array_begin(w, 4);
dbus_w_string(w, qari->name);
dbus_w_array_end(w, artists);
mpris_dict_entry_begin(w, "xesam:album", "s");
dbus_w_cstring(w, "Quran");
mpris_dict_entry_begin(w, "xesam:trackNumber", "i");
dbus_w_i32(w, (s32)TrackSurah(snapshot->key) + 1);
mpris_dict_entry_begin(w, "xesam:comment", "as");
u32 comments = dbus_w_array_begin(w, 4);
dbus_w_string(w, surah->english);
dbus_w_array_end(w, comments);
if(snapshot->duration_s) {
u64 total = app_track_total(app);
u32 rate = app->position.rate ? app->position.rate : 44100;
mpris_dict_entry_begin(w, "mpris:length", "x");
dbus_w_i64(w, (s64)(total * 1000000ull / rate));
}
if(snapshot->downloaded == 1000) {
char path[1024], url[1100];
if(store_track_path(app->store, snapshot->key, false, path, sizeof(path))) {
snprintf(url, sizeof(url), "file://%s", path);
mpris_dict_entry_begin(w, "xesam:url", "s");
dbus_w_cstring(w, url);
}
}
}
dbus_w_array_end(w, array);
}
// NOTE: writes the variant (signature + value) of one property. false = no such property.
internal b32 mpris_write_property(Mpris *mpris, DBusWriter *w, String8 interface, String8 name)
{
App *app = mpris->app;
PlayerSnapshot snapshot = player_snapshot(app);
b32 stopped = (snapshot.key == TRACK_NONE);
#define IS(text) str8_is_match(name, str8((char *)(text)))
if(str8_is_match(interface, str8((char *)MPRIS_ROOT))) {
if(IS("CanQuit")) { dbus_w_signature(w, "b"); dbus_w_bool(w, true); return true; }
if(IS("CanRaise")) { dbus_w_signature(w, "b"); dbus_w_bool(w, false); return true; }
if(IS("HasTrackList")) { dbus_w_signature(w, "b"); dbus_w_bool(w, false); return true; }
if(IS("Identity")) { dbus_w_signature(w, "s"); dbus_w_cstring(w, "Quran Player"); return true; }
if(IS("DesktopEntry")) { dbus_w_signature(w, "s"); dbus_w_cstring(w, "mp3_player"); return true; }
if(IS("SupportedUriSchemes") || IS("SupportedMimeTypes")) {
dbus_w_signature(w, "as");
dbus_w_array_end(w, dbus_w_array_begin(w, 4));
return true;
}
return false;
}
if(!str8_is_match(interface, str8((char *)MPRIS_PLAYER))) return false;
if(IS("PlaybackStatus")) {
const char *status = (snapshot.state == PLAYER_STOPPED) ? "Stopped" : (snapshot.state == PLAYER_PAUSED) ? "Paused" : "Playing";
dbus_w_signature(w, "s");
dbus_w_cstring(w, status);
return true;
}
if(IS("Rate") || IS("MinimumRate") || IS("MaximumRate")) { dbus_w_signature(w, "d"); dbus_w_f64(w, 1.0); return true; }
if(IS("Metadata")) { dbus_w_signature(w, "a{sv}"); mpris_write_metadata(mpris, w, &snapshot); return true; }
if(IS("Volume")) { dbus_w_signature(w, "d"); dbus_w_f64(w, round(app->settings.volume * 100.0) / 100.0); return true; } // stored as f32: 0.3 not 0.30000001
if(IS("Position")) { dbus_w_signature(w, "x"); dbus_w_i64(w, mpris_position_us(app)); return true; }
if(IS("CanGoNext")) { dbus_w_signature(w, "b"); dbus_w_bool(w, !stopped && TrackSurah(snapshot.key) + 1 < SURAH_COUNT); return true; }
if(IS("CanGoPrevious")) { dbus_w_signature(w, "b"); dbus_w_bool(w, !stopped && TrackSurah(snapshot.key) > 0); return true; }
if(IS("CanPlay")) { dbus_w_signature(w, "b"); dbus_w_bool(w, app->audio_ok); return true; }
if(IS("CanPause") || IS("CanControl")) { dbus_w_signature(w, "b"); dbus_w_bool(w, app->audio_ok); return true; }
if(IS("CanSeek")) { dbus_w_signature(w, "b"); dbus_w_bool(w, !stopped); return true; }
#undef IS
return false;
}
internal void mpris_write_all(Mpris *mpris, DBusWriter *w, String8 interface)
{
b32 root = str8_is_match(interface, str8((char *)MPRIS_ROOT));
const char **names = root ? mpris_root_properties : mpris_player_properties;
u32 count = root ? ArrayCount(mpris_root_properties) : ArrayCount(mpris_player_properties);
u32 array = dbus_w_array_begin(w, 8);
if(root || str8_is_match(interface, str8((char *)MPRIS_PLAYER))) {
for(u32 index = 0; index < count; ++index) {
dbus_w_align(w, 8);
dbus_w_cstring(w, names[index]);
mpris_write_property(mpris, w, interface, str8((char *)names[index]));
}
}
dbus_w_array_end(w, array);
}
//- method calls
internal void mpris_run(Mpris *mpris, const char *command)
{
char line[64], error[128];
snprintf(line, sizeof(line), "%s", command);
player_command(mpris->app, line, error, sizeof(error));
}
internal void mpris_handle(void *user, DBusConnection *bus, DBusMessage *message)
{
Mpris *mpris = (Mpris *)user;
App *app = mpris->app;
if(message->type != DBUS_METHOD_CALL) return; // NameAcquired and friends
u8 body[4096];
DBusWriter w;
dbus_w_init(&w, body, sizeof(body));
DBusReader args = dbus_body(message);
#define CALL(iface, method) (str8_is_match(message->interface, str8((char *)(iface))) && str8_is_match(message->member, str8((char *)(method))))
if(CALL("org.freedesktop.DBus.Peer", "Ping")) {
dbus_reply(bus, message, "", NULL, 0);
return;
}
if(!str8_is_match(message->path, str8((char *)MPRIS_PATH))) {
dbus_reply_error(bus, message, "org.freedesktop.DBus.Error.UnknownObject", "no such object");
return;
}
if(CALL("org.freedesktop.DBus.Introspectable", "Introspect")) {
u8 xml[sizeof(mpris_introspection) + 16];
DBusWriter x;
dbus_w_init(&x, xml, sizeof(xml));
dbus_w_cstring(&x, mpris_introspection);
dbus_reply(bus, message, "s", xml, x.size);
} else if(CALL(MPRIS_PROPERTIES, "Get")) {
String8 interface = dbus_r_string(&args);
String8 name = dbus_r_string(&args);
if(args.bad || !mpris_write_property(mpris, &w, interface, name)) {
dbus_reply_error(bus, message, "org.freedesktop.DBus.Error.UnknownProperty", "no such property");
return;
}
dbus_reply(bus, message, "v", body, w.size);
} else if(CALL(MPRIS_PROPERTIES, "GetAll")) {
String8 interface = dbus_r_string(&args);
mpris_write_all(mpris, &w, interface);
dbus_reply(bus, message, "a{sv}", body, w.size);
} else if(CALL(MPRIS_PROPERTIES, "Set")) {
String8 interface = dbus_r_string(&args);
String8 name = dbus_r_string(&args);
String8 signature = dbus_r_signature(&args);
if(str8_is_match(interface, str8((char *)MPRIS_PLAYER)) && str8_is_match(name, str8((char *)"Volume")) &&
str8_is_match(signature, str8((char *)"d"))) {
f64 volume = dbus_r_f64(&args);
if(!args.bad) app_set_volume(app, (f32)Clamp(volume, 0.0, 1.0));
dbus_reply(bus, message, "", NULL, 0);
} else {
dbus_reply_error(bus, message, "org.freedesktop.DBus.Error.PropertyReadOnly", "only Volume can be set");
}
} else if(CALL(MPRIS_ROOT, "Raise")) {
dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_ROOT, "Quit")) {
app->quit = true;
dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "PlayPause")) { mpris_run(mpris, "toggle"); dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "Play")) { mpris_run(mpris, "play"); dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "Pause")) { mpris_run(mpris, "pause"); dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "Stop")) { mpris_run(mpris, "stop"); dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "Next")) { mpris_run(mpris, "next"); dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "Previous")) { mpris_run(mpris, "prev"); dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "Seek")) {
s64 offset = dbus_r_i64(&args);
if(!args.bad) app_seek_seconds(app, (f64)offset / 1e6);
dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "SetPosition")) {
// NOTE: ignored unless it names the current track (the spec's guard against stale clients)
String8 track = dbus_r_string(&args);
s64 position = dbus_r_i64(&args);
char current[64];
mpris_track_id(current, sizeof(current), app_current_key(app));
u64 total_us = app->position.rate ? app_track_total(app) * 1000000ull / app->position.rate : 0;
if(!args.bad && str8_is_match(track, str8(current)) && position >= 0 && (u64)position <= total_us && app->position.rate) {
decoder_command(app->decoder, DECODER_SEEK, 0, (u64)position * app->position.rate / 1000000ull);
}
dbus_reply(bus, message, "", NULL, 0);
} else if(CALL(MPRIS_PLAYER, "OpenUri")) {
dbus_reply_error(bus, message, "org.freedesktop.DBus.Error.NotSupported", "play surahs with mp3_player ctl play ");
} else {
dbus_reply_error(bus, message, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method");
}
#undef CALL
}
//- lifecycle
internal b32 mpris_open(Mpris *mpris, App *app)
{
MemSetZero(mpris, sizeof(*mpris));
mpris->app = app;
mpris->bus.fd = -1;
mpris->last_key = TRACK_NONE;
if(getenv("MP3_PLAYER_NO_MPRIS")) return false;
if(!dbus_connect_session(&mpris->bus)) {
Log("mpris: no session bus, media keys via playerctl won't reach us");
return false;
}
// NOTE: the well known name, or a per instance one when another player already has it (the
// spec's convention, playerctl lists both). MP3_PLAYER_MPRIS_NAME renames it (tests).
const char *base = getenv("MP3_PLAYER_MPRIS_NAME");
for(u32 attempt = 0; attempt < 2; ++attempt) {
if(attempt == 0) snprintf(mpris->name, sizeof(mpris->name), MPRIS_ROOT ".%s", base ? base : "mp3_player");
else snprintf(mpris->name, sizeof(mpris->name), MPRIS_ROOT ".%s.instance%d", base ? base : "mp3_player", (int)getpid());
u8 body[256];
DBusWriter w;
dbus_w_init(&w, body, sizeof(body));
dbus_w_cstring(&w, mpris->name);
dbus_w_u32(&w, 4); // DBUS_NAME_FLAG_DO_NOT_QUEUE
DBusMessage reply;
if(!dbus_call(&mpris->bus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", "su", body, w.size, &reply, 1000000000ull)) break;
DBusReader r = dbus_body(&reply);
u32 result = dbus_r_u32(&r);
if(result == 1 || result == 4) { // primary owner / already owner
mpris->active = true;
// NOTE: from here on the socket is only read from the main loop's poll, never blocking
struct timeval none = {};
setsockopt(mpris->bus.fd, SOL_SOCKET, SO_RCVTIMEO, &none, sizeof(none));
return true;
}
}
Log("mpris: couldn't get a bus name");
dbus_close(&mpris->bus);
return false;
}
internal void mpris_close(Mpris *mpris)
{
dbus_close(&mpris->bus); // the bus releases our name when the connection drops
mpris->active = false;
}
internal int mpris_fd(Mpris *mpris)
{
return mpris->active ? mpris->bus.fd : -1;
}
internal void mpris_poll(Mpris *mpris)
{
if(mpris->active && !dbus_poll(&mpris->bus, mpris_handle, mpris)) {
Log("mpris: lost the session bus");
mpris->active = false;
}
}
internal void mpris_emit_changed(Mpris *mpris, const char *interface, const char **names, u32 count)
{
u8 body[4096];
DBusWriter w;
dbus_w_init(&w, body, sizeof(body));
dbus_w_cstring(&w, interface);
u32 array = dbus_w_array_begin(&w, 8);
for(u32 index = 0; index < count; ++index) {
dbus_w_align(&w, 8);
dbus_w_cstring(&w, names[index]);
mpris_write_property(mpris, &w, str8((char *)interface), str8((char *)names[index]));
}
dbus_w_array_end(&w, array);
dbus_w_array_end(&w, dbus_w_array_begin(&w, 4)); // invalidated: none, we always send values
if(!w.overflow) dbus_send(&mpris->bus, DBUS_SIGNAL, DBUS_FLAG_NO_REPLY_EXPECTED, MPRIS_PATH, MPRIS_PROPERTIES, "PropertiesChanged", NULL, 0, NULL, "sa{sv}as", body, w.size);
}
// NOTE: once per loop pass. clients cache properties and only hear about changes, so every
// change to something they show has to be signalled. Position is the exception (the spec says
// clients extrapolate it): only jumps are announced, through Seeked.
internal void mpris_publish(Mpris *mpris)
{
if(!mpris->active) return;
App *app = mpris->app;
PlayerSnapshot snapshot = player_snapshot(app);
//- jumps in position (seek, or a track restarted)
u64 now = time_now_ns();
s64 position = mpris_position_us(app);
if(snapshot.key != TRACK_NONE && snapshot.key == mpris->last_key && mpris->last_check_ns) {
s64 expected = mpris->last_position_us + ((snapshot.state == PLAYER_PLAYING) ? (s64)((now - mpris->last_check_ns) / 1000) : 0);
s64 off = position - expected;
if(off > 1500000 || off < -1500000) {
u8 body[16];
DBusWriter w;
dbus_w_init(&w, body, sizeof(body));
dbus_w_i64(&w, position);
dbus_send(&mpris->bus, DBUS_SIGNAL, DBUS_FLAG_NO_REPLY_EXPECTED, MPRIS_PATH, MPRIS_PLAYER, "Seeked", NULL, 0, NULL, "x", body, w.size);
}
}
mpris->last_position_us = position;
mpris->last_check_ns = now;
mpris->last_key = snapshot.key;
//- property changes. position_s changes every second and isn't a property: compare without it
PlayerSnapshot a = snapshot, b = mpris->published;
a.position_s = b.position_s = 0;
if(mpris->any_published && memcmp(&a, &b, sizeof(a)) == 0) return;
const char *names[8];
u32 count = 0;
b32 first = !mpris->any_published;
if(first || snapshot.state != mpris->published.state) names[count++] = "PlaybackStatus";
if(first || snapshot.key != mpris->published.key || snapshot.duration_s != mpris->published.duration_s ||
(snapshot.downloaded == 1000) != (mpris->published.downloaded == 1000)) {
names[count++] = "Metadata";
names[count++] = "CanGoNext";
names[count++] = "CanGoPrevious";
names[count++] = "CanSeek";
}
if(first || snapshot.volume != mpris->published.volume) names[count++] = "Volume";
mpris->published = snapshot;
mpris->any_published = true;
if(count) mpris_emit_changed(mpris, MPRIS_PLAYER, names, count);
}
// NOTE: track changes come from the audio threads (autoplay, a queue moving on), which don't wake
// the main loop. while something plays, look once a second so clients see them, also with the
// window hidden. -1 = no deadline.
internal s64 mpris_timeout(Mpris *mpris)
{
if(!mpris->active || mpris->app->paused || app_current_key(mpris->app) == TRACK_NONE) return -1;
return 1000000000ll;
}