empress 3.0.3

A D-Bus MPRIS daemon for controlling media players.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::{collections::HashMap, fmt::Debug, future::Future, time::Instant};

use anyhow::{anyhow, Context};
use zbus::{
    fdo,
    names::{BusName, WellKnownName},
    zvariant::{ObjectPath, OwnedValue},
    Connection,
};

use super::{
    mpris::{self, player::PlaybackStatus, MediaPlayerProxy, PlayerProxy},
    position::PositionCache,
    MatchPlayer, Position,
};
use crate::{
    opts::Offset,
    timeout::{self, Timeout},
    Result,
};

pub(super) trait Action {
    type Arg;
    type Output;

    fn can_run(&self, player: &Player) -> impl Future<Output = Result<Option<Self::Arg>>>;

    fn run(
        &self,
        player: &mut Player,
        arg: Self::Arg,
    ) -> impl Future<Output = Result<Self::Output>>;
}

#[derive(Debug)]
pub(super) struct Player {
    status: PlaybackStatus,
    last_update: Instant,
    position: PositionCache,
    mp2: Timeout<MediaPlayerProxy<'static>>,
    inner: Timeout<PlayerProxy<'static>>,
}

#[inline]
async fn timeout<
    'a,
    T: 'a,
    F: FnOnce(&'a T) -> FR + 'a,
    FR: std::future::Future<Output = Result<R, E>> + 'a,
    R,
    E,
>(
    t: &'a Timeout<T>,
    f: F,
) -> Result<R, crate::timeout::Error<E>> {
    t.try_run(std::time::Duration::from_secs(2), f).await
}

// Handle players that do not include required properties
fn recover_noncompliant<T>(
    r: Result<T, timeout::Error<fdo::Error>>,
) -> Result<Option<T>, timeout::Error<fdo::Error>> {
    let e = match r {
        Err(e) => e,
        Ok(o) => return Ok(Some(o)),
    };

    if let timeout::Error::Other(fdo::Error::ZBus(zbus::Error::FDO(e))) = &e {
        if matches!(**e, fdo::Error::NotSupported(_)) {
            return Ok(None);
        }
    }

    Err(e)
}

impl Player {
    pub async fn new(
        now: Instant,
        name: impl Into<BusName<'static>> + Clone,
        conn: &Connection,
    ) -> Result<Self> {
        let mut ret = Self {
            status: PlaybackStatus::Stopped,
            last_update: now,
            position: PositionCache::default(),
            mp2: MediaPlayerProxy::builder(conn)
                .destination(name.clone())
                .context("Error setting MediaPlayer2 proxy destination")?
                .build()
                .await
                .context("Error building MediaPlayer2 proxy")?
                .into(),
            inner: PlayerProxy::builder(conn)
                .destination(name)
                .context("Error setting player proxy destination")?
                .build()
                .await
                .context("Error building player proxy")?
                .into(),
        };

        ret.refresh(now).await?;

        Ok(ret)
    }

    #[inline]
    pub async fn refresh(&mut self, now: impl Into<Option<Instant>>) -> Result<Option<Instant>> {
        Ok(self.update_status(self.playback_status().await?, now))
    }

    //////// Accessors ////////

    #[inline]
    pub fn status(&self) -> PlaybackStatus { self.status }

    #[inline]
    pub fn update_status(
        &mut self,
        status: PlaybackStatus,
        now: impl Into<Option<Instant>>,
    ) -> Option<Instant> {
        if self.status == status {
            return None;
        }

        let now = now.into().unwrap_or_else(Instant::now);
        self.status = status;
        self.last_update = now;
        self.position
            .try_update_status(Some(status.is_playing()), None, now);
        Some(now)
    }

    #[inline]
    pub fn last_update(&self) -> Instant { self.last_update }

    #[inline]
    pub fn force_update(&mut self) -> Instant {
        let now = Instant::now();
        self.last_update = now;
        now
    }

    pub async fn force_update_position(
        &self,
        micros: Option<i64>,
    ) -> Result<Position, timeout::Error<fdo::Error>> {
        let now = Instant::now();
        let micros = if let Some(micros) = micros {
            micros
        } else {
            timeout(&self.inner, PlayerProxy::position).await?
        };
        let rate = timeout(&self.inner, PlayerProxy::rate).await?;

        Ok(self
            .position
            .force_seek(micros, self.status.is_playing(), rate, now))
    }

    pub fn update_rate(&self, rate: f64) {
        self.position.try_update_status(None, Some(rate), None);
    }

    #[inline]
    pub fn bus(&self) -> &WellKnownName {
        let player_dest = unsafe { self.inner.smuggle(|p| p.inner().destination()) };
        debug_assert!(self.mp2.block(|m| m.inner().destination() == player_dest));
        match player_dest {
            BusName::Unique(u) => unreachable!("MPRIS bus had unique name {:?}", u.as_str()),
            BusName::WellKnown(w) => w,
        }
    }

    //////// Methods under MediaPlayer2 ////////

    pub async fn raise(&mut self) -> Result {
        timeout(&self.mp2, MediaPlayerProxy::raise)
            .await
            .context("Proxy call for Raise failed")?;

        Ok(())
    }

    //////// Methods under MediaPlayer2.Player ////////

    pub async fn next(&mut self) -> Result {
        timeout(&self.inner, PlayerProxy::next)
            .await
            .context("Proxy call for Next failed")
    }

    pub async fn previous(&mut self) -> Result {
        timeout(&self.inner, PlayerProxy::previous)
            .await
            .context("Proxy call for Previous failed")
    }

    pub async fn pause(&mut self) -> Result {
        timeout(&self.inner, PlayerProxy::pause)
            .await
            .context("Proxy call for Pause failed")
    }

    pub async fn stop(&mut self) -> Result {
        timeout(&self.inner, PlayerProxy::stop)
            .await
            .context("Proxy call for Stop failed")
    }

    pub async fn play(&mut self) -> Result {
        timeout(&self.inner, PlayerProxy::play)
            .await
            .context("Proxy call for Play failed")
    }

    pub async fn set_position(&mut self, id: ObjectPath<'_>, micros: i64) -> Result {
        timeout(&self.inner, |p| p.set_position(id, micros))
            .await
            .context("Proxy call for SetPosition failed")
    }

    //////// Properties under MediaPlayer2 ////////

    pub async fn can_raise(&self) -> Result<bool> {
        timeout(&self.mp2, MediaPlayerProxy::can_raise)
            .await
            .context("Proxy property get for CanRaise failed")
    }

    pub async fn identity(&self) -> Result<String> {
        timeout(&self.mp2, MediaPlayerProxy::identity)
            .await
            .context("Proxy property get for Identity failed")
    }

    //////// Properties under MediaPlayer2.Player ////////

    pub async fn playback_status(&self) -> Result<PlaybackStatus> {
        timeout(&self.inner, PlayerProxy::playback_status)
            .await
            .context("Proxy property get for PlaybackStatus failed")
    }

    pub async fn metadata(&self) -> Result<HashMap<String, OwnedValue>> {
        timeout(&self.inner, PlayerProxy::metadata)
            .await
            .context("Proxy property get for Metadata failed")
    }

    pub async fn volume(&self) -> Result<Option<f64>> {
        recover_noncompliant(timeout(&self.inner, PlayerProxy::volume).await)
            .context("Proxy property get for Volume failed")
    }

    pub async fn set_volume(&self, vol: f64) -> Result<()> {
        timeout(&self.inner, |p| p.set_volume(vol))
            .await
            .context("Proxy property set for Volume failed")
    }

    pub async fn position(&self) -> Result<Option<Position>> {
        recover_noncompliant(if let Some(pos) = self.position.get() {
            Ok(pos)
        } else {
            self.force_update_position(None).await
        })
        .context("Proxy property get for Position or Rate failed")
    }

    pub async fn can_go_next(&self) -> Result<bool> {
        timeout(&self.inner, PlayerProxy::can_go_next)
            .await
            .context("Proxy property get for CanGoNext failed")
    }

    pub async fn can_go_previous(&self) -> Result<bool> {
        timeout(&self.inner, PlayerProxy::can_go_previous)
            .await
            .context("Proxy property get for CanGoPrevious failed")
    }

    pub async fn can_play(&self) -> Result<bool> {
        timeout(&self.inner, PlayerProxy::can_play)
            .await
            .context("Proxy property get for CanPlay failed")
    }

    pub async fn can_pause(&self) -> Result<bool> {
        timeout(&self.inner, PlayerProxy::can_pause)
            .await
            .context("Proxy property get for CanPause failed")
    }

    pub async fn can_seek(&self) -> Result<bool> {
        timeout(&self.inner, PlayerProxy::can_seek)
            .await
            .context("Proxy property get for CanSeek failed")
    }

    pub async fn can_control(&self) -> Result<bool> {
        timeout(&self.inner, PlayerProxy::can_control)
            .await
            .context("Proxy property get for CanControl failed")
    }

    //////// Empress-specific wrapper methods ////////

    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        reason = "This seems relatively unavoidable here"
    )]
    async fn offset_position(&mut self, pos: Offset) -> Result<f64> {
        let meta = self.metadata().await?;

        let pos = match pos {
            Offset::Relative(p) => {
                self.position()
                    .await?
                    .context("Player did not report a position")?
                    .get(None)
                    + (p * 1e6).round() as i64
            },
            Offset::Absolute(p) => (p * 1e6).round() as i64,
        };

        self.set_position(
            meta.get(mpris::track_list::ATTR_TRACK_ID)
                .context("Missing track ID in metadata")?
                .downcast_ref::<&ObjectPath>()
                .map(ObjectPath::as_ref)?,
            pos,
        )
        .await?;

        Ok(pos as f64 / 1e6)
    }

    async fn offset_volume(&mut self, vol: Offset) -> Result<f64> {
        let (vol, set) = match vol {
            Offset::Relative(v) => {
                let old = self
                    .volume()
                    .await?
                    .context("Player did not report a volume level")?;
                let new = old + v;

                if (new - old).abs() > 1e-5 {
                    (new, true)
                } else {
                    (old, false)
                }
            },
            Offset::Absolute(v) => (v, true),
        };

        if !vol.is_finite() {
            return Err(anyhow!("Invalid volume {vol:?}"));
        }

        Ok(if set {
            // Safety check
            let vol = vol.clamp(0.0, 1.0);

            self.set_volume(vol).await?;

            vol
        } else {
            vol
        })
    }
}

