Keep the episode position and skip unplayable items safely in the player
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c14ab8dfea
commit
4d0b352258
3 files changed
+152
-11
No files matched your search
@@ -356,12 +356,14 @@ async fn podcast_queue_survives_server_browser_server_round_trip() {
|
||||
let mut incoming = state(queue.clone());
|
||||
incoming.queue_pos = 3;
|
||||
incoming.paused = true;
|
||||
incoming.position_secs = 1200.0;
|
||||
|
||||
// peer -> server -> browser
|
||||
let payload = web_playback_payload(&pool, &incoming).await.unwrap();
|
||||
let tracks = payload["tracks"].as_array().unwrap();
|
||||
assert_eq!(tracks.len(), 4, "no item is dropped");
|
||||
assert_eq!(payload["index"], 3);
|
||||
assert_eq!(payload["position_seconds"], 1200.0);
|
||||
assert_eq!(tracks[0]["source"]["kind"], "podcast_episode");
|
||||
assert_eq!(tracks[0]["unavailable"], true);
|
||||
assert_eq!(tracks[1]["source"]["kind"], "private");
|
||||
@@ -385,6 +387,8 @@ async fn podcast_queue_survives_server_browser_server_round_trip() {
|
||||
assert_eq!(outgoing.queue[..4], queue[..]);
|
||||
assert_eq!(outgoing.queue_pos, 3);
|
||||
assert!(outgoing.paused);
|
||||
// The episode position goes back to the peer (handoff web -> TUI).
|
||||
assert_eq!(outgoing.position_secs, 1200.0);
|
||||
let library = &outgoing.queue[4];
|
||||
assert_eq!(library.id, 77);
|
||||
assert_eq!(library.content_id.as_deref(), Some(CONTENT_ID));
|
||||
|
||||
@@ -774,6 +774,9 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
|
||||
audio.addEventListener('timeupdate', () => {
|
||||
// Unloading the audio for an unplayable item fires a late
|
||||
// timeupdate at 0; keep that item's handed-off position.
|
||||
if (!this._currentItemHasLocalAudio()) return;
|
||||
this.currentTime = audio.currentTime;
|
||||
this.duration = audio.duration || 0;
|
||||
this.progress = this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
|
||||
@@ -887,7 +890,8 @@ document.addEventListener('alpine:init', () => {
|
||||
// Podcast episodes stay in the queue; this player skips them.
|
||||
const playable = this._playableQueueIndex(queue.tracks, idx, idx >= previousIndex ? 1 : -1);
|
||||
if (playable < 0) {
|
||||
this._showUnplayableQueueItem(track);
|
||||
// Staying on the current item keeps its position.
|
||||
this._showUnplayableQueueItem(track, track === this.currentTrack ? this.currentTime : 0);
|
||||
return;
|
||||
}
|
||||
queue.currentIndex = playable;
|
||||
@@ -916,7 +920,7 @@ document.addEventListener('alpine:init', () => {
|
||||
_playLocal(track, options = {}) {
|
||||
if (this._isUnplayableQueueItem(track)) {
|
||||
this._recordHistory('replaced');
|
||||
this._showUnplayableQueueItem(track);
|
||||
this._showUnplayableQueueItem(track, options.position_seconds);
|
||||
return;
|
||||
}
|
||||
this._recordHistory('replaced');
|
||||
@@ -977,12 +981,25 @@ document.addEventListener('alpine:init', () => {
|
||||
return;
|
||||
}
|
||||
if (this._isUnplayableQueueItem(this.currentTrack)) {
|
||||
this.next();
|
||||
// Not next(): with repeat "one" it would resume this item again.
|
||||
this._skipUnplayableCurrentItem();
|
||||
return;
|
||||
}
|
||||
audio.play().catch(() => {});
|
||||
},
|
||||
|
||||
_skipUnplayableCurrentItem() {
|
||||
const queue = Alpine.store('queue');
|
||||
const tracks = queue?.tracks || [];
|
||||
let idx = this._playableQueueIndex(tracks, Number(queue?.currentIndex ?? -1) + 1, 1);
|
||||
if (idx < 0 && this.repeatMode === 'all') idx = this._playableQueueIndex(tracks, 0, 1);
|
||||
if (idx < 0) {
|
||||
this._showUnplayableQueueItem(this.currentTrack, this.currentTime);
|
||||
return;
|
||||
}
|
||||
this.playQueueIndex(idx);
|
||||
},
|
||||
|
||||
toggle() {
|
||||
if (!this.currentTrack) return;
|
||||
if (this.isPlaying) { this.pause(); }
|
||||
@@ -1060,7 +1077,8 @@ document.addEventListener('alpine:init', () => {
|
||||
this._recordHistory('skipped');
|
||||
|
||||
let nextIdx;
|
||||
if (this.repeatMode === 'one') {
|
||||
// Repeat "one" cannot repeat an item this player cannot play.
|
||||
if (this.repeatMode === 'one' && !this._isUnplayableQueueItem(this.currentTrack)) {
|
||||
this.seek(0);
|
||||
this._historyRecorded = false;
|
||||
this._resetPlaybackTracking();
|
||||
@@ -1234,8 +1252,12 @@ document.addEventListener('alpine:init', () => {
|
||||
const queue = Alpine.store('queue');
|
||||
const track = this.currentTrack || queue?.tracks?.[queue.currentIndex] || null;
|
||||
if (!track && (!queue || queue.tracks.length === 0)) return null;
|
||||
// <audio> holds an older track while an unplayable item is current.
|
||||
const position = this._currentItemHasLocalAudio(track)
|
||||
? (audio.currentTime || this.currentTime || 0)
|
||||
: (this.currentTime || 0);
|
||||
return this._remotePlaybackPayload(track, {
|
||||
position_seconds: audio.currentTime || this.currentTime || 0,
|
||||
position_seconds: position,
|
||||
duration_seconds: this._trackDuration(),
|
||||
paused: !this.isPlaying,
|
||||
});
|
||||
@@ -1300,7 +1322,7 @@ document.addEventListener('alpine:init', () => {
|
||||
this._remoteStateReceivedAt = Date.now();
|
||||
|
||||
if (this._isUnplayableQueueItem(track)) {
|
||||
this._showUnplayableQueueItem(track);
|
||||
this._showUnplayableQueueItem(track, desiredTime);
|
||||
this._updateMediaSession();
|
||||
return;
|
||||
}
|
||||
@@ -1363,7 +1385,10 @@ document.addEventListener('alpine:init', () => {
|
||||
const track = payload.track || queue.tracks[queue.currentIndex];
|
||||
if (track?.unavailable || (track && !track.stream_url)) {
|
||||
this._applyRemotePlaybackState({ ...payload, track, paused: true });
|
||||
this._pauseLocal();
|
||||
// This device is now active, so _applyRemotePlaybackState
|
||||
// does not set the time: keep the handed-off position as
|
||||
// the item's position and unload the previous audio.
|
||||
this._showUnplayableQueueItem(track, payload.position_seconds);
|
||||
} else if (track) {
|
||||
this._playLocal(track, payload);
|
||||
}
|
||||
@@ -1438,7 +1463,13 @@ document.addEventListener('alpine:init', () => {
|
||||
return -1;
|
||||
},
|
||||
|
||||
_showUnplayableQueueItem(track) {
|
||||
_currentItemHasLocalAudio(track = this.currentTrack) {
|
||||
// Whether <audio> can hold this item: podcast episodes, private
|
||||
// items and unresolved federation items are never loaded.
|
||||
return !!track && !track.unavailable && !!track.stream_url && !this._isUnplayableQueueItem(track);
|
||||
},
|
||||
|
||||
_showUnplayableQueueItem(track, positionSeconds = 0) {
|
||||
// Unload the previous source so a later play() cannot resume it.
|
||||
audio.pause();
|
||||
audio.removeAttribute('src');
|
||||
@@ -1447,9 +1478,15 @@ document.addEventListener('alpine:init', () => {
|
||||
this.currentTrack = track;
|
||||
this._historyTrack = null;
|
||||
this._localSourceTrackId = track?.id ?? null;
|
||||
this.currentTime = 0;
|
||||
this.progress = 0;
|
||||
this.duration = Number(track?.duration_seconds || 0);
|
||||
// Keep the item's position (handoff, restore) so it is reported back unchanged.
|
||||
let position = Math.max(0, Number(positionSeconds || 0));
|
||||
if (!Number.isFinite(position)) position = 0;
|
||||
if (this.duration > 0) position = Math.min(position, this.duration);
|
||||
this.currentTime = position;
|
||||
this._remoteStateBaseTime = position;
|
||||
this._remoteStateReceivedAt = Date.now();
|
||||
this.progress = this.duration > 0 ? (position / this.duration) * 100 : 0;
|
||||
Alpine.store('queue')?.syncCurrentIndexToTrack(track);
|
||||
},
|
||||
|
||||
@@ -1559,7 +1596,7 @@ document.addEventListener('alpine:init', () => {
|
||||
queue.currentIndex = idx;
|
||||
const currentTrack = restored.tracks[idx];
|
||||
if (this._isUnplayableQueueItem(currentTrack)) {
|
||||
this._showUnplayableQueueItem(currentTrack);
|
||||
this._showUnplayableQueueItem(currentTrack, (state.position_ms || 0) / 1000);
|
||||
} else if (currentTrack) {
|
||||
this.currentTrack = currentTrack;
|
||||
this._historyTrack = currentTrack;
|
||||
|
||||
@@ -96,3 +96,103 @@ test('restoring merges library tracks and external items', () => {
|
||||
assert.equal(restored.positions[3], 2);
|
||||
assert.equal(restored.positions[2], undefined);
|
||||
});
|
||||
|
||||
// Production methods by name, for flows that span several of them.
|
||||
function method(name) {
|
||||
const start = template.indexOf(`\n ${name}(`);
|
||||
assert.ok(start >= 0, `method ${name} not found`);
|
||||
const end = template.indexOf('\n },\n', start);
|
||||
return template.slice(start + 1, end + 11);
|
||||
}
|
||||
|
||||
function activePlayer(queueTracks, currentIndex, audioState = {}) {
|
||||
// The browser as the active (local) playback device.
|
||||
const names = [
|
||||
'_executeRemoteCommand', '_applyRemotePlaybackState', '_tickRemoteProgress',
|
||||
'_devicePlaybackStatePayload', '_remotePlaybackPayload', '_trackDuration',
|
||||
'_pauseLocal', '_playLocal', 'resume', 'next', 'playQueueIndex', 'seek',
|
||||
'_skipUnplayableCurrentItem', '_currentItemHasLocalAudio', '_showUnplayableQueueItem',
|
||||
'_queueItemSourceKind', '_isUnplayableQueueItem', '_playableQueueIndex',
|
||||
];
|
||||
const audio = Object.assign({
|
||||
paused: true, currentTime: 0, duration: NaN, src: '',
|
||||
played: [],
|
||||
pause() { this.paused = true; },
|
||||
play() { this.paused = false; this.played.push(this.src); return Promise.resolve(); },
|
||||
removeAttribute(name) { if (name === 'src') this.src = ''; },
|
||||
load() { this.currentTime = 0; },
|
||||
addEventListener() {}, removeEventListener() {},
|
||||
}, audioState);
|
||||
const queue = {
|
||||
tracks: queueTracks, currentIndex,
|
||||
_tracksWithJamDefaults: tracks => tracks,
|
||||
syncCurrentIndexToTrack(track) {
|
||||
const index = this.tracks.indexOf(track);
|
||||
if (index >= 0) this.currentIndex = index;
|
||||
},
|
||||
};
|
||||
const stores = {queue, devices: {heartbeat() {}}};
|
||||
const context = vm.createContext({audio, Alpine: {store: name => stores[name]}});
|
||||
vm.runInContext('this.methods = {' + names.map(method).join('\n') + '};', context);
|
||||
return Object.assign(context.methods, {
|
||||
audio, queue,
|
||||
currentTrack: queueTracks[currentIndex] || null, currentTime: 0, duration: 0, progress: 0,
|
||||
isPlaying: false, shuffle: false, repeatMode: 'off', volume: 0.5,
|
||||
_remoteStateBaseTime: 0, _remoteStateReceivedAt: 0,
|
||||
_isLocalPlaybackDevice: () => true, _shouldSendRemote: () => false,
|
||||
_shouldMirrorRemoteLocally: () => false,
|
||||
_setVolumeLocal(v) { this.volume = v; }, _updateMediaSession() {}, _saveState() {},
|
||||
_recordHistory() {}, _resetPlaybackTracking() {}, _mirrorRemoteTrack() {},
|
||||
});
|
||||
}
|
||||
|
||||
const episode = Object.assign({}, podcast, {duration_seconds: 1800});
|
||||
|
||||
test('handoff of a podcast episode keeps its position for the next handoff', () => {
|
||||
for (const audioTime of [95, 0]) {
|
||||
// <audio> still holds a music track (95 s) or the page is fresh (0 s).
|
||||
const p = activePlayer([song(1)], 0, {currentTime: audioTime, src: '/api/player/stream/1'});
|
||||
p._executeRemoteCommand({command: 'transfer_state', payload: {
|
||||
tracks: [song(1), episode], index: 1, track: episode,
|
||||
position_seconds: 1200, duration_seconds: 1800, paused: false,
|
||||
}});
|
||||
assert.equal(p.currentTrack, episode);
|
||||
assert.equal(p.currentTime, 1200);
|
||||
assert.equal(p.isPlaying, false);
|
||||
assert.equal(p.audio.src, '', 'the previous track is unloaded');
|
||||
const reported = p._devicePlaybackStatePayload();
|
||||
assert.equal(reported.position_seconds, 1200);
|
||||
assert.equal(reported.index, 1);
|
||||
assert.equal(reported.paused, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('library tracks still report the audio position', () => {
|
||||
const p = activePlayer([song(1)], 0, {currentTime: 42, src: '/api/player/stream/1'});
|
||||
p.currentTime = 40;
|
||||
assert.equal(p._devicePlaybackStatePayload().position_seconds, 42);
|
||||
});
|
||||
|
||||
test('resume on an unplayable item skips it, also with repeat one', () => {
|
||||
for (const repeatMode of ['one', 'off', 'all']) {
|
||||
const p = activePlayer([podcast], 0);
|
||||
p.repeatMode = repeatMode;
|
||||
p.currentTime = 30;
|
||||
p.resume();
|
||||
p.next();
|
||||
assert.equal(p.currentTrack, podcast);
|
||||
assert.equal(p.isPlaying, false);
|
||||
assert.equal(p.currentTime, 30, 'the item keeps its position');
|
||||
assert.deepEqual(p.audio.played, []);
|
||||
}
|
||||
const p = activePlayer([song(1), podcast, song(2)], 1);
|
||||
p.repeatMode = 'one';
|
||||
p.resume();
|
||||
assert.equal(p.currentTrack.id, 2);
|
||||
assert.deepEqual(p.audio.played, ['/api/player/stream/2']);
|
||||
// Repeat all wraps around to the first playable item.
|
||||
const wrap = activePlayer([song(1), podcast], 1);
|
||||
wrap.repeatMode = 'all';
|
||||
wrap.resume();
|
||||
assert.equal(wrap.currentTrack.id, 1);
|
||||
});
|
||||
Reference in new issue
Block a user