Add Chromium fallback for failed playback
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
import { ChildProcess, spawn } from "child_process";
|
||||
import { mkdtemp, rm } from "fs/promises";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
|
||||
export interface ChromiumProcess {
|
||||
process: ChildProcess;
|
||||
profilePath: string;
|
||||
generation: number;
|
||||
}
|
||||
|
||||
export class ChromiumFallback {
|
||||
private active: ChromiumProcess | null = null;
|
||||
private generation = 0;
|
||||
|
||||
constructor(
|
||||
private readonly onExit: (url: string) => void = () => undefined,
|
||||
private readonly executable = process.env.QUEUECUBE_CHROME_BIN || "chromium",
|
||||
) {}
|
||||
|
||||
public get isRunning(): boolean {
|
||||
return this.active !== null;
|
||||
}
|
||||
|
||||
public async start(url: string, isCurrent: () => boolean): Promise<boolean> {
|
||||
await this.stop();
|
||||
const generation = ++this.generation;
|
||||
const profilePath = await mkdtemp(path.join(os.tmpdir(), "queuecube-chrome-"));
|
||||
|
||||
if (generation !== this.generation || !isCurrent()) {
|
||||
await this.removeProfile(profilePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
let child: ChildProcess;
|
||||
try {
|
||||
child = spawn(this.executable, [
|
||||
"--kiosk",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
`--user-data-dir=${profilePath}`,
|
||||
"--",
|
||||
url,
|
||||
], { detached: true, stdio: "ignore" });
|
||||
} catch (error) {
|
||||
await this.removeProfile(profilePath);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const active = { process: child, profilePath, generation };
|
||||
this.active = active;
|
||||
child.once("spawn", () => {
|
||||
if (this.active !== active || generation !== this.generation) {
|
||||
this.signalOwnedGroup(child, "SIGTERM");
|
||||
}
|
||||
});
|
||||
|
||||
return new Promise<boolean>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const cleanup = () => {
|
||||
if (this.active === active) {
|
||||
this.active = null;
|
||||
// Chromium can exit before its helper processes. Reap only the
|
||||
// process group created for this fallback instance.
|
||||
this.signalOwnedGroup(child, "SIGTERM");
|
||||
this.onExit(url);
|
||||
}
|
||||
void this.removeProfile(profilePath);
|
||||
};
|
||||
|
||||
child.once("error", (error) => {
|
||||
cleanup();
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
child.once("exit", () => {
|
||||
cleanup();
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
child.once("spawn", () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (generation !== this.generation || !isCurrent()) {
|
||||
void this.stopActive(active);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public async stop(): Promise<void> {
|
||||
this.generation++;
|
||||
const active = this.active;
|
||||
if (active) await this.stopActive(active);
|
||||
}
|
||||
|
||||
private async stopActive(active: ChromiumProcess): Promise<void> {
|
||||
if (this.active === active) this.active = null;
|
||||
|
||||
const child = active.process;
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
if (child.pid) this.signalOwnedGroup(child, "SIGTERM");
|
||||
|
||||
await Promise.race([
|
||||
new Promise<void>((resolve) => child.once("exit", () => resolve())),
|
||||
new Promise<void>((resolve) => setTimeout(resolve, 2000)),
|
||||
]);
|
||||
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
if (child.pid) this.signalOwnedGroup(child, "SIGKILL");
|
||||
await Promise.race([
|
||||
new Promise<void>((resolve) => child.once("exit", () => resolve())),
|
||||
new Promise<void>((resolve) => setTimeout(resolve, 1000)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
await this.removeProfile(active.profilePath);
|
||||
}
|
||||
|
||||
private async removeProfile(profilePath: string): Promise<void> {
|
||||
try {
|
||||
await rm(profilePath, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`Failed to remove Chromium profile ${profilePath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
private signalOwnedGroup(child: ChildProcess, signal: NodeJS.Signals): void {
|
||||
if (!child.pid) return;
|
||||
try {
|
||||
// detached=true gives this instance its own process group. Signal only
|
||||
// that group so Chromium helpers cannot outlive the owned browser.
|
||||
process.kill(-child.pid, signal);
|
||||
} catch (error: any) {
|
||||
if (error.code !== "ESRCH") child.kill(signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
+115
-15
@@ -24,6 +24,7 @@ import { PlaylistItem, LinkMetadata } from './types';
|
||||
import { FavoritesStore } from "./FavoritesStore";
|
||||
import { Bonjour } from "bonjour-service";
|
||||
import os from 'os';
|
||||
import { ChromiumFallback } from "./ChromiumFallback";
|
||||
|
||||
interface PendingCommand {
|
||||
resolve: (value: any) => void;
|
||||
@@ -68,6 +69,16 @@ 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 activeEntryId: number | null = null;
|
||||
private browserUrl: string | null = null;
|
||||
private browserFallback = new ChromiumFallback((url) => {
|
||||
if (this.browserUrl === url) {
|
||||
this.browserUrl = null;
|
||||
this.handleEvent(UserEvent.NowPlayingUpdate, {});
|
||||
}
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.socket = this.tryRespawnPlayerProcess();
|
||||
@@ -271,6 +282,10 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getNowPlaying(): Promise<PlaylistItem> {
|
||||
if (this.browserUrl) {
|
||||
return { id: -1, filename: this.browserUrl, title: this.browserUrl, playing: true, current: true };
|
||||
}
|
||||
|
||||
const playlist = await this.getPlaylist();
|
||||
const currentlyPlayingSong = playlist.find((item: PlaylistItem) => item.current);
|
||||
const fetchMediaTitle = async (): Promise<string | null> => {
|
||||
@@ -310,6 +325,7 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getCurrentFile(): Promise<string | null> {
|
||||
if (this.browserUrl) return this.browserUrl;
|
||||
return this.writeCommand("get_property", ["stream-open-filename"])
|
||||
.then((response) => {
|
||||
return response.data;
|
||||
@@ -317,6 +333,7 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getPauseState(): Promise<boolean> {
|
||||
if (this.browserUrl) return false;
|
||||
return this.writeCommand("get_property", ["pause"])
|
||||
.then((response) => {
|
||||
return response.data;
|
||||
@@ -331,6 +348,7 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getTimePosition(): Promise<number | null> {
|
||||
if (this.browserUrl) return null;
|
||||
return this.writeCommand("get_property", ["time-pos"])
|
||||
.then((response) => {
|
||||
return response.data;
|
||||
@@ -338,6 +356,7 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getDuration(): Promise<number | null> {
|
||||
if (this.browserUrl) return null;
|
||||
return this.writeCommand("get_property", ["duration"])
|
||||
.then((response) => {
|
||||
return response.data;
|
||||
@@ -345,6 +364,7 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getSeekable(): Promise<boolean | null> {
|
||||
if (this.browserUrl) return false;
|
||||
return this.writeCommand("get_property", ["seekable"])
|
||||
.then((response) => {
|
||||
return response.data;
|
||||
@@ -352,6 +372,7 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async getIdle(): Promise<boolean> {
|
||||
if (this.browserUrl) return false;
|
||||
return this.writeCommand("get_property", ["idle"])
|
||||
.then((response) => {
|
||||
return response.data;
|
||||
@@ -359,14 +380,17 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async append(url: string) {
|
||||
await this.cancelBrowserFallback();
|
||||
await this.loadFile(url, "append-play");
|
||||
}
|
||||
|
||||
public async replace(url: string) {
|
||||
await this.loadFile(url, "replace");
|
||||
await this.cancelBrowserFallback();
|
||||
await this.loadFile(url, "replace", true, [], false);
|
||||
}
|
||||
|
||||
public async initiateScreenSharing(url: string) {
|
||||
await this.cancelBrowserFallback();
|
||||
console.log(`Initiating screen sharing with file: ${url}`);
|
||||
|
||||
this.metadata.set(url, {
|
||||
@@ -407,18 +431,26 @@ export class MediaPlayer {
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
await this.cancelBrowserFallback();
|
||||
return this.modify(UserEvent.NowPlayingUpdate, () => this.writeCommand("stop", []));
|
||||
}
|
||||
|
||||
public async shutdown() {
|
||||
await this.cancelBrowserFallback();
|
||||
}
|
||||
|
||||
public async skip() {
|
||||
await this.cancelBrowserFallback();
|
||||
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-next", []));
|
||||
}
|
||||
|
||||
public async skipTo(index: number) {
|
||||
await this.cancelBrowserFallback();
|
||||
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-play-index", [index]));
|
||||
}
|
||||
|
||||
public async previous() {
|
||||
await this.cancelBrowserFallback();
|
||||
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-prev", []));
|
||||
}
|
||||
|
||||
@@ -470,7 +502,10 @@ export class MediaPlayer {
|
||||
};
|
||||
}
|
||||
|
||||
private async loadFile(url: string, mode: string, fetchMetadata: boolean = true, options: string[] = []) {
|
||||
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);
|
||||
this.lastLoadCandidate = url;
|
||||
this.playbackErrors.delete(url);
|
||||
const loadPromise = this.modify(
|
||||
@@ -675,25 +710,30 @@ export class MediaPlayer {
|
||||
} else if (response.event) {
|
||||
if (response.event === "start-file") {
|
||||
// Clear any previous error for the file that is starting
|
||||
const file = response.file || this.lastLoadCandidate;
|
||||
if (file) {
|
||||
this.currentFile = file;
|
||||
this.playbackErrors.delete(file);
|
||||
}
|
||||
if (this.browserUrl) void this.cancelBrowserFallback();
|
||||
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;
|
||||
this.currentFile = file || null;
|
||||
if (file) this.playbackErrors.delete(file);
|
||||
if (entryId !== null && !response.file) void this.refreshCurrentFile(entryId);
|
||||
|
||||
this.currentMediaTitle = null;
|
||||
this.currentPlaybackMetadata = {};
|
||||
} else if (response.event === "property-change") {
|
||||
this.handlePropertyChange(response);
|
||||
} else if (response.event === "end-file" && response.reason === "error") {
|
||||
const file = response.file || this.currentFile || this.lastLoadCandidate || "Unknown file";
|
||||
const errorMessage = response.error || response["file-error"] || "Unknown playback error";
|
||||
|
||||
this.playbackErrors.set(file, errorMessage);
|
||||
this.handleEvent(UserEvent.PlaybackError, {
|
||||
filename: file,
|
||||
error: errorMessage
|
||||
});
|
||||
void this.handlePlaybackFailure(response);
|
||||
} else if (response.event === "end-file") {
|
||||
const file = response.file || this.currentFile || this.lastLoadCandidate;
|
||||
if (file) this.fallbackCandidates.delete(file);
|
||||
}
|
||||
|
||||
this.handleEvent(UserEvent.MPDUpdate, response);
|
||||
@@ -707,6 +747,66 @@ export class MediaPlayer {
|
||||
}
|
||||
}
|
||||
|
||||
private async handlePlaybackFailure(response: any) {
|
||||
const entryId = typeof response.playlist_entry_id === "number"
|
||||
? response.playlist_entry_id
|
||||
: this.activeEntryId;
|
||||
if (entryId === null || entryId !== this.activeEntryId) 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 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);
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshCurrentFile(entryId: number) {
|
||||
try {
|
||||
const playlist = (await this.writeCommand("get_property", ["playlist"])).data as PlaylistItem[];
|
||||
if (this.activeEntryId !== entryId) return;
|
||||
const file = playlist.find((item) => item.id === entryId)?.filename || null;
|
||||
this.currentFile = 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) {
|
||||
try {
|
||||
const started = await this.browserFallback.start(url, () =>
|
||||
generation === this.loadGeneration && this.currentFile === url,
|
||||
);
|
||||
if (started && this.browserFallback.isRunning && generation === this.loadGeneration && this.currentFile === url) {
|
||||
this.browserUrl = url;
|
||||
this.handleEvent(UserEvent.NowPlayingUpdate, {});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to start Chromium fallback for ${url}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
private async cancelBrowserFallback() {
|
||||
this.loadGeneration++;
|
||||
this.fallbackCandidates.clear();
|
||||
this.activeEntryId = null;
|
||||
this.browserUrl = null;
|
||||
await this.browserFallback.stop();
|
||||
}
|
||||
|
||||
private handlePropertyChange(response: any) {
|
||||
const previousTitle = this.getCurrentDynamicTitle();
|
||||
|
||||
|
||||
@@ -372,6 +372,9 @@ const server = app.listen(port, () => {
|
||||
// Add graceful shutdown handling
|
||||
const shutdown = async () => {
|
||||
console.log('Received shutdown signal. Closing server...');
|
||||
|
||||
// Invalidate pending playback failures and close only QueueCube's owned browser.
|
||||
await mediaPlayer.shutdown();
|
||||
|
||||
// Stop zeroconf service
|
||||
mediaPlayer.stopZeroconfService();
|
||||
|
||||
Reference in New Issue
Block a user