impl MatchPlayer for Player {
    fn bus(&self) -> &str {
        self.bus()
            .strip_prefix(mpris::BUS_NAME.as_str())
            .and_then(|s| s.strip_prefix('.'))
            .unwrap_or("")
    }

    fn status(&self) -> PlaybackStatus { self.status }
}

trait IntoOption {
    type Output;

    fn into_option(self) -> Option<Self::Output>;
}

impl IntoOption for bool {
    type Output = ();

    #[inline]
    fn into_option(self) -> Option<Self::Output> { self.then_some(()) }
}

impl<T> IntoOption for Option<T> {
    type Output = T;

    #[inline]
    fn into_option(self) -> Option<Self::Output> { self }
}

macro_rules! action {
    (
        $vis:vis $name:ident $(($($inp:ty),* $(,)?))?: fn($($parm:ty),*) -> $output:ty,
        |$cr_me:pat_param, $cr_player:ident| $can_run:expr,
        |$r_me:pat_param, $r_player:ident, $r_arg:pat_param| $run:expr $(,)?
    ) => {
        #[derive(Clone, Copy)]
        $vis struct $name $(($(pub $inp,)*))?;

        impl Action for $name {
            type Arg = ($($parm,)*);
            type Output = $output;

            async fn can_run(&self, $cr_player: &Player) -> Result<Option<Self::Arg>> {
                let $cr_me = self;
                Ok(IntoOption::into_option($can_run))
            }

            async fn run(
                &self,
                $r_player: &mut Player,
                $r_arg: Self::Arg
            ) -> Result<Self::Output> {
                let $r_me = self;
                $run
            }
        }
    };
}

