jellytau_lib/player/stream_end.rs
1//! Telling a *finished* stream apart from a *truncated* one.
2//!
3//! TRACES: UR-040 | DR-129 | UT-117
4//!
5//! Background audio-only playback of a video item streams a **progressive mp3
6//! transcode over plain HTTP** (see
7//! `OnlineRepository::build_audio_only_stream_url_for_video`). That response has
8//! no reliable length — a live transcode is chunked — so when the connection
9//! drops mid-episode the data source simply sees end-of-input. ExoPlayer cannot
10//! distinguish that from the real end of the media and reports
11//! `Player.STATE_ENDED`, which the app then treats as "the episode finished".
12//!
13//! The user-visible damage is not the missed advance itself. Playback parks in
14//! ExoPlayer's `STATE_ENDED`, and the next play intent from the lockscreen,
15//! notification or a Bluetooth reconnect goes through media3's
16//! `Util.handlePlayButtonAction`, which seeks an ENDED player to its default
17//! position before playing — so **the episode starts over from 0:00**. On a
18//! flaky connection that reads as "it randomly restarts the episode".
19//!
20//! The player itself has no way to know; the *duration* does. Jellyfin gives us
21//! the item's real runtime, so an end reported well short of it is a truncation,
22//! not a finish — and the right response is to re-open the stream where it died,
23//! which is the "buffer and resume" the user expects.
24
25use crate::player::media::{MediaItem, MediaSource, MediaType};
26
27/// How far short of the item's runtime a stream may end and still count as a
28/// natural finish.
29///
30/// Sized to swallow the two sources of slack in the comparison — the position
31/// poll is up to 250 ms stale, and Jellyfin's reported runtime can disagree with
32/// the transcoded output by a second or two — while staying far below the
33/// minutes-long gap a dropped connection leaves. Erring long is the safe
34/// direction: a false "finished" is the bug we are fixing, whereas a false
35/// "truncated" only re-opens the stream for its last few seconds and then ends
36/// again normally.
37pub const TRUNCATED_STREAM_TOLERANCE_SECS: f64 = 10.0;
38
39/// Consecutive resume attempts allowed at the same position before giving up.
40///
41/// A resume re-opens the same URL, so a server that is genuinely gone would
42/// otherwise end → resume → end forever. Progress past the last attempt resets
43/// the budget (see [`ResumeTracker`]), so this only bounds *stuck* retries.
44pub const MAX_STALLED_RESUME_ATTEMPTS: u32 = 3;
45
46/// Position change that counts as "this is a different playback context" —
47/// either the resume made progress, or a different item is loaded.
48const RESUME_PROGRESS_EPSILON_SECS: f64 = 1.0;
49
50/// A video item played through the native *audio* path — i.e. the background
51/// audio-only handoff, the only place a length-less progressive transcode is
52/// used. Jellyfin's item-type taxonomy stays in Rust (CLAUDE.md).
53///
54/// TRACES: UR-040 | DR-129, DR-203 | UT-117, UT-200
55pub fn is_audio_only_video(item: &MediaItem) -> bool {
56 item.media_type == MediaType::Audio
57 && matches!(item.item_type.as_deref(), Some("Episode") | Some("Movie"))
58}
59
60/// Would the *player's own* load-error retry restart this stream from its
61/// beginning? If so the retry must be switched off and recovery left to
62/// [`crate::player::PlayerController::recoverable_error_resume`].
63///
64/// ExoPlayer resumes a failed load in place only when it knows where "in place"
65/// is: `ProgressiveMediaPeriod.configureRetry` keeps the load position when the
66/// content length is known *or* the extractor produced a seek map with a
67/// duration, and otherwise treats the source as live — the data at the URL is
68/// assumed to have changed, so it resets every sample queue and re-requests the
69/// URL from offset 0.
70///
71/// The handoff transcode satisfies neither condition: it is chunked (no
72/// `Content-Length`) and a live mp3 encode carries no `Xing` header, so the
73/// player reports its duration as unset — visible in logcat as every position
74/// tick reading `<position> / 0.0`. Its URL carries `StartTimeTicks` = the
75/// handoff point, so restarting it from offset 0 restarts the *episode* at the
76/// handoff point, and playback then runs on from there. Nothing surfaces: no
77/// error, no `STATE_ENDED`, so neither the truncation path nor the error path of
78/// DR-129 is consulted, and the app's only sign of it is a position that jumps
79/// backwards. That is the "it randomly jumps back to where audio-only started"
80/// the user sees, and how random it is depends on whether a network blip happens
81/// to land while a load is in flight rather than while the ~50s buffer covers it.
82///
83/// A retry that can only restart the stream is worth less than no retry at all:
84/// declining it turns the silent rewind into a recoverable error, which
85/// `recoverable_error_resume` answers by re-opening the stream at the position
86/// playback actually reached (`StartTimeTicks` rewritten, backoff and attempt
87/// budget included). Every other source keeps the player's retry: a static file
88/// and an HLS playlist both declare their timeline, so ExoPlayer resumes them
89/// exactly where the load failed.
90///
91/// TRACES: UR-040, UR-004 | DR-203 | UT-200
92#[cfg_attr(not(target_os = "android"), allow(dead_code))]
93pub fn player_retry_restarts_stream(item: &MediaItem) -> bool {
94 is_audio_only_video(item) && matches!(item.source, MediaSource::Remote { .. })
95}
96
97/// Did this end-of-stream happen far enough short of the item's runtime to be a
98/// truncation rather than a finish?
99///
100/// `position` and `duration` must be on the same timeline — for a handoff stream
101/// built with `StartTimeTicks`, that means the *absolute* position (handoff base
102/// + the player's relative position) against the item's full runtime.
103///
104/// An unknown or non-positive `duration` answers `false`: with nothing to
105/// compare against, the reported end is taken at face value (previous behaviour).
106pub fn is_truncated_end(position: f64, duration: Option<f64>, tolerance: f64) -> bool {
107 let Some(duration) = duration else {
108 return false;
109 };
110 if duration <= 0.0 {
111 return false;
112 }
113 position.max(0.0) + tolerance < duration
114}
115
116/// Rewrite an audio-only stream URL to start at `position_seconds`.
117///
118/// Resuming re-opens *the stream we were already playing*, so the URL is edited
119/// in place rather than rebuilt from the repository: every other parameter —
120/// `AudioStreamIndex` (the track the user picked in the video player),
121/// `MediaSourceId`, `api_key` — is carried over untouched, and no network call
122/// is needed to recover from a network failure.
123pub fn with_start_time(url: &str, position_seconds: f64) -> String {
124 let ticks = (position_seconds.max(0.0) * 10_000_000.0) as i64;
125 let param = format!("StartTimeTicks={}", ticks);
126
127 let (base, query) = match url.split_once('?') {
128 Some((base, query)) => (base, query),
129 // No query string at all: the URL was not built by us, but appending the
130 // parameter is still the correct request to make.
131 None => return format!("{}?{}", url, param),
132 };
133
134 let mut replaced = false;
135 let mut parts: Vec<String> = query
136 .split('&')
137 .map(|part| {
138 if part.split('=').next() == Some("StartTimeTicks") {
139 replaced = true;
140 param.clone()
141 } else {
142 part.to_string()
143 }
144 })
145 .collect();
146
147 if !replaced {
148 parts.push(param);
149 }
150
151 format!("{}?{}", base, parts.join("&"))
152}
153
154/// The last playback time actually observed while media was loaded.
155///
156/// Some backends expose position and duration as **live** properties of the
157/// loaded file — MPV's `time-pos` and `duration` stop resolving the moment it
158/// unloads the file at EOF. Reading them straight through means that at exactly
159/// the moment end-of-file handling wants to know where playback got to, the
160/// answer is `0.0` / unknown: the player appears to rewind to 0:00 as it ends.
161///
162/// The polling thread records here, and the accessors fall back to it, so an EOF
163/// reads as the last timestamp rather than as zero.
164#[derive(Debug, Default, Clone, Copy)]
165pub struct ObservedTime {
166 position: f64,
167 duration: Option<f64>,
168}
169
170impl ObservedTime {
171 /// Record a live reading. Non-positive durations are treated as unknown —
172 /// that is how a backend reports "not established yet", not a real zero.
173 pub fn record(&mut self, position: f64, duration: f64) {
174 self.position = position.max(0.0);
175 if duration > 0.0 {
176 self.duration = Some(duration);
177 }
178 }
179
180 /// Record a position alone, e.g. straight after a seek, before the next poll.
181 pub fn record_position(&mut self, position: f64) {
182 self.position = position.max(0.0);
183 }
184
185 /// Forget everything — a different file is loading, and the previous one's
186 /// timestamp must not leak into it.
187 pub fn reset(&mut self) {
188 *self = Self::default();
189 }
190
191 /// The live reading if there is one, else the last observed value.
192 pub fn position_or_last(&self, live: Option<f64>) -> f64 {
193 live.filter(|p| *p >= 0.0).unwrap_or(self.position)
194 }
195
196 /// The last observed position, with no live reading to prefer — the case
197 /// where the *reporter* is the only source there is (webview-rendered media,
198 /// which the native backend cannot see at all).
199 pub fn last_position(&self) -> f64 {
200 self.position
201 }
202
203 /// The last observed duration, if one was ever established.
204 pub fn last_duration(&self) -> Option<f64> {
205 self.duration
206 }
207
208 /// The live reading if there is one, else the last observed value.
209 pub fn duration_or_last(&self, live: Option<f64>) -> Option<f64> {
210 live.filter(|d| *d > 0.0).or(self.duration)
211 }
212}
213
214/// Budget for consecutive resume attempts that make no progress.
215///
216/// Held by the player controller across ends of the *same* stream. Any position
217/// change larger than [`RESUME_PROGRESS_EPSILON_SECS`] — the resume played on,
218/// or a different item was loaded — is a fresh context and refills the budget.
219#[derive(Debug, Default)]
220pub struct ResumeTracker {
221 last_position: Option<f64>,
222 attempts: u32,
223}
224
225impl ResumeTracker {
226 /// Record an attempt at `position`, returning its 1-based number — or `None`
227 /// once the budget is spent. Callers use the number to back off: a stream
228 /// that failed twice at the same spot is waiting on something slower than an
229 /// immediate retry can outrun.
230 pub fn allow_attempt(&mut self, position: f64) -> Option<u32> {
231 let progressed = match self.last_position {
232 Some(last) => (position - last).abs() > RESUME_PROGRESS_EPSILON_SECS,
233 None => true,
234 };
235 if progressed {
236 self.attempts = 0;
237 }
238 self.last_position = Some(position);
239 self.attempts += 1;
240 (self.attempts <= MAX_STALLED_RESUME_ATTEMPTS).then_some(self.attempts)
241 }
242
243 /// Forget the budget — a new item is playing, so nothing is stuck.
244 pub fn reset(&mut self) {
245 self.last_position = None;
246 self.attempts = 0;
247 }
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 use std::path::PathBuf;
255
256 /// The background-audio handoff item, as `player_enter_background_audio`
257 /// builds it: the episode replayed as AUDIO off a remote stream URL whose
258 /// `StartTimeTicks` is the handoff point.
259 fn handoff_item() -> MediaItem {
260 MediaItem {
261 id: "ep2".to_string(),
262 title: "Episode 2".to_string(),
263 name: None,
264 artist: None,
265 album: None,
266 album_name: None,
267 album_id: None,
268 artist_items: None,
269 artists: None,
270 primary_image_tag: None,
271 image_id: None,
272 item_type: Some("Episode".to_string()),
273 playlist_id: None,
274 duration: Some(1500.0),
275 artwork_url: None,
276 media_type: MediaType::Audio,
277 source: MediaSource::Remote {
278 stream_url: "http://s/Audio/ep2/universal?Container=mp3&StartTimeTicks=1250000000"
279 .to_string(),
280 jellyfin_item_id: "ep2".to_string(),
281 },
282 video_codec: None,
283 needs_transcoding: false,
284 video_width: None,
285 video_height: None,
286 subtitles: vec![],
287 series_id: Some("series1".to_string()),
288 server_id: None,
289 }
290 }
291
292 /// The reported bug: a load error on the length-less handoff transcode let
293 /// ExoPlayer "retry" the only way it can — from offset 0 — which re-opens
294 /// the URL at its `StartTimeTicks` and drops playback back to the handoff
295 /// point, silently. This item must never be left to the player's own retry.
296 #[test]
297 fn test_handoff_transcode_must_not_use_the_players_own_retry() {
298 assert!(player_retry_restarts_stream(&handoff_item()));
299 }
300
301 #[test]
302 fn test_music_keeps_the_players_retry() {
303 // `/Audio/{id}/stream?Static=true` — a real Content-Length and byte
304 // ranges, so ExoPlayer resumes it where the load failed.
305 let track = MediaItem {
306 item_type: Some("Audio".to_string()),
307 ..handoff_item()
308 };
309 assert!(!player_retry_restarts_stream(&track));
310 }
311
312 #[test]
313 fn test_video_keeps_the_players_retry() {
314 // An HLS playlist declares its segments, so a failed segment load is
315 // retried at that segment, not at the start of the episode.
316 let video = MediaItem {
317 media_type: MediaType::Video,
318 ..handoff_item()
319 };
320 assert!(!player_retry_restarts_stream(&video));
321 }
322
323 #[test]
324 fn test_downloaded_episode_keeps_the_players_retry() {
325 // A local file has no length problem and no network to lose.
326 let local = MediaItem {
327 source: MediaSource::Local {
328 file_path: PathBuf::from("/data/ep2.mkv"),
329 jellyfin_item_id: Some("ep2".to_string()),
330 },
331 ..handoff_item()
332 };
333 assert!(!player_retry_restarts_stream(&local));
334 }
335
336 #[test]
337 fn test_end_near_duration_is_a_natural_finish() {
338 // Episode runtime 25:00, stream ended at 24:56 — that is the end.
339 assert!(!is_truncated_end(
340 1496.0,
341 Some(1500.0),
342 TRUNCATED_STREAM_TOLERANCE_SECS
343 ));
344 }
345
346 #[test]
347 fn test_end_far_short_of_duration_is_truncated() {
348 // Episode runtime 25:00, stream died at 10:00 — the connection dropped.
349 assert!(is_truncated_end(
350 600.0,
351 Some(1500.0),
352 TRUNCATED_STREAM_TOLERANCE_SECS
353 ));
354 }
355
356 #[test]
357 fn test_unknown_duration_is_taken_at_face_value() {
358 // Nothing to compare against: keep the previous end-of-track behaviour
359 // rather than resuming a stream that may really have finished.
360 assert!(!is_truncated_end(
361 600.0,
362 None,
363 TRUNCATED_STREAM_TOLERANCE_SECS
364 ));
365 assert!(!is_truncated_end(
366 600.0,
367 Some(0.0),
368 TRUNCATED_STREAM_TOLERANCE_SECS
369 ));
370 }
371
372 #[test]
373 fn test_tolerance_boundary() {
374 // Exactly one tolerance short still counts as finished, so poll staleness
375 // and runtime rounding never fabricate a truncation.
376 assert!(!is_truncated_end(1490.0, Some(1500.0), 10.0));
377 assert!(is_truncated_end(1489.0, Some(1500.0), 10.0));
378 }
379
380 #[test]
381 fn test_with_start_time_replaces_existing_ticks() {
382 let url = "http://s/Audio/ep2/universal?api_key=k&AudioStreamIndex=2&StartTimeTicks=1200000000&Container=mp3";
383 let out = with_start_time(url, 600.0);
384 assert_eq!(
385 out,
386 "http://s/Audio/ep2/universal?api_key=k&AudioStreamIndex=2&StartTimeTicks=6000000000&Container=mp3"
387 );
388 }
389
390 #[test]
391 fn test_with_start_time_appends_when_absent() {
392 // The next-episode stream is built without StartTimeTicks.
393 let url = "http://s/Audio/ep3/universal?api_key=k&AudioStreamIndex=0";
394 let out = with_start_time(url, 90.0);
395 assert_eq!(
396 out,
397 "http://s/Audio/ep3/universal?api_key=k&AudioStreamIndex=0&StartTimeTicks=900000000"
398 );
399 }
400
401 #[test]
402 fn test_with_start_time_preserves_selected_audio_track() {
403 // The whole point of editing the URL instead of rebuilding it: the track
404 // the user chose in the video player survives the resume.
405 let url = "http://s/Audio/ep2/universal?AudioStreamIndex=3&MediaSourceId=src-1";
406 let out = with_start_time(url, 10.0);
407 assert!(out.contains("AudioStreamIndex=3"));
408 assert!(out.contains("MediaSourceId=src-1"));
409 }
410
411 #[test]
412 fn test_with_start_time_without_query() {
413 assert_eq!(
414 with_start_time("http://s/Audio/ep2/universal", 1.0),
415 "http://s/Audio/ep2/universal?StartTimeTicks=10000000"
416 );
417 }
418
419 /// The bug: MPV unloads the file at EOF, so `time-pos` stops resolving and a
420 /// straight read reports 0.0 — the position collapses to zero at precisely
421 /// the moment end-of-file handling needs to know where playback reached.
422 #[test]
423 fn test_eof_reads_as_the_last_observed_timestamp() {
424 let mut observed = ObservedTime::default();
425 observed.record(178.0, 180.0);
426
427 // The file is gone: both live properties fail.
428 assert_eq!(observed.position_or_last(None), 178.0);
429 assert_eq!(observed.duration_or_last(None), Some(180.0));
430 }
431
432 #[test]
433 fn test_live_readings_win_while_the_file_is_loaded() {
434 let mut observed = ObservedTime::default();
435 observed.record(178.0, 180.0);
436
437 assert_eq!(observed.position_or_last(Some(12.0)), 12.0);
438 assert_eq!(observed.duration_or_last(Some(240.0)), Some(240.0));
439 }
440
441 #[test]
442 fn test_unestablished_duration_is_not_recorded_as_zero() {
443 let mut observed = ObservedTime::default();
444 // A backend reports 0.0 for "duration not known yet", not a real zero.
445 observed.record(5.0, 0.0);
446 assert_eq!(observed.duration_or_last(None), None);
447 assert_eq!(observed.position_or_last(None), 5.0);
448
449 observed.record(6.0, 180.0);
450 assert_eq!(observed.duration_or_last(Some(0.0)), Some(180.0));
451 }
452
453 #[test]
454 fn test_reset_stops_the_previous_file_leaking_into_the_next() {
455 let mut observed = ObservedTime::default();
456 observed.record(178.0, 180.0);
457 observed.reset();
458
459 assert_eq!(observed.position_or_last(None), 0.0);
460 assert_eq!(observed.duration_or_last(None), None);
461 }
462
463 #[test]
464 fn test_seek_updates_the_last_position_before_the_next_poll() {
465 let mut observed = ObservedTime::default();
466 observed.record(10.0, 180.0);
467 observed.record_position(120.0);
468
469 assert_eq!(observed.position_or_last(None), 120.0);
470 assert_eq!(
471 observed.duration_or_last(None),
472 Some(180.0),
473 "seeking does not change how long the file is"
474 );
475 }
476
477 #[test]
478 fn test_resume_tracker_bounds_stalled_retries() {
479 let mut tracker = ResumeTracker::default();
480 // Same position over and over: the stream is not recovering.
481 for n in 1..=MAX_STALLED_RESUME_ATTEMPTS {
482 assert_eq!(
483 tracker.allow_attempt(600.0),
484 Some(n),
485 "attempts are numbered so callers can back off"
486 );
487 }
488 assert_eq!(
489 tracker.allow_attempt(600.0),
490 None,
491 "a stream that ends at the same position every time must stop retrying"
492 );
493 }
494
495 #[test]
496 fn test_resume_tracker_refills_after_progress() {
497 let mut tracker = ResumeTracker::default();
498 for _ in 0..MAX_STALLED_RESUME_ATTEMPTS {
499 tracker.allow_attempt(600.0);
500 }
501 assert_eq!(tracker.allow_attempt(600.0), None);
502 // The next drop happened further in — the resumes are working, so the
503 // budget must not be exhausted by earlier trouble.
504 assert_eq!(tracker.allow_attempt(900.0), Some(1));
505 }
506
507 #[test]
508 fn test_resume_tracker_reset() {
509 let mut tracker = ResumeTracker::default();
510 for _ in 0..=MAX_STALLED_RESUME_ATTEMPTS {
511 tracker.allow_attempt(600.0);
512 }
513 tracker.reset();
514 assert_eq!(tracker.allow_attempt(600.0), Some(1));
515 }
516}