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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813// 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 Allocator = std.mem.Allocator;const Io = std.Io;const mdbus = @import("mdbus");const dbus = @import("dbus_service");
/// The four interfaces, generated by dbus-codegen from the introspection/// XML in `dbus/`.const I = @import("mpris_interfaces");
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 = I.MediaPlayer2.name;pub const player_interface = I.Player.name;pub const tracklist_interface = I.TrackList.name;pub const playlists_interface = I.Playlists.name;
/// 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,media_player2: MediaPlayer2,player_impl: PlayerImpl,track_list: TrackList,playlists: Playlists,interfaces_buf: [4]dbus.Object.Implementation,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, .media_player2 = .{ .server = self }, .player_impl = .{ .server = self }, .track_list = .{ .server = self }, .playlists = .{ .server = self }, .interfaces_buf = undefined, .objects = undefined, .arena = .init(gpa), .taken_at = .now(io, .awake), }; var n: usize = 0; self.interfaces_buf[n] = I.MediaPlayer2.Server(MediaPlayer2).implementation(&self.media_player2); n += 1; self.interfaces_buf[n] = I.Player.Server(PlayerImpl).implementation(&self.player_impl); n += 1; if (options.track_list) { self.interfaces_buf[n] = I.TrackList.Server(TrackList).implementation(&self.track_list); n += 1; } if (options.playlists) { self.interfaces_buf[n] = I.Playlists.Server(Playlists).implementation(&self.playlists); n += 1; } self.objects = .{.{ .path = object_path, .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, &.{I.TrackList.Tracks.name}); 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 I.Player.emitSeeked(&self.service, object_path, .{ .position = 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(I.Player.PlaybackStatus.name); if (old.loop_status != new.loop_status) c.player.add(I.Player.LoopStatus.name); if (old.shuffle != new.shuffle) c.player.add(I.Player.Shuffle.name); if (old.volume != new.volume) c.player.add(I.Player.Volume.name); if (!old.metadata.eql(new.metadata)) c.player.add(I.Player.Metadata.name); if (old.can_go_next != new.can_go_next) c.player.add(I.Player.CanGoNext.name); if (old.can_go_previous != new.can_go_previous) c.player.add(I.Player.CanGoPrevious.name); if (old.can_play != new.can_play) c.player.add(I.Player.CanPlay.name); if (old.can_pause != new.can_pause) c.player.add(I.Player.CanPause.name); if (old.can_seek != new.can_seek) c.player.add(I.Player.CanSeek.name); if (old.playlists.len != new.playlists.len) c.playlists.add(I.Playlists.PlaylistCount.name); 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(I.Playlists.ActivePlaylist.name); c.tracks = !state.tracksEql(old.tracks, new.tracks); return c;}
fn emitTrackListReplaced(self: *Server, s: State) !void { const tracks = try self.gpa.alloc(dbus.ObjectPath, s.tracks.len); defer self.gpa.free(tracks); for (s.tracks, tracks) |t, *p| p.* = .{ .path = validPath(t.trackid) }; try I.TrackList.emitTrackListReplaced(&self.service, object_path, .{ .tracks = tracks, .current_track = .{ .path = validPath(s.metadata.trackid) }, });}
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 ---------------------------//// The bindings encode what a getter or handler returns after it has// returned, by which time `update` may have freed the snapshot it came from.// So whatever is returned is either a copy, in the call's arena, or// something that outlives the server.
/// The current snapshot, locked until `unlock`.fn lock(self: *Server) *const State { self.mutex.lockUncancelable(self.io); return &self.current;}
fn unlock(self: *Server) void { self.mutex.unlock(self.io);}
/// One field of the current snapshot, which must be a plain value.fn field(self: *Server, comptime name: []const u8) @FieldType(State, name) { defer self.unlock(); return @field(self.lock(), name);}
/// Where the track is now: the snapshot's position, moved on while playing.fn positionNow(self: *Server, s: *const 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 command(self: *Server, comptime name: []const u8) void { if (@field(self.player, name)) |cb| cb(self.player.context);}
fn dupeStrings(arena: Allocator, list: []const []const u8) ![]const []const u8 { const out = try arena.alloc([]const u8, list.len); for (list, out) |s, *o| o.* = try arena.dupe(u8, s); return out;}
fn objectPath(arena: Allocator, p: []const u8) !dbus.ObjectPath { return .{ .path = try arena.dupe(u8, validPath(p)) };}
/// A track as the `a{sv}` MPRIS metadata is: only what it has, copied into/// `arena`.fn metadata(arena: Allocator, m: Metadata) !dbus.Vardict { var entries: std.ArrayList(dbus.Vardict.Entry) = .empty; try put(arena, &entries, "mpris:trackid", "o", dbus.ObjectPath, try objectPath(arena, m.trackid)); if (m.length_us) |v| try put(arena, &entries, "mpris:length", "x", i64, v); if (m.art_url) |v| try put(arena, &entries, "mpris:artUrl", "s", []const u8, try arena.dupe(u8, v)); if (m.title) |v| try put(arena, &entries, "xesam:title", "s", []const u8, try arena.dupe(u8, v)); if (m.artists.len > 0) try put(arena, &entries, "xesam:artist", "as", []const []const u8, try dupeStrings(arena, m.artists)); if (m.album) |v| try put(arena, &entries, "xesam:album", "s", []const u8, try arena.dupe(u8, v)); if (m.album_artists.len > 0) try put(arena, &entries, "xesam:albumArtist", "as", []const []const u8, try dupeStrings(arena, m.album_artists)); if (m.track_number) |v| try put(arena, &entries, "xesam:trackNumber", "i", i32, v); if (m.disc_number) |v| try put(arena, &entries, "xesam:discNumber", "i", i32, v); if (m.url) |v| try put(arena, &entries, "xesam:url", "s", []const u8, try arena.dupe(u8, v)); if (m.user_rating) |v| try put(arena, &entries, "xesam:userRating", "d", f64, v); return .{ .entries = entries.items };}
fn put(arena: Allocator, entries: *std.ArrayList(dbus.Vardict.Entry), key: []const u8, comptime sig: []const u8, comptime T: type, value: T) !void { // A variant points at its value rather than holding it. const p = try arena.create(T); p.* = value; try entries.append(arena, .{ .key = key, .value = .of(sig, p) });}
const PlaylistTuple = struct { dbus.ObjectPath, []const u8, []const u8 };
fn playlist(arena: Allocator, p: Playlist) !PlaylistTuple { return .{ try objectPath(arena, p.id), try arena.dupe(u8, p.name), try arena.dupe(u8, p.icon) };}
// --- org.mpris.MediaPlayer2 ----------------------------------------------------
const MediaPlayer2 = struct { server: *Server,
pub fn raise(self: *MediaPlayer2, _: *dbus.Call, _: I.MediaPlayer2.Raise.In) !void { self.server.command("raise"); } pub fn quit(self: *MediaPlayer2, _: *dbus.Call, _: I.MediaPlayer2.Quit.In) !void { self.server.command("quit"); }
pub fn getCanQuit(self: *MediaPlayer2, _: Allocator) !bool { return self.server.player.quit != null; } pub fn getCanRaise(self: *MediaPlayer2, _: Allocator) !bool { return self.server.player.raise != null; } pub fn getHasTrackList(self: *MediaPlayer2, _: Allocator) !bool { return self.server.options.track_list; } pub fn getIdentity(self: *MediaPlayer2, _: Allocator) ![]const u8 { return self.server.options.identity; } pub fn getDesktopEntry(self: *MediaPlayer2, _: Allocator) ![]const u8 { return self.server.options.desktop_entry; } pub fn getSupportedUriSchemes(self: *MediaPlayer2, _: Allocator) ![]const []const u8 { return self.server.options.supported_uri_schemes; } pub fn getSupportedMimeTypes(self: *MediaPlayer2, _: Allocator) ![]const []const u8 { return self.server.options.supported_mime_types; }};
// --- org.mpris.MediaPlayer2.Player ---------------------------------------------
const PlayerImpl = struct { server: *Server,
pub fn next(self: *PlayerImpl, _: *dbus.Call, _: I.Player.Next.In) !void { self.server.command("next"); } pub fn previous(self: *PlayerImpl, _: *dbus.Call, _: I.Player.Previous.In) !void { self.server.command("previous"); } pub fn pause(self: *PlayerImpl, _: *dbus.Call, _: I.Player.Pause.In) !void { self.server.command("pause"); } pub fn playPause(self: *PlayerImpl, _: *dbus.Call, _: I.Player.PlayPause.In) !void { self.server.command("play_pause"); } pub fn stop(self: *PlayerImpl, _: *dbus.Call, _: I.Player.Stop.In) !void { self.server.command("stop"); } pub fn play(self: *PlayerImpl, _: *dbus.Call, _: I.Player.Play.In) !void { self.server.command("play"); }
pub fn seek(self: *PlayerImpl, _: *dbus.Call, in: I.Player.Seek.In) !void { const server = self.server; const cb = server.player.set_position orelse return; const target, const length, const can_seek = blk: { const s = server.lock(); defer server.unlock(); // 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 .{ server.positionNow(s) +| in.offset, s.metadata.length_us, s.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) { server.command("next"); return; }; cb(server.player.context, @max(target, 0)); }
pub fn setPosition(self: *PlayerImpl, _: *dbus.Call, in: I.Player.SetPosition.In) !void { const server = self.server; const cb = server.player.set_position orelse return; const current, const length = blk: { const s = server.lock(); defer server.unlock(); break :blk .{ std.mem.eql(u8, in.track_id.path, s.metadata.trackid), s.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 in.position < 0) return; if (length) |len| if (in.position > len) return; cb(server.player.context, in.position); }
pub fn openUri(self: *PlayerImpl, call: *dbus.Call, in: I.Player.OpenUri.In) !void { const cb = self.server.player.open_uri orelse return call.fail(dbus.errors.not_supported, "This player cannot open URIs"); cb(self.server.player.context, in.uri); }
pub fn getPlaybackStatus(self: *PlayerImpl, _: Allocator) ![]const u8 { return @tagName(self.server.field("playback_status")); }
pub fn getLoopStatus(self: *PlayerImpl, _: Allocator) ![]const u8 { return @tagName(self.server.field("loop_status")); } pub fn setLoopStatus(self: *PlayerImpl, value: []const u8) !void { const status = std.meta.stringToEnum(LoopStatus, value) orelse return error.InvalidArgs; const cb = self.server.player.set_loop_status orelse return error.NotSupported; cb(self.server.player.context, status); }
// The only rate a music player needs is the normal one, which // `MinimumRate` and `MaximumRate` say. pub fn getRate(_: *PlayerImpl, _: Allocator) !f64 { return 1.0; } pub fn setRate(_: *PlayerImpl, value: f64) !void { if (value != 1.0) return error.NotSupported; } pub fn getMinimumRate(_: *PlayerImpl, _: Allocator) !f64 { return 1.0; } pub fn getMaximumRate(_: *PlayerImpl, _: Allocator) !f64 { return 1.0; }
pub fn getShuffle(self: *PlayerImpl, _: Allocator) !bool { return self.server.field("shuffle"); } pub fn setShuffle(self: *PlayerImpl, value: bool) !void { const cb = self.server.player.set_shuffle orelse return error.NotSupported; cb(self.server.player.context, value); }
pub fn getMetadata(self: *PlayerImpl, arena: Allocator) !dbus.Vardict { const s = self.server.lock(); defer self.server.unlock(); return metadata(arena, s.metadata); }
pub fn getVolume(self: *PlayerImpl, _: Allocator) !f64 { return self.server.field("volume"); } pub fn setVolume(self: *PlayerImpl, value: f64) !void { // Infinity and NaN are no volume at all, whatever the caller meant. if (!std.math.isFinite(value)) return error.InvalidArgs; const cb = self.server.player.set_volume orelse return error.NotSupported; // Negative is taken as zero, as the specification says. cb(self.server.player.context, @max(value, 0)); }
pub fn getPosition(self: *PlayerImpl, _: Allocator) !i64 { const s = self.server.lock(); defer self.server.unlock(); return self.server.positionNow(s); }
pub fn getCanGoNext(self: *PlayerImpl, _: Allocator) !bool { return self.server.field("can_go_next"); } pub fn getCanGoPrevious(self: *PlayerImpl, _: Allocator) !bool { return self.server.field("can_go_previous"); } pub fn getCanPlay(self: *PlayerImpl, _: Allocator) !bool { return self.server.field("can_play"); } pub fn getCanPause(self: *PlayerImpl, _: Allocator) !bool { return self.server.field("can_pause"); } pub fn getCanSeek(self: *PlayerImpl, _: Allocator) !bool { return self.server.field("can_seek"); } pub fn getCanControl(_: *PlayerImpl, _: Allocator) !bool { return true; }};
// --- org.mpris.MediaPlayer2.TrackList --------------------------------------------
const TrackList = struct { server: *Server,
pub fn getTracksMetadata(self: *TrackList, call: *dbus.Call, in: I.TrackList.GetTracksMetadata.In) !I.TrackList.GetTracksMetadata.Out { const s = self.server.lock(); defer self.server.unlock(); var out: std.ArrayList(dbus.Vardict) = .empty; for (in.track_ids) |id| { // Ids that are not in the list are left out, as the specification // says, rather than answered with an error. for (s.tracks) |t| { if (std.mem.eql(u8, t.trackid, id.path)) { try out.append(call.arena, try metadata(call.arena, t)); break; } } } return .{ .metadata = out.items }; }
pub fn addTrack(_: *TrackList, call: *dbus.Call, _: I.TrackList.AddTrack.In) !void { return call.fail(dbus.errors.not_supported, "This track list cannot be edited"); }
pub fn removeTrack(_: *TrackList, call: *dbus.Call, _: I.TrackList.RemoveTrack.In) !void { return call.fail(dbus.errors.not_supported, "This track list cannot be edited"); }
pub fn goTo(self: *TrackList, _: *dbus.Call, in: I.TrackList.GoTo.In) !void { const cb = self.server.player.go_to orelse return; cb(self.server.player.context, in.track_id.path); }
pub fn getTracks(self: *TrackList, arena: Allocator) ![]const dbus.ObjectPath { const s = self.server.lock(); defer self.server.unlock(); const out = try arena.alloc(dbus.ObjectPath, s.tracks.len); for (s.tracks, out) |t, *o| o.* = try objectPath(arena, t.trackid); return out; }
pub fn getCanEditTracks(_: *TrackList, _: Allocator) !bool { return false; }};
// --- org.mpris.MediaPlayer2.Playlists --------------------------------------------
const Playlists = struct { server: *Server,
pub fn activatePlaylist(self: *Playlists, _: *dbus.Call, in: I.Playlists.ActivatePlaylist.In) !void { const cb = self.server.player.activate_playlist orelse return; cb(self.server.player.context, in.playlist_id.path); }
pub fn getPlaylists(self: *Playlists, call: *dbus.Call, in: I.Playlists.GetPlaylists.In) !I.Playlists.GetPlaylists.Out { // `in.order` is ignored: the list is kept in the one order it has. const s = self.server.lock(); defer self.server.unlock(); const all = s.playlists; var out: std.ArrayList(PlaylistTuple) = .empty; var i: usize = in.index; while (i < all.len and out.items.len < in.max_count) : (i += 1) { try out.append(call.arena, try playlist(call.arena, all[if (in.reverse_order) all.len - 1 - i else i])); } return .{ .playlists = out.items }; }
pub fn getPlaylistCount(self: *Playlists, _: Allocator) !u32 { return @intCast(self.server.field("playlists").len); }
pub fn getOrderings(_: *Playlists, _: Allocator) ![]const []const u8 { return &.{"UserDefined"}; }
pub fn getActivePlaylist(self: *Playlists, arena: Allocator) !I.Playlists.ActivePlaylist.Type { const s = self.server.lock(); defer self.server.unlock(); return .{ s.active_playlist != null, try playlist(arena, s.active_playlist orelse .{ .id = "/", .name = "" }) }; }};
// --- 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 arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const m = try metadata(a, .{ .trackid = "/t/1", .length_us = 214_000_000, .title = "Desperado", .artists = &.{"Eagles"}, }); try testing.expectEqual(@as(usize, 4), m.entries.len); for ([_][]const u8{ "mpris:trackid", "mpris:length", "xesam:title", "xesam:artist" }, m.entries) |want, got| { try testing.expectEqualStrings(want, got.key); } try testing.expectEqual(@as(?i64, 214_000_000), try m.get("x", i64, "mpris:length", a)); const artists = (try m.get("as", []const []const u8, "xesam:artist", a)).?; try testing.expectEqualStrings("Eagles", artists[0]);}
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); }}