kithara-queue 0.0.1-alpha5

Queue/playlist orchestration: gapless, crossfade-aware.
Documentation
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
use std::sync::atomic::{AtomicU64, Ordering};

use kithara_bufpool::HasPool;
use kithara_events::TrackId;
#[cfg(test)]
use kithara_play::PlaybackShared;
pub use kithara_play::player::PlaybackView;
use kithara_play::{CrossfadeSettings, ResourceSrc, SelectionPlayback};

use crate::track::TrackSource;

/// Transition style for a track switch.
///
/// Mirrors the Apple-idiomatic pattern of a namespace-style type with
/// variants describing "what" — not "how" — so the same method
/// signature handles both manual and auto-advance cases.
///
/// - [`Transition::None`] — immediate cut (0 seconds). Matches
///   `AVQueuePlayer`'s user-initiated selection idiom.
/// - [`Transition::Crossfade`] — use the player's configured
///   [`PlayerImpl::crossfade_duration`](kithara_play::PlayerImpl::crossfade_duration).
/// - [`Transition::CrossfadeWith`] — explicit override in seconds.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Transition {
    /// No crossfade; immediate cut.
    None,
    /// Use the player's configured crossfade duration.
    Crossfade,
    /// Use an explicit crossfade duration (seconds).
    CrossfadeWith { settings: CrossfadeSettings },
}

impl Transition {
    /// Resolve the transition to an actual crossfade duration in
    /// seconds using `default` for [`Transition::Crossfade`].
    #[must_use]
    pub const fn settings(self, default: CrossfadeSettings) -> CrossfadeSettings {
        match self {
            Self::None => CrossfadeSettings {
                duration: 0.0,
                ..default
            },
            Self::Crossfade => default,
            Self::CrossfadeWith { settings } => settings,
        }
    }
}

/// A pending-select entry: a track id waiting to be applied plus the
/// [`Transition`] the caller asked for. Stored until loading finishes.
#[derive(Clone, Copy, Debug)]
pub(super) struct PendingSelect {
    pub(super) reason: crate::AdvanceReason,
    pub(super) settings: CrossfadeSettings,
    pub(super) playback: SelectionPlayback,
    pub(super) id: TrackId,
}

/// Crossfade-arm coordination state. Replaces the `u64::MAX` sentinel
/// previously stored in `crossfade_armed_for`; "no track armed" is the
/// explicit [`CrossfadeArm::Disarmed`] variant.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CrossfadeArm {
    Disarmed,
    Armed { for_track: TrackId },
}

impl CrossfadeArm {
    pub(super) const fn armed(for_track: TrackId) -> Self {
        Self::Armed { for_track }
    }

    pub(super) fn is_armed_for(self, id: TrackId) -> bool {
        matches!(self, Self::Armed { for_track } if for_track == id)
    }
}

/// Pending-select phase. Replaces `Option<PendingSelect>` where `None`
/// conflated "idle" with "absent"; [`SelectPhase::Idle`] makes the
/// no-selection state explicit.
#[derive(Clone, Copy, Debug)]
pub(super) enum SelectPhase {
    Idle,
    Pending(PendingSelect),
}

/// Cached monotonic playback position. Replaces the `f64::NAN` sentinel
/// stored in `cached_position`; "no value yet" is the explicit
/// [`CachedPosition::Unknown`] variant.
#[derive(Clone, Copy, Debug)]
pub(super) enum CachedPosition {
    Unknown,
    Known { seconds: f64 },
}

impl CachedPosition {
    /// Build a [`CachedPosition::Known`], canonicalising a `NaN` input to
    /// [`CachedPosition::Unknown`] so the type never carries a `NaN`.
    pub(super) const fn known(seconds: f64) -> Self {
        if seconds.is_nan() {
            Self::Unknown
        } else {
            Self::Known { seconds }
        }
    }
}

impl From<CachedPosition> for Option<f64> {
    fn from(pos: CachedPosition) -> Self {
        match pos {
            CachedPosition::Known { seconds } => Some(seconds),
            CachedPosition::Unknown => None,
        }
    }
}

/// Lock-free [`CrossfadeArm`] cell for the `tick` hot path. The
/// `u64::MAX` bit pattern encodes [`CrossfadeArm::Disarmed`]; real ids
/// are allocated monotonically from `0`, so the top of the range is
/// free as the sentinel. Orderings match the original raw-`AtomicU64`
/// accessors: `Acquire` load, `Release` store, `AcqRel` swap /
/// compare-exchange.
pub(super) struct AtomicTrackId(AtomicU64);

impl AtomicTrackId {
    const NONE_BITS: u64 = u64::MAX;

