1
//! The system MEDIA SESSION - what the desktop's media widget shows.
2
//!
3
//! This is the second output in the input subsystem, next to [`crate::haptics`]:
4
//! nothing is being reported, the app is telling the platform something. It
5
//! lives here because the transport it feeds is the same one the media KEYS
6
//! arrive on, and because on every platform the two are one object - an app
7
//! becomes eligible to receive `Play`/`Next` precisely by declaring what it is
8
//! playing.
9
//!
10
//! # Why the app pushes this instead of the engine deriving it
11
//!
12
//! Azul has no playback state machine (11c is blocked on exactly that), and it
13
//! never will have one that covers the interesting cases: an app playing audio
14
//! through `rodio`, through a system framework, or over the network knows what
15
//! it is playing and the toolkit cannot see it. So the app pushes, and the
16
//! engine's only job is to fan that out to the platform session APIs.
17
//!
18
//! # Where it goes
19
//!
20
//! | platform | sink | notes |
21
//! |---|---|---|
22
//! | Linux | MPRIS `org.mpris.MediaPlayer2.Player` | `Metadata`, `PlaybackStatus`, `Position` |
23
//! | macOS | `MPNowPlayingInfoCenter` | artwork needs image bytes, not a URL - dropped |
24
//! | Windows | - | needs an SMTC backend that does not exist yet |
25
//! | iOS / Android | - | both have an equivalent; no backend yet |
26
//!
27
//! Publishing on a platform with no sink is a no-op, not an error: the same
28
//! call site has to be correct everywhere.
29

            
30
use alloc::vec::Vec;
31

            
32
use azul_css::AzString;
33

            
34
/// What the player is doing right now.
35
///
36
/// Deliberately three states and not four: MPRIS has exactly these, and
37
/// macOS's `MPNowPlayingPlaybackState` adds `unknown` and `interrupted` which
38
/// no app can meaningfully assert about itself - `interrupted` is something the
39
/// SYSTEM does to you (a phone call), not something you declare.
40
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
41
#[repr(C)]
42
pub enum MediaPlaybackState {
43
    /// Nothing is loaded, or playback finished. The desktop widget shows no
44
    /// track.
45
    #[default]
46
    Stopped = 0,
47
    /// Advancing. A desktop extrapolates the position from here, which is why
48
    /// this must be honest even when the position is not being republished.
49
    Playing = 1,
50
    /// Loaded and holding position.
51
    Paused = 2,
52
}
53

            
54
/// What the app is playing, as the system media widget should show it.
55
///
56
/// Every field is optional in the sense that an empty string or a zero is a
57
/// valid "I do not know" - there is no `Option` here because a media widget
58
/// treats an absent title and an empty title identically, and the FFI cost of
59
/// six `Option<AzString>`s would buy nothing.
60
#[derive(Debug, Clone, PartialEq, Eq)]
61
#[repr(C)]
62
pub struct NowPlayingInfo {
63
    /// What the player is doing. This is the field that decides whether the
64
    /// desktop shows a play or a pause button.
65
    pub state: MediaPlaybackState,
66
    /// Track title. Empty means unknown.
67
    pub title: AzString,
68
    /// Performer. Empty means unknown.
69
    ///
70
    /// ONE artist, not a list, even though MPRIS's `xesam:artist` is an array
71
    /// of strings: every widget that displays it joins the array back into one
72
    /// line, and an app with several artists can join them itself with the
73
    /// separator its locale wants. The MPRIS backend wraps this in a
74
    /// single-element array because the spec's type demands it.
75
    pub artist: AzString,
76
    /// Album title. Empty means unknown.
77
    pub album: AzString,
78
    /// Cover art, as a URI - `file://` or `http(s)://`.
79
    ///
80
    /// A URI and not bytes because that is what MPRIS wants and because the
81
    /// alternative makes every publish copy an image. macOS is the platform
82
    /// that pays for this: `MPMediaItemArtwork` needs a decoded image, so the
83
    /// macOS backend drops this field rather than fetching a URL from inside a
84
    /// UI toolkit.
85
    pub artwork_url: AzString,
86
    /// Track length in MILLISECONDS. `0` means unknown, which is correct for a
87
    /// live stream.
88
    ///
89
    /// 64-bit because 32-bit milliseconds overflow at 49.7 days but, more to
90
    /// the point, because a `u32` of *microseconds* - the unit MPRIS actually
91
    /// wants - overflows at 71 minutes, which is an ordinary audiobook chapter.
92
    /// The conversion to microseconds happens in the backend.
93
    pub duration_ms: u64,
94
    /// How far in, in MILLISECONDS.
95
    ///
96
    /// SEE [`MediaSessionManager::set`]: this field deliberately does NOT
97
    /// trigger a change announcement, because MPRIS forbids announcing it.
98
    pub position_ms: u64,
99
    /// The app's OUTPUT VOLUME, `0.0` silent to `1.0` full, or `None` when the
100
    /// app does not expose one (9h-i-a-i-b).
101
    ///
102
    /// azul plays no audio; this is the app's own volume, published so the
103
    /// desktop can show it and ask to change it - MPRIS `Volume` is a
104
    /// read/WRITE property, and some desktops render a volume slider only
105
    /// when it exists. A request to change it arrives as a `MediaControl`
106
    /// event of kind `SetVolume`; the app applies it to its own output and
107
    /// publishes the new value here. `None` answers the property with `1.0`
108
    /// and still accepts writes, so a desktop's slider is never dead.
109
    /// Only MPRIS has a per-player volume: Windows SMTC, the Apple remote
110
    /// command centre and Android's session (for local playback) route volume
111
    /// to the system mixer and carry none.
112
    pub volume: azul_css::OptionF32,
113
}
114

            
115
impl Default for NowPlayingInfo {
116
    /// A stopped player with no track and no volume of its own. Spelled out
117
    /// rather than derived so that the "not reported" state of every field is
118
    /// visible in one place: empty strings, zero times, `None` volume.
119
29200
    fn default() -> Self {
120
29200
        Self {
121
29200
            state: MediaPlaybackState::Stopped,
122
29200
            title: AzString::from_const_str(""),
123
29200
            artist: AzString::from_const_str(""),
124
29200
            album: AzString::from_const_str(""),
125
29200
            artwork_url: AzString::from_const_str(""),
126
29200
            duration_ms: 0,
127
29200
            position_ms: 0,
128
29200
            volume: azul_css::OptionF32::None,
129
29200
        }
130
29200
    }
131
}
132

            
133
impl NowPlayingInfo {
134
    /// A stopped player with no track - what an app that has published nothing
135
    /// looks like.
136
    #[must_use]
137
134
    pub fn empty() -> Self {
138
134
        Self::default()
139
134
    }
140

            
141
    /// True when two publishes differ in a way the platform must be TOLD about,
142
    /// as opposed to one it will read for itself.
143
    ///
144
    /// Everything except the position. See [`MediaSessionManager::set`].
145
    #[must_use]
146
145
    pub fn differs_in_announced_fields(&self, other: &Self) -> bool {
147
145
        self.state != other.state
148
133
            || self.title != other.title
149
132
            || self.artist != other.artist
150
131
            || self.album != other.album
151
130
            || self.artwork_url != other.artwork_url
152
129
            || self.duration_ms != other.duration_ms
153
128
            || self.volume != other.volume
154
145
    }
155

            
156
    /// True when this is a DIFFERENT TRACK, not merely a different state of
157
    /// the same one.
158
    ///
159
    /// MPRIS identifies a track by `mpris:trackid`, and a desktop keys its
160
    /// progress bar and its "song changed" notification on that id. Minting a
161
    /// new one when the user merely hit pause would reset the progress bar and
162
    /// pop a notification for a track that never changed - so pausing, seeking
163
    /// and cover-art changes are all the SAME track.
164
    ///
165
    /// The duration counts as identity because two tracks with the same title
166
    /// and artist but different lengths are a live version and a studio one.
167
    #[must_use]
168
149
    pub fn is_different_track(&self, other: &Self) -> bool {
169
149
        self.title != other.title
170
137
            || self.artist != other.artist
171
136
            || self.album != other.album
172
135
            || self.duration_ms != other.duration_ms
173
149
    }
174

            
175
    /// The track length in MICROSECONDS, which is the unit MPRIS's
176
    /// `mpris:length` and `Position` both use.
177
    ///
178
    /// Saturating and `i64`, because D-Bus types this signed: a nonsense
179
    /// duration from an app must clamp rather than wrap into a negative
180
    /// length, which some clients render as a progress bar running backwards.
181
    #[must_use]
182
4
    pub fn duration_us(&self) -> i64 {
183
4
        Self::ms_to_us(self.duration_ms)
184
4
    }
185

            
186
    /// The playback position in MICROSECONDS. See [`Self::duration_us`].
187
    #[must_use]
188
267
    pub fn position_us(&self) -> i64 {
189
267
        Self::ms_to_us(self.position_ms)
190
267
    }
191

            
192
271
    fn ms_to_us(ms: u64) -> i64 {
193
271
        i64::try_from(ms.saturating_mul(1000)).unwrap_or(i64::MAX)
194
271
    }
195
}
196

            
197
/// Milliseconds as `WinRT` `TimeSpan` ticks, which are 100 NANOSECONDS each.
198
///
199
/// A third unit, disagreeing with both of the others: MPRIS wants microseconds
200
/// and macOS wants seconds. Publishing milliseconds into a `TimeSpan` makes a
201
/// three-minute track show as 18 microseconds and pins the scrubber at zero -
202
/// the same class of silent factor error `duration_us` guards, so it gets the
203
/// same treatment and the same test.
204
///
205
/// Saturating, because `TimeSpan::Duration` is signed and a nonsense duration
206
/// must clamp rather than wrap negative.
207
#[must_use]
208
5
pub fn ms_to_winrt_ticks(ms: u64) -> i64 {
209
5
    i64::try_from(ms.saturating_mul(10_000)).unwrap_or(i64::MAX)
210
5
}
211

            
212
/// Holds the current session state and remembers whether the platform has been
213
/// told about it.
214
///
215
/// Mirrors [`crate::haptics::HapticManager`]: the callback thread writes, the
216
/// shell drains once per pass. The difference is that this is a LATEST-WINS
217
/// value rather than a queue - a media widget wants the current track, not
218
/// every track the app has ever played.
219
/// What a control request from the platform's media controls asks for
220
/// (9h-i-a-i-a, 9h-i-a-i-b): everything a transport KEY cannot carry.
221
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
222
#[repr(C)]
223
pub enum MediaControlKind {
224
    /// Move by `position_us` RELATIVE to the current position (MPRIS `Seek`;
225
    /// negative moves back). The app clamps to the track.
226
    SeekRelative,
227
    /// Jump to the ABSOLUTE `position_us` (MPRIS `SetPosition`, SMTC's
228
    /// position change, `MPChangePlaybackPositionCommand`, `onSeekTo`).
229
    SeekAbsolute,
230
    /// Open and play `uri` (MPRIS `OpenUri`). `position_us` is 0.
231
    OpenUri,
232
    /// Set the app's output volume to `volume` (MPRIS `Volume` written;
233
    /// `0.0` silent, `1.0` full, above `1.0` is amplification a client may
234
    /// ask for and the app may clamp). The app applies it and publishes the
235
    /// result in `NowPlayingInfo::volume`.
236
    SetVolume,
237
}
238

            
239
/// One inbound request from the platform's media controls (9h-i-a-i-a): a
240
/// desktop scrubber, a lock-screen slider, `playerctl position 30`, a volume
241
/// slider in the desktop's media widget.
242
///
243
/// Unlike the transport commands, which become media KEY events, these carry
244
/// a value - a position, a URI, a volume - which is why they are their own
245
/// event kind (`EventType::MediaControl`) with their own data rather than a
246
/// key code.
247
#[derive(Debug, Clone, PartialEq)]
248
#[repr(C)]
249
pub struct MediaControlRequest {
250
    /// The URI for `OpenUri`, empty otherwise.
251
    pub uri: AzString,
252
    /// For `SeekAbsolute`: the track id the request was made against, so an
253
    /// app can drop a seek meant for a track that has since ended - MPRIS
254
    /// says exactly that about `SetPosition`. Empty when the platform gave
255
    /// none.
256
    pub track_id: AzString,
257
    /// Microseconds, the MPRIS unit; relative for `SeekRelative`, absolute for
258
    /// `SeekAbsolute`, 0 otherwise.
259
    pub position_us: i64,
260
    pub kind: MediaControlKind,
261
    /// For `SetVolume`: the requested volume, `0.0`..`1.0`. `0.0` otherwise.
262
    pub volume: f32,
263
}
264

            
265
impl_option!(
266
    MediaControlRequest,
267
    OptionMediaControlRequest,
268
    copy = false,
269
    [Debug, Clone, PartialEq]
270
);
271

            
272
/// What the system did with the audio the app took over (9h-i-a-i-d-i).
273
///
274
/// Delivered as a `SystemAudioChange` event and readable through
275
/// `CallbackInfo::get_system_audio_change`. The vocabulary is the union of
276
/// iOS's interruption notification and Android's audio-focus changes, each
277
/// variant naming what the APP should do.
278
#[repr(C)]
279
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
280
pub enum SystemAudioChange {
281
    /// The takeover is in place: the app owns the system audio. iOS session
282
    /// activated, Android focus granted (possibly after a delay), or a
283
    /// platform where nothing needed taking (desktop mixers share).
284
    Granted,
285
    /// Something took it for a while - a call, an alarm, another player:
286
    /// PAUSE. iOS interruption began; Android `AUDIOFOCUS_LOSS_TRANSIENT`.
287
    Interrupted,
288
    /// Something short wants to be heard over the app - a navigation prompt,
289
    /// a notification: LOWER the volume and keep playing. Android
290
    /// `AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK`; iOS has no ducking signal, it
291
    /// interrupts instead.
292
    Ducked,
293
    /// The interruption or ducking ended and the app SHOULD RESUME where it
294
    /// was: iOS ended with the "should resume" hint, Android regained
295
    /// `AUDIOFOCUS_GAIN` after a transient loss.
296
    Resumed,
297
    /// The interruption ended WITHOUT a resume hint (iOS): the session is the
298
    /// app's again, but it must wait for the user to press play.
299
    Ended,
300
    /// The takeover was refused or is gone for good: iOS could not activate
301
    /// the session, Android refused the request or reported
302
    /// `AUDIOFOCUS_LOSS`. STOP, and take over again only on the user's ask.
303
    Lost,
304
}
305

            
306
impl_option!(
307
    SystemAudioChange,
308
    OptionSystemAudioChange,
309
    [Debug, Clone, Copy, PartialEq, Eq]
310
);
311

            
312
/// A position jump larger than this, on the same track, is a SEEK the app
313
/// made on its own (a click on its own progress bar) and is announced back to
314
/// the desktop (`Seeked`) so a scrubber re-syncs.
315
///
316
/// A player reports its position once per frame, so the natural step is
317
/// ~16 ms; 2 s is far above any frame stutter and far below any jump a person
318
/// would make.
319
pub const POSITION_JUMP_THRESHOLD_US: i64 = 2_000_000;
320

            
321
#[derive(Debug, Clone, PartialEq, Default)]
322
pub struct MediaSessionManager {
323
    info: NowPlayingInfo,
324
    /// Set when [`Self::set`] changes a field the platform must be told about.
325
    needs_publish: bool,
326
    /// Requests received since the last pass, delivered as `MediaControl`
327
    /// events by the `EventProvider` impl and cleared by the dispatcher
328
    /// afterwards.
329
    pending_requests: Vec<MediaControlRequest>,
330
    /// The most recent seek, kept after delivery so a callback can read it
331
    /// (`CallbackInfo::get_media_control_request`).
332
    last_request: Option<MediaControlRequest>,
333
    /// A position jump the APP reported; the platform side announces it
334
    /// (MPRIS `Seeked`) once, then this is cleared.
335
    seeked_to_us: Option<i64>,
336
    /// Whether the app currently ASKS to own the system audio
337
    /// (`CallbackInfo::set_system_audio_takeover`), 9h-i-a-i-d-i. What the
338
    /// platform did about it arrives as [`SystemAudioChange`]s.
339
    system_audio_active: bool,
340
    /// System audio changes received since the last pass, delivered as
341
    /// `SystemAudioChange` events and cleared with the requests.
342
    pending_audio_changes: Vec<SystemAudioChange>,
343
    /// The most recent change, kept after delivery for
344
    /// `CallbackInfo::get_system_audio_change`.
345
    last_audio_change: Option<SystemAudioChange>,
346
}
347

            
348
impl MediaSessionManager {
349
    #[must_use]
350
29066
    pub fn new() -> Self {
351
29066
        Self::default()
352
29066
    }
353

            
354
    /// Record what the app is playing.
355
    ///
356
    /// # Why a position-only change does not mark this dirty
357
    ///
358
    /// A player calls this once per frame with an advancing position. If that
359
    /// marked the session dirty, every frame would put a `PropertiesChanged`
360
    /// signal on the session bus - 60 D-Bus broadcasts a second, woken up in
361
    /// every listening process on the desktop.
362
    ///
363
    /// It would also be WRONG rather than merely wasteful: the MPRIS spec says
364
    /// `Position` must not appear in `PropertiesChanged` at all, precisely
365
    /// because it changes continuously. Clients extrapolate it from
366
    /// `PlaybackStatus` and `Rate` and read the property when they need a
367
    /// precise value, so the stored position is served on demand instead.
368
145
    pub fn set(&mut self, info: NowPlayingInfo) {
369
145
        if self.info.differs_in_announced_fields(&info) {
370
19
            self.needs_publish = true;
371
126
        }
372
        // A jump on the SAME track is a seek the app made on its own
373
        // (9h-i-a-i-a): remembered for the platform to announce. A new track
374
        // starting at 0 is not a seek, and neither is the ordinary per-frame
375
        // advance.
376
145
        if !self.info.is_different_track(&info)
377
131
            && (info.position_us() - self.info.position_us()).abs() > POSITION_JUMP_THRESHOLD_US
378
4
        {
379
4
            self.seeked_to_us = Some(info.position_us());
380
141
        }
381
145
        self.info = info;
382
145
    }
383

            
384
    /// What the app last published, whether or not the platform has been told.
385
    ///
386
    /// This is what a property GETTER answers with, which is why it is
387
    /// unconditional: a desktop reading `Position` must get the current value
388
    /// even though no announcement was made for it.
389
    #[must_use]
390
2
    pub const fn current(&self) -> &NowPlayingInfo {
391
2
        &self.info
392
2
    }
393

            
394
    /// The session to announce, or `None` when nothing announceable changed.
395
143
    pub fn take_if_dirty(&mut self) -> Option<NowPlayingInfo> {
396
143
        if core::mem::take(&mut self.needs_publish) {
397
19
            Some(self.info.clone())
398
        } else {
399
124
            None
400
        }
401
143
    }
402

            
403
    /// An inbound seek from the platform (9h-i-a-i-a). Queued; the next pass
404
    /// delivers it as a `MediaControl` event at the root.
405
2
    pub fn push_request(&mut self, request: MediaControlRequest) {
406
2
        self.pending_requests.push(request);
407
2
    }
408

            
409
    /// The seek being delivered this pass, or the last one delivered - what
410
    /// a `MediaControl` callback reads.
411
    #[must_use]
412
3
    pub fn current_request(&self) -> Option<&MediaControlRequest> {
413
3
        self.pending_requests.first().or(self.last_request.as_ref())
414
3
    }
415

            
416
    /// The pass is over: the queued seeks were delivered. The newest is kept
417
    /// as `last_request`.
418
2
    pub fn clear_pending_requests(&mut self) {
419
2
        if let Some(last) = self.pending_requests.pop() {
420
1
            self.last_request = Some(last);
421
1
        }
422
2
        self.pending_requests.clear();
423
2
        if let Some(last) = self.pending_audio_changes.pop() {
424
1
            self.last_audio_change = Some(last);
425
1
        }
426
2
        self.pending_audio_changes.clear();
427
2
    }
428

            
429
    #[must_use]
430
1
    pub const fn has_pending_requests(&self) -> bool {
431
1
        !self.pending_requests.is_empty() || !self.pending_audio_changes.is_empty()
432
1
    }
433

            
434
    /// Record what the app asked for (9h-i-a-i-d-i): `true` while it wants
435
    /// to own the system audio.
436
1
    pub const fn set_system_audio_active(&mut self, active: bool) {
437
1
        self.system_audio_active = active;
438
1
    }
439

            
440
    #[must_use]
441
2
    pub const fn is_system_audio_active(&self) -> bool {
442
2
        self.system_audio_active
443
2
    }
444

            
445
    /// Queue what the system did with the audio; delivered as a
446
    /// `SystemAudioChange` event at the root on the next pass. `Lost` also
447
    /// ends the app's claim, so `is_system_audio_active` reads false after it
448
    /// without the app having to clean up.
449
2
    pub fn push_system_audio_change(&mut self, change: SystemAudioChange) {
450
2
        if change == SystemAudioChange::Lost {
451
1
            self.system_audio_active = false;
452
1
        }
453
2
        self.pending_audio_changes.push(change);
454
2
    }
455

            
456
    /// The change being delivered on this pass, or the last one delivered.
457
    #[must_use]
458
1
    pub fn current_system_audio_change(&self) -> Option<SystemAudioChange> {
459
1
        self.pending_audio_changes
460
1
            .first()
461
1
            .copied()
462
1
            .or(self.last_audio_change)
463
1
    }
464

            
465
    /// The position jump to announce (MPRIS `Seeked`), if any; cleared by
466
    /// the take.
467
4
    pub const fn take_seeked(&mut self) -> Option<i64> {
468
4
        self.seeked_to_us.take()
469
4
    }
470
}
471

            
472
impl crate::events::EventProvider for MediaSessionManager {
473
    /// One `MediaControl` event per queued request, at the root: a seek is a
474
    /// window-level command like a media key, not a node's.
475
148
    fn get_pending_events(
476
148
        &self,
477
148
        timestamp: crate::task::Instant,
478
148
    ) -> Vec<crate::events::SyntheticEvent> {
479
        use crate::events::{
480
            EventData, EventSource, EventType, MediaControlEventData, SyntheticEvent,
481
            SystemAudioEventData,
482
        };
483
148
        let controls = self.pending_requests.iter().map(|req| {
484
2
            SyntheticEvent::new(
485
2
                EventType::MediaControl,
486
2
                EventSource::User,
487
                crate::dom::DomNodeId::ROOT,
488
2
                timestamp.clone(),
489
2
                EventData::MediaControl(MediaControlEventData {
490
2
                    volume: req.volume,
491
2
                    kind: req.kind,
492
2
                    position_us: req.position_us,
493
2
                }),
494
            )
495
2
        });
496
148
        let audio = self.pending_audio_changes.iter().map(|change| {
497
1
            SyntheticEvent::new(
498
1
                EventType::SystemAudioChange,
499
1
                EventSource::User,
500
                crate::dom::DomNodeId::ROOT,
501
1
                timestamp.clone(),
502
1
                EventData::SystemAudio(SystemAudioEventData { change: *change }),
503
            )
504
1
        });
505
148
        controls.chain(audio).collect()
506
148
    }
507
}
508

            
509
#[cfg(test)]
510
mod seek_tests {
511
    use super::*;
512
    use crate::events::SystemAudioEventData;
513

            
514
4
    fn at(position_us: i64) -> NowPlayingInfo {
515
4
        let mut i = NowPlayingInfo::empty();
516
4
        i.position_ms = u64::try_from(position_us / 1000).unwrap_or(0);
517
4
        i
518
4
    }
519

            
520
    #[test]
521
1
    fn a_queued_seek_is_delivered_once_then_readable_as_the_last() {
522
        use crate::events::EventProvider;
523
1
        let mut m = MediaSessionManager::new();
524
1
        assert!(m.current_request().is_none());
525
1
        m.push_request(MediaControlRequest {
526
1
            kind: MediaControlKind::SeekAbsolute,
527
1
            position_us: 30_000_000,
528
1
            uri: AzString::from_const_str(""),
529
1
            track_id: AzString::from_const_str("/org/mpris/MediaPlayer2/Track/1"),
530
1
            volume: 0.0,
531
1
        });
532
1
        let events =
533
1
            m.get_pending_events(crate::task::Instant::Tick(crate::task::SystemTick::new(0)));
534
1
        assert_eq!(events.len(), 1);
535
1
        assert_eq!(events[0].event_type, crate::events::EventType::MediaControl);
536
1
        assert_eq!(m.current_request().map(|r| r.position_us), Some(30_000_000));
537
1
        m.clear_pending_requests();
538
1
        assert!(!m.has_pending_requests());
539
1
        assert!(m
540
1
            .get_pending_events(crate::task::Instant::Tick(crate::task::SystemTick::new(0)))
541
1
            .is_empty());
542
1
        assert_eq!(
543
1
            m.current_request().map(|r| r.position_us),
544
            Some(30_000_000),
545
            "still readable"
546
        );
547
1
    }
548

            
549
    #[test]
550
1
    fn a_volume_change_is_announced_and_a_set_volume_request_carries_its_value() {
551
        use crate::events::{EventData, EventProvider};
552
1
        let mut m = MediaSessionManager::new();
553
1
        let mut i = NowPlayingInfo::empty();
554
1
        i.volume = azul_css::OptionF32::Some(0.5);
555
1
        m.set(i.clone());
556
1
        assert!(
557
1
            m.take_if_dirty().is_some(),
558
            "a volume is an announced field (MPRIS Volume)"
559
        );
560
1
        i.volume = azul_css::OptionF32::Some(0.25);
561
1
        m.set(i.clone());
562
1
        assert!(m.take_if_dirty().is_some(), "and so is a change to it");
563
1
        m.set(i);
564
1
        assert!(m.take_if_dirty().is_none(), "the same volume again is not");
565
1
        m.push_request(MediaControlRequest {
566
1
            kind: MediaControlKind::SetVolume,
567
1
            position_us: 0,
568
1
            uri: AzString::from_const_str(""),
569
1
            track_id: AzString::from_const_str(""),
570
1
            volume: 0.75,
571
1
        });
572
1
        let events =
573
1
            m.get_pending_events(crate::task::Instant::Tick(crate::task::SystemTick::new(0)));
574
1
        assert_eq!(events.len(), 1);
575
1
        match &events[0].data {
576
1
            EventData::MediaControl(d) => {
577
1
                assert_eq!(d.kind, MediaControlKind::SetVolume);
578
1
                assert_eq!(d.volume, 0.75);
579
            }
580
            other => panic!("not a media control event: {:?}", other),
581
        }
582
1
    }
583

            
584
    /// 9h-i-a-i-d-i: a system audio change is delivered once, stays readable,
585
    /// and `Lost` ends the app's claim by itself.
586
    #[test]
587
1
    fn a_system_audio_change_is_delivered_once_and_lost_ends_the_claim() {
588
        use crate::events::{EventData, EventProvider};
589
1
        let mut m = MediaSessionManager::new();
590
1
        m.set_system_audio_active(true);
591
1
        m.push_system_audio_change(SystemAudioChange::Interrupted);
592
1
        let events =
593
1
            m.get_pending_events(crate::task::Instant::Tick(crate::task::SystemTick::new(0)));
594
1
        assert_eq!(events.len(), 1);
595
1
        assert_eq!(
596
1
            events[0].event_type,
597
            crate::events::EventType::SystemAudioChange
598
        );
599
1
        assert!(matches!(
600
1
            events[0].data,
601
            EventData::SystemAudio(SystemAudioEventData {
602
                change: SystemAudioChange::Interrupted
603
            })
604
        ));
605
1
        assert!(
606
1
            m.is_system_audio_active(),
607
            "an interruption does not end the claim"
608
        );
609
1
        m.clear_pending_requests();
610
1
        assert!(m
611
1
            .get_pending_events(crate::task::Instant::Tick(crate::task::SystemTick::new(0)))
612
1
            .is_empty());
613
1
        assert_eq!(
614
1
            m.current_system_audio_change(),
615
            Some(SystemAudioChange::Interrupted),
616
            "still readable"
617
        );
618
1
        m.push_system_audio_change(SystemAudioChange::Lost);
619
1
        assert!(!m.is_system_audio_active(), "Lost ends the claim");
620
1
    }
621

            
622
    #[test]
623
1
    fn only_a_jump_on_the_same_track_is_announced_as_a_seek() {
624
1
        let mut m = MediaSessionManager::new();
625
1
        m.set(at(1_000_000));
626
1
        m.set(at(1_016_000));
627
1
        assert_eq!(m.take_seeked(), None, "the per-frame advance is not a seek");
628
1
        m.set(at(40_000_000));
629
1
        assert_eq!(m.take_seeked(), Some(40_000_000), "a jump is");
630
1
        assert_eq!(m.take_seeked(), None, "announced once");
631
1
        m.set(at(1_000_000));
632
1
        assert_eq!(m.take_seeked(), Some(1_000_000), "backwards too");
633
1
    }
634
}
635

            
636
#[cfg(test)]
637
mod tests {
638
    use super::*;
639

            
640
127
    fn track(title: &str) -> NowPlayingInfo {
641
127
        NowPlayingInfo {
642
127
            state: MediaPlaybackState::Playing,
643
127
            title: title.into(),
644
127
            ..NowPlayingInfo::empty()
645
127
        }
646
127
    }
647

            
648
    #[test]
649
1
    fn a_fresh_manager_has_nothing_to_announce() {
650
1
        let mut m = MediaSessionManager::new();
651
1
        assert!(m.take_if_dirty().is_none());
652
1
        assert_eq!(*m.current(), NowPlayingInfo::empty());
653
1
    }
654

            
655
    #[test]
656
1
    fn a_new_track_is_announced_once() {
657
1
        let mut m = MediaSessionManager::new();
658
1
        m.set(track("Aja"));
659
1
        assert_eq!(m.take_if_dirty().map(|i| i.title), Some("Aja".into()));
660
        // Draining twice must not announce the same track again: a desktop
661
        // that redraws its widget on every signal would flicker.
662
1
        assert!(m.take_if_dirty().is_none());
663
1
    }
664

            
665
    /// THE POINT OF THE WHOLE DIRTY SPLIT. A player pushing an advancing
666
    /// position must not put a signal on the bus per frame.
667
    #[test]
668
1
    fn a_position_only_change_is_not_announced() {
669
1
        let mut m = MediaSessionManager::new();
670
1
        m.set(track("Aja"));
671
1
        let _ = m.take_if_dirty();
672

            
673
121
        for pos in 1..=120u64 {
674
120
            let mut t = track("Aja");
675
120
            t.position_ms = pos * 16;
676
120
            m.set(t);
677
120
            assert!(
678
120
                m.take_if_dirty().is_none(),
679
                "a position-only change announced itself at frame {pos}"
680
            );
681
        }
682

            
683
        // ...but it IS stored, because the property getter answers from here.
684
1
        assert_eq!(m.current().position_ms, 120 * 16);
685
1
    }
686

            
687
    /// The other half: a real change while the position is also moving still
688
    /// gets announced. Comparing the whole struct would have made this pass
689
    /// for the wrong reason, so it changes the state AND the position.
690
    #[test]
691
1
    fn a_real_change_is_announced_even_while_the_position_moves() {
692
1
        let mut m = MediaSessionManager::new();
693
1
        m.set(track("Aja"));
694
1
        let _ = m.take_if_dirty();
695

            
696
1
        let mut paused = track("Aja");
697
1
        paused.state = MediaPlaybackState::Paused;
698
1
        paused.position_ms = 4_000;
699
1
        m.set(paused);
700
1
        assert_eq!(
701
1
            m.take_if_dirty().map(|i| i.state),
702
            Some(MediaPlaybackState::Paused)
703
        );
704
1
    }
705

            
706
    #[test]
707
1
    fn every_announced_field_actually_announces() {
708
1
        let base = track("Aja");
709
1
        let mut cases: alloc::vec::Vec<(&str, NowPlayingInfo)> = alloc::vec::Vec::new();
710

            
711
1
        let mut c = base.clone();
712
1
        c.state = MediaPlaybackState::Stopped;
713
1
        cases.push(("state", c));
714
1
        let mut c = base.clone();
715
1
        c.title = "Peg".into();
716
1
        cases.push(("title", c));
717
1
        let mut c = base.clone();
718
1
        c.artist = "Steely Dan".into();
719
1
        cases.push(("artist", c));
720
1
        let mut c = base.clone();
721
1
        c.album = "Aja".into();
722
1
        cases.push(("album", c));
723
1
        let mut c = base.clone();
724
1
        c.artwork_url = "file:///cover.png".into();
725
1
        cases.push(("artwork_url", c));
726
1
        let mut c = base.clone();
727
1
        c.duration_ms = 480_000;
728
1
        cases.push(("duration_ms", c));
729

            
730
7
        for (field, changed) in cases {
731
6
            let mut m = MediaSessionManager::new();
732
6
            m.set(base.clone());
733
6
            let _ = m.take_if_dirty();
734
6
            m.set(changed);
735
6
            assert!(
736
6
                m.take_if_dirty().is_some(),
737
                "changing `{field}` did not announce itself"
738
            );
739
        }
740

            
741
        // And the one field that must NOT, stated as a case in the same list
742
        // so that adding a field to the struct forces a decision about it.
743
1
        let mut m = MediaSessionManager::new();
744
1
        m.set(base.clone());
745
1
        let _ = m.take_if_dirty();
746
1
        let mut moved = base.clone();
747
1
        moved.position_ms = 9_999;
748
1
        m.set(moved);
749
1
        assert!(m.take_if_dirty().is_none(), "position_ms announced itself");
750
1
    }
751

            
752
    /// A podcast is longer than a `u32` of microseconds can hold. The struct
753
    /// stores milliseconds and the backend converts, so this pins that the
754
    /// conversion has room - and that a nonsense value clamps instead of
755
    /// wrapping negative, which a client would render as a backwards bar.
756
    #[test]
757
1
    fn the_microsecond_conversion_has_room_and_clamps() {
758
1
        let mut i = NowPlayingInfo::empty();
759

            
760
1
        i.duration_ms = 3 * 60 * 60 * 1000;
761
1
        assert_eq!(i.duration_us(), 10_800_000_000);
762
1
        assert!(i.duration_us() > i64::from(u32::MAX));
763

            
764
1
        i.position_ms = 1_500;
765
1
        assert_eq!(i.position_us(), 1_500_000);
766

            
767
1
        i.duration_ms = u64::MAX;
768
1
        assert_eq!(i.duration_us(), i64::MAX, "an absurd duration must clamp");
769
1
        assert!(i.duration_us() > 0, "and must never come out negative");
770
1
    }
771

            
772
    /// A THIRD unit, and the one most likely to be got wrong because it looks
773
    /// like a duration rather than a count: WinRT `TimeSpan` ticks are 100ns.
774
    #[test]
775
1
    fn winrt_ticks_are_hundred_nanoseconds_and_clamp() {
776
        // One second.
777
1
        assert_eq!(ms_to_winrt_ticks(1_000), 10_000_000);
778
        // A three-minute track, the value a wrong factor makes absurd.
779
1
        assert_eq!(ms_to_winrt_ticks(180_000), 1_800_000_000);
780
1
        assert_eq!(ms_to_winrt_ticks(0), 0);
781
1
        assert_eq!(ms_to_winrt_ticks(u64::MAX), i64::MAX);
782
1
        assert!(ms_to_winrt_ticks(u64::MAX) > 0, "must never wrap negative");
783
1
    }
784

            
785
    /// THE DISCRIMINANTS CROSS A JNI BOUNDARY. `AzulMediaSession.publish`
786
    /// switches on these exact integers to pick an Android `PlaybackState`
787
    /// constant, and renumbering the enum would make a playing track report as
788
    /// stopped with nothing failing to compile - the same hazard as the sensor
789
    /// kind codes, and the same guard.
790
    ///
791
    /// APPEND, never renumber, if a state is ever added.
792
    #[test]
793
1
    fn the_playback_state_discriminants_are_the_jni_wire_codes() {
794
1
        assert_eq!(MediaPlaybackState::Stopped as i32, 0);
795
1
        assert_eq!(MediaPlaybackState::Playing as i32, 1);
796
1
        assert_eq!(MediaPlaybackState::Paused as i32, 2);
797
1
    }
798

            
799
    /// `mpris:trackid` is what a desktop keys its progress bar on, so a pause
800
    /// must not look like a new track.
801
    #[test]
802
1
    fn pausing_is_the_same_track_but_a_new_title_is_not() {
803
1
        let playing = track("Aja");
804
1
        let mut paused = playing.clone();
805
1
        paused.state = MediaPlaybackState::Paused;
806
1
        paused.position_ms = 30_000;
807
1
        assert!(!playing.is_different_track(&paused));
808

            
809
        // Late-arriving cover art is also still the same track.
810
1
        let mut with_art = playing.clone();
811
1
        with_art.artwork_url = "file:///cover.png".into();
812
1
        assert!(!playing.is_different_track(&with_art));
813

            
814
1
        let next = track("Peg");
815
1
        assert!(playing.is_different_track(&next));
816

            
817
        // A live version shares a title and artist but not a length.
818
1
        let mut live = playing.clone();
819
1
        live.duration_ms = 480_000;
820
1
        assert!(playing.is_different_track(&live));
821
1
    }
822
}