action!(
    pub Raise: fn() -> (),
    |Self, p| p.can_raise().await?,
    |Self, p, ()| p.raise().await,
);
action!(
    pub Next: fn() -> (),
    |Self, p| p.can_go_next().await?,
    |Self, p, ()| p.next().await,
);
action!(
    pub Prev: fn() -> (),
    |Self, p| p.can_go_previous().await?,
    |Self, p, ()| p.previous().await,
);
action!(
    pub Pause: fn() -> (),
    |Self, p| p.status.can_pause() && p.can_pause().await?,
    |Self, p, ()| p.pause().await,
);
action!(
    pub PlayPause: fn(bool) -> (),
    |Self, p| match p.status {
        PlaybackStatus::Playing if p.can_pause().await? => Some((true,)),
        PlaybackStatus::Paused if p.can_play().await? => Some((false,)),
        _ => None,
    },
    |Self, p, (playing,)| if playing {
        p.pause().await
    } else {
        p.play().await
    }
);
action!(
    pub Stop: fn() -> (),
    |Self, p| p.status.can_stop() && p.can_control().await?,
    |Self, p, ()| p.stop().await,
);
action!(
    pub Play: fn() -> (),
    |Self, p| p.status.can_play() && p.can_play().await?,
    |Self, p, ()| p.play().await,
);
action!(
    pub Seek(Offset): fn() -> f64,
    |Self(_), p| p.can_seek().await?,
    |Self(pos), p, ()| p.offset_position(*pos).await,
);
action!(
    pub SetVolume(Offset): fn() -> f64,
    |Self(_), p| p.can_control().await?,
    |Self(vol), p, ()| p.offset_volume(*vol).await,
);