    /// CAS [`CrossfadeArm::Disarmed`] → `Armed(track)`.
    pub(super) fn arm_if_disarmed(&self, track: TrackId) -> bool {
        self.0
            .compare_exchange(
                Self::NONE_BITS,
                track.as_u64(),
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }

    const fn decode(bits: u64) -> CrossfadeArm {
        if bits == Self::NONE_BITS {
            CrossfadeArm::Disarmed
        } else {
            CrossfadeArm::Armed {
                for_track: TrackId(bits),
            }
        }
    }

    /// CAS `Armed(track)` → [`CrossfadeArm::Disarmed`]. Returns `true` when
    /// `track` was the armed id.
    pub(super) fn disarm_if_matches(&self, track: TrackId) -> bool {
        self.0
            .compare_exchange(
                track.as_u64(),
                Self::NONE_BITS,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }

    pub(super) const fn disarmed() -> Self {
        Self(AtomicU64::new(Self::NONE_BITS))
    }

    const fn encode(arm: CrossfadeArm) -> u64 {
        match arm {
            CrossfadeArm::Disarmed => Self::NONE_BITS,
            CrossfadeArm::Armed { for_track } => for_track.as_u64(),
        }
    }

    pub(super) fn load(&self) -> CrossfadeArm {
        Self::decode(self.0.load(Ordering::Acquire))
    }

    pub(super) fn store(&self, arm: CrossfadeArm) {
        self.0.store(Self::encode(arm), Ordering::Release);
    }

    pub(super) fn take_if_matches(&self, track: TrackId) -> bool {
        self.0
            .compare_exchange(
                track.as_u64(),
                Self::NONE_BITS,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }
}

/// Lock-free [`CachedPosition`] cell for the `tick` hot path. The
/// `f64::NAN` bit pattern encodes [`CachedPosition::Unknown`]; any `NaN`
/// observed on load (including a `NaN` written through `store`)
/// canonicalises back to `Unknown`.
pub(super) struct AtomicCachedPosition(AtomicU64);

impl AtomicCachedPosition {
    pub(super) fn load(&self) -> CachedPosition {
        let seconds = f64::from_bits(self.0.load(Ordering::Acquire));
        if seconds.is_nan() {
            CachedPosition::Unknown
        } else {
            CachedPosition::Known { seconds }
        }
    }

    pub(super) fn store(&self, pos: CachedPosition) {
        let bits = match pos {
            CachedPosition::Unknown => f64::NAN.to_bits(),
            CachedPosition::Known { seconds } => seconds.to_bits(),
        };
        self.0.store(bits, Ordering::Release);
    }

    pub(super) const fn unknown() -> Self {
        Self(AtomicU64::new(f64::NAN.to_bits()))
    }
}

/// Where a new track should land in the queue's internal `Vec`.
#[derive(Clone, Copy, Debug)]
pub(super) enum Placement {
    /// Push past the tail — used by `Queue::append`.
    Append,
    /// Insert at a caller-resolved position — used by `Queue::insert`
    /// after it looks up `after_id`.
    At(usize),
}

/// Current playback position and total duration in seconds, bundled
/// so the `should_arm_crossfade` signature does not put 3 consecutive
/// raw float parameters at the API boundary.
#[derive(Clone, Copy, Debug)]
pub(crate) struct PlaybackTime {
    pub(crate) dur: f64,
    pub(crate) pos: f64,
}

/// Decide whether `Queue::tick` should arm the pre-end advance.
///
/// Returns `true` when:
/// - `crossfade > 0` (no pre-arm without crossfade — natural-EOF advance is
///   handled via [`PlayerEvent::ItemDidPlayToEnd`] instead), AND
/// - `time.pos` and `time.dur` are positive (track has meaningful position + duration), AND
/// - remaining playtime is below `crossfade` seconds, AND
/// - we haven't already armed for this track this play-through.
pub(crate) fn should_arm_crossfade(
    time: PlaybackTime,
    crossfade: f32,
    current_id: TrackId,
    armed_for: CrossfadeArm,
) -> bool {
    let PlaybackTime { pos, dur } = time;
    crossfade > 0.0
        && dur > 0.0
        && pos > 0.0
        && dur - pos <= f64::from(crossfade)
        && !armed_for.is_armed_for(current_id)
}

pub(super) fn extract_track_name<S>(source: &TrackSource<S>) -> String
where
    S: HasPool<u8> + HasPool<f32> + Send + Sync + 'static,
{
    let raw = match source {
        TrackSource::Uri(s) => s.as_str(),
        TrackSource::Config(cfg) => return name_from_src(cfg.source()),
    };
    name_from_raw(raw)
}

fn name_from_src(src: &ResourceSrc) -> String {
    match src {
        ResourceSrc::Url(url) => {
            let path = url.path();
            name_from_raw(path)
        }
        ResourceSrc::Path(p) => p.file_name().map_or_else(
            || "Unknown".to_string(),
            |n| n.to_string_lossy().into_owned(),
        ),
    }
}

fn name_from_raw(s: &str) -> String {
    s.rsplit('/')
        .find(|seg| !seg.is_empty())
        .unwrap_or("Unknown")
        .to_string()
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::Ordering;

    use kithara_test_utils::kithara;

    use super::*;

    #[kithara::test]
    fn atomic_track_id_disarmed_loads_disarmed() {
        let cell = AtomicTrackId::disarmed();
        assert_eq!(cell.load(), CrossfadeArm::Disarmed);
    }

    #[kithara::test]
    fn atomic_track_id_take_if_matches_only_disarms_matching_track() {
        let cell = AtomicTrackId::disarmed();
        cell.store(CrossfadeArm::armed(TrackId(7)));
        assert_eq!(
            cell.load(),
            CrossfadeArm::Armed {
                for_track: TrackId(7),
            }
        );
        assert!(!cell.take_if_matches(TrackId(8)));
        assert_eq!(
            cell.load(),
            CrossfadeArm::Armed {
                for_track: TrackId(7),
            }
        );
        assert!(cell.take_if_matches(TrackId(7)));
        assert_eq!(cell.load(), CrossfadeArm::Disarmed);
    }

    #[kithara::test]
    fn atomic_track_id_cas_arm_then_disarm() {
        let cell = AtomicTrackId::disarmed();
        cell.arm_if_disarmed(TrackId(3));
        cell.arm_if_disarmed(TrackId(4));
        assert_eq!(
            cell.load(),
            CrossfadeArm::Armed {
                for_track: TrackId(3),
            },
            "a second arm must not replace the armed track"
        );
        assert!(!cell.disarm_if_matches(TrackId(4)));
        assert!(cell.disarm_if_matches(TrackId(3)));
        assert_eq!(cell.load(), CrossfadeArm::Disarmed);
    }

    #[kithara::test]
    fn atomic_cached_position_unknown_loads_none() {
        let cell = AtomicCachedPosition::unknown();
        assert_eq!(Option::<f64>::from(cell.load()), None);
    }

    #[kithara::test]
    fn atomic_cached_position_round_trip_zero() {
        let cell = AtomicCachedPosition::unknown();
        cell.store(CachedPosition::known(0.0));
        assert_eq!(Option::<f64>::from(cell.load()), Some(0.0));
    }

    #[kithara::test]
    fn cached_position_known_nan_canonicalises_to_unknown() {
        assert!(matches!(
            CachedPosition::known(f64::NAN),
            CachedPosition::Unknown
        ));
    }

    fn view_of(frontier: f64, cached: f64) -> PlaybackView {
        let shared = PlaybackShared::default();
        shared.duration.store(200.0, Ordering::Relaxed);
        shared.frontier.store(frontier, Ordering::Relaxed);
        shared.cached.store(cached, Ordering::Relaxed);
        PlaybackView::from(shared.snapshot())
    }

    /// A fully downloaded track must report its cached span, not the sliver
    /// the decoder has produced — that span is what a host progress bar and
    /// `loadedTimeRanges` mean by "available without more network".
    #[kithara::test]
    fn buffered_covers_the_cached_span() {
        assert_eq!(view_of(4.0, 120.0).buffered, Some(120.0));
    }

    /// The frontier is a floor, not a value the cached span replaces: a
    /// reported window that falls behind the playhead makes the host pause
    /// into a buffering deadlock.
    #[kithara::test]
    fn buffered_never_falls_behind_the_decoded_frontier() {
        assert_eq!(view_of(90.0, 12.0).buffered, Some(90.0));
    }

    #[kithara::test]
    fn buffered_is_zero_when_nothing_is_available() {
        assert_eq!(view_of(0.0, 0.0).buffered, Some(0.0));
    }

    #[kithara::test]
    fn crossfade_arm_is_armed_for_matches_track() {
        let arm = CrossfadeArm::armed(TrackId(2));
        assert!(arm.is_armed_for(TrackId(2)));
        assert!(!arm.is_armed_for(TrackId(3)));
    }

    #[kithara::test]
    fn select_phase_pending_carries_captured_policy() {
        let phase = SelectPhase::Pending(PendingSelect {
            id: TrackId(5),
            settings: CrossfadeSettings {
                duration: 0.0,
                ..CrossfadeSettings::default()
            },
            playback: SelectionPlayback::Play,
            reason: crate::AdvanceReason::UserSelect,
        });
        match phase {
            SelectPhase::Pending(p) => {
                assert_eq!(p.id, TrackId(5));
                assert_eq!(p.settings.duration, 0.0);
                assert_eq!(p.playback, SelectionPlayback::Play);
                assert_eq!(p.reason, crate::AdvanceReason::UserSelect);
            }
            SelectPhase::Idle => panic!("expected Pending"),
        }
    }
}