Preserve fallback eligibility across queue transitions

This commit is contained in:
2026-11-07 10:50:06 -08:00
parent 3d7104b6b7
commit f80fd99211
2 changed files with 197 additions and 73 deletions
+98 -40
View File
@@ -69,9 +69,13 @@ export class MediaPlayer {
private lastLoadCandidate: string | null = null;
private currentMediaTitle: string | null = null;
private currentPlaybackMetadata: Record<string, string> = {};
private loadGeneration = 0;
private fallbackCandidates: Map<string, number> = new Map();
private activeAttemptGeneration = 0;
private fallbackCandidates: Set<string> = new Set();
private entryCandidates: Map<number, string> = new Map();
private pendingCandidateUrls: string[] = [];
private activeEntryId: number | null = null;
private activeUrl: string | null = null;
private fallbackSuppressedUntilStart = false;
private browserUrl: string | null = null;
private browserFallback = new ChromiumFallback((url) => {
if (this.browserUrl === url) {
@@ -380,17 +384,18 @@ export class MediaPlayer {
}
public async append(url: string) {
await this.cancelBrowserFallback();
await this.loadFile(url, "append-play");
}
public async replace(url: string) {
await this.cancelBrowserFallback();
this.clearFallbackCandidates();
await this.loadFile(url, "replace", true, [], false);
}
public async initiateScreenSharing(url: string) {
await this.cancelBrowserFallback();
this.clearFallbackCandidates();
console.log(`Initiating screen sharing with file: ${url}`);
this.metadata.set(url, {
@@ -446,6 +451,16 @@ export class MediaPlayer {
public async skipTo(index: number) {
await this.cancelBrowserFallback();
try {
const playlist = (await this.writeCommand("get_property", ["playlist"])).data as PlaylistItem[];
const target = playlist[index];
if (target && this.fallbackCandidates.has(target.filename)) {
this.entryCandidates.set(target.id, target.filename);
this.removePendingCandidate(target.filename);
}
} catch {
// Existing entry-to-URL mappings remain available if MPV is transitioning.
}
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-play-index", [index]));
}
@@ -503,9 +518,10 @@ export class MediaPlayer {
}
private async loadFile(url: string, mode: string, fetchMetadata: boolean = true, options: string[] = [], fallbackEligible: boolean = true) {
const generation = ++this.loadGeneration;
if (fallbackEligible) this.fallbackCandidates.set(url, generation);
else this.fallbackCandidates.delete(url);
if (fallbackEligible) {
this.fallbackCandidates.add(url);
this.pendingCandidateUrls.push(url);
}
this.lastLoadCandidate = url;
this.playbackErrors.delete(url);
const loadPromise = this.modify(
@@ -519,7 +535,15 @@ export class MediaPlayer {
});
}
await loadPromise;
const result = await loadPromise;
if (result?.error !== "success") {
if (fallbackEligible) {
this.removePendingCandidate(url);
if (![...this.entryCandidates.values()].includes(url)) this.fallbackCandidates.delete(url);
}
return;
}
if (fallbackEligible) void this.rememberPlaylistEntry(url);
}
private async modify<T>(event: UserEvent, func: () => Promise<T>): Promise<T> {
@@ -709,21 +733,25 @@ export class MediaPlayer {
}
} else if (response.event) {
if (response.event === "start-file") {
// Clear any previous error for the file that is starting
if (this.browserUrl) void this.cancelBrowserFallback();
// A new MPV entry supersedes pending browser startup and playback state.
const hadBrowser = !!this.browserUrl || this.browserFallback.isRunning;
this.activeAttemptGeneration++;
this.fallbackSuppressedUntilStart = false;
this.browserUrl = null;
if (hadBrowser) void this.browserFallback.stop();
const entryId = typeof response.playlist_entry_id === "number"
? response.playlist_entry_id
: null;
const pendingCandidate = this.lastLoadCandidate && this.fallbackCandidates.has(this.lastLoadCandidate)
? this.lastLoadCandidate
: null;
const file = response.file || pendingCandidate;
this.activeEntryId = typeof response.playlist_entry_id === "number"
? response.playlist_entry_id
: null;
let file = response.file || (entryId === null ? null : this.entryCandidates.get(entryId)) || null;
if (!file && this.pendingCandidateUrls.length > 0) {
file = this.pendingCandidateUrls.shift() || null;
if (entryId !== null && file) this.entryCandidates.set(entryId, file);
}
this.activeEntryId = entryId;
this.activeUrl = file;
this.currentFile = file || null;
if (file) this.playbackErrors.delete(file);
if (entryId !== null && !response.file) void this.refreshCurrentFile(entryId);
if (entryId !== null && !file) void this.refreshCurrentFile(entryId, this.activeAttemptGeneration);
this.currentMediaTitle = null;
this.currentPlaybackMetadata = {};
@@ -732,8 +760,7 @@ export class MediaPlayer {
} else if (response.event === "end-file" && response.reason === "error") {
void this.handlePlaybackFailure(response);
} else if (response.event === "end-file") {
const file = response.file || this.currentFile || this.lastLoadCandidate;
if (file) this.fallbackCandidates.delete(file);
// Keep entry eligibility for a later replay of this queue item.
}
this.handleEvent(UserEvent.MPDUpdate, response);
@@ -751,46 +778,64 @@ export class MediaPlayer {
const entryId = typeof response.playlist_entry_id === "number"
? response.playlist_entry_id
: this.activeEntryId;
if (entryId === null || entryId !== this.activeEntryId) return;
if (entryId === null) return;
let file = response.file as string | undefined;
try {
const playlist = (await this.writeCommand("get_property", ["playlist"])).data as PlaylistItem[];
file = playlist.find((item) => item.id === entryId)?.filename || file;
} catch {
// MPV can be transitioning already; use the active load URL if available.
}
file = file || this.currentFile || this.lastLoadCandidate || "Unknown file";
const attemptGeneration = this.activeAttemptGeneration;
const file = this.entryCandidates.get(entryId) || response.file ||
(entryId === this.activeEntryId ? this.activeUrl : null);
if (!file) return;
const errorMessage = response.file_error || response.error || response["file-error"] || "Unknown playback error";
this.playbackErrors.set(file, errorMessage);
this.handleEvent(UserEvent.PlaybackError, { filename: file, error: errorMessage });
const candidateGeneration = this.fallbackCandidates.get(file);
this.fallbackCandidates.delete(file);
if (entryId === this.activeEntryId && candidateGeneration === this.loadGeneration) {
void this.startBrowserFallback(file, candidateGeneration);
// end-file identifies the failed playlist entry even if MPV has already
// cleared its current entry or advanced before any asynchronous query.
// A user transition increments the attempt generation and prevents stale
// failures from opening a browser.
if (this.fallbackCandidates.has(file) &&
(entryId === this.activeEntryId || (this.activeEntryId === null && !this.fallbackSuppressedUntilStart)) &&
attemptGeneration === this.activeAttemptGeneration) {
void this.startBrowserFallback(file, attemptGeneration, entryId);
}
}
private async refreshCurrentFile(entryId: number) {
private async refreshCurrentFile(entryId: number, attemptGeneration: number) {
try {
const playlist = (await this.writeCommand("get_property", ["playlist"])).data as PlaylistItem[];
if (this.activeEntryId !== entryId) return;
if (this.activeEntryId !== entryId || this.activeAttemptGeneration !== attemptGeneration) return;
const file = playlist.find((item) => item.id === entryId)?.filename || null;
this.currentFile = file;
this.activeUrl = file;
if (file && this.fallbackCandidates.has(file)) this.entryCandidates.set(entryId, file);
if (this.browserUrl && this.browserUrl !== file) void this.cancelBrowserFallback();
} catch {
// The player may be transitioning; a later start-file event will refresh it.
}
}
private async startBrowserFallback(url: string, generation: number) {
private async rememberPlaylistEntry(url: string) {
try {
const playlist = (await this.writeCommand("get_property", ["playlist"])).data as PlaylistItem[];
const entry = playlist.filter((item) => item.filename === url && !this.entryCandidates.has(item.id)).at(-1);
if (entry) {
this.entryCandidates.set(entry.id, url);
this.removePendingCandidate(url);
}
} catch {
// The pending candidate is associated when MPV emits start-file instead.
}
}
private async startBrowserFallback(url: string, generation: number, entryId: number) {
try {
const started = await this.browserFallback.start(url, () =>
generation === this.loadGeneration && this.currentFile === url,
generation === this.activeAttemptGeneration &&
this.activeEntryId === entryId &&
this.activeUrl === url,
);
if (started && this.browserFallback.isRunning && generation === this.loadGeneration && this.currentFile === url) {
if (started && this.browserFallback.isRunning &&
generation === this.activeAttemptGeneration &&
this.activeEntryId === entryId && this.activeUrl === url) {
this.browserUrl = url;
this.handleEvent(UserEvent.NowPlayingUpdate, {});
}
@@ -800,13 +845,26 @@ export class MediaPlayer {
}
private async cancelBrowserFallback() {
this.loadGeneration++;
this.fallbackCandidates.clear();
this.activeAttemptGeneration++;
this.fallbackSuppressedUntilStart = true;
this.activeEntryId = null;
this.activeUrl = null;
this.currentFile = null;
this.browserUrl = null;
await this.browserFallback.stop();
}
private clearFallbackCandidates() {
this.fallbackCandidates.clear();
this.entryCandidates.clear();
this.pendingCandidateUrls = [];
}
private removePendingCandidate(url: string) {
const index = this.pendingCandidateUrls.indexOf(url);
if (index >= 0) this.pendingCandidateUrls.splice(index, 1);
}
private handlePropertyChange(response: any) {
const previousTitle = this.getCurrentDynamicTitle();