Something went wrong. Try again.
MPRIS for Zig: a media player's side of the D-Bus remote control interfaces, on mdbus and zig-dbus-service.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An MPRIS player on the session bus.//!//! A program hands over two things: a `Player.snapshot` that describes what//! it is doing, and the `Player` commands it can carry out. The server owns//! `org.mpris.MediaPlayer2.<name>`, serves the four MPRIS interfaces at//! `/org/mpris/MediaPlayer2` from the latest snapshot, and turns calls from//! desktop shells, media keys and `playerctl` into commands.//!//! Whenever the program's state changes it calls `update`, from any thread.//! That takes a new snapshot, compares it with the last, and says what//! changed the way the specification asks://!//! - `PropertiesChanged` for the properties whose values differ;//! - `Seeked` when the position jumped within the same track -- the one//! position change the specification signals, since `Position` itself//! changes all the time and never emits;//! - `TrackListReplaced` when the list of tracks is a different list.//!//! `Position` is read live: the snapshot's position moved on by the time//! since it was taken, while playing.
const Server = @This();
const std = @import("std");const Io = std.Io;const mdbus = @import("mdbus");const dbus = @import("dbus_service");
const state = @import("state.zig");const State = state.State;const Metadata = state.Metadata;const Playlist = state.Playlist;const LoopStatus = state.LoopStatus;
const log = std.log.scoped(.mpris);
pub const object_path = "/org/mpris/MediaPlayer2";pub const bus_name_prefix = "org.mpris.MediaPlayer2.";pub const root_interface = "org.mpris.MediaPlayer2";pub const player_interface = "org.mpris.MediaPlayer2.Player";pub const tracklist_interface = "org.mpris.MediaPlayer2.TrackList";pub const playlists_interface = "org.mpris.MediaPlayer2.Playlists";
/// How far the position may be from where it would have got to by itself/// before the difference is a seek rather than a report arriving a little/// early or late.const seek_threshold_us = 1_500_000;
pub const Options = struct { /// The last element of the bus name, `org.mpris.MediaPlayer2.<name>`. name: []const u8, /// What the player calls itself: "Pipit". identity: []const u8, /// The basename of its `.desktop` file, without the extension, so a /// shell can find its icon. desktop_entry: []const u8 = "", supported_uri_schemes: []const []const u8 = &.{}, supported_mime_types: []const []const u8 = &.{}, /// Whether to serve `org.mpris.MediaPlayer2.TrackList`. track_list: bool = true, /// Whether to serve `org.mpris.MediaPlayer2.Playlists`. playlists: bool = true,};
/// What the program does for the server. Commands are called on the/// server's thread and should hand their work off rather than do it there,/// since nothing else is answered while one runs. A command left null is/// one the player cannot do.pub const Player = struct { context: *anyopaque, /// Describe the player now. Everything it puts in `out` must be /// allocated in `arena` or outlive the server: the server keeps the /// snapshot until the next one. snapshot: *const fn (context: *anyopaque, arena: std.mem.Allocator, out: *State) anyerror!void,
raise: ?*const fn (context: *anyopaque) void = null, quit: ?*const fn (context: *anyopaque) void = null, next: ?*const fn (context: *anyopaque) void = null, previous: ?*const fn (context: *anyopaque) void = null, play: ?*const fn (context: *anyopaque) void = null, pause: ?*const fn (context: *anyopaque) void = null, play_pause: ?*const fn (context: *anyopaque) void = null, stop: ?*const fn (context: *anyopaque) void = null, /// Go to `position_us` in the current track. `Seek`, which is relative, /// arrives here as an absolute position. set_position: ?*const fn (context: *anyopaque, position_us: i64) void = null, open_uri: ?*const fn (context: *anyopaque, uri: []const u8) void = null, set_loop_status: ?*const fn (context: *anyopaque, status: LoopStatus) void = null, set_shuffle: ?*const fn (context: *anyopaque, shuffle: bool) void = null, set_volume: ?*const fn (context: *anyopaque, volume: f64) void = null, /// Play the track with this id from the track list. go_to: ?*const fn (context: *anyopaque, trackid: []const u8) void = null, /// Play the playlist with this id. activate_playlist: ?*const fn (context: *anyopaque, id: []const u8) void = null,};
gpa: std.mem.Allocator,io: Io,options: Options,player: Player,service: dbus.Service,interfaces_buf: [4]*const dbus.Interface,objects: [1]dbus.Object,bus_name_buf: [256]u8 = undefined,bus_name: []const u8 = "",
/// Held by `update` while it replaces the snapshot, and by every getter/// while it reads it.mutex: Io.Mutex = .init,arena: std.heap.ArenaAllocator,current: State = .{},taken_at: Io.Timestamp,
/// Make a server. `connection` is borrowed, and belongs to the server's/// thread from `run` until it returns. The server must not move, so it is/// allocated here.pub fn create(gpa: std.mem.Allocator, io: Io, connection: *mdbus.Connection, options: Options, player: Player) !*Server { const self = try gpa.create(Server); errdefer gpa.destroy(self); self.* = .{ .gpa = gpa, .io = io, .options = options, .player = player, .service = undefined, .interfaces_buf = undefined, .objects = undefined, .arena = .init(gpa), .taken_at = .now(io, .awake), }; var n: usize = 0; self.interfaces_buf[n] = &root; n += 1; self.interfaces_buf[n] = &player_iface; n += 1; if (options.track_list) { self.interfaces_buf[n] = &tracklist; n += 1; } if (options.playlists) { self.interfaces_buf[n] = &playlists; n += 1; } self.objects = .{.{ .path = object_path, .context = self, .interfaces = self.interfaces_buf[0..n] }}; self.service = try .init(gpa, io, connection, &self.objects); return self;}
pub fn destroy(self: *Server) void { self.service.deinit(); self.arena.deinit(); self.gpa.destroy(self);}
/// Take the first snapshot and own the bus name: `org.mpris.MediaPlayer2.<name>`,/// or, if another player already has that, the same with `.instance<pid>`/// after it, as the specification says a second instance should. Call it/// before `run`.pub fn start(self: *Server) !void { try self.update(); const plain = try std.fmt.bufPrint(&self.bus_name_buf, "{s}{s}", .{ bus_name_prefix, self.options.name }); self.service.requestName(plain) catch |err| switch (err) { error.NameTaken => { const pid = std.os.linux.getpid(); const instance = try std.fmt.bufPrint(&self.bus_name_buf, "{s}{s}.instance{d}", .{ bus_name_prefix, self.options.name, pid }); try self.service.requestName(instance); self.bus_name = instance; return; }, else => return err, }; self.bus_name = plain;}
/// Serve until `stop`. On a thread of its own.pub fn run(self: *Server) !void { return self.service.run();}
/// Make `run` return. Safe from any thread.pub fn stop(self: *Server) void { self.service.stop();}
/// The player's state has changed: take a new snapshot, and tell the bus/// what is different. Safe from any thread.pub fn update(self: *Server) !void { var next_arena: std.heap.ArenaAllocator = .init(self.gpa); errdefer next_arena.deinit(); var next: State = .{}; try self.player.snapshot(self.player.context, next_arena.allocator(), &next); const now: Io.Timestamp = .now(self.io, .awake);
var old_arena: std.heap.ArenaAllocator = undefined; const old: State, const old_taken = blk: { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); const o = self.current; const t = self.taken_at; old_arena = self.arena; self.arena = next_arena; self.current = next; self.taken_at = now; break :blk .{ o, t }; }; defer old_arena.deinit();
const changes = diff(old, next); if (changes.player.len > 0) try self.service.propertiesChanged(object_path, player_interface, changes.player.slice()); if (self.options.playlists and changes.playlists.len > 0) { try self.service.propertiesChanged(object_path, playlists_interface, changes.playlists.slice()); } if (self.options.track_list and changes.tracks) { try self.service.propertiesChanged(object_path, tracklist_interface, &.{"Tracks"}); try self.emitTrackListReplaced(next); }
// A seek is a jump in position within one track: where it is now is not // where it would have got to since the last snapshot. if (std.mem.eql(u8, old.metadata.trackid, next.metadata.trackid)) { const since: i64 = @intCast(@divTrunc(old_taken.durationTo(now).nanoseconds, std.time.ns_per_us)); const expected = if (old.playback_status == .Playing) old.position_us + since else old.position_us; if (@abs(next.position_us - expected) > seek_threshold_us) try self.emitSeeked(next.position_us); }}
pub const Changes = struct { player: Names = .{}, playlists: Names = .{}, tracks: bool = false,
pub const Names = struct { buf: [16][]const u8 = undefined, len: usize = 0,
fn add(self: *Names, name: []const u8) void { self.buf[self.len] = name; self.len += 1; }
pub fn slice(self: *const Names) []const []const u8 { return self.buf[0..self.len]; } };};
/// What differs between two snapshots, by property name.pub fn diff(old: State, new: State) Changes { var c: Changes = .{}; if (old.playback_status != new.playback_status) c.player.add("PlaybackStatus"); if (old.loop_status != new.loop_status) c.player.add("LoopStatus"); if (old.shuffle != new.shuffle) c.player.add("Shuffle"); if (old.volume != new.volume) c.player.add("Volume"); if (!old.metadata.eql(new.metadata)) c.player.add("Metadata"); if (old.can_go_next != new.can_go_next) c.player.add("CanGoNext"); if (old.can_go_previous != new.can_go_previous) c.player.add("CanGoPrevious"); if (old.can_play != new.can_play) c.player.add("CanPlay"); if (old.can_pause != new.can_pause) c.player.add("CanPause"); if (old.can_seek != new.can_seek) c.player.add("CanSeek"); if (old.playlists.len != new.playlists.len) c.playlists.add("PlaylistCount"); const old_active = old.active_playlist; const new_active = new.active_playlist; const active_same = if (old_active == null or new_active == null) old_active == null and new_active == null else old_active.?.eql(new_active.?); if (!active_same) c.playlists.add("ActivePlaylist"); c.tracks = !state.tracksEql(old.tracks, new.tracks); return c;}
fn emitSeeked(self: *Server, position_us: i64) !void { var body: dbus.Encoder = .init(self.gpa); defer body.deinit(); try body.int64(position_us); try self.service.emitSignal(object_path, player_interface, "Seeked", "x", body.bytes());}
fn emitTrackListReplaced(self: *Server, s: State) !void { var body: dbus.Encoder = .init(self.gpa); defer body.deinit(); const list = try body.beginArray('o'); for (s.tracks) |t| try body.objectPath(validPath(t.trackid)); try body.endArray(list); try body.objectPath(validPath(s.metadata.trackid)); try self.service.emitSignal(object_path, tracklist_interface, "TrackListReplaced", "aoo", body.bytes());}
fn validPath(p: []const u8) []const u8 { return if (mdbus.wire.validObjectPath(p)) p else state.no_track;}
// --- reading the snapshot, on the service's thread ---------------------------
fn from(context: *anyopaque) *Server { return @ptrCast(@alignCast(context));}
/// Run `f` with the current snapshot, locked.fn read(context: *anyopaque, value: *dbus.Encoder, comptime f: fn (*Server, State, *dbus.Encoder) anyerror!void) anyerror!void { const self = from(context); self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); return f(self, self.current, value);}
/// Where the track is now: the snapshot's position, moved on while playing.fn positionNow(self: *Server, s: State) i64 { var p = s.position_us; if (s.playback_status == .Playing) { const since = self.taken_at.durationTo(.now(self.io, .awake)); p += @intCast(@divTrunc(since.nanoseconds, std.time.ns_per_us)); } if (s.metadata.length_us) |len| p = @min(p, len); return @max(p, 0);}
fn writeStrings(enc: *dbus.Encoder, list: []const []const u8) !void { const a = try enc.beginArray('s'); for (list) |s| try enc.string(s); try enc.endArray(a);}
/// A track as the `a{sv}` MPRIS metadata is: only what it has.pub fn writeMetadata(enc: *dbus.Encoder, m: Metadata) !void { const dict = try enc.beginArray('{'); try entry(enc, "mpris:trackid", "o"); try enc.objectPath(validPath(m.trackid)); if (m.length_us) |v| { try entry(enc, "mpris:length", "x"); try enc.int64(v); } if (m.art_url) |v| { try entry(enc, "mpris:artUrl", "s"); try enc.string(v); } if (m.title) |v| { try entry(enc, "xesam:title", "s"); try enc.string(v); } if (m.artists.len > 0) { try entry(enc, "xesam:artist", "as"); try writeStrings(enc, m.artists); } if (m.album) |v| { try entry(enc, "xesam:album", "s"); try enc.string(v); } if (m.album_artists.len > 0) { try entry(enc, "xesam:albumArtist", "as"); try writeStrings(enc, m.album_artists); } if (m.track_number) |v| { try entry(enc, "xesam:trackNumber", "i"); try enc.int32(v); } if (m.disc_number) |v| { try entry(enc, "xesam:discNumber", "i"); try enc.int32(v); } if (m.url) |v| { try entry(enc, "xesam:url", "s"); try enc.string(v); } if (m.user_rating) |v| { try entry(enc, "xesam:userRating", "d"); try enc.double(v); } try enc.endArray(dict);}
fn entry(enc: *dbus.Encoder, key: []const u8, signature: []const u8) !void { try enc.dictEntryAlignment(); try enc.string(key); try enc.variantSignature(signature);}
fn writePlaylist(enc: *dbus.Encoder, p: Playlist) !void { try enc.structAlignment(); try enc.objectPath(validPath(p.id)); try enc.string(p.name); try enc.string(p.icon);}
// --- org.mpris.MediaPlayer2 ----------------------------------------------------
fn command(comptime field: []const u8) fn (*anyopaque, *dbus.Call) anyerror!void { return struct { fn f(context: *anyopaque, _: *dbus.Call) anyerror!void { const self = from(context); if (@field(self.player, field)) |cb| cb(self.player.context); } }.f;}
fn constBool(comptime v: bool) fn (*anyopaque, *dbus.Encoder) anyerror!void { return struct { fn f(_: *anyopaque, value: *dbus.Encoder) anyerror!void { try value.boolean(v); } }.f;}
fn constDouble(comptime v: f64) fn (*anyopaque, *dbus.Encoder) anyerror!void { return struct { fn f(_: *anyopaque, value: *dbus.Encoder) anyerror!void { try value.double(v); } }.f;}
fn hasCommand(comptime field: []const u8) fn (*anyopaque, *dbus.Encoder) anyerror!void { return struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { try value.boolean(@field(from(context).player, field) != null); } }.f;}
const root: dbus.Interface = .{ .name = root_interface, .methods = &.{ .{ .name = "Raise", .handler = command("raise") }, .{ .name = "Quit", .handler = command("quit") }, }, .properties = &.{ .{ .name = "CanQuit", .signature = "b", .get = hasCommand("quit") }, .{ .name = "CanRaise", .signature = "b", .get = hasCommand("raise") }, .{ .name = "HasTrackList", .signature = "b", .get = struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { try value.boolean(from(context).options.track_list); } }.f }, .{ .name = "Identity", .signature = "s", .get = struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { try value.string(from(context).options.identity); } }.f }, .{ .name = "DesktopEntry", .signature = "s", .get = struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { try value.string(from(context).options.desktop_entry); } }.f }, .{ .name = "SupportedUriSchemes", .signature = "as", .get = struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { try writeStrings(value, from(context).options.supported_uri_schemes); } }.f }, .{ .name = "SupportedMimeTypes", .signature = "as", .get = struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { try writeStrings(value, from(context).options.supported_mime_types); } }.f }, },};
// --- org.mpris.MediaPlayer2.Player ---------------------------------------------
fn seek(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); const offset = try call.args.int64(); const cb = self.player.set_position orelse return; const target, const length, const can_seek = blk: { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); // Saturating: the offset is whatever the caller sent, and past the // end or before the start is all a huge one can mean. break :blk .{ self.positionNow(self.current) +| offset, self.current.metadata.length_us, self.current.can_seek }; }; if (!can_seek) return; // Past the end is the next track, and before the start is the start. if (length) |len| if (target > len) { if (self.player.next) |next| next(self.player.context); return; }; cb(self.player.context, @max(target, 0));}
fn setPosition(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); const trackid = try call.args.objectPath(); const position = try call.args.int64(); const cb = self.player.set_position orelse return; const current, const length = blk: { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); break :blk .{ std.mem.eql(u8, trackid, self.current.metadata.trackid), self.current.metadata.length_us }; }; // A position for a track that is no longer playing is ignored, and so is // one outside the track: both are what the specification says. if (!current or position < 0) return; if (length) |len| if (position > len) return; cb(self.player.context, position);}
fn openUri(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); const uri = try call.args.string(); const cb = self.player.open_uri orelse return call.fail(dbus.errors.not_supported, "This player cannot open URIs"); cb(self.player.context, uri);}
fn getPlaybackStatus(self: *Server, s: State, value: *dbus.Encoder) anyerror!void { _ = self; try value.string(@tagName(s.playback_status));}
fn getLoopStatus(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { try value.string(@tagName(s.loop_status));}
fn setLoopStatus(context: *anyopaque, value: *dbus.Decoder) anyerror!void { const self = from(context); const status = std.meta.stringToEnum(LoopStatus, try value.string()) orelse return error.InvalidArgs; const cb = self.player.set_loop_status orelse return error.NotSupported; cb(self.player.context, status);}
fn setRate(_: *anyopaque, value: *dbus.Decoder) anyerror!void { // The only rate a music player needs is the normal one, which // `MinimumRate` and `MaximumRate` say. if (try value.double() != 1.0) return error.NotSupported;}
fn getShuffle(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { try value.boolean(s.shuffle);}
fn setShuffle(context: *anyopaque, value: *dbus.Decoder) anyerror!void { const self = from(context); const on = try value.boolean(); const cb = self.player.set_shuffle orelse return error.NotSupported; cb(self.player.context, on);}
fn getMetadata(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { try writeMetadata(value, s.metadata);}
fn getVolume(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { try value.double(s.volume);}
fn setVolume(context: *anyopaque, value: *dbus.Decoder) anyerror!void { const self = from(context); const v = try value.double(); // Infinity and NaN are no volume at all, whatever the caller meant. if (!std.math.isFinite(v)) return error.InvalidArgs; const cb = self.player.set_volume orelse return error.NotSupported; // Negative is taken as zero, as the specification says. cb(self.player.context, @max(v, 0));}
fn getPosition(self: *Server, s: State, value: *dbus.Encoder) anyerror!void { try value.int64(self.positionNow(s));}
fn stateBool(comptime field: []const u8) fn (*anyopaque, *dbus.Encoder) anyerror!void { return struct { fn g(self: *Server, s: State, value: *dbus.Encoder) anyerror!void { _ = self; try value.boolean(@field(s, field)); } fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { return read(context, value, g); } }.f;}
fn reader(comptime g: fn (*Server, State, *dbus.Encoder) anyerror!void) fn (*anyopaque, *dbus.Encoder) anyerror!void { return struct { fn f(context: *anyopaque, value: *dbus.Encoder) anyerror!void { return read(context, value, g); } }.f;}
const player_iface: dbus.Interface = .{ .name = player_interface, .methods = &.{ .{ .name = "Next", .handler = command("next") }, .{ .name = "Previous", .handler = command("previous") }, .{ .name = "Pause", .handler = command("pause") }, .{ .name = "PlayPause", .handler = command("play_pause") }, .{ .name = "Stop", .handler = command("stop") }, .{ .name = "Play", .handler = command("play") }, .{ .name = "Seek", .in = &.{.{ .name = "Offset", .signature = "x" }}, .handler = seek }, .{ .name = "SetPosition", .in = &.{ .{ .name = "TrackId", .signature = "o" }, .{ .name = "Position", .signature = "x" } }, .handler = setPosition }, .{ .name = "OpenUri", .in = &.{.{ .name = "Uri", .signature = "s" }}, .handler = openUri }, }, .properties = &.{ .{ .name = "PlaybackStatus", .signature = "s", .get = reader(getPlaybackStatus) }, .{ .name = "LoopStatus", .signature = "s", .access = .readwrite, .get = reader(getLoopStatus), .set = setLoopStatus }, .{ .name = "Rate", .signature = "d", .access = .readwrite, .get = constDouble(1.0), .set = setRate }, .{ .name = "Shuffle", .signature = "b", .access = .readwrite, .get = reader(getShuffle), .set = setShuffle }, .{ .name = "Metadata", .signature = "a{sv}", .get = reader(getMetadata) }, .{ .name = "Volume", .signature = "d", .access = .readwrite, .get = reader(getVolume), .set = setVolume }, // Changes all the time, and so never says so: `Seeked` is the signal // for a jump. .{ .name = "Position", .signature = "x", .emits_changed = .false, .get = reader(getPosition) }, .{ .name = "MinimumRate", .signature = "d", .emits_changed = .@"const", .get = constDouble(1.0) }, .{ .name = "MaximumRate", .signature = "d", .emits_changed = .@"const", .get = constDouble(1.0) }, .{ .name = "CanGoNext", .signature = "b", .get = stateBool("can_go_next") }, .{ .name = "CanGoPrevious", .signature = "b", .get = stateBool("can_go_previous") }, .{ .name = "CanPlay", .signature = "b", .get = stateBool("can_play") }, .{ .name = "CanPause", .signature = "b", .get = stateBool("can_pause") }, .{ .name = "CanSeek", .signature = "b", .get = stateBool("can_seek") }, .{ .name = "CanControl", .signature = "b", .emits_changed = .@"const", .get = constBool(true) }, }, .signals = &.{.{ .name = "Seeked", .args = &.{.{ .name = "Position", .signature = "x" }} }},};
// --- org.mpris.MediaPlayer2.TrackList --------------------------------------------
fn getTracksMetadata(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); const out = try call.reply.beginArray('a'); const end = try call.args.beginArray('o'); while (!try call.args.arrayFinished(end)) { const id = try call.args.objectPath(); // Ids that are not in the list are left out, as the specification // says, rather than answered with an error. for (self.current.tracks) |t| { if (std.mem.eql(u8, t.trackid, id)) { try writeMetadata(&call.reply, t); break; } } } try call.reply.endArray(out);}
fn goTo(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); const id = try call.args.objectPath(); const cb = self.player.go_to orelse return; cb(self.player.context, id);}
fn notEditable(_: *anyopaque, call: *dbus.Call) anyerror!void { return call.fail(dbus.errors.not_supported, "This track list cannot be edited");}
fn getTracks(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { const a = try value.beginArray('o'); for (s.tracks) |t| try value.objectPath(validPath(t.trackid)); try value.endArray(a);}
const tracklist: dbus.Interface = .{ .name = tracklist_interface, .methods = &.{ .{ .name = "GetTracksMetadata", .in = &.{.{ .name = "TrackIds", .signature = "ao" }}, .out = &.{.{ .name = "Metadata", .signature = "aa{sv}" }}, .handler = getTracksMetadata }, .{ .name = "AddTrack", .in = &.{ .{ .name = "Uri", .signature = "s" }, .{ .name = "AfterTrack", .signature = "o" }, .{ .name = "SetAsCurrent", .signature = "b" } }, .handler = notEditable }, .{ .name = "RemoveTrack", .in = &.{.{ .name = "TrackId", .signature = "o" }}, .handler = notEditable }, .{ .name = "GoTo", .in = &.{.{ .name = "TrackId", .signature = "o" }}, .handler = goTo }, }, .properties = &.{ // A list, so only named when it changes; `TrackListReplaced` carries // the new one. .{ .name = "Tracks", .signature = "ao", .emits_changed = .invalidates, .get = reader(getTracks) }, .{ .name = "CanEditTracks", .signature = "b", .emits_changed = .@"const", .get = constBool(false) }, }, .signals = &.{ .{ .name = "TrackListReplaced", .args = &.{ .{ .name = "Tracks", .signature = "ao" }, .{ .name = "CurrentTrack", .signature = "o" } } }, .{ .name = "TrackAdded", .args = &.{ .{ .name = "Metadata", .signature = "a{sv}" }, .{ .name = "AfterTrack", .signature = "o" } } }, .{ .name = "TrackRemoved", .args = &.{.{ .name = "TrackId", .signature = "o" }} }, .{ .name = "TrackMetadataChanged", .args = &.{ .{ .name = "TrackId", .signature = "o" }, .{ .name = "Metadata", .signature = "a{sv}" } } }, },};
// --- org.mpris.MediaPlayer2.Playlists --------------------------------------------
fn activatePlaylist(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); const id = try call.args.objectPath(); const cb = self.player.activate_playlist orelse return; cb(self.player.context, id);}
fn getPlaylists(context: *anyopaque, call: *dbus.Call) anyerror!void { const self = from(context); const index = try call.args.uint32(); const max_count = try call.args.uint32(); _ = try call.args.string(); // the ordering: the list is kept in the one order it has const reverse = try call.args.boolean(); self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); const all = self.current.playlists; const out = try call.reply.beginArray('('); var i: usize = index; var n: usize = 0; while (i < all.len and n < max_count) : ({ i += 1; n += 1; }) { try writePlaylist(&call.reply, all[if (reverse) all.len - 1 - i else i]); } try call.reply.endArray(out);}
fn getPlaylistCount(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { try value.uint32(@intCast(s.playlists.len));}
fn getOrderings(_: *anyopaque, value: *dbus.Encoder) anyerror!void { try writeStrings(value, &.{"UserDefined"});}
fn getActivePlaylist(_: *Server, s: State, value: *dbus.Encoder) anyerror!void { try value.structAlignment(); try value.boolean(s.active_playlist != null); try writePlaylist(value, s.active_playlist orelse .{ .id = "/", .name = "" });}
const playlists: dbus.Interface = .{ .name = playlists_interface, .methods = &.{ .{ .name = "ActivatePlaylist", .in = &.{.{ .name = "PlaylistId", .signature = "o" }}, .handler = activatePlaylist }, .{ .name = "GetPlaylists", .in = &.{ .{ .name = "Index", .signature = "u" }, .{ .name = "MaxCount", .signature = "u" }, .{ .name = "Order", .signature = "s" }, .{ .name = "ReverseOrder", .signature = "b" } }, .out = &.{.{ .name = "Playlists", .signature = "a(oss)" }}, .handler = getPlaylists }, }, .properties = &.{ .{ .name = "PlaylistCount", .signature = "u", .get = reader(getPlaylistCount) }, .{ .name = "Orderings", .signature = "as", .emits_changed = .@"const", .get = getOrderings }, .{ .name = "ActivePlaylist", .signature = "(b(oss))", .get = reader(getActivePlaylist) }, }, .signals = &.{.{ .name = "PlaylistChanged", .args = &.{.{ .name = "Playlist", .signature = "(oss)" }} }},};
// --- tests -------------------------------------------------------------------------
const testing = std.testing;
test "a change of track is Metadata, and a seek is not a property" { const a: State = .{ .playback_status = .Playing, .metadata = .{ .trackid = "/t/1", .title = "One" } }; var b = a; b.metadata = .{ .trackid = "/t/2", .title = "Two" }; b.position_us = 90_000_000; const c = diff(a, b); try testing.expectEqual(@as(usize, 1), c.player.len); try testing.expectEqualStrings("Metadata", c.player.slice()[0]);}
test "every player property that changed, and only those" { const a: State = .{}; const b: State = .{ .playback_status = .Playing, .shuffle = true, .volume = 0.5, .can_play = true }; const c = diff(a, b); const names = c.player.slice(); try testing.expectEqual(@as(usize, 4), names.len); for ([_][]const u8{ "PlaybackStatus", "Shuffle", "Volume", "CanPlay" }, names) |want, got| { try testing.expectEqualStrings(want, got); } try testing.expect(!c.tracks); try testing.expectEqual(@as(usize, 0), c.playlists.len);}
test "the track list and playlists changing" { const t = [_]Metadata{ .{ .trackid = "/t/1" }, .{ .trackid = "/t/2" } }; const p = [_]Playlist{.{ .id = "/p/1", .name = "Favorites" }}; const a: State = .{}; const b: State = .{ .tracks = &t, .playlists = &p, .active_playlist = p[0] }; const c = diff(a, b); try testing.expect(c.tracks); try testing.expectEqual(@as(usize, 2), c.playlists.len);}
test "metadata carries only what the track has" { var enc: dbus.Encoder = .init(testing.allocator); defer enc.deinit(); try writeMetadata(&enc, .{ .trackid = "/t/1", .length_us = 214_000_000, .title = "Desperado", .artists = &.{"Eagles"}, }); var dec: dbus.Decoder = .{ .data = enc.bytes(), .endian = .little, .base_offset = 0 }; const end = try dec.beginArray('{'); var keys: [8][]const u8 = undefined; var n: usize = 0; while (!try dec.arrayFinished(end)) : (n += 1) { try dec.structAlignment(); keys[n] = try dec.string(); try dec.skipSignatureValue("v"); } try testing.expectEqual(@as(usize, 4), n); try testing.expectEqualStrings("mpris:trackid", keys[0]); try testing.expectEqualStrings("mpris:length", keys[1]); try testing.expectEqualStrings("xesam:title", keys[2]); try testing.expectEqualStrings("xesam:artist", keys[3]);}
test "a track id that is not a path is sent as no track" { try testing.expectEqualStrings(state.no_track, validPath("not a path")); try testing.expectEqualStrings("/t/1", validPath("/t/1"));}
test "a seek by any offset lands in the track, or on the next one" { const Player_ = struct { position: ?i64 = null, nexts: usize = 0, fn snapshot(_: *anyopaque, _: std.mem.Allocator, out: *State) anyerror!void { out.* = .{ .playback_status = .Paused, .position_us = 60_000_000, .can_seek = true, .metadata = .{ .trackid = "/t/1", .length_us = 180_000_000 }, }; } fn setPosition(context: *anyopaque, position_us: i64) void { const self: *@This() = @ptrCast(@alignCast(context)); self.position = position_us; } fn next(context: *anyopaque) void { const self: *@This() = @ptrCast(@alignCast(context)); self.nexts += 1; } }; var p: Player_ = .{}; // Nothing here reaches the connection: that is `start` and `run`. var connection: mdbus.Connection = undefined; const server = try create(testing.allocator, testing.io, &connection, .{ .name = "t", .identity = "T" }, .{ .context = &p, .snapshot = Player_.snapshot, .set_position = Player_.setPosition, .next = Player_.next, }); defer server.destroy(); try server.update();
for ([_]i64{ std.math.maxInt(i64), std.math.minInt(i64) }) |offset| { var body: dbus.Encoder = .init(testing.allocator); defer body.deinit(); try body.int64(offset); const data = try mdbus.wire.encodeMessage(testing.allocator, .{ .message_type = .method_call, .path = object_path, .interface = player_interface, .member = "Seek", .signature = "x", }, 1, body.bytes(), 0); var message = try mdbus.wire.parseMessage(testing.allocator, data, &.{}); defer message.deinit(); const reply = try server.service.dispatcher.dispatch(&message); defer reply.deinit(testing.allocator); try testing.expect(reply == .ok); } // Past the end is the next track, and before the start is the start. try testing.expectEqual(@as(usize, 1), p.nexts); try testing.expectEqual(@as(?i64, 0), p.position);}
test "a volume that is not a number is refused, and a negative one is none" { const Player_ = struct { volume: ?f64 = null, fn snapshot(_: *anyopaque, _: std.mem.Allocator, out: *State) anyerror!void { out.* = .{}; } fn setVolume(context: *anyopaque, v: f64) void { const self: *@This() = @ptrCast(@alignCast(context)); self.volume = v; } }; var p: Player_ = .{}; var connection: mdbus.Connection = undefined; const server = try create(testing.allocator, testing.io, &connection, .{ .name = "t", .identity = "T" }, .{ .context = &p, .snapshot = Player_.snapshot, .set_volume = Player_.setVolume, }); defer server.destroy(); try server.update();
const cases = [_]struct { f64, bool }{ .{ std.math.inf(f64), false }, .{ -std.math.inf(f64), false }, .{ std.math.nan(f64), false }, .{ -0.5, true }, }; for (cases) |c| { p.volume = null; var body: dbus.Encoder = .init(testing.allocator); defer body.deinit(); try body.string(player_interface); try body.string("Volume"); try body.variantSignature("d"); try body.double(c[0]); const data = try mdbus.wire.encodeMessage(testing.allocator, .{ .message_type = .method_call, .path = object_path, .interface = dbus.dispatch.properties_interface, .member = "Set", .signature = "ssv", }, 1, body.bytes(), 0); var message = try mdbus.wire.parseMessage(testing.allocator, data, &.{}); defer message.deinit(); const reply = try server.service.dispatcher.dispatch(&message); defer reply.deinit(testing.allocator); try testing.expectEqual(c[1], reply == .ok); if (c[1]) try testing.expectEqual(@as(?f64, 0), p.volume) else try testing.expectEqual(@as(?f64, null), p.volume); }}