mirror of
https://github.com/4gray/iptvnator.git
synced 2026-10-11 11:06:16 -08:00
fix(playback): harden external launch lifecycle
This commit is contained in:
1 parent
13b1cfe57e
commit
1e8770c049
52 files changed
+5096
-649
No files matched your search
@@ -3,4 +3,4 @@ type: fix
|
||||
area: playback
|
||||
---
|
||||
|
||||
MPV and VLC recovery actions now stay available after launch attempts, show precise opening, started, playing, and failure feedback, and prevent overlapping external-player launches. External-player errors remain visible in the playback dock until dismissed.
|
||||
MPV and VLC recovery actions now stay available, show precise opening, started, playing, and failure feedback, and prevent overlapping launches. The dock keeps Stop available when teardown is still needed and lets terminal errors be dismissed.
|
||||
@@ -291,16 +291,87 @@ Key files:
|
||||
evidence or ownership state. MPV/VLC actions remain mounted after an attempt
|
||||
and expose credential-free per-target launching/started/playing/error state;
|
||||
only an exact Electron `playing` update is labelled Playing. One handshake is
|
||||
allowed at a time. Its fieldless intent is bound to the exact session returned
|
||||
allowed at a time. The renderer claims the credential-free content identity
|
||||
before awaiting Electron, so primary Play is disabled and a launching or
|
||||
closable-error alternative remains owned before the controller commits it.
|
||||
Every route action that can start the same external playback, including
|
||||
Restart and the provider-source shortcut, observes that local pre-IPC guard.
|
||||
The Xtream VOD diagnostic-fallback handler records the same route-scoped
|
||||
destination and pending generation before invoking MPV/VLC, so route reuse
|
||||
cannot orphan that process outside the next route's close-before-play path.
|
||||
Its fieldless intent is bound to the exact session returned
|
||||
by the source owner's launch promise, so a late timed-out attempt cannot take
|
||||
over a retry; later global updates must match that ID. A replacement waits for
|
||||
confirmed teardown of the tracked external process, applies the old exact
|
||||
close before launch, and cancels an unlaunched handoff if diagnostic ownership
|
||||
changes. If the local
|
||||
handshake times out after an exact Electron session is known, that ID remains
|
||||
changes. Process teardown has bounded graceful and forced confirmation
|
||||
windows, and reusable MPV bounds the IPC command that precedes them; if any
|
||||
stage cannot reach a confirmed exit, the exact session stays live and the
|
||||
replacement fails closed instead of overlapping it. A process-wide teardown
|
||||
gate starts before any potentially slow teardown preparation, including VLC
|
||||
position flush and a reused player's protocol quit, and rejects every
|
||||
MPV/VLC spawn until that exact child reports exit. If bounded
|
||||
teardown fails while a fresh launch is still pending, that launch IPC rejects
|
||||
and the exact session remains a closable error instead of hanging forever.
|
||||
If a pre-content reuse failure has no still-live displaced session to restore,
|
||||
the replacement error keeps its attached closer so Stop can retry the orphaned
|
||||
child teardown. A terminal error without a closer is never restorable.
|
||||
A failed close is single-flight only while its promise is pending: Stop can
|
||||
retry the same exact child after a bounded confirmation failure. Reuse maps
|
||||
the child to its current content session, so a stale older closer becomes a
|
||||
no-op instead of terminating a newer `loadfile`/VLC enqueue handoff.
|
||||
A duplicate close for an already closed session returns its terminal snapshot
|
||||
without re-entering the saved closer, and a late process error cannot revive
|
||||
that terminal session. Reused MPV commands are bound to the socket captured
|
||||
for that exact child, so a later process cannot inherit a stale protocol quit.
|
||||
Stop observed before a pending MPV content command or VLC enqueue command
|
||||
prevents that command from dispatching. A source handoff fails closed while
|
||||
a live session has no closer (`canClose: false`); renderer Dismiss is not
|
||||
teardown confirmation. That denied handoff advances neither the multi-source
|
||||
switch token nor the playback generation, so it cannot cancel the sole launch
|
||||
already in flight.
|
||||
VLC rechecks the gate at each concrete spawn after port allocation or reuse
|
||||
work; if a post-start fallback is blocked there, the opened session becomes
|
||||
an error rather than retaining a false started status. A failed RC-port
|
||||
allocation never claims reuse ownership, so the fallback VLC child retains
|
||||
its exact one-shot closer.
|
||||
Reuse failures before a content command restore the globally displaced
|
||||
renderer session, not the reusable process's prior owner, and only while the
|
||||
exact displaced-session ID is still active; after
|
||||
`loadfile`/VLC `clear` is dispatched,
|
||||
the replacement owns the process and remains a closable error instead of
|
||||
restoring stale content metadata. Stop during an in-flight MPV or VLC reuse
|
||||
command, including during failed-command teardown or the subsequent VLC
|
||||
fallback port-allocation wait, settles that exact close without falling
|
||||
through to a fresh spawn;
|
||||
a stopped VLC spawn error that reports only `close` also settles its original
|
||||
launch IPC with the exact closed session;
|
||||
a fresh fallback retires the old child's exit under its prior session so it
|
||||
cannot close the replacement. Source handoffs recheck ownership after launch
|
||||
and accept only `opened`/`playing`; a stale returned session is closed exactly
|
||||
and a Stop-returned `closed` session is never committed. If that exact stale
|
||||
close fails, its credential-free destination owner is retained for the next
|
||||
close attempt. Retained destination ownership is scoped to the initiating
|
||||
playlist/VOD route key, so route reuse cannot expose Stop for the previous
|
||||
movie's external session. Play/Resume capture that route key before awaiting
|
||||
close and cancel if navigation changes it; a late diagnostic fallback closes
|
||||
its exact returned session instead of adopting it on the new route. They
|
||||
supersede an older source resolution before awaiting the shared
|
||||
close-before-replacement path, and accepting a diagnostic fallback retires
|
||||
the same older resolution before opening MPV/VLC. They publish the route-source
|
||||
badge, caption evidence, and position only after start succeeds.
|
||||
Closable errors still participate in every replacement close and keep Stop as
|
||||
the global dock's only teardown affordance; Dismiss is reserved for terminal
|
||||
errors that have no closer. The shared `isLiveExternalPlayerSession` predicate
|
||||
keeps M3U and series ownership while
|
||||
such an error can still be stopped; consumers must not treat every `error`
|
||||
status as terminal.
|
||||
If the local handshake times out after an exact Electron session is known,
|
||||
that ID remains
|
||||
correlated so a later exact update can recover the UI. The global dock mirrors
|
||||
those statuses, keeps errors visible until dismissal, and intentionally has no
|
||||
retry because it does not own the original launch headers or credentials.
|
||||
those statuses, keeps closable errors visible until Stop confirms teardown and
|
||||
terminal errors visible until dismissal, and intentionally has no retry because
|
||||
it does not own the original launch headers or credentials.
|
||||
- The built-in HTML5/hls.js player is the second guarded consumer.
|
||||
`HtmlVideoPlayerComponent` provides a component-scoped
|
||||
`WebVideoControlsAdapter`; its neutral `web-video-support` bridge is shared
|
||||
|
||||
@@ -827,16 +827,87 @@ app as a real argument, so it is not an option.
|
||||
evidence or ownership state. MPV/VLC actions remain mounted after an attempt
|
||||
and expose credential-free per-target launching/started/playing/error state;
|
||||
only an exact Electron `playing` update is labelled Playing. One handshake is
|
||||
allowed at a time. Its fieldless intent is bound to the exact session returned
|
||||
allowed at a time. The renderer claims the credential-free content identity
|
||||
before awaiting Electron, so primary Play is disabled and a launching or
|
||||
closable-error alternative remains owned before the controller commits it.
|
||||
Every route action that can start the same external playback, including
|
||||
Restart and the provider-source shortcut, observes that local pre-IPC guard.
|
||||
The Xtream VOD diagnostic-fallback handler records the same route-scoped
|
||||
destination and pending generation before invoking MPV/VLC, so route reuse
|
||||
cannot orphan that process outside the next route's close-before-play path.
|
||||
Its fieldless intent is bound to the exact session returned
|
||||
by the source owner's launch promise, so a late timed-out attempt cannot take
|
||||
over a retry; later global updates must match that ID. A replacement waits for
|
||||
confirmed teardown of the tracked external process, applies the old exact
|
||||
close before launch, and cancels an unlaunched handoff if diagnostic ownership
|
||||
changes. If the local
|
||||
handshake times out after an exact Electron session is known, that ID remains
|
||||
changes. Process teardown has bounded graceful and forced confirmation
|
||||
windows, and reusable MPV bounds the IPC command that precedes them; if any
|
||||
stage cannot reach a confirmed exit, the exact session stays live and the
|
||||
replacement fails closed instead of overlapping it. A process-wide teardown
|
||||
gate starts before any potentially slow teardown preparation, including VLC
|
||||
position flush and a reused player's protocol quit, and rejects every
|
||||
MPV/VLC spawn until that exact child reports exit. If bounded
|
||||
teardown fails while a fresh launch is still pending, that launch IPC rejects
|
||||
and the exact session remains a closable error instead of hanging forever.
|
||||
If a pre-content reuse failure has no still-live displaced session to restore,
|
||||
the replacement error keeps its attached closer so Stop can retry the orphaned
|
||||
child teardown. A terminal error without a closer is never restorable.
|
||||
A failed close is single-flight only while its promise is pending: Stop can
|
||||
retry the same exact child after a bounded confirmation failure. Reuse maps
|
||||
the child to its current content session, so a stale older closer becomes a
|
||||
no-op instead of terminating a newer `loadfile`/VLC enqueue handoff.
|
||||
A duplicate close for an already closed session returns its terminal snapshot
|
||||
without re-entering the saved closer, and a late process error cannot revive
|
||||
that terminal session. Reused MPV commands are bound to the socket captured
|
||||
for that exact child, so a later process cannot inherit a stale protocol quit.
|
||||
Stop observed before a pending MPV content command or VLC enqueue command
|
||||
prevents that command from dispatching. A source handoff fails closed while
|
||||
a live session has no closer (`canClose: false`); renderer Dismiss is not
|
||||
teardown confirmation. That denied handoff advances neither the multi-source
|
||||
switch token nor the playback generation, so it cannot cancel the sole launch
|
||||
already in flight.
|
||||
VLC rechecks the gate at each concrete spawn after port allocation or reuse
|
||||
work; if a post-start fallback is blocked there, the opened session becomes
|
||||
an error rather than retaining a false started status. A failed RC-port
|
||||
allocation never claims reuse ownership, so the fallback VLC child retains
|
||||
its exact one-shot closer.
|
||||
Reuse failures before a content command restore the globally displaced
|
||||
renderer session, not the reusable process's prior owner, and only while the
|
||||
exact displaced-session ID is still active; after
|
||||
`loadfile`/VLC `clear` is dispatched,
|
||||
the replacement owns the process and remains a closable error instead of
|
||||
restoring stale content metadata. Stop during an in-flight MPV or VLC reuse
|
||||
command, including during failed-command teardown or the subsequent VLC
|
||||
fallback port-allocation wait, settles that exact close without falling
|
||||
through to a fresh spawn;
|
||||
a stopped VLC spawn error that reports only `close` also settles its original
|
||||
launch IPC with the exact closed session;
|
||||
a fresh fallback retires the old child's exit under its prior session so it
|
||||
cannot close the replacement. Source handoffs recheck ownership after launch
|
||||
and accept only `opened`/`playing`; a stale returned session is closed exactly
|
||||
and a Stop-returned `closed` session is never committed. If that exact stale
|
||||
close fails, its credential-free destination owner is retained for the next
|
||||
close attempt. Retained destination ownership is scoped to the initiating
|
||||
playlist/VOD route key, so route reuse cannot expose Stop for the previous
|
||||
movie's external session. Play/Resume capture that route key before awaiting
|
||||
close and cancel if navigation changes it; a late diagnostic fallback closes
|
||||
its exact returned session instead of adopting it on the new route. They
|
||||
supersede an older source resolution before awaiting the shared
|
||||
close-before-replacement path, and accepting a diagnostic fallback retires
|
||||
the same older resolution before opening MPV/VLC. They publish the route-source
|
||||
badge, caption evidence, and position only after start succeeds.
|
||||
Closable errors still participate in every replacement close and keep Stop as
|
||||
the global dock's only teardown affordance; Dismiss is reserved for terminal
|
||||
errors that have no closer. The shared `isLiveExternalPlayerSession` predicate
|
||||
keeps M3U and series ownership while
|
||||
such an error can still be stopped; consumers must not treat every `error`
|
||||
status as terminal.
|
||||
If the local handshake times out after an exact Electron session is known,
|
||||
that ID remains
|
||||
correlated so a later exact update can recover the UI. The global dock mirrors
|
||||
those statuses, keeps errors visible until dismissal, and intentionally has no
|
||||
retry because it does not own the original launch headers or credentials.
|
||||
those statuses, keeps closable errors visible until Stop confirms teardown and
|
||||
terminal errors visible until dismissal, and intentionally has no retry because
|
||||
it does not own the original launch headers or credentials.
|
||||
- DASH + ClearKey (M3U module): `.mpd` channels play through a lazily loaded
|
||||
Shaka Player source engine inside the HTML5 and ArtPlayer components (no new
|
||||
player in settings). ClearKey keys come from `#KODIPROP:inputstream.adaptive.*`
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { ChildProcess } from 'child_process';
|
||||
import { EventEmitter } from 'events';
|
||||
import { waitForExternalPlayerProcessExit } from './external-player-process';
|
||||
import {
|
||||
ExternalPlayerProcessTeardownGate,
|
||||
terminateExternalPlayerProcess,
|
||||
waitForExternalPlayerProcessExit,
|
||||
} from './external-player-process';
|
||||
|
||||
function createMockChildProcess(): ChildProcess {
|
||||
return Object.assign(new EventEmitter(), {
|
||||
@@ -53,4 +57,94 @@ describe('external player process teardown', () => {
|
||||
|
||||
await expect(exit).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('escalates teardown and resolves only after confirmed exit', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const child = createMockChildProcess();
|
||||
const teardown = terminateExternalPlayerProcess(child);
|
||||
|
||||
expect(child.kill).toHaveBeenNthCalledWith(1);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(3_000);
|
||||
|
||||
expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL');
|
||||
|
||||
child.emit('close', null, 'SIGKILL');
|
||||
|
||||
await expect(teardown).resolves.toBeUndefined();
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('allows a protocol quit grace period before forced termination', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const child = createMockChildProcess();
|
||||
const teardown = terminateExternalPlayerProcess(child, {
|
||||
sendTerminationSignal: false,
|
||||
});
|
||||
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
|
||||
await jest.advanceTimersByTimeAsync(3_000);
|
||||
|
||||
expect(child.kill).toHaveBeenCalledWith('SIGKILL');
|
||||
|
||||
child.emit('exit', null, 'SIGKILL');
|
||||
|
||||
await expect(teardown).resolves.toBeUndefined();
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects after a bounded forced-teardown wait', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const child = createMockChildProcess();
|
||||
const teardown = terminateExternalPlayerProcess(child);
|
||||
const result = expect(teardown).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
|
||||
await result;
|
||||
expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL');
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('blocks replacement launches until an unconfirmed child actually exits', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const child = createMockChildProcess();
|
||||
const gate = new ExternalPlayerProcessTeardownGate();
|
||||
const teardown = gate.terminate(child);
|
||||
const rejection = expect(teardown).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
expect(() => gate.assertLaunchAllowed()).toThrow(
|
||||
'previous external player is still shutting down'
|
||||
);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(() => gate.assertLaunchAllowed()).toThrow(
|
||||
'previous external player is still shutting down'
|
||||
);
|
||||
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
child.emit('exit', 0);
|
||||
|
||||
expect(() => gate.assertLaunchAllowed()).not.toThrow();
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,91 @@
|
||||
import type { ChildProcess } from 'child_process';
|
||||
|
||||
const TERMINATION_GRACE_PERIOD_MS = 3_000;
|
||||
const FORCED_TERMINATION_WAIT_MS = 2_000;
|
||||
|
||||
interface TerminateExternalPlayerProcessOptions {
|
||||
sendTerminationSignal?: boolean;
|
||||
}
|
||||
|
||||
const EXTERNAL_PLAYER_TEARDOWN_PENDING_ERROR =
|
||||
'Cannot launch player because the previous external player is still shutting down';
|
||||
|
||||
/**
|
||||
* Serializes replacement launches against exact children whose exit has not
|
||||
* been confirmed. `ChildProcess.killed` only means a signal was sent, so it is
|
||||
* deliberately not used as a release condition.
|
||||
*/
|
||||
export class ExternalPlayerProcessTeardownGate {
|
||||
private readonly pending = new Map<ChildProcess, () => void>();
|
||||
|
||||
assertLaunchAllowed(): void {
|
||||
for (const child of this.pending.keys()) {
|
||||
if (hasExited(child)) {
|
||||
this.release(child);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.pending.size > 0) {
|
||||
throw new Error(EXTERNAL_PLAYER_TEARDOWN_PENDING_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guard replacement launches before a potentially slow protocol-level
|
||||
* quit command is dispatched. `terminate()` keeps using the same exact
|
||||
* child registration once that command completes or fails.
|
||||
*/
|
||||
beginTeardown(child: ChildProcess): void {
|
||||
this.track(child);
|
||||
}
|
||||
|
||||
async terminate(
|
||||
child: ChildProcess,
|
||||
options: TerminateExternalPlayerProcessOptions = {}
|
||||
): Promise<void> {
|
||||
this.track(child);
|
||||
try {
|
||||
await terminateExternalPlayerProcess(child, options);
|
||||
} finally {
|
||||
if (hasExited(child)) {
|
||||
this.release(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
terminateInBackground(child: ChildProcess): void {
|
||||
void this.terminate(child).catch(() => {
|
||||
// The child remains registered until an exact exit/close event.
|
||||
// A later launch therefore still fails closed.
|
||||
});
|
||||
}
|
||||
|
||||
private track(child: ChildProcess): void {
|
||||
if (hasExited(child) || this.pending.has(child)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const release = () => this.release(child);
|
||||
this.pending.set(child, release);
|
||||
child.once('exit', release);
|
||||
child.once('close', release);
|
||||
}
|
||||
|
||||
private release(child: ChildProcess): void {
|
||||
const release = this.pending.get(child);
|
||||
if (!release) {
|
||||
return;
|
||||
}
|
||||
|
||||
child.off('exit', release);
|
||||
child.off('close', release);
|
||||
this.pending.delete(child);
|
||||
}
|
||||
}
|
||||
|
||||
export const externalPlayerProcessTeardownGate =
|
||||
new ExternalPlayerProcessTeardownGate();
|
||||
|
||||
/**
|
||||
* Resolves only after the exact child has stopped. A sent termination signal
|
||||
* is not itself proof that a replacement can be started safely.
|
||||
@@ -22,19 +108,80 @@ export function waitForExternalPlayerProcessExit(
|
||||
});
|
||||
}
|
||||
|
||||
export function terminateExternalPlayerProcess(
|
||||
child: ChildProcess
|
||||
export async function terminateExternalPlayerProcess(
|
||||
child: ChildProcess,
|
||||
options: TerminateExternalPlayerProcessOptions = {}
|
||||
): Promise<void> {
|
||||
const exited = waitForExternalPlayerProcessExit(child);
|
||||
if (!hasExited(child) && !child.killed) {
|
||||
if (hasExited(child)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
options.sendTerminationSignal !== false &&
|
||||
!hasExited(child) &&
|
||||
!child.killed
|
||||
) {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {
|
||||
// Keep waiting: failing closed prevents a replacement launch from
|
||||
// overlapping a child whose teardown could not be confirmed.
|
||||
// The forced termination attempt below still gets a chance to
|
||||
// confirm that the exact child stopped.
|
||||
}
|
||||
}
|
||||
return exited;
|
||||
|
||||
if (
|
||||
await waitForExternalPlayerProcessExitWithin(
|
||||
child,
|
||||
TERMINATION_GRACE_PERIOD_MS
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch {
|
||||
// Keep waiting for the bounded confirmation window. If the child does
|
||||
// not report exit, reject so callers cannot launch a replacement.
|
||||
}
|
||||
|
||||
if (
|
||||
await waitForExternalPlayerProcessExitWithin(
|
||||
child,
|
||||
FORCED_TERMINATION_WAIT_MS
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('External player process did not exit');
|
||||
}
|
||||
|
||||
function waitForExternalPlayerProcessExitWithin(
|
||||
child: ChildProcess,
|
||||
timeoutMs: number
|
||||
): Promise<boolean> {
|
||||
if (hasExited(child)) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const complete = (exited: boolean) => {
|
||||
child.off('exit', onExit);
|
||||
child.off('close', onExit);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
resolve(exited);
|
||||
};
|
||||
const onExit = () => complete(true);
|
||||
|
||||
child.once('exit', onExit);
|
||||
child.once('close', onExit);
|
||||
timer = setTimeout(() => complete(hasExited(child)), timeoutMs);
|
||||
timer.unref();
|
||||
});
|
||||
}
|
||||
|
||||
function hasExited(child: ChildProcess): boolean {
|
||||
|
||||
@@ -47,7 +47,27 @@ describe('ExternalPlayerSessionRegistry', () => {
|
||||
expect(registry.getActiveSessionId()).toBeNull();
|
||||
});
|
||||
|
||||
it('marks the session closed even when the runtime close fails', async () => {
|
||||
it('does not invoke a stale closer for an already closed session', async () => {
|
||||
const close = jest.fn();
|
||||
const session = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Closed',
|
||||
streamUrl: 'https://example.com/closed.m3u8',
|
||||
});
|
||||
registry.attachCloser(session.id, close);
|
||||
registry.markClosed(session.id);
|
||||
|
||||
const closed = await registry.closeSession(session.id);
|
||||
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
expect(closed).toMatchObject({
|
||||
id: session.id,
|
||||
status: 'closed',
|
||||
canClose: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the session live when runtime close cannot be confirmed', async () => {
|
||||
const close = jest.fn().mockRejectedValue(new Error('close failed'));
|
||||
const session = registry.beginSession({
|
||||
player: 'vlc',
|
||||
@@ -57,12 +77,14 @@ describe('ExternalPlayerSessionRegistry', () => {
|
||||
|
||||
registry.attachCloser(session.id, close);
|
||||
|
||||
const closed = await registry.closeSession(session.id);
|
||||
await expect(registry.closeSession(session.id)).rejects.toThrow(
|
||||
'close failed'
|
||||
);
|
||||
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(closed?.status).toBe('closed');
|
||||
expect(closed?.canClose).toBe(false);
|
||||
expect(registry.getActiveSessionId()).toBeNull();
|
||||
expect(registry.getSession(session.id)?.status).toBe('launching');
|
||||
expect(registry.getSession(session.id)?.canClose).toBe(true);
|
||||
expect(registry.getActiveSessionId()).toBe(session.id);
|
||||
});
|
||||
|
||||
it('marks runtime failures as errors without clearing the active id', () => {
|
||||
@@ -78,4 +100,121 @@ describe('ExternalPlayerSessionRegistry', () => {
|
||||
expect(errored?.error).toBe('Failed to launch');
|
||||
expect(registry.getActiveSessionId()).toBe(session.id);
|
||||
});
|
||||
|
||||
it('does not overwrite terminal status with late lifecycle updates', () => {
|
||||
const failed = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Failed',
|
||||
streamUrl: 'https://example.com/failed.m3u8',
|
||||
});
|
||||
registry.markError(failed.id, 'Failed to launch');
|
||||
|
||||
expect(registry.markOpened(failed.id)?.status).toBe('error');
|
||||
|
||||
const closed = registry.beginSession({
|
||||
player: 'vlc',
|
||||
title: 'Closed',
|
||||
streamUrl: 'https://example.com/closed.m3u8',
|
||||
});
|
||||
registry.markClosed(closed.id);
|
||||
|
||||
expect(registry.markPlaying(closed.id)?.status).toBe('closed');
|
||||
expect(
|
||||
registry.markError(closed.id, 'Late process exit')?.status
|
||||
).toBe('closed');
|
||||
expect(updates.at(-1)).toMatchObject({
|
||||
id: closed.id,
|
||||
status: 'closed',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps confirmed playback ahead of a late opened acknowledgement', () => {
|
||||
const session = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Fast playback',
|
||||
streamUrl: 'https://example.com/fast.m3u8',
|
||||
});
|
||||
|
||||
expect(registry.markPlaying(session.id)?.status).toBe('playing');
|
||||
expect(registry.markOpened(session.id)?.status).toBe('playing');
|
||||
});
|
||||
|
||||
it('restores a previous live session after a replacement fails', () => {
|
||||
const previous = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Previous',
|
||||
streamUrl: 'https://example.com/previous.m3u8',
|
||||
});
|
||||
registry.attachCloser(previous.id, jest.fn());
|
||||
registry.markOpened(previous.id);
|
||||
const replacement = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Replacement',
|
||||
streamUrl: 'https://example.com/replacement.m3u8',
|
||||
});
|
||||
registry.markError(replacement.id, 'teardown unconfirmed');
|
||||
|
||||
const restored = registry.restoreActiveSession(
|
||||
previous.id,
|
||||
replacement.id
|
||||
);
|
||||
|
||||
expect(restored).toMatchObject({
|
||||
id: previous.id,
|
||||
status: 'opened',
|
||||
canClose: true,
|
||||
});
|
||||
expect(registry.getActiveSessionId()).toBe(previous.id);
|
||||
expect(updates.at(-1)).toMatchObject({
|
||||
id: previous.id,
|
||||
restoredFromSessionId: replacement.id,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not restore over a newer active session', () => {
|
||||
const previous = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Previous',
|
||||
streamUrl: 'https://example.com/previous.m3u8',
|
||||
});
|
||||
registry.markOpened(previous.id);
|
||||
const failedReplacement = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Failed replacement',
|
||||
streamUrl: 'https://example.com/failed.m3u8',
|
||||
});
|
||||
const newer = registry.beginSession({
|
||||
player: 'vlc',
|
||||
title: 'Newer',
|
||||
streamUrl: 'https://example.com/newer.m3u8',
|
||||
});
|
||||
const updateCount = updates.length;
|
||||
|
||||
expect(
|
||||
registry.restoreActiveSession(previous.id, failedReplacement.id)
|
||||
).toBeNull();
|
||||
expect(registry.getActiveSessionId()).toBe(newer.id);
|
||||
expect(updates).toHaveLength(updateCount);
|
||||
});
|
||||
|
||||
it('does not restore an unclosable terminal error session', () => {
|
||||
const terminal = registry.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Terminal failure',
|
||||
streamUrl: 'https://example.com/terminal.m3u8',
|
||||
});
|
||||
registry.markError(terminal.id, 'No player process remains');
|
||||
const replacement = registry.beginSession({
|
||||
player: 'vlc',
|
||||
title: 'Replacement',
|
||||
streamUrl: 'https://example.com/replacement.m3u8',
|
||||
});
|
||||
const updateCount = updates.length;
|
||||
|
||||
expect(
|
||||
registry.restoreActiveSession(terminal.id, replacement.id)
|
||||
).toBeNull();
|
||||
expect(registry.getActiveSessionId()).toBe(replacement.id);
|
||||
expect(updates).toHaveLength(updateCount);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,19 @@ interface ExternalPlayerSessionRuntime {
|
||||
close?: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
interface MarkExternalPlayerSessionErrorOptions {
|
||||
canClose?: boolean;
|
||||
}
|
||||
|
||||
function isRestorableSession(session: ExternalPlayerSession): boolean {
|
||||
return (
|
||||
session.status === 'launching' ||
|
||||
session.status === 'opened' ||
|
||||
session.status === 'playing' ||
|
||||
(session.status === 'error' && session.canClose)
|
||||
);
|
||||
}
|
||||
|
||||
export class ExternalPlayerSessionRegistry {
|
||||
private readonly sessions = new Map<string, ExternalPlayerSessionRuntime>();
|
||||
private activeSessionId: string | null = null;
|
||||
@@ -62,6 +75,32 @@ export class ExternalPlayerSessionRegistry {
|
||||
return this.sessions.get(id)?.snapshot ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-publish the exact still-live session that a failed replacement had
|
||||
* temporarily displaced. Its existing closer remains attached.
|
||||
*/
|
||||
restoreActiveSession(
|
||||
id: string,
|
||||
displacedSessionId: string
|
||||
): ExternalPlayerSession | null {
|
||||
const runtime = this.sessions.get(id);
|
||||
if (
|
||||
!runtime ||
|
||||
!isRestorableSession(runtime.snapshot) ||
|
||||
this.activeSessionId !== displacedSessionId
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.activeSessionId = id;
|
||||
this.onUpdate({
|
||||
...runtime.snapshot,
|
||||
updatedAt: new Date().toISOString(),
|
||||
restoredFromSessionId: displacedSessionId,
|
||||
});
|
||||
return runtime.snapshot;
|
||||
}
|
||||
|
||||
attachCloser(
|
||||
id: string,
|
||||
close: () => Promise<void> | void
|
||||
@@ -95,12 +134,21 @@ export class ExternalPlayerSessionRegistry {
|
||||
}
|
||||
|
||||
markOpened(id: string): ExternalPlayerSession | null {
|
||||
const current = this.getSession(id);
|
||||
if (!current || current.status !== 'launching') {
|
||||
return current;
|
||||
}
|
||||
return this.updateSession(id, { status: 'opened' });
|
||||
}
|
||||
|
||||
markPlaying(id: string): ExternalPlayerSession | null {
|
||||
const current = this.getSession(id);
|
||||
if (!current || current.status === 'playing') {
|
||||
if (
|
||||
!current ||
|
||||
current.status === 'playing' ||
|
||||
current.status === 'error' ||
|
||||
current.status === 'closed'
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
|
||||
@@ -108,17 +156,30 @@ export class ExternalPlayerSessionRegistry {
|
||||
}
|
||||
|
||||
markClosed(id: string): ExternalPlayerSession | null {
|
||||
const current = this.getSession(id);
|
||||
if (!current || current.status === 'closed') {
|
||||
return current;
|
||||
}
|
||||
if (this.activeSessionId === id) {
|
||||
this.activeSessionId = null;
|
||||
}
|
||||
return this.updateSession(id, { status: 'closed', canClose: false });
|
||||
}
|
||||
|
||||
markError(id: string, error: string): ExternalPlayerSession | null {
|
||||
markError(
|
||||
id: string,
|
||||
error: string,
|
||||
options: MarkExternalPlayerSessionErrorOptions = {}
|
||||
): ExternalPlayerSession | null {
|
||||
const current = this.getSession(id);
|
||||
if (!current || current.status === 'closed') {
|
||||
return current;
|
||||
}
|
||||
|
||||
return this.updateSession(id, {
|
||||
status: 'error',
|
||||
error,
|
||||
canClose: false,
|
||||
canClose: options.canClose ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -128,13 +189,19 @@ export class ExternalPlayerSessionRegistry {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await runtime.close?.();
|
||||
} catch {
|
||||
// Close failures must not keep the session in a live state; the
|
||||
// registry still reports it as closed below.
|
||||
// A renderer can deliver a delayed duplicate Stop after the exact
|
||||
// child has already exited and a newer external player owns the
|
||||
// process slot. Never re-enter the terminal session's saved closer:
|
||||
// its protocol endpoint may since have been reused by another child.
|
||||
if (runtime.snapshot.status === 'closed') {
|
||||
return runtime.snapshot;
|
||||
}
|
||||
|
||||
// A failed closer cannot prove that the underlying process stopped.
|
||||
// Preserve the live session and propagate the failure so callers do
|
||||
// not start a replacement process alongside it.
|
||||
await runtime.close?.();
|
||||
|
||||
return this.markClosed(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
import { ChildProcess } from 'child_process';
|
||||
import { createConnection } from 'net';
|
||||
import {
|
||||
ExternalPlayerSession,
|
||||
PlayerContentInfo,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { joinMpvHeaderFields } from '../util/mpv-string-list.util';
|
||||
import { externalPlayerProcessTeardownGate } from './external-player-process';
|
||||
import {
|
||||
externalPlayerSessions,
|
||||
traceExternalPlayer,
|
||||
} from './external-player-runtime';
|
||||
|
||||
const MPV_IPC_COMMAND_TIMEOUT_MS = 2_000;
|
||||
|
||||
export interface MpvReuseAttemptState {
|
||||
contentMutated: boolean;
|
||||
teardownUnconfirmed: boolean;
|
||||
}
|
||||
|
||||
interface MpvReuseOptions {
|
||||
session: ExternalPlayerSession;
|
||||
previousProcessSessionId: string | null;
|
||||
url: string;
|
||||
title: string;
|
||||
effectiveUserAgent?: string;
|
||||
effectiveReferer?: string;
|
||||
headerFields: string[];
|
||||
contentInfo?: PlayerContentInfo;
|
||||
startTime?: number;
|
||||
state: MpvReuseAttemptState;
|
||||
startPositionPolling: (
|
||||
socketPath: string,
|
||||
contentInfo: PlayerContentInfo,
|
||||
sessionId: string
|
||||
) => void;
|
||||
stopPositionPolling: () => void;
|
||||
}
|
||||
|
||||
function sendMpvCommand(
|
||||
socketPath: string,
|
||||
command: string,
|
||||
args: Array<string | number>,
|
||||
shouldDispatch?: () => boolean
|
||||
): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = createConnection(socketPath);
|
||||
const request = JSON.stringify({ command: [command, ...args] }) + '\n';
|
||||
let settled = false;
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
const complete = (error?: Error, dispatched = true) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle);
|
||||
if (!dispatched && !client.destroyed) client.destroy();
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(dispatched);
|
||||
}
|
||||
};
|
||||
|
||||
client.on('connect', () => {
|
||||
if (shouldDispatch && !shouldDispatch()) {
|
||||
complete(undefined, false);
|
||||
return;
|
||||
}
|
||||
traceExternalPlayer('mpv ipc command', {
|
||||
command,
|
||||
argsCount: args.length,
|
||||
});
|
||||
try {
|
||||
client.write(request);
|
||||
client.end();
|
||||
complete();
|
||||
} catch (error) {
|
||||
complete(
|
||||
error instanceof Error ? error : new Error(String(error))
|
||||
);
|
||||
}
|
||||
});
|
||||
client.on('error', (error) => complete(error));
|
||||
timeoutHandle = setTimeout(() => {
|
||||
complete(new Error('MPV IPC command timed out'));
|
||||
client.destroy();
|
||||
}, MPV_IPC_COMMAND_TIMEOUT_MS);
|
||||
timeoutHandle.unref();
|
||||
});
|
||||
}
|
||||
|
||||
/** Owns the one MPV child/socket retained when instance reuse is enabled. */
|
||||
export class MpvReusableProcess {
|
||||
private process: ChildProcess | null = null;
|
||||
private socketPath: string | null = null;
|
||||
private processSessionId: string | null = null;
|
||||
private readonly processSessionIds = new WeakMap<ChildProcess, string>();
|
||||
|
||||
currentSessionId(): string | null {
|
||||
return this.processSessionId;
|
||||
}
|
||||
|
||||
sessionIdFor(process: ChildProcess, fallback: string): string {
|
||||
return this.processSessionIds.get(process) ?? fallback;
|
||||
}
|
||||
|
||||
owns(process: ChildProcess, sessionId: string): boolean {
|
||||
return this.processSessionIds.get(process) === sessionId;
|
||||
}
|
||||
|
||||
track(process: ChildProcess, socketPath: string, sessionId: string): void {
|
||||
this.process = process;
|
||||
this.socketPath = socketPath;
|
||||
this.processSessionId = sessionId;
|
||||
this.processSessionIds.set(process, sessionId);
|
||||
}
|
||||
|
||||
clear(process: ChildProcess): boolean {
|
||||
if (this.process !== process) return false;
|
||||
this.process = null;
|
||||
this.socketPath = null;
|
||||
this.processSessionId = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
stopStored(
|
||||
reason: string,
|
||||
stopPositionPolling: () => void,
|
||||
guardFutureLaunches = false
|
||||
): void {
|
||||
const process = this.process;
|
||||
if (!process || process.killed) return;
|
||||
traceExternalPlayer(reason);
|
||||
if (guardFutureLaunches) {
|
||||
externalPlayerProcessTeardownGate.terminateInBackground(process);
|
||||
} else {
|
||||
process.kill();
|
||||
}
|
||||
this.clear(process);
|
||||
stopPositionPolling();
|
||||
}
|
||||
|
||||
async tryReuse(
|
||||
options: MpvReuseOptions
|
||||
): Promise<ExternalPlayerSession | null> {
|
||||
const reusedProcess = this.process;
|
||||
const reusedSocketPath = this.socketPath;
|
||||
if (!reusedProcess || reusedProcess.killed || !reusedSocketPath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
traceExternalPlayer('reuse existing mpv instance');
|
||||
const { session, state } = options;
|
||||
const reusedProcessSessionId =
|
||||
this.processSessionIds.get(reusedProcess) ??
|
||||
options.previousProcessSessionId;
|
||||
let closeRequested = false;
|
||||
let retryableClose: Promise<void> | null = null;
|
||||
let launchClose: Promise<void> | null = null;
|
||||
|
||||
const ownsReusedProcess = () =>
|
||||
this.processSessionIds.get(reusedProcess) === session.id ||
|
||||
externalPlayerSessions.getActiveSessionId() === session.id;
|
||||
const closeReusedProcess = async () => {
|
||||
externalPlayerProcessTeardownGate.beginTeardown(reusedProcess);
|
||||
try {
|
||||
await sendMpvCommand(reusedSocketPath, 'quit', []);
|
||||
} catch {
|
||||
await externalPlayerProcessTeardownGate.terminate(
|
||||
reusedProcess
|
||||
);
|
||||
return;
|
||||
}
|
||||
await externalPlayerProcessTeardownGate.terminate(reusedProcess, {
|
||||
sendTerminationSignal: false,
|
||||
});
|
||||
};
|
||||
const finishRequestedClose = async () => {
|
||||
if (launchClose) {
|
||||
try {
|
||||
await launchClose;
|
||||
} catch (error) {
|
||||
state.teardownUnconfirmed = true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return externalPlayerSessions.markClosed(session.id) ?? session;
|
||||
};
|
||||
|
||||
externalPlayerSessions.attachCloser(session.id, () => {
|
||||
closeRequested = true;
|
||||
if (!ownsReusedProcess()) return;
|
||||
if (!retryableClose) {
|
||||
const closeAttempt = closeReusedProcess();
|
||||
retryableClose = closeAttempt;
|
||||
launchClose ??= closeAttempt;
|
||||
void closeAttempt.catch((error) => {
|
||||
if (retryableClose === closeAttempt) retryableClose = null;
|
||||
state.teardownUnconfirmed = true;
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{ canClose: true }
|
||||
);
|
||||
});
|
||||
}
|
||||
return retryableClose;
|
||||
});
|
||||
|
||||
try {
|
||||
await this.applyReuseCommands(
|
||||
options,
|
||||
reusedSocketPath,
|
||||
() => !closeRequested
|
||||
);
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
|
||||
state.contentMutated = true;
|
||||
this.processSessionId = session.id;
|
||||
this.processSessionIds.set(reusedProcess, session.id);
|
||||
options.stopPositionPolling();
|
||||
|
||||
if (options.startTime) {
|
||||
await sendMpvCommand(
|
||||
reusedSocketPath,
|
||||
'seek',
|
||||
[String(options.startTime), 'absolute'],
|
||||
() => !closeRequested
|
||||
);
|
||||
}
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
|
||||
if (options.contentInfo) {
|
||||
options.startPositionPolling(
|
||||
reusedSocketPath,
|
||||
options.contentInfo,
|
||||
session.id
|
||||
);
|
||||
} else {
|
||||
options.stopPositionPolling();
|
||||
}
|
||||
return externalPlayerSessions.markOpened(session.id) ?? session;
|
||||
} catch (error) {
|
||||
const current = externalPlayerSessions.getSession(session.id);
|
||||
if (current?.status === 'closed') return current;
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
console.error('Failed to send command to existing MPV:', error);
|
||||
|
||||
if (state.contentMutated) {
|
||||
if (reusedProcessSessionId) {
|
||||
this.processSessionIds.set(
|
||||
reusedProcess,
|
||||
reusedProcessSessionId
|
||||
);
|
||||
} else {
|
||||
this.processSessionIds.delete(reusedProcess);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await externalPlayerProcessTeardownGate.terminate(
|
||||
reusedProcess
|
||||
);
|
||||
} catch (teardownError) {
|
||||
if (state.contentMutated) {
|
||||
this.processSessionIds.set(reusedProcess, session.id);
|
||||
}
|
||||
state.teardownUnconfirmed = true;
|
||||
throw teardownError;
|
||||
}
|
||||
this.clear(reusedProcess);
|
||||
options.stopPositionPolling();
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async applyReuseCommands(
|
||||
options: MpvReuseOptions,
|
||||
socketPath: string,
|
||||
shouldDispatch: () => boolean
|
||||
): Promise<void> {
|
||||
if (options.effectiveUserAgent) {
|
||||
const dispatched = await sendMpvCommand(
|
||||
socketPath,
|
||||
'set_property',
|
||||
['user-agent', options.effectiveUserAgent],
|
||||
shouldDispatch
|
||||
);
|
||||
if (!dispatched) return;
|
||||
}
|
||||
if (options.effectiveReferer) {
|
||||
const dispatched = await sendMpvCommand(
|
||||
socketPath,
|
||||
'set_property',
|
||||
['referrer', options.effectiveReferer],
|
||||
shouldDispatch
|
||||
);
|
||||
if (!dispatched) return;
|
||||
}
|
||||
if (options.headerFields.length > 0) {
|
||||
const dispatched = await sendMpvCommand(
|
||||
socketPath,
|
||||
'set_property',
|
||||
[
|
||||
'http-header-fields',
|
||||
joinMpvHeaderFields(options.headerFields),
|
||||
],
|
||||
shouldDispatch
|
||||
);
|
||||
if (!dispatched) return;
|
||||
}
|
||||
if (!shouldDispatch()) return;
|
||||
const loadFileArgs: Array<string | number> = [options.url, 'replace'];
|
||||
if (options.title) {
|
||||
loadFileArgs.push(-1, `force-media-title=${options.title}`);
|
||||
}
|
||||
const dispatched = await sendMpvCommand(
|
||||
socketPath,
|
||||
'loadfile',
|
||||
loadFileArgs,
|
||||
shouldDispatch
|
||||
);
|
||||
if (!dispatched) return;
|
||||
traceExternalPlayer('loaded new url in existing mpv instance');
|
||||
}
|
||||
}
|
||||
@@ -50,8 +50,17 @@ import {
|
||||
store,
|
||||
} from '../services/store.service';
|
||||
import { externalPlayerSessions } from './external-player-runtime';
|
||||
import { openMpvPlayer, shutdownMpvSession } from './mpv-session.service';
|
||||
import { openVlcPlayer, shutdownVlcSession } from './vlc-session.service';
|
||||
import { externalPlayerProcessTeardownGate } from './external-player-process';
|
||||
import {
|
||||
openMpvPlayer,
|
||||
setMpvReuseInstance,
|
||||
shutdownMpvSession,
|
||||
} from './mpv-session.service';
|
||||
import {
|
||||
openVlcPlayer,
|
||||
setVlcReuseInstance,
|
||||
shutdownVlcSession,
|
||||
} from './vlc-session.service';
|
||||
|
||||
function createMockChildProcess(): ChildProcess {
|
||||
return Object.assign(new EventEmitter(), {
|
||||
@@ -116,6 +125,222 @@ describe('external player shutdown on app quit', () => {
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('blocks a launch until MPV exits after reuse is disabled', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'Reusable MPV stream',
|
||||
url: 'https://example.com/live.m3u8',
|
||||
});
|
||||
|
||||
setMpvReuseInstance(false);
|
||||
|
||||
await expect(
|
||||
openMpvPlayer({
|
||||
title: 'Replacement MPV stream',
|
||||
url: 'https://example.com/replacement.m3u8',
|
||||
})
|
||||
).rejects.toThrow('previous external player is still shutting down');
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
});
|
||||
|
||||
it('settles a fresh MPV launch when Stop wins before startup confirmation', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const proc = createMockChildProcess();
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
Object.defineProperty(proc, 'killed', { value: true });
|
||||
setImmediate(() => {
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: false,
|
||||
});
|
||||
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Stopped stream',
|
||||
url: 'https://example.com/stopped.m3u8',
|
||||
});
|
||||
const sessionId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(sessionId);
|
||||
|
||||
await jest.runAllTimersAsync();
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
|
||||
let launchSettled = false;
|
||||
void opening.then(() => {
|
||||
launchSettled = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(launchSettled).toBe(true);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('settles a fresh MPV launch when bounded Stop cannot confirm exit', async () => {
|
||||
jest.useFakeTimers();
|
||||
const proc = createMockChildProcess();
|
||||
try {
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
Object.defineProperty(proc, 'killed', {
|
||||
value: true,
|
||||
configurable: true,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: false,
|
||||
});
|
||||
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Unresponsive stream',
|
||||
url: 'https://example.com/unresponsive.m3u8',
|
||||
});
|
||||
let launchSettled = false;
|
||||
void opening.then(
|
||||
() => {
|
||||
launchSettled = true;
|
||||
},
|
||||
() => {
|
||||
launchSettled = true;
|
||||
}
|
||||
);
|
||||
const sessionId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(sessionId);
|
||||
const closeRejection = expect(closing).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await closeRejection;
|
||||
await Promise.resolve();
|
||||
|
||||
expect(launchSettled).toBe(true);
|
||||
expect(externalPlayerSessions.getSession(sessionId)).toMatchObject({
|
||||
status: 'error',
|
||||
canClose: true,
|
||||
});
|
||||
} finally {
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not let a stale reusable MPV closer stop the remapped session', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
Object.defineProperty(proc, 'exitCode', {
|
||||
value: 0,
|
||||
configurable: true,
|
||||
});
|
||||
proc.emit('exit', 0);
|
||||
return true;
|
||||
});
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
const previous = await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
});
|
||||
const current = await openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
(proc.kill as jest.Mock).mockClear();
|
||||
|
||||
await expect(
|
||||
externalPlayerSessions.closeSession(previous.id)
|
||||
).resolves.toMatchObject({ status: 'closed' });
|
||||
|
||||
expect(proc.kill).not.toHaveBeenCalled();
|
||||
expect(externalPlayerSessions.getSession(current.id)).toMatchObject({
|
||||
status: 'opened',
|
||||
canClose: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not send a stale quit after a closed reused session is replaced', async () => {
|
||||
shutdownMpvSession();
|
||||
const firstProc = createMockChildProcess();
|
||||
const nextProc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock)
|
||||
.mockReturnValueOnce(firstProc)
|
||||
.mockReturnValueOnce(nextProc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
const written: string[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn((chunk: string) => written.push(chunk)),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
});
|
||||
const reused = await openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
|
||||
Object.defineProperty(firstProc, 'exitCode', { value: 0 });
|
||||
firstProc.emit('exit', 0);
|
||||
const current = await openMpvPlayer({
|
||||
title: 'Third stream',
|
||||
url: 'https://example.com/three.m3u8',
|
||||
});
|
||||
written.length = 0;
|
||||
|
||||
await expect(
|
||||
externalPlayerSessions.closeSession(reused.id)
|
||||
).resolves.toMatchObject({ status: 'closed' });
|
||||
|
||||
expect(written).toEqual([]);
|
||||
expect(nextProc.kill).not.toHaveBeenCalled();
|
||||
expect(externalPlayerSessions.getSession(current.id)).toMatchObject({
|
||||
status: 'opened',
|
||||
canClose: true,
|
||||
});
|
||||
|
||||
shutdownMpvSession();
|
||||
});
|
||||
|
||||
it('escapes commas in http header fields passed to mpv', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
@@ -205,6 +430,553 @@ describe('external player shutdown on app quit', () => {
|
||||
shutdownMpvSession();
|
||||
});
|
||||
|
||||
it('bounds a reused MPV close when its IPC socket never connects', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
});
|
||||
const reused = await openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() =>
|
||||
Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
})
|
||||
);
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const closing = externalPlayerSessions.closeSession(reused.id);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(2_000);
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
await expect(closing).resolves.toMatchObject({
|
||||
id: reused.id,
|
||||
status: 'closed',
|
||||
});
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('allows Stop to retry a reused MPV teardown after confirmation times out', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
});
|
||||
const reused = await openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('error', new Error('quit failed')));
|
||||
return socket;
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const firstClose = externalPlayerSessions.closeSession(reused.id);
|
||||
const firstRejection = expect(firstClose).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await firstRejection;
|
||||
const killsAfterFirstAttempt = (proc.kill as jest.Mock).mock.calls
|
||||
.length;
|
||||
|
||||
const retry = externalPlayerSessions.closeSession(reused.id);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect((proc.kill as jest.Mock).mock.calls.length).toBeGreaterThan(
|
||||
killsAfterFirstAttempt
|
||||
);
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
|
||||
await expect(retry).resolves.toMatchObject({ status: 'closed' });
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('guards reused MPV teardown while its protocol quit is pending', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
});
|
||||
const session = await openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
|
||||
const sockets: EventEmitter[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
sockets.push(socket);
|
||||
return socket;
|
||||
});
|
||||
const closing = externalPlayerSessions.closeSession(session.id);
|
||||
|
||||
try {
|
||||
expect(() =>
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed()
|
||||
).toThrow('previous external player is still shutting down');
|
||||
} finally {
|
||||
while (sockets.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
sockets[0].emit('connect');
|
||||
proc.emit('exit', 0);
|
||||
await closing;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not dispatch reused MPV content after Stop interrupts header setup', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
|
||||
const sockets: Array<
|
||||
EventEmitter & { write: jest.Mock; end: jest.Mock }
|
||||
> = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
sockets.push(socket);
|
||||
if (sockets.length > 2) {
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
}
|
||||
return socket;
|
||||
});
|
||||
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
userAgent: 'IPTVnator test agent',
|
||||
});
|
||||
while (sockets.length < 1) await Promise.resolve();
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
while (sockets.length < 2) await Promise.resolve();
|
||||
|
||||
sockets[0].emit('connect');
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
sockets[1].emit('connect');
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
await expect(opening).resolves.toMatchObject({ status: 'closed' });
|
||||
const commands = sockets.flatMap((socket) =>
|
||||
socket.write.mock.calls.map(([request]) =>
|
||||
JSON.parse(String(request)).command[0]
|
||||
)
|
||||
);
|
||||
expect(commands).not.toContain('loadfile');
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not spawn a replacement when Stop interrupts reused MPV seek', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
|
||||
const sockets: EventEmitter[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
sockets.push(socket);
|
||||
if (sockets.length === 1 || sockets.length === 3) {
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
}
|
||||
return socket;
|
||||
});
|
||||
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
startTime: 120,
|
||||
});
|
||||
while (sockets.length < 2) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
while (sockets.length < 3) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
sockets[1].emit('error', new Error('connection closed'));
|
||||
|
||||
await expect(closing).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not spawn fresh when Stop arrives during failed MPV reuse teardown', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() =>
|
||||
socket.emit('error', new Error('reuse command failed'))
|
||||
);
|
||||
return socket;
|
||||
});
|
||||
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 20 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('restores the globally displaced session when reusable MPV teardown is unconfirmed', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
const displaced = externalPlayerSessions.beginSession({
|
||||
player: 'vlc',
|
||||
title: 'Current VLC stream',
|
||||
streamUrl: 'https://example.com/current-vlc.m3u8',
|
||||
});
|
||||
externalPlayerSessions.attachCloser(displaced.id, jest.fn());
|
||||
externalPlayerSessions.markOpened(displaced.id);
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() =>
|
||||
socket.emit('error', new Error('reuse command failed'))
|
||||
);
|
||||
return socket;
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const rejection = expect(opening).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 4 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(externalPlayerSessions.getActiveSessionId()).toBe(
|
||||
displaced.id
|
||||
);
|
||||
expect(
|
||||
externalPlayerSessions.getSession(displaced.id)
|
||||
).toMatchObject({
|
||||
status: 'opened',
|
||||
canClose: true,
|
||||
});
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps an orphaned reusable MPV teardown failure closable', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
const previous = await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
externalPlayerSessions.markClosed(previous.id);
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() =>
|
||||
socket.emit('error', new Error('reuse command failed'))
|
||||
);
|
||||
return socket;
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const rejection = expect(opening).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 4 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(
|
||||
externalPlayerSessions.getSession(replacementId)
|
||||
).toMatchObject({
|
||||
title: 'Second stream',
|
||||
status: 'error',
|
||||
canClose: true,
|
||||
});
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps replacement ownership when reused MPV content changed before teardown failed', async () => {
|
||||
shutdownMpvSession();
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
const previous = await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
let connectionCount = 0;
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
connectionCount += 1;
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => {
|
||||
if (connectionCount === 1) {
|
||||
socket.emit('connect');
|
||||
} else {
|
||||
socket.emit('error', new Error('seek failed'));
|
||||
}
|
||||
});
|
||||
return socket;
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
startTime: 120,
|
||||
});
|
||||
const replacementId = externalPlayerSessions.getActiveSessionId();
|
||||
const rejection = expect(opening).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 4 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(replacementId).not.toBe(previous.id);
|
||||
expect(externalPlayerSessions.getActiveSessionId()).toBe(
|
||||
replacementId
|
||||
);
|
||||
expect(
|
||||
externalPlayerSessions.getSession(replacementId as string)
|
||||
).toMatchObject({
|
||||
title: 'Second stream',
|
||||
status: 'error',
|
||||
canClose: true,
|
||||
});
|
||||
|
||||
Object.defineProperty(proc, 'killed', { value: true });
|
||||
await expect(
|
||||
openMpvPlayer({
|
||||
title: 'Third stream',
|
||||
url: 'https://example.com/three.m3u8',
|
||||
})
|
||||
).rejects.toThrow(
|
||||
'previous external player is still shutting down'
|
||||
);
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('waits for the stale reusable MPV process to exit before spawning fresh', async () => {
|
||||
shutdownMpvSession();
|
||||
const staleProc = createMockChildProcess();
|
||||
@@ -247,6 +1019,107 @@ describe('external player shutdown on app quit', () => {
|
||||
shutdownMpvSession();
|
||||
});
|
||||
|
||||
it('rechecks the process-wide teardown gate before fallback MPV spawn', async () => {
|
||||
shutdownMpvSession();
|
||||
const staleProc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(staleProc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => socket.emit('error', new Error('stale socket')));
|
||||
return socket;
|
||||
});
|
||||
|
||||
const opening = openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(staleProc.kill).toHaveBeenCalledTimes(1);
|
||||
|
||||
const blocker = createMockChildProcess();
|
||||
const blockerTeardown =
|
||||
externalPlayerProcessTeardownGate.terminate(blocker);
|
||||
try {
|
||||
Object.defineProperty(staleProc, 'exitCode', { value: 0 });
|
||||
staleProc.emit('exit', 0);
|
||||
|
||||
await expect(opening).rejects.toThrow(
|
||||
'previous external player is still shutting down'
|
||||
);
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
Object.defineProperty(blocker, 'exitCode', { value: 0 });
|
||||
blocker.emit('exit', 0);
|
||||
await blockerTeardown;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the fallback MPV session live after partial reuse failure', async () => {
|
||||
shutdownMpvSession();
|
||||
const reusedProc = createMockChildProcess();
|
||||
(reusedProc.kill as jest.Mock).mockImplementation(() => {
|
||||
setImmediate(() => {
|
||||
Object.defineProperty(reusedProc, 'exitCode', { value: 0 });
|
||||
reusedProc.emit('exit', 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
const freshProc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock)
|
||||
.mockReturnValueOnce(reusedProc)
|
||||
.mockReturnValueOnce(freshProc);
|
||||
mockStoreValues({
|
||||
[MPV_PLAYER_PATH]: '/usr/bin/mpv',
|
||||
[MPV_REUSE_INSTANCE]: true,
|
||||
});
|
||||
await openMpvPlayer({
|
||||
title: 'First stream',
|
||||
url: 'https://example.com/one.m3u8',
|
||||
});
|
||||
let connectionCount = 0;
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(() => {
|
||||
connectionCount += 1;
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
write: jest.fn(),
|
||||
end: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
});
|
||||
setImmediate(() => {
|
||||
if (connectionCount === 1) {
|
||||
socket.emit('connect');
|
||||
} else {
|
||||
socket.emit('error', new Error('seek failed'));
|
||||
}
|
||||
});
|
||||
return socket;
|
||||
});
|
||||
|
||||
const session = await openMpvPlayer({
|
||||
title: 'Second stream',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
startTime: 120,
|
||||
});
|
||||
|
||||
expect(spawn).toHaveBeenCalledTimes(2);
|
||||
expect(session.status).toBe('opened');
|
||||
expect(externalPlayerSessions.getSession(session.id)?.status).toBe(
|
||||
'opened'
|
||||
);
|
||||
shutdownMpvSession();
|
||||
});
|
||||
|
||||
it('does not track non-reusable MPV processes for shutdown', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
@@ -326,4 +1199,33 @@ describe('external player shutdown on app quit', () => {
|
||||
shutdownVlcSession();
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('blocks a launch until VLC exits after reuse is disabled', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(spawn as unknown as jest.Mock).mockReturnValue(proc);
|
||||
mockStoreValues({
|
||||
[VLC_PLAYER_PATH]: '/usr/bin/vlc',
|
||||
[VLC_REUSE_INSTANCE]: true,
|
||||
});
|
||||
const openPromise = openVlcPlayer({
|
||||
title: 'Reusable VLC stream',
|
||||
url: 'https://example.com/live.m3u8',
|
||||
});
|
||||
await waitForSpawnCallCount(1);
|
||||
proc.emit('spawn');
|
||||
await openPromise;
|
||||
|
||||
setVlcReuseInstance(false);
|
||||
|
||||
await expect(
|
||||
openVlcPlayer({
|
||||
title: 'Replacement VLC stream',
|
||||
url: 'https://example.com/replacement.m3u8',
|
||||
})
|
||||
).rejects.toThrow('previous external player is still shutting down');
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ChildProcess, spawn } from 'child_process';
|
||||
import { spawn } from 'child_process';
|
||||
import { createConnection } from 'net';
|
||||
import { PlayerContentInfo } from '@iptvnator/shared/interfaces';
|
||||
import {
|
||||
@@ -29,10 +29,11 @@ import {
|
||||
sendPlayerErrorNotification,
|
||||
traceExternalPlayer,
|
||||
} from './external-player-runtime';
|
||||
import { externalPlayerProcessTeardownGate } from './external-player-process';
|
||||
import {
|
||||
terminateExternalPlayerProcess,
|
||||
waitForExternalPlayerProcessExit,
|
||||
} from './external-player-process';
|
||||
MpvReusableProcess,
|
||||
MpvReuseAttemptState,
|
||||
} from './mpv-reusable-process';
|
||||
|
||||
export interface OpenExternalPlayerRequest {
|
||||
url: string;
|
||||
@@ -46,8 +47,7 @@ export interface OpenExternalPlayerRequest {
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
let mpvProcess: ChildProcess | null = null;
|
||||
let mpvSocketPath: string | null = null;
|
||||
const reusableMpvProcess = new MpvReusableProcess();
|
||||
let positionPollingInterval: NodeJS.Timeout | null = null;
|
||||
|
||||
function getMpvPath(options: PlayerPathOptions = {}): string {
|
||||
@@ -156,53 +156,16 @@ function startPositionPolling(
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function sendMpvCommand(
|
||||
command: string,
|
||||
args: Array<string | number>
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!mpvSocketPath) {
|
||||
reject(new Error('No MPV socket path available'));
|
||||
return;
|
||||
}
|
||||
|
||||
const client = createConnection(mpvSocketPath);
|
||||
const request = JSON.stringify({ command: [command, ...args] }) + '\n';
|
||||
|
||||
client.on('connect', () => {
|
||||
traceExternalPlayer('mpv ipc command', {
|
||||
command,
|
||||
argsCount: args.length,
|
||||
});
|
||||
client.write(request);
|
||||
client.end();
|
||||
resolve();
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
console.error('MPV socket error:', err);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function killStoredMpvProcess(reason: string): void {
|
||||
if (!mpvProcess || mpvProcess.killed) {
|
||||
return;
|
||||
}
|
||||
traceExternalPlayer(reason);
|
||||
mpvProcess.kill();
|
||||
mpvProcess = null;
|
||||
mpvSocketPath = null;
|
||||
stopPositionPolling();
|
||||
}
|
||||
|
||||
export function setMpvReuseInstance(reuseInstance: boolean): void {
|
||||
traceExternalPlayer('set mpv reuse instance', { reuseInstance });
|
||||
store.set(MPV_REUSE_INSTANCE, reuseInstance);
|
||||
|
||||
if (!reuseInstance) {
|
||||
killStoredMpvProcess('clean up mpv process after disabling reuse');
|
||||
reusableMpvProcess.stopStored(
|
||||
'clean up mpv process after disabling reuse',
|
||||
stopPositionPolling,
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,7 +175,10 @@ export function setMpvReuseInstance(reuseInstance: boolean): void {
|
||||
* app and keeps playing after quit.
|
||||
*/
|
||||
export function shutdownMpvSession(): void {
|
||||
killStoredMpvProcess('kill reused mpv process on app shutdown');
|
||||
reusableMpvProcess.stopStored(
|
||||
'kill reused mpv process on app shutdown',
|
||||
stopPositionPolling
|
||||
);
|
||||
}
|
||||
|
||||
export async function openMpvPlayer({
|
||||
@@ -226,6 +192,9 @@ export async function openMpvPlayer({
|
||||
startTime,
|
||||
headers,
|
||||
}: OpenExternalPlayerRequest) {
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed();
|
||||
const displacedSessionId = externalPlayerSessions.getActiveSessionId();
|
||||
const previousProcessSessionId = reusableMpvProcess.currentSessionId();
|
||||
const session = externalPlayerSessions.beginSession({
|
||||
player: 'mpv',
|
||||
title,
|
||||
@@ -233,6 +202,11 @@ export async function openMpvPlayer({
|
||||
streamUrl: url,
|
||||
contentInfo,
|
||||
});
|
||||
const reuseState: MpvReuseAttemptState = {
|
||||
teardownUnconfirmed: false,
|
||||
contentMutated: false,
|
||||
};
|
||||
let freshTeardownUnconfirmed = false;
|
||||
|
||||
try {
|
||||
const isFlatpak = isRunningInFlatpak();
|
||||
@@ -277,84 +251,22 @@ export async function openMpvPlayer({
|
||||
parseExternalPlayerArguments(customMpvArguments).length,
|
||||
});
|
||||
|
||||
if (
|
||||
reuseInstance &&
|
||||
mpvProcess &&
|
||||
!mpvProcess.killed &&
|
||||
mpvSocketPath
|
||||
) {
|
||||
traceExternalPlayer('reuse existing mpv instance');
|
||||
const reusedProcess = mpvProcess;
|
||||
try {
|
||||
if (effectiveUserAgent) {
|
||||
await sendMpvCommand('set_property', [
|
||||
'user-agent',
|
||||
effectiveUserAgent,
|
||||
]);
|
||||
}
|
||||
if (effectiveReferer) {
|
||||
await sendMpvCommand('set_property', [
|
||||
'referrer',
|
||||
effectiveReferer,
|
||||
]);
|
||||
}
|
||||
if (headerFields.length > 0) {
|
||||
await sendMpvCommand('set_property', [
|
||||
'http-header-fields',
|
||||
joinMpvHeaderFields(headerFields),
|
||||
]);
|
||||
}
|
||||
|
||||
const loadFileArgs: Array<string | number> = [url, 'replace'];
|
||||
const loadFileOptions: string[] = [];
|
||||
|
||||
if (title) {
|
||||
loadFileOptions.push(`force-media-title=${title}`);
|
||||
}
|
||||
if (loadFileOptions.length > 0) {
|
||||
loadFileArgs.push(-1, loadFileOptions.join(','));
|
||||
}
|
||||
|
||||
await sendMpvCommand('loadfile', loadFileArgs);
|
||||
traceExternalPlayer('loaded new url in existing mpv instance');
|
||||
|
||||
externalPlayerSessions.attachCloser(session.id, async () => {
|
||||
try {
|
||||
await sendMpvCommand('quit', []);
|
||||
} catch {
|
||||
await terminateExternalPlayerProcess(reusedProcess);
|
||||
return;
|
||||
}
|
||||
await waitForExternalPlayerProcessExit(reusedProcess);
|
||||
});
|
||||
|
||||
if (startTime) {
|
||||
await sendMpvCommand('seek', [
|
||||
String(startTime),
|
||||
'absolute',
|
||||
]);
|
||||
}
|
||||
|
||||
if (contentInfo) {
|
||||
startPositionPolling(
|
||||
mpvSocketPath,
|
||||
contentInfo,
|
||||
session.id
|
||||
);
|
||||
} else {
|
||||
stopPositionPolling();
|
||||
}
|
||||
|
||||
return externalPlayerSessions.markOpened(session.id) ?? session;
|
||||
} catch (err) {
|
||||
console.error('Failed to send command to existing MPV:', err);
|
||||
await terminateExternalPlayerProcess(reusedProcess);
|
||||
if (mpvProcess === reusedProcess) {
|
||||
mpvProcess = null;
|
||||
mpvSocketPath = null;
|
||||
}
|
||||
stopPositionPolling();
|
||||
}
|
||||
if (reuseInstance) {
|
||||
const reused = await reusableMpvProcess.tryReuse({
|
||||
session,
|
||||
previousProcessSessionId,
|
||||
url,
|
||||
title,
|
||||
effectiveUserAgent,
|
||||
effectiveReferer,
|
||||
headerFields,
|
||||
contentInfo,
|
||||
startTime,
|
||||
state: reuseState,
|
||||
startPositionPolling,
|
||||
stopPositionPolling,
|
||||
});
|
||||
if (reused) return reused;
|
||||
}
|
||||
|
||||
traceExternalPlayer('create new mpv instance');
|
||||
@@ -397,10 +309,36 @@ export async function openMpvPlayer({
|
||||
args.push(url);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let startConfirmationTimer: NodeJS.Timeout | null = null;
|
||||
const resolveLaunch = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (startConfirmationTimer) {
|
||||
clearTimeout(startConfirmationTimer);
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
const rejectLaunch = (error: Error) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (startConfirmationTimer) {
|
||||
clearTimeout(startConfirmationTimer);
|
||||
}
|
||||
reject(error);
|
||||
};
|
||||
const spawnSpec = buildExternalPlayerSpawnSpec(
|
||||
mpvLaunchContext,
|
||||
buildPlayerArgsWithCustomArguments(customMpvArguments, args)
|
||||
);
|
||||
// Reuse teardown yields while waiting for the old child. Another
|
||||
// external process may enter teardown during that window, so the
|
||||
// process-wide invariant must be checked at the actual spawn too.
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed();
|
||||
const proc = spawn(spawnSpec.command, spawnSpec.args, {
|
||||
shell: false,
|
||||
detached: !reuseInstance,
|
||||
@@ -465,20 +403,28 @@ export async function openMpvPlayer({
|
||||
|
||||
proc.on('error', (err) => {
|
||||
console.error('Failed to start MPV player:', err);
|
||||
mpvProcess = null;
|
||||
mpvSocketPath = null;
|
||||
const processSessionId = reusableMpvProcess.sessionIdFor(
|
||||
proc,
|
||||
session.id
|
||||
);
|
||||
reusableMpvProcess.clear(proc);
|
||||
stopPositionPolling();
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
processSessionId,
|
||||
`Failed to start MPV player: ${err.message}`
|
||||
);
|
||||
reject(buildPlayerStartError('MPV', err, mpvLaunchContext));
|
||||
rejectLaunch(
|
||||
buildPlayerStartError('MPV', err, mpvLaunchContext)
|
||||
);
|
||||
});
|
||||
|
||||
proc.on('exit', (code) => {
|
||||
traceExternalPlayer('mpv exited', { code });
|
||||
mpvProcess = null;
|
||||
mpvSocketPath = null;
|
||||
const processSessionId = reusableMpvProcess.sessionIdFor(
|
||||
proc,
|
||||
session.id
|
||||
);
|
||||
reusableMpvProcess.clear(proc);
|
||||
stopPositionPolling();
|
||||
|
||||
if (code !== 0 && code !== null) {
|
||||
@@ -490,18 +436,19 @@ export async function openMpvPlayer({
|
||||
`MPV player closed unexpectedly (exit code: ${code})`
|
||||
);
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
processSessionId,
|
||||
`MPV player closed unexpectedly (exit code: ${code})`
|
||||
);
|
||||
resolveLaunch();
|
||||
return;
|
||||
}
|
||||
|
||||
externalPlayerSessions.markClosed(session.id);
|
||||
externalPlayerSessions.markClosed(processSessionId);
|
||||
resolveLaunch();
|
||||
});
|
||||
|
||||
if (reuseInstance && socketPath) {
|
||||
mpvProcess = proc;
|
||||
mpvSocketPath = socketPath;
|
||||
reusableMpvProcess.track(proc, socketPath, session.id);
|
||||
traceExternalPlayer('stored mpv process for reuse', {
|
||||
socketPath,
|
||||
});
|
||||
@@ -510,29 +457,66 @@ export async function openMpvPlayer({
|
||||
}
|
||||
|
||||
externalPlayerSessions.attachCloser(session.id, async () => {
|
||||
await terminateExternalPlayerProcess(proc);
|
||||
if (
|
||||
reuseInstance &&
|
||||
!reusableMpvProcess.owns(proc, session.id)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await externalPlayerProcessTeardownGate.terminate(proc);
|
||||
} catch (error) {
|
||||
const teardownError =
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(String(error));
|
||||
freshTeardownUnconfirmed = true;
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
teardownError.message,
|
||||
{ canClose: true }
|
||||
);
|
||||
rejectLaunch(teardownError);
|
||||
throw teardownError;
|
||||
}
|
||||
});
|
||||
|
||||
if (useMpvSocketBridge && contentInfo && socketPath) {
|
||||
startPositionPolling(socketPath, contentInfo, session.id);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
startConfirmationTimer = setTimeout(() => {
|
||||
if (!proc.killed) {
|
||||
resolve();
|
||||
resolveLaunch();
|
||||
}
|
||||
}, 100);
|
||||
startConfirmationTimer.unref();
|
||||
});
|
||||
|
||||
return externalPlayerSessions.markOpened(session.id) ?? session;
|
||||
} catch (error) {
|
||||
console.error('Error opening MPV player:', error);
|
||||
mpvProcess = null;
|
||||
mpvSocketPath = null;
|
||||
stopPositionPolling();
|
||||
if (!reuseState.teardownUnconfirmed && !freshTeardownUnconfirmed) {
|
||||
stopPositionPolling();
|
||||
}
|
||||
const restoredSession =
|
||||
reuseState.teardownUnconfirmed &&
|
||||
!reuseState.contentMutated &&
|
||||
displacedSessionId
|
||||
? externalPlayerSessions.restoreActiveSession(
|
||||
displacedSessionId,
|
||||
session.id
|
||||
)
|
||||
: null;
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
error instanceof Error ? error.message : String(error)
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{
|
||||
canClose:
|
||||
freshTeardownUnconfirmed ||
|
||||
(reuseState.teardownUnconfirmed &&
|
||||
(reuseState.contentMutated || !restoredSession)),
|
||||
}
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { createConnection } from 'net';
|
||||
import { ExternalPlaybackSnapshot } from './external-player-runtime';
|
||||
|
||||
export function buildVlcEnqueueCommands(options: {
|
||||
url: string;
|
||||
title?: string;
|
||||
userAgent?: string;
|
||||
referer?: string;
|
||||
origin?: string;
|
||||
headers?: Record<string, string>;
|
||||
startTime?: number;
|
||||
}): string[] {
|
||||
const inputOptions: string[] = [];
|
||||
|
||||
if (options.userAgent) {
|
||||
inputOptions.push(`:http-user-agent=${options.userAgent}`);
|
||||
}
|
||||
if (options.referer) {
|
||||
inputOptions.push(`:http-referrer=${options.referer}`);
|
||||
} else if (options.origin) {
|
||||
inputOptions.push(`:http-referrer=${options.origin}`);
|
||||
}
|
||||
Object.entries(options.headers ?? {}).forEach(([name, value]) => {
|
||||
if (!name || value === undefined || value === null) return;
|
||||
const trimmedValue = String(value).trim();
|
||||
if (!trimmedValue) return;
|
||||
inputOptions.push(`:http-header=${name}: ${trimmedValue}`);
|
||||
});
|
||||
if (options.title) {
|
||||
inputOptions.push(`:meta-title=${options.title}`);
|
||||
}
|
||||
|
||||
const inputLine =
|
||||
inputOptions.length > 0
|
||||
? `${options.url} ${inputOptions.join(' ')}`
|
||||
: options.url;
|
||||
const commands = ['clear', `add ${inputLine}`];
|
||||
if (options.startTime && Number.isFinite(options.startTime)) {
|
||||
commands.push(`seek ${Math.floor(options.startTime)}`);
|
||||
}
|
||||
return commands;
|
||||
}
|
||||
|
||||
export function sendVlcRcCommand(
|
||||
port: number,
|
||||
command: string,
|
||||
onDispatched?: () => void,
|
||||
shouldDispatch?: () => boolean
|
||||
): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = createConnection({ port, host: '127.0.0.1' });
|
||||
let settled = false;
|
||||
const finish = (error?: Error, dispatched = true) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
if (!client.destroyed) client.destroy();
|
||||
if (error) reject(error);
|
||||
else resolve(dispatched);
|
||||
};
|
||||
const timeoutHandle = setTimeout(
|
||||
() => finish(new Error('VLC RC command timed out')),
|
||||
2_000
|
||||
);
|
||||
|
||||
client.on('connect', () => {
|
||||
if (shouldDispatch && !shouldDispatch()) {
|
||||
finish(undefined, false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
client.write(`${command}\n`);
|
||||
onDispatched?.();
|
||||
} catch (error) {
|
||||
finish(
|
||||
error instanceof Error ? error : new Error(String(error))
|
||||
);
|
||||
}
|
||||
});
|
||||
client.on('data', (chunk) => {
|
||||
if (chunk.toString().includes('>')) finish();
|
||||
});
|
||||
client.on('error', (error) => finish(error));
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendVlcRcCommands(
|
||||
port: number,
|
||||
commands: string[],
|
||||
onCommandSent?: (command: string, index: number) => void,
|
||||
shouldDispatch?: () => boolean
|
||||
): Promise<void> {
|
||||
for (const [index, command] of commands.entries()) {
|
||||
if (shouldDispatch && !shouldDispatch()) return;
|
||||
const dispatched = await sendVlcRcCommand(
|
||||
port,
|
||||
command,
|
||||
() => onCommandSent?.(command, index),
|
||||
shouldDispatch
|
||||
);
|
||||
if (!dispatched) return;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseVlcRcNumericResponse(data: string): string {
|
||||
return data.match(/>\s*(-?\d+(?:\.\d+)?)/)?.[1] ?? '';
|
||||
}
|
||||
|
||||
export function parseVlcRcPlaybackState(data: string): string | null {
|
||||
return (
|
||||
data
|
||||
.match(/\(\s*state\s+([^)]+)\s*\)/i)?.[1]
|
||||
?.trim()
|
||||
.toLowerCase() ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function getVlcCommandResponse(port: number, command: string): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const client = createConnection({ port, host: '127.0.0.1' });
|
||||
let data = '';
|
||||
let settled = false;
|
||||
const finish = (result: string) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
if (!client.destroyed) client.destroy();
|
||||
resolve(result);
|
||||
};
|
||||
const timeoutHandle = setTimeout(() => finish(''), 2_000);
|
||||
|
||||
client.on('connect', () => client.write(`${command}\n`));
|
||||
client.on('data', (chunk) => {
|
||||
data += chunk.toString();
|
||||
if (data.includes('>')) finish(data);
|
||||
});
|
||||
client.on('error', () => finish(''));
|
||||
});
|
||||
}
|
||||
|
||||
export async function getVlcPlaybackState(
|
||||
port: number
|
||||
): Promise<string | null> {
|
||||
return parseVlcRcPlaybackState(await getVlcCommandResponse(port, 'status'));
|
||||
}
|
||||
|
||||
export async function getVlcPlaybackSnapshot(
|
||||
port: number
|
||||
): Promise<ExternalPlaybackSnapshot | null> {
|
||||
const time = parseInt(
|
||||
parseVlcRcNumericResponse(
|
||||
await getVlcCommandResponse(port, 'get_time')
|
||||
),
|
||||
10
|
||||
);
|
||||
const duration = parseInt(
|
||||
parseVlcRcNumericResponse(
|
||||
await getVlcCommandResponse(port, 'get_length')
|
||||
),
|
||||
10
|
||||
);
|
||||
if (Number.isNaN(time)) return null;
|
||||
return {
|
||||
positionSeconds: time,
|
||||
durationSeconds: Number.isNaN(duration) ? null : duration,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { ChildProcess } from 'child_process';
|
||||
import {
|
||||
ExternalPlayerSession,
|
||||
PlayerContentInfo,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { externalPlayerProcessTeardownGate } from './external-player-process';
|
||||
import {
|
||||
ExternalPlaybackSnapshot,
|
||||
externalPlayerSessions,
|
||||
sendPlaybackPositionUpdate,
|
||||
traceExternalPlayer,
|
||||
} from './external-player-runtime';
|
||||
import {
|
||||
buildVlcEnqueueCommands,
|
||||
sendVlcRcCommand,
|
||||
sendVlcRcCommands,
|
||||
} from './vlc-rc';
|
||||
|
||||
export interface VlcReuseAttemptState {
|
||||
contentMutated: boolean;
|
||||
teardownUnconfirmed: boolean;
|
||||
closeRequested: boolean;
|
||||
requestedClose: Promise<void> | null;
|
||||
}
|
||||
|
||||
interface VlcReuseOptions {
|
||||
session: ExternalPlayerSession;
|
||||
previousProcessSessionId: string | null;
|
||||
url: string;
|
||||
title: string;
|
||||
effectiveUserAgent?: string;
|
||||
effectiveReferer?: string;
|
||||
effectiveOrigin?: string;
|
||||
mergedHeaders: Record<string, string>;
|
||||
contentInfo?: PlayerContentInfo;
|
||||
startTime?: number;
|
||||
state: VlcReuseAttemptState;
|
||||
startPositionPolling: (
|
||||
port: number,
|
||||
contentInfo: PlayerContentInfo,
|
||||
sessionId: string,
|
||||
onSnapshot?: (snapshot: ExternalPlaybackSnapshot) => void,
|
||||
onStopped?: () => void
|
||||
) => void;
|
||||
stopPositionPolling: () => void;
|
||||
}
|
||||
|
||||
/** Owns the one VLC child/RC port retained when instance reuse is enabled. */
|
||||
export class VlcReusableProcess {
|
||||
private process: ChildProcess | null = null;
|
||||
private rcPort: number | null = null;
|
||||
private processSessionId: string | null = null;
|
||||
private readonly processSessionIds = new WeakMap<ChildProcess, string>();
|
||||
|
||||
currentSessionId(): string | null {
|
||||
return this.processSessionId;
|
||||
}
|
||||
|
||||
sessionIdFor(process: ChildProcess, fallback: string): string {
|
||||
return this.processSessionIds.get(process) ?? fallback;
|
||||
}
|
||||
|
||||
owns(process: ChildProcess, sessionId: string): boolean {
|
||||
return this.processSessionIds.get(process) === sessionId;
|
||||
}
|
||||
|
||||
track(process: ChildProcess, rcPort: number, sessionId: string): void {
|
||||
this.process = process;
|
||||
this.rcPort = rcPort;
|
||||
this.processSessionId = sessionId;
|
||||
this.processSessionIds.set(process, sessionId);
|
||||
}
|
||||
|
||||
clear(process: ChildProcess): boolean {
|
||||
if (this.process !== process) return false;
|
||||
this.process = null;
|
||||
this.rcPort = null;
|
||||
this.processSessionId = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
stopStored(
|
||||
reason: string,
|
||||
stopPositionPolling: () => void,
|
||||
guardFutureLaunches = false
|
||||
): void {
|
||||
const process = this.process;
|
||||
if (!process || process.killed) return;
|
||||
traceExternalPlayer(reason);
|
||||
if (guardFutureLaunches) {
|
||||
externalPlayerProcessTeardownGate.terminateInBackground(process);
|
||||
} else {
|
||||
process.kill();
|
||||
}
|
||||
this.clear(process);
|
||||
stopPositionPolling();
|
||||
}
|
||||
|
||||
async tryReuse(
|
||||
options: VlcReuseOptions
|
||||
): Promise<ExternalPlayerSession | null> {
|
||||
const reusedProcess = this.process;
|
||||
const reusedRcPort = this.rcPort;
|
||||
if (!reusedProcess || reusedProcess.killed || !reusedRcPort)
|
||||
return null;
|
||||
|
||||
traceExternalPlayer('reuse existing vlc instance', {
|
||||
rcPort: reusedRcPort,
|
||||
});
|
||||
const { session, state } = options;
|
||||
const reusedProcessSessionId =
|
||||
this.processSessionIds.get(reusedProcess) ??
|
||||
options.previousProcessSessionId;
|
||||
let closeRequested = false;
|
||||
let retryableClose: Promise<void> | null = null;
|
||||
let launchClose: Promise<void> | null = null;
|
||||
|
||||
const ownsReusedProcess = () =>
|
||||
this.processSessionIds.get(reusedProcess) === session.id ||
|
||||
externalPlayerSessions.getActiveSessionId() === session.id;
|
||||
const closeReusedProcess = async () => {
|
||||
externalPlayerProcessTeardownGate.beginTeardown(reusedProcess);
|
||||
try {
|
||||
await sendVlcRcCommand(reusedRcPort, 'quit');
|
||||
} catch {
|
||||
await externalPlayerProcessTeardownGate.terminate(
|
||||
reusedProcess
|
||||
);
|
||||
return;
|
||||
}
|
||||
await externalPlayerProcessTeardownGate.terminate(reusedProcess, {
|
||||
sendTerminationSignal: false,
|
||||
});
|
||||
};
|
||||
const finishRequestedClose = async () => {
|
||||
if (launchClose) {
|
||||
try {
|
||||
await launchClose;
|
||||
} catch (error) {
|
||||
state.teardownUnconfirmed = true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return externalPlayerSessions.markClosed(session.id) ?? session;
|
||||
};
|
||||
|
||||
externalPlayerSessions.attachCloser(session.id, () => {
|
||||
closeRequested = true;
|
||||
state.closeRequested = true;
|
||||
if (!ownsReusedProcess()) return;
|
||||
if (!retryableClose) {
|
||||
const closeAttempt = closeReusedProcess();
|
||||
retryableClose = closeAttempt;
|
||||
launchClose ??= closeAttempt;
|
||||
void closeAttempt.catch((error) => {
|
||||
if (retryableClose === closeAttempt) retryableClose = null;
|
||||
state.teardownUnconfirmed = true;
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{ canClose: true }
|
||||
);
|
||||
});
|
||||
}
|
||||
state.requestedClose = retryableClose;
|
||||
return retryableClose;
|
||||
});
|
||||
|
||||
try {
|
||||
await sendVlcRcCommands(
|
||||
reusedRcPort,
|
||||
buildVlcEnqueueCommands({
|
||||
url: options.url,
|
||||
title: options.title,
|
||||
userAgent: options.effectiveUserAgent,
|
||||
referer: options.effectiveReferer,
|
||||
origin: options.effectiveOrigin,
|
||||
headers: options.mergedHeaders,
|
||||
startTime: options.startTime,
|
||||
}),
|
||||
(_command, index) => {
|
||||
if (index !== 0) return;
|
||||
state.contentMutated = true;
|
||||
this.processSessionId = session.id;
|
||||
this.processSessionIds.set(reusedProcess, session.id);
|
||||
options.stopPositionPolling();
|
||||
},
|
||||
() => !closeRequested
|
||||
);
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
traceExternalPlayer('loaded new url in existing vlc instance');
|
||||
|
||||
let lastSnapshot: ExternalPlaybackSnapshot | null = null;
|
||||
if (options.contentInfo) {
|
||||
options.startPositionPolling(
|
||||
reusedRcPort,
|
||||
options.contentInfo,
|
||||
session.id,
|
||||
(snapshot) => {
|
||||
lastSnapshot = snapshot;
|
||||
},
|
||||
() => {
|
||||
if (
|
||||
lastSnapshot &&
|
||||
externalPlayerSessions.getSession(session.id)
|
||||
?.status !== 'closed'
|
||||
) {
|
||||
sendPlaybackPositionUpdate(
|
||||
session.id,
|
||||
options.contentInfo as PlayerContentInfo,
|
||||
lastSnapshot
|
||||
);
|
||||
}
|
||||
externalPlayerSessions.markClosed(session.id);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
options.stopPositionPolling();
|
||||
}
|
||||
return externalPlayerSessions.markOpened(session.id) ?? session;
|
||||
} catch (error) {
|
||||
const current = externalPlayerSessions.getSession(session.id);
|
||||
if (current?.status === 'closed') return current;
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
console.error(
|
||||
'Failed to reuse existing VLC, spawning fresh:',
|
||||
error
|
||||
);
|
||||
|
||||
if (state.contentMutated) {
|
||||
if (reusedProcessSessionId) {
|
||||
this.processSessionIds.set(
|
||||
reusedProcess,
|
||||
reusedProcessSessionId
|
||||
);
|
||||
} else {
|
||||
this.processSessionIds.delete(reusedProcess);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await externalPlayerProcessTeardownGate.terminate(
|
||||
reusedProcess
|
||||
);
|
||||
} catch (teardownError) {
|
||||
if (state.contentMutated) {
|
||||
this.processSessionIds.set(reusedProcess, session.id);
|
||||
}
|
||||
state.teardownUnconfirmed = true;
|
||||
throw teardownError;
|
||||
}
|
||||
this.clear(reusedProcess);
|
||||
options.stopPositionPolling();
|
||||
if (closeRequested) return await finishRequestedClose();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
store,
|
||||
} from '../services/store.service';
|
||||
import { externalPlayerSessions } from './external-player-runtime';
|
||||
import { externalPlayerProcessTeardownGate } from './external-player-process';
|
||||
import { openVlcPlayer, shutdownVlcSession } from './vlc-session.service';
|
||||
|
||||
const spawnMock = spawn as unknown as jest.Mock;
|
||||
@@ -196,6 +197,356 @@ describe('vlc-session.service process lifecycle', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('guards reused VLC teardown while its protocol quit is pending', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
const sockets: EventEmitter[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(
|
||||
() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn((data: string) => {
|
||||
if (data !== 'quit\n') {
|
||||
setImmediate(() =>
|
||||
socket.emit('data', Buffer.from('> '))
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
sockets.push(socket);
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
}
|
||||
);
|
||||
const session = await openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const closing = externalPlayerSessions.closeSession(session.id);
|
||||
|
||||
try {
|
||||
expect(() =>
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed()
|
||||
).toThrow('previous external player is still shutting down');
|
||||
} finally {
|
||||
while (sockets.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
sockets.at(-1)?.emit('data', Buffer.from('> '));
|
||||
proc.emit('exit', 0);
|
||||
await closing;
|
||||
}
|
||||
});
|
||||
|
||||
it('guards a VLC content session while Stop flushes its position', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
setImmediate(() => {
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Movie',
|
||||
url: streamUrl,
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 1,
|
||||
contentType: 'vod',
|
||||
},
|
||||
});
|
||||
await waitForSpawnCallCount(1);
|
||||
proc.emit('spawn');
|
||||
const session = await opening;
|
||||
|
||||
const sockets: EventEmitter[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(
|
||||
() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn((data: string) => {
|
||||
rcWrites.push(data);
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
sockets.push(socket);
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
}
|
||||
);
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(session.id);
|
||||
while (!rcWrites.includes('get_time\n')) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
try {
|
||||
expect(() =>
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed()
|
||||
).toThrow('previous external player is still shutting down');
|
||||
} finally {
|
||||
sockets[0].emit('data', Buffer.from('> 12'));
|
||||
while (sockets.length < 2) {
|
||||
await new Promise<void>((resolve) =>
|
||||
setImmediate(resolve)
|
||||
);
|
||||
}
|
||||
sockets[1].emit('data', Buffer.from('> 120'));
|
||||
await closing;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not spawn a replacement when Stop interrupts a reuse command', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
const sockets: EventEmitter[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(
|
||||
() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn((data: string) => {
|
||||
rcWrites.push(data);
|
||||
if (data !== 'clear\n') {
|
||||
setImmediate(() =>
|
||||
socket.emit('data', Buffer.from('> '))
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
sockets.push(socket);
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
}
|
||||
);
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(rcWrites).toEqual(['clear\n']);
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(rcWrites).toEqual(['clear\n', 'quit\n']);
|
||||
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
sockets[0].emit('error', new Error('connection closed'));
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
await expect(closing).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not enqueue reused VLC content after Stop interrupts clear', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
const sockets: EventEmitter[] = [];
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(
|
||||
() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn((data: string) => {
|
||||
rcWrites.push(data);
|
||||
if (data === 'quit\n') {
|
||||
setImmediate(() =>
|
||||
socket.emit('data', Buffer.from('> '))
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
sockets.push(socket);
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
}
|
||||
);
|
||||
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(rcWrites).toEqual(['clear\n']);
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(rcWrites).toEqual(['clear\n', 'quit\n']);
|
||||
|
||||
sockets[0].emit('data', Buffer.from('> '));
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
await expect(opening).resolves.toMatchObject({ status: 'closed' });
|
||||
expect(rcWrites).toEqual(['clear\n', 'quit\n']);
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not spawn fresh when Stop arrives during failed VLC reuse teardown', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
installRcSocketMock('error');
|
||||
spawnMock.mockReturnValue(proc);
|
||||
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 20 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
setImmediate(() => proc.emit('spawn'));
|
||||
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not spawn fresh when Stop arrives during fallback port allocation', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
setImmediate(() => {
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
let releaseClose: (() => void) | undefined;
|
||||
(createConnection as unknown as jest.Mock)
|
||||
.mockImplementationOnce(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn(),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
setImmediate(() =>
|
||||
socket.emit('error', new Error('rc connect failed'))
|
||||
);
|
||||
return socket;
|
||||
})
|
||||
.mockImplementationOnce(() => {
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn((data: string) => {
|
||||
rcWrites.push(data);
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
releaseClose = () => socket.emit('data', Buffer.from('> '));
|
||||
setImmediate(() => socket.emit('connect'));
|
||||
return socket;
|
||||
});
|
||||
let releasePort: (() => void) | undefined;
|
||||
(createServer as unknown as jest.Mock).mockImplementationOnce(
|
||||
() => ({
|
||||
unref: jest.fn(),
|
||||
on: jest.fn(),
|
||||
listen: (
|
||||
_port: number,
|
||||
_host: string,
|
||||
cb: () => void
|
||||
) => {
|
||||
releasePort = cb;
|
||||
},
|
||||
address: () => ({ port: 43211 }),
|
||||
close: (cb?: () => void) => cb?.(),
|
||||
})
|
||||
);
|
||||
spawnMock.mockReturnValue(proc);
|
||||
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 20 && !releasePort;
|
||||
attempt += 1
|
||||
) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(releasePort).toBeDefined();
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(replacementId);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 20 && !releaseClose;
|
||||
attempt += 1
|
||||
) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(releaseClose).toBeDefined();
|
||||
|
||||
// Resume the pending launch while Stop is still awaiting the old
|
||||
// reuse closer. It must observe that cancellation instead of
|
||||
// attaching a fresh child to the same session.
|
||||
releasePort?.();
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
releaseClose?.();
|
||||
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
id: replacementId,
|
||||
status: 'closed',
|
||||
});
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('kills the stale instance and spawns fresh when RC reuse fails', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
@@ -221,9 +572,595 @@ describe('vlc-session.service process lifecycle', () => {
|
||||
expect(spawnMock).toHaveBeenCalledTimes(2);
|
||||
expect(session.status).toBe('opened');
|
||||
});
|
||||
|
||||
it('keeps the fallback VLC session live after partial reuse failure', async () => {
|
||||
const reusedProc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(reusedProc);
|
||||
(reusedProc.kill as jest.Mock).mockImplementation(() => {
|
||||
setImmediate(() => {
|
||||
Object.defineProperty(reusedProc, 'exitCode', { value: 0 });
|
||||
reusedProc.emit('exit', 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
let connectionCount = 0;
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(
|
||||
() => {
|
||||
connectionCount += 1;
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn(() => {
|
||||
setImmediate(() =>
|
||||
socket.emit('data', Buffer.from('> '))
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
setImmediate(() => {
|
||||
if (connectionCount <= 2) {
|
||||
socket.emit('connect');
|
||||
} else {
|
||||
socket.emit('error', new Error('seek failed'));
|
||||
}
|
||||
});
|
||||
return socket;
|
||||
}
|
||||
);
|
||||
const freshProc = createMockChildProcess();
|
||||
spawnMock.mockReturnValueOnce(freshProc);
|
||||
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
startTime: 120,
|
||||
});
|
||||
await waitForSpawnCallCount(2);
|
||||
freshProc.emit('spawn');
|
||||
const session = await opening;
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledTimes(2);
|
||||
expect(session.status).toBe('opened');
|
||||
expect(externalPlayerSessions.getSession(session.id)?.status).toBe(
|
||||
'opened'
|
||||
);
|
||||
});
|
||||
|
||||
it('restores the globally displaced session when reusable VLC teardown is unconfirmed', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
const displaced = externalPlayerSessions.beginSession({
|
||||
player: 'mpv',
|
||||
title: 'Current MPV stream',
|
||||
streamUrl: 'https://example.com/current-mpv.m3u8',
|
||||
});
|
||||
externalPlayerSessions.attachCloser(displaced.id, jest.fn());
|
||||
externalPlayerSessions.markOpened(displaced.id);
|
||||
installRcSocketMock('error');
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const rejection = expect(opening).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 5 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(externalPlayerSessions.getActiveSessionId()).toBe(
|
||||
displaced.id
|
||||
);
|
||||
expect(
|
||||
externalPlayerSessions.getSession(displaced.id)
|
||||
).toMatchObject({ status: 'opened', canClose: true });
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps an orphaned reusable VLC teardown failure closable when the displaced session is terminal', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
const previousId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
externalPlayerSessions.markError(previousId, 'Old terminal error');
|
||||
installRcSocketMock('error');
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const rejection = expect(opening).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 5 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(
|
||||
externalPlayerSessions.getSession(replacementId)
|
||||
).toMatchObject({
|
||||
title: 'Second',
|
||||
status: 'error',
|
||||
canClose: true,
|
||||
});
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps replacement ownership when reused VLC content changed before teardown failed', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
const previousId = externalPlayerSessions.getActiveSessionId();
|
||||
let connectionCount = 0;
|
||||
(createConnection as unknown as jest.Mock).mockImplementation(
|
||||
() => {
|
||||
connectionCount += 1;
|
||||
const socket = Object.assign(new EventEmitter(), {
|
||||
destroyed: false,
|
||||
write: jest.fn(() => {
|
||||
setImmediate(() =>
|
||||
socket.emit('data', Buffer.from('> '))
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
destroy: jest.fn(() => {
|
||||
socket.destroyed = true;
|
||||
}),
|
||||
});
|
||||
setImmediate(() => {
|
||||
if (connectionCount <= 2) {
|
||||
socket.emit('connect');
|
||||
} else {
|
||||
socket.emit('error', new Error('seek failed'));
|
||||
}
|
||||
});
|
||||
return socket;
|
||||
}
|
||||
);
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
startTime: 120,
|
||||
});
|
||||
const replacementId =
|
||||
externalPlayerSessions.getActiveSessionId();
|
||||
const rejection = expect(opening).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 5 && !(proc.kill as jest.Mock).mock.calls.length;
|
||||
attempt += 1
|
||||
) {
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
}
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await rejection;
|
||||
|
||||
expect(replacementId).not.toBe(previousId);
|
||||
expect(externalPlayerSessions.getActiveSessionId()).toBe(
|
||||
replacementId
|
||||
);
|
||||
expect(
|
||||
externalPlayerSessions.getSession(replacementId as string)
|
||||
).toMatchObject({
|
||||
title: 'Second',
|
||||
status: 'error',
|
||||
canClose: true,
|
||||
});
|
||||
|
||||
Object.defineProperty(proc, 'killed', { value: true });
|
||||
await expect(
|
||||
openVlcPlayer({
|
||||
title: 'Third',
|
||||
url: 'https://example.com/three.m3u8',
|
||||
})
|
||||
).rejects.toThrow(
|
||||
'previous external player is still shutting down'
|
||||
);
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not let a stale reusable VLC closer stop the remapped session', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
Object.defineProperty(proc, 'exitCode', {
|
||||
value: 0,
|
||||
configurable: true,
|
||||
});
|
||||
proc.emit('exit', 0);
|
||||
return true;
|
||||
});
|
||||
await openTrackedVlcInstance(proc);
|
||||
const previousId = externalPlayerSessions.getActiveSessionId();
|
||||
installRcSocketMock('ack');
|
||||
const current = await openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
(proc.kill as jest.Mock).mockClear();
|
||||
|
||||
await expect(
|
||||
externalPlayerSessions.closeSession(previousId as string)
|
||||
).resolves.toMatchObject({ status: 'closed' });
|
||||
|
||||
expect(proc.kill).not.toHaveBeenCalled();
|
||||
expect(externalPlayerSessions.getSession(current.id)).toMatchObject(
|
||||
{ status: 'opened', canClose: true }
|
||||
);
|
||||
});
|
||||
|
||||
it('does not send a stale quit after a closed reused session is replaced', async () => {
|
||||
const firstProc = createMockChildProcess();
|
||||
const nextProc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(firstProc);
|
||||
installRcSocketMock('ack');
|
||||
const reused = await openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
|
||||
spawnMock.mockReturnValueOnce(nextProc);
|
||||
Object.defineProperty(firstProc, 'exitCode', { value: 0 });
|
||||
firstProc.emit('exit', 0);
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Third',
|
||||
url: 'https://example.com/three.m3u8',
|
||||
});
|
||||
await waitForSpawnCallCount(2);
|
||||
nextProc.emit('spawn');
|
||||
const current = await opening;
|
||||
rcWrites.length = 0;
|
||||
|
||||
await expect(
|
||||
externalPlayerSessions.closeSession(reused.id)
|
||||
).resolves.toMatchObject({ status: 'closed' });
|
||||
|
||||
expect(rcWrites).toEqual([]);
|
||||
expect(nextProc.kill).not.toHaveBeenCalled();
|
||||
expect(externalPlayerSessions.getSession(current.id)).toMatchObject(
|
||||
{ status: 'opened', canClose: true }
|
||||
);
|
||||
});
|
||||
|
||||
it('allows Stop to retry a reused VLC teardown after confirmation times out', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
await openTrackedVlcInstance(proc);
|
||||
installRcSocketMock('ack');
|
||||
const reused = await openVlcPlayer({
|
||||
title: 'Second',
|
||||
url: 'https://example.com/two.m3u8',
|
||||
});
|
||||
installRcSocketMock('error');
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const firstClose = externalPlayerSessions.closeSession(
|
||||
reused.id
|
||||
);
|
||||
const firstRejection = expect(firstClose).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await firstRejection;
|
||||
const killsAfterFirstAttempt = (proc.kill as jest.Mock).mock
|
||||
.calls.length;
|
||||
|
||||
const retry = externalPlayerSessions.closeSession(reused.id);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(
|
||||
(proc.kill as jest.Mock).mock.calls.length
|
||||
).toBeGreaterThan(killsAfterFirstAttempt);
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
|
||||
await expect(retry).resolves.toMatchObject({
|
||||
status: 'closed',
|
||||
});
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('process exit handling', () => {
|
||||
it('keeps a reused-mode VLC child closable when RC port allocation fails', async () => {
|
||||
mockStoreValues({
|
||||
[VLC_PLAYER_PATH]: '/usr/bin/vlc',
|
||||
[VLC_REUSE_INSTANCE]: true,
|
||||
});
|
||||
let rejectPort: ((error: Error) => void) | undefined;
|
||||
(createServer as unknown as jest.Mock).mockImplementation(() => ({
|
||||
unref: jest.fn(),
|
||||
on: jest.fn((event: string, listener: (error: Error) => void) => {
|
||||
if (event === 'error') rejectPort = listener;
|
||||
}),
|
||||
listen: () =>
|
||||
setImmediate(() =>
|
||||
rejectPort?.(new Error('port allocation failed'))
|
||||
),
|
||||
address: () => null,
|
||||
close: jest.fn(),
|
||||
}));
|
||||
const proc = createMockChildProcess();
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
|
||||
const opening = openVlcPlayer({ title: 'Fallback', url: streamUrl });
|
||||
await waitForSpawnCallCount(1);
|
||||
proc.emit('spawn');
|
||||
const session = await opening;
|
||||
|
||||
const closing = externalPlayerSessions.closeSession(session.id);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
expect(proc.kill).toHaveBeenCalledTimes(1);
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
});
|
||||
|
||||
it('rechecks teardown immediately before a delayed spawn', async () => {
|
||||
let releasePort: (() => void) | undefined;
|
||||
(createServer as unknown as jest.Mock).mockImplementation(() => ({
|
||||
unref: jest.fn(),
|
||||
on: jest.fn(),
|
||||
listen: (_port: number, _host: string, cb: () => void) => {
|
||||
releasePort = cb;
|
||||
},
|
||||
address: () => ({ port: 43210 }),
|
||||
close: (cb?: () => void) => cb?.(),
|
||||
}));
|
||||
const opening = openVlcPlayer({
|
||||
title: 'Delayed',
|
||||
url: streamUrl,
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 1,
|
||||
contentType: 'vod',
|
||||
},
|
||||
});
|
||||
while (!releasePort) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
const blocker = createMockChildProcess();
|
||||
const unexpected = createMockChildProcess();
|
||||
spawnMock.mockReturnValueOnce(unexpected);
|
||||
try {
|
||||
externalPlayerProcessTeardownGate.terminateInBackground(
|
||||
blocker
|
||||
);
|
||||
releasePort();
|
||||
setImmediate(() => unexpected.emit('spawn'));
|
||||
|
||||
await expect(opening).rejects.toThrow(
|
||||
'previous external player is still shutting down'
|
||||
);
|
||||
expect(spawnMock).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
Object.defineProperty(blocker, 'exitCode', { value: 0 });
|
||||
blocker.emit('exit', 0);
|
||||
Object.defineProperty(unexpected, 'exitCode', { value: 0 });
|
||||
unexpected.emit('exit', 0);
|
||||
// The fixed path never consumes the one-shot spawn result;
|
||||
// do not let it leak into the next lifecycle case.
|
||||
spawnMock.mockReset();
|
||||
}
|
||||
});
|
||||
|
||||
it('settles a fresh VLC launch when Stop wins before spawn', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
Object.defineProperty(proc, 'killed', { value: true });
|
||||
setImmediate(() => {
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
|
||||
const opening = openVlcPlayer({ title: 'S', url: streamUrl });
|
||||
await waitForSpawnCallCount(1);
|
||||
const sessionId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(sessionId);
|
||||
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
id: sessionId,
|
||||
status: 'closed',
|
||||
});
|
||||
});
|
||||
|
||||
it('settles a fresh VLC launch when bounded Stop cannot confirm exit', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
try {
|
||||
(proc.kill as jest.Mock).mockImplementation(() => {
|
||||
Object.defineProperty(proc, 'killed', {
|
||||
value: true,
|
||||
configurable: true,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
|
||||
const opening = openVlcPlayer({ title: 'S', url: streamUrl });
|
||||
await waitForSpawnCallCount(1);
|
||||
jest.useFakeTimers();
|
||||
let launchSettled = false;
|
||||
void opening.then(
|
||||
() => {
|
||||
launchSettled = true;
|
||||
},
|
||||
() => {
|
||||
launchSettled = true;
|
||||
}
|
||||
);
|
||||
const sessionId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(sessionId);
|
||||
const closeRejection = expect(closing).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await closeRejection;
|
||||
await Promise.resolve();
|
||||
|
||||
expect(launchSettled).toBe(true);
|
||||
expect(
|
||||
externalPlayerSessions.getSession(sessionId)
|
||||
).toMatchObject({ status: 'error', canClose: true });
|
||||
} finally {
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('allows Stop to retry a fresh VLC teardown after confirmation times out', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
(proc.kill as jest.Mock).mockImplementation(() => true);
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
const opening = openVlcPlayer({ title: 'S', url: streamUrl });
|
||||
await waitForSpawnCallCount(1);
|
||||
proc.emit('spawn');
|
||||
const session = await opening;
|
||||
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const firstClose = externalPlayerSessions.closeSession(
|
||||
session.id
|
||||
);
|
||||
const firstRejection = expect(firstClose).rejects.toThrow(
|
||||
'External player process did not exit'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await firstRejection;
|
||||
const killsAfterFirstAttempt = (proc.kill as jest.Mock).mock
|
||||
.calls.length;
|
||||
|
||||
const retry = externalPlayerSessions.closeSession(session.id);
|
||||
await Promise.resolve();
|
||||
Object.defineProperty(proc, 'exitCode', { value: 0 });
|
||||
proc.emit('exit', 0);
|
||||
|
||||
await expect(retry).resolves.toMatchObject({
|
||||
status: 'closed',
|
||||
});
|
||||
expect(
|
||||
(proc.kill as jest.Mock).mock.calls.length
|
||||
).toBeGreaterThan(killsAfterFirstAttempt);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('marks an opened VLC session failed when its fallback spawn is blocked', async () => {
|
||||
const initial = createMockChildProcess();
|
||||
spawnMock.mockReturnValueOnce(initial);
|
||||
const opening = openVlcPlayer({
|
||||
title: 'S',
|
||||
url: streamUrl,
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 1,
|
||||
contentType: 'vod',
|
||||
},
|
||||
});
|
||||
await waitForSpawnCallCount(1);
|
||||
initial.emit('spawn');
|
||||
const session = await opening;
|
||||
const blocker = createMockChildProcess();
|
||||
externalPlayerProcessTeardownGate.terminateInBackground(blocker);
|
||||
|
||||
try {
|
||||
Object.defineProperty(initial, 'exitCode', { value: 1 });
|
||||
initial.emit('exit', 1);
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
externalPlayerSessions.getSession(session.id)
|
||||
).toMatchObject({ status: 'error', canClose: false });
|
||||
} finally {
|
||||
Object.defineProperty(blocker, 'exitCode', { value: 0 });
|
||||
blocker.emit('exit', 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('settles a stopped VLC launch when spawn errors then only closes', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
|
||||
const opening = openVlcPlayer({ title: 'S', url: streamUrl });
|
||||
const sessionId =
|
||||
externalPlayerSessions.getActiveSessionId() as string;
|
||||
const closing = externalPlayerSessions.closeSession(sessionId);
|
||||
let launchResult: unknown;
|
||||
void opening.then((result) => {
|
||||
launchResult = result;
|
||||
});
|
||||
|
||||
proc.emit(
|
||||
'error',
|
||||
Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' })
|
||||
);
|
||||
Object.defineProperty(proc, 'exitCode', { value: -2 });
|
||||
proc.emit('close', -2, null);
|
||||
|
||||
await expect(closing).resolves.toMatchObject({ status: 'closed' });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(launchResult).toMatchObject({
|
||||
id: sessionId,
|
||||
status: 'closed',
|
||||
});
|
||||
});
|
||||
|
||||
it('waits for a detached VLC process to exit before closing its session', async () => {
|
||||
const proc = createMockChildProcess();
|
||||
spawnMock.mockReturnValueOnce(proc);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ChildProcess, spawn } from 'child_process';
|
||||
import { AddressInfo, createConnection, createServer } from 'net';
|
||||
import { spawn } from 'child_process';
|
||||
import { AddressInfo, createServer } from 'net';
|
||||
import { PlayerContentInfo } from '@iptvnator/shared/interfaces';
|
||||
import {
|
||||
VLC_PLAYER_ARGUMENTS,
|
||||
@@ -28,10 +28,17 @@ import {
|
||||
sendPlayerErrorNotification,
|
||||
traceExternalPlayer,
|
||||
} from './external-player-runtime';
|
||||
import { externalPlayerProcessTeardownGate } from './external-player-process';
|
||||
import { getVlcPlaybackSnapshot, getVlcPlaybackState } from './vlc-rc';
|
||||
export {
|
||||
buildVlcEnqueueCommands,
|
||||
parseVlcRcNumericResponse,
|
||||
parseVlcRcPlaybackState,
|
||||
} from './vlc-rc';
|
||||
import {
|
||||
terminateExternalPlayerProcess,
|
||||
waitForExternalPlayerProcessExit,
|
||||
} from './external-player-process';
|
||||
VlcReusableProcess,
|
||||
VlcReuseAttemptState,
|
||||
} from './vlc-reusable-process';
|
||||
|
||||
export interface OpenVlcPlayerRequest {
|
||||
url: string;
|
||||
@@ -45,8 +52,7 @@ export interface OpenVlcPlayerRequest {
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
let vlcProcess: ChildProcess | null = null;
|
||||
let vlcRcPort: number | null = null;
|
||||
const reusableVlcProcess = new VlcReusableProcess();
|
||||
let vlcPollingInterval: NodeJS.Timeout | null = null;
|
||||
|
||||
function getVlcPath(options: PlayerPathOptions = {}): string {
|
||||
@@ -56,103 +62,6 @@ function getVlcPath(options: PlayerPathOptions = {}): string {
|
||||
);
|
||||
}
|
||||
|
||||
export function buildVlcEnqueueCommands(options: {
|
||||
url: string;
|
||||
title?: string;
|
||||
userAgent?: string;
|
||||
referer?: string;
|
||||
origin?: string;
|
||||
headers?: Record<string, string>;
|
||||
startTime?: number;
|
||||
}): string[] {
|
||||
const inputOptions: string[] = [];
|
||||
|
||||
if (options.userAgent) {
|
||||
inputOptions.push(`:http-user-agent=${options.userAgent}`);
|
||||
}
|
||||
if (options.referer) {
|
||||
inputOptions.push(`:http-referrer=${options.referer}`);
|
||||
} else if (options.origin) {
|
||||
inputOptions.push(`:http-referrer=${options.origin}`);
|
||||
}
|
||||
Object.entries(options.headers ?? {}).forEach(([name, value]) => {
|
||||
if (!name || value === undefined || value === null) return;
|
||||
const trimmedValue = String(value).trim();
|
||||
if (!trimmedValue) return;
|
||||
inputOptions.push(`:http-header=${name}: ${trimmedValue}`);
|
||||
});
|
||||
if (options.title) {
|
||||
inputOptions.push(`:meta-title=${options.title}`);
|
||||
}
|
||||
|
||||
const inputLine =
|
||||
inputOptions.length > 0
|
||||
? `${options.url} ${inputOptions.join(' ')}`
|
||||
: options.url;
|
||||
|
||||
const commands = ['clear', `add ${inputLine}`];
|
||||
|
||||
if (options.startTime && Number.isFinite(options.startTime)) {
|
||||
commands.push(`seek ${Math.floor(options.startTime)}`);
|
||||
}
|
||||
|
||||
return commands;
|
||||
}
|
||||
|
||||
function sendVlcRcCommand(port: number, command: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = createConnection({ port, host: '127.0.0.1' });
|
||||
let settled = false;
|
||||
|
||||
const finish = (err?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
if (!client.destroyed) client.destroy();
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve();
|
||||
};
|
||||
|
||||
const timeoutHandle = setTimeout(
|
||||
() => finish(new Error('VLC RC command timed out')),
|
||||
2000
|
||||
);
|
||||
|
||||
client.on('connect', () => {
|
||||
client.write(`${command}\n`);
|
||||
});
|
||||
client.on('data', (chunk) => {
|
||||
if (chunk.toString().includes('>')) {
|
||||
finish();
|
||||
}
|
||||
});
|
||||
client.on('error', (err) => finish(err));
|
||||
});
|
||||
}
|
||||
|
||||
async function sendVlcRcCommands(
|
||||
port: number,
|
||||
commands: string[]
|
||||
): Promise<void> {
|
||||
for (const command of commands) {
|
||||
await sendVlcRcCommand(port, command);
|
||||
}
|
||||
}
|
||||
|
||||
export function parseVlcRcNumericResponse(data: string): string {
|
||||
const match = data.match(/>\s*(-?\d+(?:\.\d+)?)/);
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
export function parseVlcRcPlaybackState(data: string): string | null {
|
||||
const match = data.match(/\(\s*state\s+([^)]+)\s*\)/i);
|
||||
return match ? match[1].trim().toLowerCase() : null;
|
||||
}
|
||||
|
||||
function stopVlcPositionPolling(): void {
|
||||
if (vlcPollingInterval) {
|
||||
clearInterval(vlcPollingInterval);
|
||||
@@ -160,69 +69,6 @@ function stopVlcPositionPolling(): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function getVlcCommandResponse(
|
||||
port: number,
|
||||
command: string
|
||||
): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const client = createConnection({ port, host: '127.0.0.1' });
|
||||
let data = '';
|
||||
let resolved = false;
|
||||
|
||||
const done = (result: string) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
if (!client.destroyed) client.destroy();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const timeoutHandle = setTimeout(() => done(''), 2000);
|
||||
|
||||
client.on('connect', () => {
|
||||
client.write(command + '\n');
|
||||
});
|
||||
|
||||
client.on('data', (chunk) => {
|
||||
data += chunk.toString();
|
||||
if (data.includes('>')) {
|
||||
done(data);
|
||||
}
|
||||
});
|
||||
|
||||
client.on('error', () => done(''));
|
||||
});
|
||||
}
|
||||
|
||||
async function getVlcProperty(port: number, command: string): Promise<string> {
|
||||
return parseVlcRcNumericResponse(
|
||||
await getVlcCommandResponse(port, command)
|
||||
);
|
||||
}
|
||||
|
||||
async function getVlcPlaybackState(port: number): Promise<string | null> {
|
||||
return parseVlcRcPlaybackState(await getVlcCommandResponse(port, 'status'));
|
||||
}
|
||||
|
||||
async function getVlcPlaybackSnapshot(
|
||||
port: number
|
||||
): Promise<ExternalPlaybackSnapshot | null> {
|
||||
const timeStr = await getVlcProperty(port, 'get_time');
|
||||
const lenStr = await getVlcProperty(port, 'get_length');
|
||||
|
||||
const position = parseInt(timeStr, 10);
|
||||
const duration = parseInt(lenStr, 10);
|
||||
|
||||
if (isNaN(position)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
positionSeconds: position,
|
||||
durationSeconds: !isNaN(duration) ? duration : null,
|
||||
};
|
||||
}
|
||||
|
||||
function startVlcPositionPolling(
|
||||
port: number,
|
||||
contentInfo: PlayerContentInfo,
|
||||
@@ -274,23 +120,16 @@ function getFreePort(): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
function killStoredVlcProcess(reason: string): void {
|
||||
if (!vlcProcess || vlcProcess.killed) {
|
||||
return;
|
||||
}
|
||||
traceExternalPlayer(reason);
|
||||
vlcProcess.kill();
|
||||
vlcProcess = null;
|
||||
vlcRcPort = null;
|
||||
stopVlcPositionPolling();
|
||||
}
|
||||
|
||||
export function setVlcReuseInstance(reuseInstance: boolean): void {
|
||||
traceExternalPlayer('set vlc reuse instance', { reuseInstance });
|
||||
store.set(VLC_REUSE_INSTANCE, reuseInstance);
|
||||
|
||||
if (!reuseInstance) {
|
||||
killStoredVlcProcess('clean up vlc process after disabling reuse');
|
||||
reusableVlcProcess.stopStored(
|
||||
'clean up vlc process after disabling reuse',
|
||||
stopVlcPositionPolling,
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,7 +139,10 @@ export function setVlcReuseInstance(reuseInstance: boolean): void {
|
||||
* playing after quit.
|
||||
*/
|
||||
export function shutdownVlcSession(): void {
|
||||
killStoredVlcProcess('kill reused vlc process on app shutdown');
|
||||
reusableVlcProcess.stopStored(
|
||||
'kill reused vlc process on app shutdown',
|
||||
stopVlcPositionPolling
|
||||
);
|
||||
}
|
||||
|
||||
export async function openVlcPlayer({
|
||||
@@ -314,6 +156,9 @@ export async function openVlcPlayer({
|
||||
startTime,
|
||||
headers,
|
||||
}: OpenVlcPlayerRequest) {
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed();
|
||||
const displacedSessionId = externalPlayerSessions.getActiveSessionId();
|
||||
const previousProcessSessionId = reusableVlcProcess.currentSessionId();
|
||||
const session = externalPlayerSessions.beginSession({
|
||||
player: 'vlc',
|
||||
title,
|
||||
@@ -321,6 +166,13 @@ export async function openVlcPlayer({
|
||||
streamUrl: url,
|
||||
contentInfo,
|
||||
});
|
||||
const reuseState: VlcReuseAttemptState = {
|
||||
teardownUnconfirmed: false,
|
||||
contentMutated: false,
|
||||
closeRequested: false,
|
||||
requestedClose: null,
|
||||
};
|
||||
let freshTeardownUnconfirmed = false;
|
||||
|
||||
try {
|
||||
const isFlatpak = isRunningInFlatpak();
|
||||
@@ -362,76 +214,23 @@ export async function openVlcPlayer({
|
||||
parseExternalPlayerArguments(customVlcArguments).length,
|
||||
});
|
||||
|
||||
if (reuseInstance && vlcProcess && !vlcProcess.killed && vlcRcPort) {
|
||||
traceExternalPlayer('reuse existing vlc instance', {
|
||||
rcPort: vlcRcPort,
|
||||
if (reuseInstance) {
|
||||
const reused = await reusableVlcProcess.tryReuse({
|
||||
session,
|
||||
previousProcessSessionId,
|
||||
url,
|
||||
title,
|
||||
effectiveUserAgent,
|
||||
effectiveReferer,
|
||||
effectiveOrigin,
|
||||
mergedHeaders,
|
||||
contentInfo,
|
||||
startTime,
|
||||
state: reuseState,
|
||||
startPositionPolling: startVlcPositionPolling,
|
||||
stopPositionPolling: stopVlcPositionPolling,
|
||||
});
|
||||
const reusedProcess = vlcProcess;
|
||||
try {
|
||||
const enqueueCommands = buildVlcEnqueueCommands({
|
||||
url,
|
||||
title,
|
||||
userAgent: effectiveUserAgent,
|
||||
referer: effectiveReferer,
|
||||
origin: effectiveOrigin,
|
||||
headers: mergedHeaders,
|
||||
startTime,
|
||||
});
|
||||
await sendVlcRcCommands(vlcRcPort, enqueueCommands);
|
||||
traceExternalPlayer('loaded new url in existing vlc instance');
|
||||
|
||||
const reusedRcPort = vlcRcPort;
|
||||
let lastReusedSnapshot: ExternalPlaybackSnapshot | null = null;
|
||||
externalPlayerSessions.attachCloser(session.id, async () => {
|
||||
try {
|
||||
await sendVlcRcCommand(reusedRcPort, 'quit');
|
||||
} catch {
|
||||
await terminateExternalPlayerProcess(reusedProcess);
|
||||
return;
|
||||
}
|
||||
await waitForExternalPlayerProcessExit(reusedProcess);
|
||||
});
|
||||
|
||||
if (contentInfo) {
|
||||
startVlcPositionPolling(
|
||||
reusedRcPort,
|
||||
contentInfo,
|
||||
session.id,
|
||||
(snapshot) => {
|
||||
lastReusedSnapshot = snapshot;
|
||||
},
|
||||
() => {
|
||||
if (
|
||||
lastReusedSnapshot &&
|
||||
externalPlayerSessions.getSession(session.id)
|
||||
?.status !== 'closed'
|
||||
) {
|
||||
sendPlaybackPositionUpdate(
|
||||
session.id,
|
||||
contentInfo,
|
||||
lastReusedSnapshot
|
||||
);
|
||||
}
|
||||
externalPlayerSessions.markClosed(session.id);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
stopVlcPositionPolling();
|
||||
}
|
||||
|
||||
return externalPlayerSessions.markOpened(session.id) ?? session;
|
||||
} catch (err) {
|
||||
console.error(
|
||||
'Failed to reuse existing VLC, spawning fresh:',
|
||||
err
|
||||
);
|
||||
await terminateExternalPlayerProcess(reusedProcess);
|
||||
if (vlcProcess === reusedProcess) {
|
||||
vlcProcess = null;
|
||||
vlcRcPort = null;
|
||||
}
|
||||
stopVlcPositionPolling();
|
||||
}
|
||||
if (reused) return reused;
|
||||
}
|
||||
|
||||
let rcPort = 0;
|
||||
@@ -489,6 +288,8 @@ export async function openVlcPlayer({
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let closeRequested = false;
|
||||
let requestedClose: Promise<void> | null = null;
|
||||
|
||||
const resolveSpawn = () => {
|
||||
if (settled) {
|
||||
@@ -509,6 +310,50 @@ export async function openVlcPlayer({
|
||||
};
|
||||
|
||||
const spawnVlc = (playerArgs: string[], isRetry = false) => {
|
||||
if (reuseState.closeRequested) {
|
||||
closeRequested = true;
|
||||
const pendingReuseClose =
|
||||
reuseState.requestedClose ?? Promise.resolve();
|
||||
void pendingReuseClose.then(() => {
|
||||
externalPlayerSessions.markClosed(session.id);
|
||||
resolveSpawn();
|
||||
}, rejectSpawn);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
externalPlayerSessions.getSession(session.id)?.status ===
|
||||
'closed'
|
||||
) {
|
||||
closeRequested = true;
|
||||
resolveSpawn();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Port allocation and reuse fallback both yield. Another
|
||||
// exact child can enter teardown during either wait, so
|
||||
// the process-wide invariant must be checked at the
|
||||
// actual spawn boundary as well as at request entry.
|
||||
externalPlayerProcessTeardownGate.assertLaunchAllowed();
|
||||
} catch (error) {
|
||||
const launchError =
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(String(error));
|
||||
if (settled) {
|
||||
const current = externalPlayerSessions.getSession(
|
||||
session.id
|
||||
);
|
||||
if (current?.status !== 'closed') {
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
launchError.message
|
||||
);
|
||||
}
|
||||
} else {
|
||||
rejectSpawn(launchError);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const spawnSpec = buildExternalPlayerSpawnSpec(
|
||||
vlcLaunchContext,
|
||||
buildPlayerArgsWithCustomArguments(
|
||||
@@ -516,18 +361,24 @@ export async function openVlcPlayer({
|
||||
playerArgs
|
||||
)
|
||||
);
|
||||
const trackProcess = reuseInstance && !isRetry;
|
||||
// Reuse ownership exists only when an RC port was allocated.
|
||||
// Without it this child is a normal one-shot process whose
|
||||
// exact session closer must still terminate it.
|
||||
const trackProcess = reuseInstance && !isRetry && rcPort > 0;
|
||||
const proc = spawn(spawnSpec.command, spawnSpec.args, {
|
||||
shell: false,
|
||||
detached: !trackProcess,
|
||||
stdio: trackProcess ? ['ignore', 'pipe', 'pipe'] : 'ignore',
|
||||
});
|
||||
|
||||
proc.once('spawn', resolveSpawn);
|
||||
proc.once('spawn', () => {
|
||||
if (!closeRequested) {
|
||||
resolveSpawn();
|
||||
}
|
||||
});
|
||||
|
||||
if (trackProcess && rcPort > 0) {
|
||||
vlcProcess = proc;
|
||||
vlcRcPort = rcPort;
|
||||
reusableVlcProcess.track(proc, rcPort, session.id);
|
||||
traceExternalPlayer('tracking vlc process for reuse', {
|
||||
rcPort,
|
||||
});
|
||||
@@ -572,9 +423,45 @@ export async function openVlcPlayer({
|
||||
);
|
||||
};
|
||||
|
||||
externalPlayerSessions.attachCloser(session.id, async () => {
|
||||
await flushVlcPlaybackPosition();
|
||||
await terminateExternalPlayerProcess(proc);
|
||||
externalPlayerSessions.attachCloser(session.id, () => {
|
||||
closeRequested = true;
|
||||
if (
|
||||
trackProcess &&
|
||||
!reusableVlcProcess.owns(proc, session.id)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!requestedClose) {
|
||||
// Position flush uses two bounded RC requests. Guard
|
||||
// the exact child before either request yields so no
|
||||
// replacement can reuse or overlap it while Stop is
|
||||
// still preparing the teardown.
|
||||
externalPlayerProcessTeardownGate.beginTeardown(proc);
|
||||
const closeAttempt = (async () => {
|
||||
await flushVlcPlaybackPosition();
|
||||
await externalPlayerProcessTeardownGate.terminate(
|
||||
proc
|
||||
);
|
||||
})();
|
||||
requestedClose = closeAttempt;
|
||||
void closeAttempt.catch((error) => {
|
||||
if (requestedClose === closeAttempt) {
|
||||
requestedClose = null;
|
||||
}
|
||||
const teardownError =
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(String(error));
|
||||
freshTeardownUnconfirmed = true;
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
teardownError.message,
|
||||
{ canClose: true }
|
||||
);
|
||||
rejectSpawn(teardownError);
|
||||
});
|
||||
}
|
||||
return requestedClose;
|
||||
});
|
||||
|
||||
if (!isRetry && rcPort > 0 && contentInfo) {
|
||||
@@ -611,9 +498,21 @@ export async function openVlcPlayer({
|
||||
|
||||
proc.on('error', (err) => {
|
||||
console.error('Failed to start VLC player:', err);
|
||||
if (vlcProcess === proc) {
|
||||
vlcProcess = null;
|
||||
vlcRcPort = null;
|
||||
const processSessionId = reusableVlcProcess.sessionIdFor(
|
||||
proc,
|
||||
session.id
|
||||
);
|
||||
reusableVlcProcess.clear(proc);
|
||||
if (closeRequested) {
|
||||
void requestedClose?.then(() => {
|
||||
// A spawn failure reports `close` without an
|
||||
// `exit` event. Close the exact session before
|
||||
// settling OPEN_VLC_PLAYER so the renderer
|
||||
// cannot receive a stale `opened` result.
|
||||
externalPlayerSessions.markClosed(session.id);
|
||||
resolveSpawn();
|
||||
}, rejectSpawn);
|
||||
return;
|
||||
}
|
||||
if (!isRetry && rcPort > 0) {
|
||||
traceExternalPlayer(
|
||||
@@ -628,7 +527,7 @@ export async function openVlcPlayer({
|
||||
spawnVlc(retryArgs, true);
|
||||
} else {
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
processSessionId,
|
||||
`Failed to start VLC player: ${err.message}`
|
||||
);
|
||||
rejectSpawn(
|
||||
@@ -639,13 +538,15 @@ export async function openVlcPlayer({
|
||||
|
||||
proc.on('exit', (code) => {
|
||||
traceExternalPlayer('vlc exited', { code });
|
||||
if (vlcProcess === proc) {
|
||||
vlcProcess = null;
|
||||
vlcRcPort = null;
|
||||
}
|
||||
const processSessionId = reusableVlcProcess.sessionIdFor(
|
||||
proc,
|
||||
session.id
|
||||
);
|
||||
reusableVlcProcess.clear(proc);
|
||||
stopVlcPositionPolling();
|
||||
|
||||
if (
|
||||
!closeRequested &&
|
||||
lastVlcSnapshot &&
|
||||
contentInfo &&
|
||||
externalPlayerSessions.getSession(session.id)
|
||||
@@ -658,7 +559,12 @@ export async function openVlcPlayer({
|
||||
);
|
||||
}
|
||||
|
||||
if (code === 1 && !isRetry && rcPort > 0) {
|
||||
if (
|
||||
code === 1 &&
|
||||
!closeRequested &&
|
||||
!isRetry &&
|
||||
rcPort > 0
|
||||
) {
|
||||
traceExternalPlayer(
|
||||
'retry vlc without rc interface after exit'
|
||||
);
|
||||
@@ -682,13 +588,15 @@ export async function openVlcPlayer({
|
||||
`VLC player closed unexpectedly (exit code: ${code})`
|
||||
);
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
processSessionId,
|
||||
`VLC player closed unexpectedly (exit code: ${code})`
|
||||
);
|
||||
resolveSpawn();
|
||||
return;
|
||||
}
|
||||
|
||||
externalPlayerSessions.markClosed(session.id);
|
||||
externalPlayerSessions.markClosed(processSessionId);
|
||||
resolveSpawn();
|
||||
});
|
||||
|
||||
if (!trackProcess) {
|
||||
@@ -702,9 +610,24 @@ export async function openVlcPlayer({
|
||||
return externalPlayerSessions.markOpened(session.id) ?? session;
|
||||
} catch (error) {
|
||||
console.error('Error opening VLC player:', error);
|
||||
const restoredSession =
|
||||
reuseState.teardownUnconfirmed &&
|
||||
!reuseState.contentMutated &&
|
||||
displacedSessionId
|
||||
? externalPlayerSessions.restoreActiveSession(
|
||||
displacedSessionId,
|
||||
session.id
|
||||
)
|
||||
: null;
|
||||
externalPlayerSessions.markError(
|
||||
session.id,
|
||||
error instanceof Error ? error.message : String(error)
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{
|
||||
canClose:
|
||||
freshTeardownUnconfirmed ||
|
||||
(reuseState.teardownUnconfirmed &&
|
||||
(reuseState.contentMutated || !restoredSession)),
|
||||
}
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -151,4 +151,30 @@ describe('ExternalPlaybackService', () => {
|
||||
service.dismissActiveSession();
|
||||
expect(service.visibleSession()).toBeNull();
|
||||
});
|
||||
|
||||
it('adopts an exactly correlated restored session after replacement teardown fails', () => {
|
||||
const previous = createSession({
|
||||
id: 'session-previous',
|
||||
status: 'opened',
|
||||
title: 'Previous stream',
|
||||
});
|
||||
const replacement = createSession({
|
||||
id: 'session-replacement',
|
||||
title: 'Replacement stream',
|
||||
});
|
||||
listener?.(previous);
|
||||
listener?.(replacement);
|
||||
|
||||
listener?.({
|
||||
...previous,
|
||||
restoredFromSessionId: replacement.id,
|
||||
updatedAt: '2026-03-07T10:00:20.000Z',
|
||||
});
|
||||
|
||||
expect(service.activeSession()).toMatchObject({
|
||||
id: previous.id,
|
||||
status: 'opened',
|
||||
});
|
||||
expect(service.visibleSession()?.id).toBe(previous.id);
|
||||
});
|
||||
});
|
||||
@@ -103,16 +103,19 @@ export class ExternalPlaybackService {
|
||||
|
||||
private handleSessionUpdate(session: ExternalPlayerSession): void {
|
||||
const current = this.activeSession();
|
||||
const restoresCurrentReplacement =
|
||||
current?.id === session.restoredFromSessionId;
|
||||
|
||||
if (
|
||||
!current ||
|
||||
current.id === session.id ||
|
||||
session.status === 'launching'
|
||||
session.status === 'launching' ||
|
||||
restoresCurrentReplacement
|
||||
) {
|
||||
this.activeSession.set(session);
|
||||
}
|
||||
|
||||
if (session.status === 'launching') {
|
||||
if (session.status === 'launching' || restoresCurrentReplacement) {
|
||||
this.dismissedSessionId.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -661,24 +661,87 @@ target becomes an explicit reopen action and a failed target becomes Try again.
|
||||
Only an exact correlated Electron `playing` session update earns the Playing
|
||||
label. A single external launch handshake owns the session: duplicate actions
|
||||
are ignored, other external actions wait, and an existing live external session
|
||||
must close before a different player can start. The source-owning host binds
|
||||
must close before a different player can start. Play, Restart, and secondary
|
||||
provider launch actions all observe the same local guard before Electron has
|
||||
returned a session. Xtream VOD also records the diagnostic fallback's
|
||||
route-scoped destination and pending generation before invoking MPV/VLC, so a
|
||||
subsequent route cannot start a second detached player while the first launch
|
||||
is being correlated. The source-owning host binds
|
||||
its returned launch promise to the fieldless current intent, so only that exact
|
||||
result supplies the initial session ID; a late result from a timed-out attempt
|
||||
cannot take over a retry. Later global updates must match the exact ID. A
|
||||
replacement does not launch until teardown of the exact spawned process is
|
||||
confirmed, and the old target is settled synchronously before the new launch so
|
||||
coalesced signal effects cannot preserve stale feedback. If diagnostic
|
||||
ownership changes during close, the unlaunched intent is cancelled without a
|
||||
false launch error. If the local handshake timeout fires after Electron has
|
||||
supplied an exact session ID, the ID stays correlated so a later `opened`,
|
||||
`playing`, or `error` update can reconcile the action with the global dock.
|
||||
coalesced signal effects cannot preserve stale feedback. Teardown waits through
|
||||
bounded graceful and forced-exit windows, and reusable MPV also bounds its IPC
|
||||
quit command before entering those windows. If any stage cannot confirm exit,
|
||||
close rejects and keeps the exact session live so a replacement cannot overlap
|
||||
it. A process-wide teardown gate starts before any potentially slow teardown
|
||||
preparation, including VLC position flush and a reused player's MPV IPC or VLC
|
||||
RC quit command, and rejects both player launches until that exact child
|
||||
reports exit; `ChildProcess.killed` is never treated as proof. If
|
||||
bounded teardown fails while a fresh launch IPC is pending, the IPC rejects and
|
||||
the exact session becomes a closable error instead of remaining in Opening.
|
||||
If a pre-content reuse failure has no still-live displaced session to restore,
|
||||
the replacement error keeps its attached closer so Stop can retry teardown of
|
||||
the orphaned reusable child. A terminal error without a closer is never
|
||||
restorable.
|
||||
A rejected close promise is cached only while that attempt is pending, so the
|
||||
dock's Stop action can retry teardown of the same exact child after an
|
||||
unconfirmed bounded attempt. Reusable children are mapped to the current
|
||||
content session; a stale older closer becomes a no-op after MPV `loadfile` or
|
||||
the VLC enqueue handoff remaps the process. Closing an already terminal session
|
||||
is also idempotent: it returns the closed snapshot without invoking the saved
|
||||
closer, and a later process error cannot revive it as a visible failure. Reused
|
||||
MPV commands use the socket captured for their exact child, so a delayed close
|
||||
cannot send `quit` to a replacement process through a newer global socket.
|
||||
If Stop is observed before a pending MPV content command or VLC enqueue command
|
||||
is dispatched, that command is skipped. A source handoff also fails closed
|
||||
while a live session has no closer (`canClose: false`); renderer Dismiss is not
|
||||
accepted as process-teardown confirmation. That denial advances neither the
|
||||
multi-source switch token nor the playback generation, so it cannot cancel the
|
||||
sole launch already in flight.
|
||||
VLC rechecks that gate immediately around every concrete spawn after
|
||||
asynchronous port allocation or reuse fallback work. If a post-start VLC
|
||||
fallback is blocked by the gate, the already-opened session transitions to
|
||||
error instead of continuing to claim that the player started. If RC-port
|
||||
allocation fails, reuse ownership is never claimed: the spawned VLC child
|
||||
keeps its exact one-shot session closer so Stop still confirms its teardown.
|
||||
During reusable-player handoff, a failure before the content command restores
|
||||
the globally displaced renderer session—not the reusable process's prior
|
||||
owner—through an exact `restoredFromSessionId` transition, but only while that
|
||||
displaced replacement is still the active session.
|
||||
After MPV `loadfile` or VLC `clear` has been dispatched, the attempted session
|
||||
owns the possibly changed process and stays a closable error instead of
|
||||
restoring stale content metadata. Such an error still participates in every
|
||||
replacement close. Stop during an in-flight MPV or VLC reuse command, including
|
||||
the teardown wait after a failed command and VLC's subsequent fallback
|
||||
port-allocation wait, settles that exact close and cancels the fallback spawn.
|
||||
If a partially applied reuse
|
||||
command is instead recovered by a fresh spawn, the old child's exit is retired
|
||||
under its previous session so it cannot close the replacement session. A
|
||||
during-start Stop also settles VLC's launch IPC when a spawn error reports
|
||||
`close` without `exit`. The dock keeps Stop as the only global teardown action
|
||||
while that exact closer remains live; safe Dismiss is available only after an
|
||||
error becomes terminal and has no closer. If diagnostic ownership changes during close, the
|
||||
unlaunched intent is cancelled without a false launch error; an exact stale
|
||||
launch whose close fails keeps its credential-free owner for the next close
|
||||
attempt. Route Play/Resume cancels older source resolution immediately but
|
||||
captures the initiating playlist/VOD route before awaiting teardown; navigation
|
||||
cancels that start. Accepting a diagnostic fallback cancels the same older
|
||||
source resolution before opening MPV/VLC, and a fallback resolving on the new
|
||||
route closes its exact returned session. The route commits its source badge and playback
|
||||
evidence only after start succeeds. If the local
|
||||
handshake timeout fires after Electron has supplied an exact session ID, the ID
|
||||
stays correlated so a later `opened`, `playing`, or `error` update can reconcile
|
||||
the action with the global dock.
|
||||
|
||||
The global external-playback dock uses the same Electron session status. It
|
||||
shows Opening player with progress during launch, Player started for `opened`,
|
||||
and Playing only for `playing`. External player errors remain visible until
|
||||
dismissed, whether startup failed or a started player exited unexpectedly;
|
||||
the dock deliberately has no retry because it does not own the original headers
|
||||
or credentials required to reconstruct a safe launch request.
|
||||
and Playing only for `playing`. An error with a live closer remains visible with
|
||||
Stop until teardown is confirmed; an unclosable terminal error remains visible
|
||||
until dismissed. The dock deliberately has no retry because it does not own the
|
||||
original headers or credentials required to reconstruct a safe launch request.
|
||||
|
||||
No recommendation mutates `Settings.player` or another persisted setting.
|
||||
Recovery recommendations never auto-switch a player or source and do not
|
||||
@@ -732,14 +795,18 @@ External MPV/VLC integration is split across focused main-process modules:
|
||||
- `apps/electron-backend/src/app/events/external-player-runtime.ts` owns shared
|
||||
session tracking, trace logging, renderer notifications, playback-position
|
||||
forwarding, and user-facing start errors.
|
||||
- `apps/electron-backend/src/app/events/mpv-session.service.ts` owns MPV process,
|
||||
socket, reuse, cleanup, and progress polling lifecycle.
|
||||
- `apps/electron-backend/src/app/events/vlc-session.service.ts` owns VLC process,
|
||||
RC interface, reuse, cleanup, command parsing, and progress polling lifecycle.
|
||||
- `apps/electron-backend/src/app/events/mpv-session.service.ts` owns fresh MPV
|
||||
launches and progress polling; `mpv-reusable-process.ts` owns the tracked
|
||||
child, captured socket, remapping, retryable close, and reuse handoff.
|
||||
- `apps/electron-backend/src/app/events/vlc-session.service.ts` owns fresh VLC
|
||||
launches and progress polling; `vlc-reusable-process.ts` owns the tracked
|
||||
child, RC-port remapping, retryable close, and reuse handoff, while
|
||||
`vlc-rc.ts` owns bounded RC commands, parsing, and playback snapshots.
|
||||
|
||||
Keep player-specific process state in the MPV/VLC session modules. Shared spawn,
|
||||
request-header, session-registry, and notification helpers belong in the
|
||||
`external-player-*` modules so IPC registration stays small and reviewable.
|
||||
Keep player-specific reusable-process state in the focused MPV/VLC managers.
|
||||
Shared spawn, request-header, session-registry, and notification helpers belong
|
||||
in the `external-player-*` modules so IPC registration stays small and
|
||||
reviewable.
|
||||
|
||||
## Flatpak External Players
|
||||
|
||||
|
||||
@@ -496,8 +496,9 @@ cut. The toast offers Undo, and adds a dub warning when
|
||||
audio track as fact. Two guesses, or a guess against a fact, stay silent.
|
||||
|
||||
Web engines only (HTML5/hls.js, Video.js, ArtPlayer). Embedded MPV suppresses
|
||||
shared diagnostics and owns its own error block; external MPV/VLC are
|
||||
fire-and-forget with no error channel back.
|
||||
shared diagnostics and owns its own error block. External MPV/VLC use managed
|
||||
Electron sessions: recovery actions and the global dock report their exact
|
||||
launch state without retaining playback headers or credentials.
|
||||
|
||||
## External players and an alternative source
|
||||
|
||||
@@ -507,7 +508,43 @@ that session carries the OTHER playlist's ids. `matchedExternalPlayback` would
|
||||
disown it: the primary button never became Stop, stopping found no session, and
|
||||
another click opened a second player. The page therefore claims a session that
|
||||
matches either the route's own stream or the alternative multi-source says is
|
||||
active (`VodDetailsPlaybackBindings.activeSource`).
|
||||
active (`VodDetailsPlaybackBindings.activeSource`). It also claims the
|
||||
credential-free destination identity before awaiting the Electron launch: the
|
||||
primary action becomes pending immediately, and a launching or closable-error
|
||||
session remains matched before the controller can truthfully mark it active.
|
||||
Restart and the provider-source shortcut read the same local pending state, so
|
||||
a second activation cannot enter the Electron launch before the first IPC
|
||||
response exists; their DOM controls stay mounted and disabled to preserve focus.
|
||||
The diagnostic-fallback handler makes that same route-scoped ownership claim
|
||||
before invoking MPV/VLC, rather than relying on the later controller commit. It
|
||||
also supersedes an older source resolution at that acceptance boundary, so the
|
||||
late switch cannot close and replace the newer diagnostic fallback.
|
||||
That retained destination is scoped to the initiating playlist/VOD route key,
|
||||
so Angular route reuse for a different movie cannot turn its Play action into
|
||||
Stop for the previous movie's still-running external session. That new route's
|
||||
Play and Resume actions still pass through the shared close-before-replacement
|
||||
path, and they recheck their captured route key after teardown, so starting it
|
||||
cannot leave the prior detached player running or launch stale content after
|
||||
navigation. A diagnostic fallback that resolves after route reuse closes its
|
||||
exact returned session instead of adopting it on the new route.
|
||||
|
||||
Before an external alternative replaces another external session, teardown of
|
||||
the exact old process must be confirmed. If close fails or times out, the
|
||||
replacement is cancelled instead of allowing two external players to overlap.
|
||||
If the old launch is still opening and has no exact closer yet, a source-row
|
||||
replacement is denied before either the multi-source switch token or playback
|
||||
generation advances; the only in-flight launch therefore remains owned and is
|
||||
not closed as superseded.
|
||||
Once that old session is closed, later duplicate Stop/Close delivery is a
|
||||
terminal no-op and cannot invoke its saved closer against a newly started MPV
|
||||
or VLC process.
|
||||
The controller commits the destination row, previous-source pointer, and switch
|
||||
notice only after the playback seam accepts that handoff and an external
|
||||
Electron launch resolves, so a rejected close or launch leaves the old source
|
||||
as the truthful selection. The host's exact switch-owner probe crosses that
|
||||
seam too: after teardown but before applying playback, the route rechecks it so
|
||||
a newer unresolvable selection cannot leave the older player launched but
|
||||
disowned by the controller.
|
||||
|
||||
`ownsContent()` answers that question once, for both consumers: the session
|
||||
matcher AND the playback-position bridge. They cannot be allowed to disagree —
|
||||
@@ -609,10 +646,22 @@ honest state, and the same one the rest of this feature takes when it does not
|
||||
know.
|
||||
|
||||
Switching sources through `startResolvedPlayback` closes the external session
|
||||
it LAUNCHED first — tracked separately from the controller's active source,
|
||||
which a switch has already moved to the destination by then. It REPLACES what is playing — with MPV or VLC and instance
|
||||
reuse off, the backend would otherwise spawn a second detached player, leaving
|
||||
both sources running and Stop owning only the newer one.
|
||||
it LAUNCHED first — tracked separately so refreshes and overlapping handoffs
|
||||
cannot disown it within the same route session. The retained identity is ignored
|
||||
after the playlist/VOD route key changes. Only after that exact teardown, the
|
||||
host ownership checks on both sides of the launch await, and an `opened` or
|
||||
`playing` launch result does the controller commit the destination. A launch
|
||||
that loses ownership while IPC is pending is closed by its exact returned
|
||||
session; a Stop that wins the race returns `closed` and is never committed. A
|
||||
partial reusable-player handoff that leaves a closable error retains its
|
||||
destination identity so the next source switch closes that exact process before
|
||||
trying again. A stale launch whose exact close fails retains the same
|
||||
credential-free identity for another close attempt. Direct route Play/Resume
|
||||
supersede an older source resolution before waiting for teardown, but update the
|
||||
active-source badge, playback evidence, and controller position only after the
|
||||
new start succeeds. With MPV or VLC and instance reuse off, applying playback
|
||||
earlier would spawn a second detached player, leaving both sources running and
|
||||
Stop owning only the newer one.
|
||||
|
||||
## Short titles and Unicode
|
||||
|
||||
|
||||
+36
-1
@@ -41,6 +41,7 @@ import {
|
||||
import {
|
||||
Channel,
|
||||
EpgProgram,
|
||||
ExternalPlayerSession,
|
||||
ResolvedPortalPlayback,
|
||||
Settings,
|
||||
VideoPlayer,
|
||||
@@ -197,6 +198,7 @@ describe('VideoPlayerComponent', () => {
|
||||
const stripCountryPrefix = signal(false);
|
||||
const epgViewMode = signal<'timeline' | 'list'>('timeline');
|
||||
const epgUrlSetting = signal<string[]>([]);
|
||||
const externalSession = signal<ExternalPlayerSession | null>(null);
|
||||
const originalElectron = window.electron;
|
||||
|
||||
const overlayRef = {
|
||||
@@ -325,6 +327,7 @@ describe('VideoPlayerComponent', () => {
|
||||
channelsLoading.set(false);
|
||||
currentEpgProgram.set(null);
|
||||
activeEpgProgram.set(null);
|
||||
externalSession.set(null);
|
||||
currentEpgProgram$.next(null);
|
||||
epgPrograms$.next([]);
|
||||
overlayMock.create.mockClear();
|
||||
@@ -415,7 +418,7 @@ describe('VideoPlayerComponent', () => {
|
||||
{
|
||||
provide: PORTAL_EXTERNAL_PLAYBACK,
|
||||
useValue: {
|
||||
activeSession: signal(null),
|
||||
activeSession: externalSession,
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -646,6 +649,38 @@ describe('VideoPlayerComponent', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('clears the channel when a closable error becomes terminal', () => {
|
||||
syncStoreState(sampleChannel);
|
||||
player.set(VideoPlayer.MPV);
|
||||
const closableError: ExternalPlayerSession = {
|
||||
id: 'external-1',
|
||||
player: 'mpv',
|
||||
status: 'error',
|
||||
title: sampleChannel.name,
|
||||
streamUrl: sampleChannel.url,
|
||||
startedAt: '2026-08-08T00:00:00.000Z',
|
||||
updatedAt: '2026-08-08T00:00:00.000Z',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
};
|
||||
externalSession.set(closableError);
|
||||
fixture.detectChanges();
|
||||
expect(storeMock.dispatch).not.toHaveBeenCalledWith(
|
||||
ChannelActions.resetActiveChannel()
|
||||
);
|
||||
|
||||
externalSession.set({
|
||||
...closableError,
|
||||
canClose: false,
|
||||
updatedAt: '2026-08-08T00:00:01.000Z',
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(storeMock.dispatch).toHaveBeenCalledWith(
|
||||
ChannelActions.resetActiveChannel()
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps DASH channels inline on the HTML5 player even when MPV is configured', () => {
|
||||
syncStoreState({
|
||||
...sampleChannel,
|
||||
|
||||
@@ -80,6 +80,7 @@ import {
|
||||
persistLiveEpgPanelState,
|
||||
persistLiveSidebarState,
|
||||
PORTAL_EXTERNAL_PLAYBACK,
|
||||
isLiveExternalPlayerSession,
|
||||
restoreLiveEpgPanelState,
|
||||
restoreLiveSidebarState,
|
||||
WorkspaceHeaderContextService,
|
||||
@@ -1114,7 +1115,10 @@ export class VideoPlayerComponent implements OnInit, OnDestroy {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `${session.id}:${session.status}`;
|
||||
const lifecycle = isLiveExternalPlayerSession(session)
|
||||
? 'live'
|
||||
: 'terminal';
|
||||
return `${session.id}:${session.status}:${lifecycle}`;
|
||||
}
|
||||
|
||||
private isExternalPlayer(
|
||||
@@ -1126,7 +1130,7 @@ export class VideoPlayerComponent implements OnInit, OnDestroy {
|
||||
private isTerminalExternalSession(
|
||||
session: ExternalPlayerSession | null | undefined
|
||||
): boolean {
|
||||
return session?.status === 'closed' || session?.status === 'error';
|
||||
return !!session && !isLiveExternalPlayerSession(session);
|
||||
}
|
||||
|
||||
private registerHeaderShortcut(): void {
|
||||
|
||||
@@ -3,7 +3,10 @@ import type {
|
||||
ExternalPlayerSession,
|
||||
PlayerContentInfo,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { createExternalPlaybackButtonState } from './external-playback-button-state';
|
||||
import {
|
||||
createExternalPlaybackButtonState,
|
||||
isLiveExternalPlayerSession,
|
||||
} from './external-playback-button-state';
|
||||
|
||||
function session(
|
||||
overrides: Partial<ExternalPlayerSession> = {}
|
||||
@@ -105,6 +108,21 @@ describe('createExternalPlaybackButtonState', () => {
|
||||
}
|
||||
);
|
||||
|
||||
it('offers Stop for an errored session whose process may still be alive', () => {
|
||||
const { api } = setup(
|
||||
session({
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
})
|
||||
);
|
||||
|
||||
expect(api.matchedSession()).not.toBeNull();
|
||||
expect(api.buttonState()).toBe('stop');
|
||||
expect(api.primaryLabel()).toBe('Stop MPV');
|
||||
expect(api.isStopAction()).toBe(true);
|
||||
});
|
||||
|
||||
it('reports a launching session', () => {
|
||||
const { api } = setup(session({ status: 'launching' }));
|
||||
|
||||
@@ -208,3 +226,30 @@ describe('createExternalPlaybackButtonState', () => {
|
||||
expect(api.matchedSession()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLiveExternalPlayerSession', () => {
|
||||
it('keeps ownership while a teardown error can still be stopped', () => {
|
||||
expect(
|
||||
isLiveExternalPlayerSession(
|
||||
session({
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
})
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('treats an unclosable error and a confirmed close as terminal', () => {
|
||||
expect(
|
||||
isLiveExternalPlayerSession(
|
||||
session({ status: 'error', canClose: false })
|
||||
)
|
||||
).toBe(false);
|
||||
expect(
|
||||
isLiveExternalPlayerSession(
|
||||
session({ status: 'closed', canClose: false })
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,21 @@ export interface ExternalPlaybackButtonStateApi {
|
||||
buttonState: Signal<ExternalPlaybackButtonState>;
|
||||
}
|
||||
|
||||
/**
|
||||
* An error can still own a real process when bounded teardown could not
|
||||
* confirm its exit. Keep that session live until Stop succeeds; only a
|
||||
* confirmed close or an unclosable failure is terminal.
|
||||
*/
|
||||
export function isLiveExternalPlayerSession(
|
||||
session: ExternalPlayerSession | null | undefined
|
||||
): session is ExternalPlayerSession {
|
||||
return (
|
||||
!!session &&
|
||||
session.status !== 'closed' &&
|
||||
(session.status !== 'error' || session.canClose)
|
||||
);
|
||||
}
|
||||
|
||||
export function createExternalPlaybackButtonState(
|
||||
config: ExternalPlaybackButtonStateConfig
|
||||
): ExternalPlaybackButtonStateApi {
|
||||
@@ -56,11 +71,7 @@ export function createExternalPlaybackButtonState(
|
||||
const matchedSession = computed(() => {
|
||||
const session = config.session();
|
||||
// A closed or errored session says nothing about what is playing now.
|
||||
if (
|
||||
!session?.contentInfo ||
|
||||
session.status === 'closed' ||
|
||||
session.status === 'error'
|
||||
) {
|
||||
if (!session?.contentInfo || !isLiveExternalPlayerSession(session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -92,6 +103,7 @@ export function createExternalPlaybackButtonState(
|
||||
return `Opening in ${player}...`;
|
||||
case 'opened':
|
||||
case 'playing':
|
||||
case 'error':
|
||||
return `Stop ${player}`;
|
||||
default:
|
||||
return null;
|
||||
@@ -104,6 +116,7 @@ export function createExternalPlaybackButtonState(
|
||||
return 'hourglass_top';
|
||||
case 'opened':
|
||||
case 'playing':
|
||||
case 'error':
|
||||
return 'stop_circle';
|
||||
default:
|
||||
return 'play_arrow';
|
||||
@@ -116,7 +129,9 @@ export function createExternalPlaybackButtonState(
|
||||
|
||||
const isStopAction = computed(() => {
|
||||
const status = matchedSession()?.status;
|
||||
return status === 'opened' || status === 'playing';
|
||||
return (
|
||||
status === 'opened' || status === 'playing' || status === 'error'
|
||||
);
|
||||
});
|
||||
|
||||
const buttonState = computed<ExternalPlaybackButtonState>(() => {
|
||||
|
||||
+2
-1
@@ -33,6 +33,7 @@ import {
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { SafePipe } from '@iptvnator/pipes';
|
||||
import {
|
||||
isLiveExternalPlayerSession,
|
||||
PORTAL_EXTERNAL_PLAYBACK,
|
||||
PORTAL_PLAYBACK_POSITIONS,
|
||||
PORTAL_PLAYER,
|
||||
@@ -438,7 +439,7 @@ export class StalkerSeriesViewComponent implements OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.status === 'opened' || session.status === 'playing') {
|
||||
if (isLiveExternalPlayerSession(session)) {
|
||||
this.openingEpisodeId.set(null);
|
||||
this.activeEpisodeId.set(session.contentInfo.contentXtreamId);
|
||||
return;
|
||||
|
||||
+2
-1
@@ -10,6 +10,7 @@ import {
|
||||
} from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import {
|
||||
isLiveExternalPlayerSession,
|
||||
PORTAL_EXTERNAL_PLAYBACK,
|
||||
PORTAL_PLAYBACK_POSITIONS,
|
||||
PORTAL_PLAYER,
|
||||
@@ -125,7 +126,7 @@ export class SerialDetailsPlaybackService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.status === 'opened' || session.status === 'playing') {
|
||||
if (isLiveExternalPlayerSession(session)) {
|
||||
this.openingEpisodeId.set(null);
|
||||
this.activeEpisodeId.set(session.contentInfo.contentXtreamId);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Signal, computed, signal } from '@angular/core';
|
||||
import type { PlayerContentInfo } from '@iptvnator/shared/interfaces';
|
||||
|
||||
interface RouteScopedExternalLaunch {
|
||||
readonly routePlaylistId: string;
|
||||
readonly routeContentId: number;
|
||||
readonly content: PlayerContentInfo;
|
||||
}
|
||||
|
||||
export interface ExternalLaunchRouteIdentity {
|
||||
readonly playlistId: string;
|
||||
readonly contentId: number;
|
||||
}
|
||||
|
||||
export interface ExternalLaunchOwner {
|
||||
readonly current: Signal<PlayerContentInfo | null>;
|
||||
/** Exact last destination retained for close-before-replacement. */
|
||||
readonly retained: Signal<PlayerContentInfo | null>;
|
||||
captureRoute(): ExternalLaunchRouteIdentity | null;
|
||||
ownsRoute(identity: ExternalLaunchRouteIdentity | null): boolean;
|
||||
set(content: PlayerContentInfo | null | undefined): void;
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
/** Retains an external destination only while its initiating VOD route owns it. */
|
||||
export function createExternalLaunchOwner(
|
||||
routePlaylistId: () => string | undefined,
|
||||
routeContentId: () => number | undefined
|
||||
): ExternalLaunchOwner {
|
||||
const launch = signal<RouteScopedExternalLaunch | null>(null);
|
||||
const captureRoute = (): ExternalLaunchRouteIdentity | null => {
|
||||
const playlistId = routePlaylistId();
|
||||
const contentId = routeContentId();
|
||||
return playlistId &&
|
||||
contentId !== undefined &&
|
||||
Number.isSafeInteger(contentId) &&
|
||||
contentId > 0
|
||||
? { playlistId, contentId }
|
||||
: null;
|
||||
};
|
||||
return {
|
||||
current: computed(() => {
|
||||
const value = launch();
|
||||
return value &&
|
||||
value.routePlaylistId === routePlaylistId() &&
|
||||
value.routeContentId === routeContentId()
|
||||
? value.content
|
||||
: null;
|
||||
}),
|
||||
retained: computed(() => launch()?.content ?? null),
|
||||
captureRoute,
|
||||
ownsRoute: (identity) => {
|
||||
const current = captureRoute();
|
||||
return (
|
||||
!!identity &&
|
||||
current?.playlistId === identity.playlistId &&
|
||||
current.contentId === identity.contentId
|
||||
);
|
||||
},
|
||||
set: (content) => {
|
||||
const route = captureRoute();
|
||||
launch.set(
|
||||
content && route
|
||||
? {
|
||||
routePlaylistId: route.playlistId,
|
||||
routeContentId: route.contentId,
|
||||
content,
|
||||
}
|
||||
: null
|
||||
);
|
||||
},
|
||||
clear: () => launch.set(null),
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs a Play/Resume only while its initiating VOD route still owns it. */
|
||||
export async function startRouteOwnedPlayback(
|
||||
owner: ExternalLaunchOwner,
|
||||
start: (isCurrent: () => boolean) => Promise<boolean>
|
||||
): Promise<boolean> {
|
||||
const route = owner.captureRoute();
|
||||
if (!route) return false;
|
||||
try {
|
||||
return await start(() => owner.ownsRoute(route));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ExternalPlayerSession } from '@iptvnator/shared/interfaces';
|
||||
|
||||
interface OwnedExternalLaunchOptions {
|
||||
launch: Promise<ExternalPlayerSession | void>;
|
||||
owns: () => boolean;
|
||||
close: (session: ExternalPlayerSession) => Promise<void>;
|
||||
warnCloseFailure: (error: unknown) => void;
|
||||
clearPending: () => void;
|
||||
clearOwnership: () => void;
|
||||
}
|
||||
|
||||
/** Settles an exact MPV/VLC launch without letting stale results take ownership. */
|
||||
export async function settleOwnedExternalLaunch(
|
||||
options: OwnedExternalLaunchOptions
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const launched = await options.launch;
|
||||
const accepted =
|
||||
launched?.status === 'opened' || launched?.status === 'playing';
|
||||
|
||||
if (accepted && options.owns()) {
|
||||
options.clearPending();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isClosableExternalLaunch(launched)) {
|
||||
try {
|
||||
await options.close(launched);
|
||||
} catch (error) {
|
||||
options.warnCloseFailure(error);
|
||||
// The exact child is still potentially live. Keep the
|
||||
// credential-free destination owner so the next source start
|
||||
// can retry its close instead of depending on the global dock.
|
||||
options.clearPending();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
options.clearPending();
|
||||
options.clearOwnership();
|
||||
return false;
|
||||
} catch {
|
||||
// A partial reuse can reject while Electron retains a matching
|
||||
// closable error session. Keep its credential-free identity so the
|
||||
// next source start can still find and close that exact process.
|
||||
options.clearPending();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isClosableExternalLaunch(
|
||||
session: ExternalPlayerSession | void
|
||||
): session is ExternalPlayerSession {
|
||||
return (
|
||||
!!session &&
|
||||
(session.status === 'launching' ||
|
||||
session.status === 'opened' ||
|
||||
session.status === 'playing' ||
|
||||
(session.status === 'error' && session.canClose))
|
||||
);
|
||||
}
|
||||
+340
-26
@@ -7,10 +7,7 @@ import {
|
||||
} from '@iptvnator/portal/shared/util';
|
||||
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
|
||||
import { PlaybackPositionRuntimeBridgeService } from '@iptvnator/services';
|
||||
import type {
|
||||
PlaybackPositionData,
|
||||
PlayerContentInfo,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import type { PlayerContentInfo } from '@iptvnator/shared/interfaces';
|
||||
import { VodDetailsPlaybackService } from './vod-details-playback.service';
|
||||
|
||||
/**
|
||||
@@ -30,18 +27,24 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
const ROUTE_VOD_ID = 650020;
|
||||
|
||||
let service: VodDetailsPlaybackService;
|
||||
/** The bridge callback the service registers at construction. */
|
||||
let positionListener: ((data: PlaybackPositionData) => void) | undefined;
|
||||
const addRecentItem = jest.fn();
|
||||
const activeSession = signal<unknown>(null);
|
||||
const closeSession = jest.fn().mockResolvedValue(undefined);
|
||||
const openResolvedPlayback = jest.fn();
|
||||
const activeSource = signal<PlayerContentInfo | null>(null);
|
||||
const currentPlaylist = signal({ id: ROUTE_PLAYLIST });
|
||||
const routeVodId = signal(ROUTE_VOD_ID);
|
||||
|
||||
function sessionFor(playlistId: string, contentXtreamId: number) {
|
||||
return {
|
||||
id: `${playlistId}:${contentXtreamId}`,
|
||||
player: 'mpv',
|
||||
status: 'playing',
|
||||
title: 'Example Movie',
|
||||
streamUrl: 'https://example.com/movie.mkv',
|
||||
startedAt: '2026-08-08T00:00:00.000Z',
|
||||
updatedAt: '2026-08-08T00:00:00.000Z',
|
||||
canClose: true,
|
||||
contentInfo: {
|
||||
playlistId,
|
||||
contentXtreamId,
|
||||
@@ -53,8 +56,13 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
beforeEach(() => {
|
||||
activeSession.set(null);
|
||||
activeSource.set(null);
|
||||
positionListener = undefined;
|
||||
currentPlaylist.set({ id: ROUTE_PLAYLIST });
|
||||
routeVodId.set(ROUTE_VOD_ID);
|
||||
addRecentItem.mockClear();
|
||||
closeSession.mockReset().mockResolvedValue(undefined);
|
||||
openResolvedPlayback
|
||||
.mockReset()
|
||||
.mockResolvedValue(sessionFor('playlist-2', 991));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
@@ -62,7 +70,7 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
{
|
||||
provide: XtreamStore,
|
||||
useValue: {
|
||||
currentPlaylist: signal({ id: ROUTE_PLAYLIST }),
|
||||
currentPlaylist,
|
||||
addRecentItem,
|
||||
constructVodStreamUrl: jest
|
||||
.fn()
|
||||
@@ -90,12 +98,7 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
{
|
||||
provide: PlaybackPositionRuntimeBridgeService,
|
||||
useValue: {
|
||||
onPlaybackPositionUpdate: (
|
||||
listener: (data: PlaybackPositionData) => void
|
||||
) => {
|
||||
positionListener = listener;
|
||||
return () => undefined;
|
||||
},
|
||||
onPlaybackPositionUpdate: () => () => undefined,
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -103,17 +106,15 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
|
||||
service = TestBed.inject(VodDetailsPlaybackService);
|
||||
service.bind({
|
||||
vodId: signal(ROUTE_VOD_ID),
|
||||
vodId: routeVodId,
|
||||
vodInfo: signal(null),
|
||||
activeSource,
|
||||
});
|
||||
});
|
||||
|
||||
it('closes the alternative it launched, once the badge has moved on', async () => {
|
||||
// The controller marks the DESTINATION active before playback is
|
||||
// handed over, so by the time the switch reaches the service the
|
||||
// running process no longer looks like "ours" — and was left playing
|
||||
// beside its replacement.
|
||||
// Ownership survives controller refreshes or overlapping UI state:
|
||||
// the exact process this page launched still has to close first.
|
||||
activeSession.set(sessionFor('playlist-2', 991));
|
||||
activeSource.set({
|
||||
playlistId: 'playlist-3',
|
||||
@@ -153,22 +154,79 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('still starts the replacement when closing the old player fails', async () => {
|
||||
it('cancels the replacement when closing the old player fails', async () => {
|
||||
activeSession.set(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
closeSession.mockRejectedValue(new Error('close ipc failed'));
|
||||
openResolvedPlayback.mockClear();
|
||||
|
||||
await expect(
|
||||
service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
})
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(openResolvedPlayback).not.toHaveBeenCalled();
|
||||
|
||||
closeSession.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('cancels the replacement while a live session cannot be closed', async () => {
|
||||
activeSession.set({
|
||||
...sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID),
|
||||
status: 'launching',
|
||||
canClose: false,
|
||||
});
|
||||
openResolvedPlayback.mockClear();
|
||||
|
||||
await expect(
|
||||
service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
})
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(closeSession).not.toHaveBeenCalled();
|
||||
expect(openResolvedPlayback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a handoff when the external player launch fails', async () => {
|
||||
openResolvedPlayback.mockRejectedValueOnce(
|
||||
new Error('previous player is still shutting down')
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-2',
|
||||
contentXtreamId: 991,
|
||||
contentType: 'vod',
|
||||
},
|
||||
})
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(openResolvedPlayback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes a closable error before starting a replacement source', async () => {
|
||||
activeSession.set({
|
||||
...sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID),
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
});
|
||||
closeSession.mockClear();
|
||||
|
||||
await service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
});
|
||||
|
||||
// The switch is already committed — the badge names the new source.
|
||||
// Bailing out here left the page claiming a source with nothing
|
||||
// started at all.
|
||||
expect(openResolvedPlayback).toHaveBeenCalledTimes(1);
|
||||
|
||||
closeSession.mockResolvedValue(undefined);
|
||||
expect(closeSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'error', canClose: true })
|
||||
);
|
||||
});
|
||||
|
||||
it('launches only the newest source when two switches overlap', async () => {
|
||||
@@ -209,6 +267,232 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
closeSession.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('checks host ownership after teardown before applying playback', async () => {
|
||||
activeSession.set(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
let releaseClose: (() => void) | undefined;
|
||||
const closing = new Promise<void>((resolve) => {
|
||||
releaseClose = resolve;
|
||||
});
|
||||
closeSession.mockReturnValue(closing);
|
||||
openResolvedPlayback.mockClear();
|
||||
let ownsSwitch = true;
|
||||
|
||||
const switching = service.startResolvedPlayback(
|
||||
{
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
},
|
||||
() => ownsSwitch
|
||||
);
|
||||
ownsSwitch = false;
|
||||
releaseClose?.();
|
||||
|
||||
await expect(switching).resolves.toBe(false);
|
||||
expect(openResolvedPlayback).not.toHaveBeenCalled();
|
||||
|
||||
closeSession.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('closes a launch that loses host ownership while IPC is pending', async () => {
|
||||
let releaseLaunch: ((value: unknown) => void) | undefined;
|
||||
const launched = sessionFor('playlist-2', 991);
|
||||
openResolvedPlayback.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
releaseLaunch = resolve;
|
||||
})
|
||||
);
|
||||
let ownsSwitch = true;
|
||||
|
||||
const switching = service.startResolvedPlayback(
|
||||
{
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
},
|
||||
() => ownsSwitch
|
||||
);
|
||||
while (openResolvedPlayback.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
ownsSwitch = false;
|
||||
releaseLaunch?.(launched);
|
||||
|
||||
await expect(switching).resolves.toBe(false);
|
||||
expect(closeSession).toHaveBeenCalledWith(launched);
|
||||
});
|
||||
|
||||
it('retains a stale launch when its exact close fails', async () => {
|
||||
let releaseLaunch: ((value: unknown) => void) | undefined;
|
||||
const launched = sessionFor('playlist-2', 991);
|
||||
const failed = {
|
||||
...launched,
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
};
|
||||
openResolvedPlayback.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
releaseLaunch = resolve;
|
||||
})
|
||||
);
|
||||
closeSession.mockRejectedValueOnce(new Error('close ipc failed'));
|
||||
let ownsSwitch = true;
|
||||
|
||||
const switching = service.startResolvedPlayback(
|
||||
{
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
},
|
||||
() => ownsSwitch
|
||||
);
|
||||
while (openResolvedPlayback.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
ownsSwitch = false;
|
||||
activeSession.set(failed);
|
||||
releaseLaunch?.(launched);
|
||||
|
||||
await expect(switching).resolves.toBe(false);
|
||||
expect(service.matchedExternalPlayback()?.id).toBe(failed.id);
|
||||
|
||||
await service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/third.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-3',
|
||||
contentXtreamId: 992,
|
||||
contentType: 'vod',
|
||||
},
|
||||
});
|
||||
expect(closeSession).toHaveBeenLastCalledWith(failed);
|
||||
});
|
||||
|
||||
it('does not commit a session stopped while launch IPC is pending', async () => {
|
||||
openResolvedPlayback.mockResolvedValueOnce({
|
||||
...sessionFor('playlist-2', 991),
|
||||
status: 'closed',
|
||||
canClose: false,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
})
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('owns an alternative immediately while its external launch is pending', async () => {
|
||||
let releaseLaunch: ((value: unknown) => void) | undefined;
|
||||
const launching = {
|
||||
...sessionFor('playlist-2', 991),
|
||||
status: 'launching',
|
||||
};
|
||||
openResolvedPlayback.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
releaseLaunch = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
const switching = service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: launching.contentInfo,
|
||||
});
|
||||
while (openResolvedPlayback.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
expect(service.isExternalLaunchPending()).toBe(true);
|
||||
activeSession.set(launching);
|
||||
expect(service.matchedExternalPlayback()?.id).toBe(launching.id);
|
||||
|
||||
const opened = { ...launching, status: 'opened' };
|
||||
activeSession.set(opened);
|
||||
releaseLaunch?.(opened);
|
||||
await expect(switching).resolves.toBe(true);
|
||||
expect(service.isExternalLaunchPending()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the pending launch when an unclosable source replacement is denied', async () => {
|
||||
let releaseLaunch: ((value: unknown) => void) | undefined;
|
||||
const launching = {
|
||||
...sessionFor('playlist-2', 991),
|
||||
status: 'launching',
|
||||
canClose: false,
|
||||
};
|
||||
openResolvedPlayback.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
releaseLaunch = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
const first = service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/first.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: launching.contentInfo,
|
||||
});
|
||||
while (openResolvedPlayback.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
activeSession.set(launching);
|
||||
|
||||
await expect(
|
||||
service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/second.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-3',
|
||||
contentXtreamId: 77,
|
||||
contentType: 'vod',
|
||||
},
|
||||
})
|
||||
).resolves.toBe(false);
|
||||
|
||||
const opened = { ...launching, status: 'opened' };
|
||||
activeSession.set(opened);
|
||||
releaseLaunch?.(opened);
|
||||
|
||||
await expect(first).resolves.toBe(true);
|
||||
expect(openResolvedPlayback).toHaveBeenCalledTimes(1);
|
||||
expect(closeSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retains a closable failed alternative for the next exact close', async () => {
|
||||
const failed = {
|
||||
...sessionFor('playlist-2', 991),
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
};
|
||||
openResolvedPlayback.mockImplementationOnce(async () => {
|
||||
activeSession.set(failed);
|
||||
throw new Error('External player process did not exit');
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/alt.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: failed.contentInfo,
|
||||
})
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(service.matchedExternalPlayback()?.id).toBe(failed.id);
|
||||
|
||||
await service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/third.mkv',
|
||||
title: 'Example Movie',
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-3',
|
||||
contentXtreamId: 992,
|
||||
contentType: 'vod',
|
||||
},
|
||||
});
|
||||
expect(closeSession).toHaveBeenCalledWith(failed);
|
||||
});
|
||||
|
||||
it('drops a switch that a plain Play overtook', async () => {
|
||||
activeSession.set(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
let releaseClose: (() => void) | undefined;
|
||||
@@ -246,6 +530,36 @@ describe('VodDetailsPlaybackService — external playback handoff', () => {
|
||||
closeSession.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('drops a plain Play when its initiating route changes during close', async () => {
|
||||
activeSession.set(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
let releaseClose: (() => void) | undefined;
|
||||
closeSession.mockReturnValue(
|
||||
new Promise<void>((resolve) => {
|
||||
releaseClose = resolve;
|
||||
})
|
||||
);
|
||||
openResolvedPlayback.mockClear();
|
||||
addRecentItem.mockClear();
|
||||
|
||||
const playing = service.playVod({
|
||||
movie_data: {
|
||||
stream_id: ROUTE_VOD_ID,
|
||||
name: 'First movie',
|
||||
container_extension: 'mkv',
|
||||
},
|
||||
} as never);
|
||||
while (closeSession.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
routeVodId.set(ROUTE_VOD_ID + 1);
|
||||
releaseClose?.();
|
||||
|
||||
await expect(playing).resolves.toBe(false);
|
||||
expect(openResolvedPlayback).not.toHaveBeenCalled();
|
||||
expect(addRecentItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops the running external player before switching sources', async () => {
|
||||
activeSession.set(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
|
||||
|
||||
@@ -2,14 +2,15 @@ import type {
|
||||
ExternalPlayerSession,
|
||||
PlayerContentInfo,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { isLiveExternalPlayerSession } from '@iptvnator/portal/shared/util';
|
||||
|
||||
/**
|
||||
* Which external player process, and which position rows, belong to this page.
|
||||
*
|
||||
* Multi-source makes both questions harder than they look: playback can be on
|
||||
* a copy of the film in ANOTHER playlist, whose ids the session and the
|
||||
* position rows then carry, and during a switch the controller has already
|
||||
* moved "active" to the destination before playback is handed over.
|
||||
* position rows then carry. A source handoff also waits for exact process
|
||||
* teardown before the destination can become active.
|
||||
*/
|
||||
|
||||
/** Ids this page owns, beyond the route's own copy. */
|
||||
@@ -53,10 +54,9 @@ export function ownsContent(
|
||||
/**
|
||||
* The external process this page started, if it is still up.
|
||||
*
|
||||
* Matched on the ids we LAUNCHED with rather than on what is active now: a
|
||||
* switch marks the destination active before handing playback over, so asking
|
||||
* "is this session ours?" at that moment answers no and leaves the running
|
||||
* process playing beside its replacement.
|
||||
* Matched on the ids we LAUNCHED with rather than only on what is active now:
|
||||
* refreshes and overlapping handoffs may update controller state while exact
|
||||
* process teardown is still in flight.
|
||||
*/
|
||||
export function runningExternalSession(
|
||||
session: ExternalPlayerSession | null,
|
||||
@@ -66,7 +66,7 @@ export function runningExternalSession(
|
||||
if (
|
||||
!session?.contentInfo ||
|
||||
session.status === 'closed' ||
|
||||
session.status === 'error'
|
||||
(session.status === 'error' && !session.canClose)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -83,26 +83,29 @@ export function runningExternalSession(
|
||||
/**
|
||||
* Close the running external player before its replacement starts.
|
||||
*
|
||||
* A failure is logged rather than propagated: the caller has already
|
||||
* committed the switch, so refusing to launch would leave the page naming a
|
||||
* source with nothing playing — worse than a possibly-lingering process, and
|
||||
* a close that rejects usually means the session was gone already.
|
||||
* A failed close leaves teardown unconfirmed. Report false so the caller can
|
||||
* cancel the replacement instead of starting a second external process.
|
||||
*/
|
||||
export async function closeRunningExternalSession(
|
||||
session: ExternalPlayerSession | null,
|
||||
close: (session: ExternalPlayerSession) => Promise<void>,
|
||||
warn: (message: string, error: unknown) => void
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
if (!session) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
if (isLiveExternalPlayerSession(session) && !session.canClose) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await close(session);
|
||||
return true;
|
||||
} catch (error) {
|
||||
warn(
|
||||
'Closing the previous external player failed; starting the replacement anyway.',
|
||||
'Closing the previous external player failed; cancelling the replacement.',
|
||||
error
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ describe('VodDetailsPlaybackService — external session ownership', () => {
|
||||
const activeSession = signal<unknown>(null);
|
||||
const closeSession = jest.fn().mockResolvedValue(undefined);
|
||||
const openResolvedPlayback = jest.fn();
|
||||
const openExternalPlayback = jest.fn();
|
||||
const supersedePendingSwitch = jest.fn();
|
||||
const activeSource = signal<PlayerContentInfo | null>(null);
|
||||
const currentPlaylist = signal({ id: ROUTE_PLAYLIST });
|
||||
const routeVodId = signal(ROUTE_VOD_ID);
|
||||
@@ -63,6 +65,7 @@ describe('VodDetailsPlaybackService — external session ownership', () => {
|
||||
return {
|
||||
player: 'mpv',
|
||||
status: 'playing',
|
||||
canClose: true,
|
||||
contentInfo: {
|
||||
playlistId,
|
||||
contentXtreamId,
|
||||
@@ -78,6 +81,14 @@ describe('VodDetailsPlaybackService — external session ownership', () => {
|
||||
routeVodId.set(ROUTE_VOD_ID);
|
||||
positionListener = undefined;
|
||||
addRecentItem.mockClear();
|
||||
closeSession.mockReset().mockResolvedValue(undefined);
|
||||
openResolvedPlayback
|
||||
.mockReset()
|
||||
.mockResolvedValue(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
openExternalPlayback
|
||||
.mockReset()
|
||||
.mockResolvedValue(sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID));
|
||||
supersedePendingSwitch.mockClear();
|
||||
getPlaybackPosition.mockReset();
|
||||
getPlaybackPosition.mockResolvedValue(null);
|
||||
|
||||
@@ -110,6 +121,7 @@ describe('VodDetailsPlaybackService — external session ownership', () => {
|
||||
useValue: {
|
||||
isEmbeddedPlayer: jest.fn().mockReturnValue(false),
|
||||
openResolvedPlayback,
|
||||
openExternalPlayback,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -131,6 +143,7 @@ describe('VodDetailsPlaybackService — external session ownership', () => {
|
||||
vodId: routeVodId,
|
||||
vodInfo: signal(null),
|
||||
activeSource,
|
||||
supersedePendingSwitch,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -176,6 +189,142 @@ describe('VodDetailsPlaybackService — external session ownership', () => {
|
||||
expect(service.matchedExternalPlayback()).toBeNull();
|
||||
});
|
||||
|
||||
it('disowns its previous external launch when the routed movie changes', async () => {
|
||||
const launched = sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID);
|
||||
await service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/route.mkv',
|
||||
title: 'First movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
});
|
||||
activeSession.set(launched);
|
||||
|
||||
routeVodId.set(ROUTE_VOD_ID + 1);
|
||||
|
||||
expect(service.matchedExternalPlayback()).toBeNull();
|
||||
expect(service.isExternalStopAction()).toBe(false);
|
||||
});
|
||||
|
||||
it('closes the previous route launch before playing the new movie', async () => {
|
||||
const launched = sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID);
|
||||
await service.startResolvedPlayback({
|
||||
streamUrl: 'https://example.com/first.mkv',
|
||||
title: 'First movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
});
|
||||
activeSession.set(launched);
|
||||
routeVodId.set(ROUTE_VOD_ID + 1);
|
||||
closeSession.mockClear();
|
||||
openResolvedPlayback.mockClear();
|
||||
|
||||
service.playVod({
|
||||
movie_data: {
|
||||
stream_id: ROUTE_VOD_ID + 1,
|
||||
name: 'Second movie',
|
||||
container_extension: 'mkv',
|
||||
},
|
||||
} as never);
|
||||
for (let attempt = 0; attempt < 10; attempt += 1) {
|
||||
if (openResolvedPlayback.mock.calls.length > 0) break;
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
expect(closeSession).toHaveBeenCalledWith(launched);
|
||||
expect(closeSession.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
openResolvedPlayback.mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it('closes a diagnostic fallback before playing the next routed movie', async () => {
|
||||
const launched = sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID);
|
||||
const launch = Promise.resolve(launched);
|
||||
const trackLaunch = jest.fn();
|
||||
openExternalPlayback.mockImplementationOnce(() => {
|
||||
activeSession.set(launched);
|
||||
expect(service.isExternalLaunchPending()).toBe(true);
|
||||
expect(service.matchedExternalPlayback()).toBe(launched);
|
||||
return launch;
|
||||
});
|
||||
|
||||
service.handleExternalFallbackRequest({
|
||||
player: 'mpv',
|
||||
playback: {
|
||||
streamUrl: 'https://example.com/first.mkv',
|
||||
title: 'First movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
},
|
||||
diagnostic: {},
|
||||
trackLaunch,
|
||||
} as never);
|
||||
expect(trackLaunch).toHaveBeenCalledWith(launch);
|
||||
await launch;
|
||||
await Promise.resolve();
|
||||
|
||||
routeVodId.set(ROUTE_VOD_ID + 1);
|
||||
closeSession.mockClear();
|
||||
openResolvedPlayback.mockClear();
|
||||
service.playVod({
|
||||
movie_data: {
|
||||
stream_id: ROUTE_VOD_ID + 1,
|
||||
name: 'Second movie',
|
||||
container_extension: 'mkv',
|
||||
},
|
||||
} as never);
|
||||
for (let attempt = 0; attempt < 10; attempt += 1) {
|
||||
if (openResolvedPlayback.mock.calls.length > 0) break;
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
expect(closeSession).toHaveBeenCalledWith(launched);
|
||||
expect(closeSession.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
openResolvedPlayback.mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it('supersedes a pending source switch before starting a diagnostic fallback', () => {
|
||||
const launched = sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID);
|
||||
|
||||
service.handleExternalFallbackRequest({
|
||||
player: 'mpv',
|
||||
playback: {
|
||||
streamUrl: 'https://example.com/first.mkv',
|
||||
title: 'First movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
},
|
||||
diagnostic: {},
|
||||
trackLaunch: jest.fn(),
|
||||
} as never);
|
||||
|
||||
expect(supersedePendingSwitch).toHaveBeenCalledTimes(1);
|
||||
expect(supersedePendingSwitch.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
openExternalPlayback.mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it('closes a diagnostic fallback that resolves after its route changed', async () => {
|
||||
const launched = sessionFor(ROUTE_PLAYLIST, ROUTE_VOD_ID);
|
||||
const pending = deferred<typeof launched>();
|
||||
const trackLaunch = jest.fn();
|
||||
openExternalPlayback.mockReturnValueOnce(pending.promise);
|
||||
|
||||
service.handleExternalFallbackRequest({
|
||||
player: 'mpv',
|
||||
playback: {
|
||||
streamUrl: 'https://example.com/first.mkv',
|
||||
title: 'First movie',
|
||||
contentInfo: launched.contentInfo,
|
||||
},
|
||||
diagnostic: {},
|
||||
trackLaunch,
|
||||
} as never);
|
||||
routeVodId.set(ROUTE_VOD_ID + 1);
|
||||
pending.resolve(launched);
|
||||
await pending.promise;
|
||||
await Promise.resolve();
|
||||
|
||||
expect(trackLaunch).toHaveBeenCalledWith(pending.promise);
|
||||
expect(closeSession).toHaveBeenCalledWith(launched);
|
||||
});
|
||||
|
||||
it('records a source started through multi-source as recently viewed', async () => {
|
||||
// Playing an alternative from the picker, or letting a pin decide the
|
||||
// primary Play, is still watching the movie — it belongs in Recently
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from '@iptvnator/portal/xtream/data-access';
|
||||
import { PlaybackPositionRuntimeBridgeService } from '@iptvnator/services';
|
||||
import {
|
||||
ExternalPlayerSession,
|
||||
PlaybackPositionData,
|
||||
PlayerContentInfo,
|
||||
ResolvedPortalPlayback,
|
||||
@@ -33,6 +34,11 @@ import {
|
||||
ownsContent,
|
||||
runningExternalSession,
|
||||
} from './vod-details-external-session';
|
||||
import {
|
||||
createExternalLaunchOwner,
|
||||
startRouteOwnedPlayback,
|
||||
} from './vod-details-external-launch-owner';
|
||||
import { settleOwnedExternalLaunch } from './vod-details-external-launch';
|
||||
import { resolveXtreamVodPlaybackPresentation } from './vod-details-playback-presentation';
|
||||
import { formatPlaybackPosition } from './vod-primary-action-position';
|
||||
|
||||
@@ -47,6 +53,8 @@ export interface VodDetailsPlaybackBindings {
|
||||
* this the session belongs to no page and never offers Stop.
|
||||
*/
|
||||
activeSource?: Signal<PlayerContentInfo | null>;
|
||||
/** Retires a source resolution that the accepted fallback now supersedes. */
|
||||
supersedePendingSwitch: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,6 +77,10 @@ export class VodDetailsPlaybackService {
|
||||
|
||||
/** Signals bound from the host component via `bind()` */
|
||||
private readonly bindings = signal<VodDetailsPlaybackBindings | null>(null);
|
||||
private readonly externalLaunchOwner = createExternalLaunchOwner(
|
||||
() => this.xtreamStore.currentPlaylist()?.id,
|
||||
() => this.bindings()?.vodId()
|
||||
);
|
||||
|
||||
readonly inlinePlayback = signal<ResolvedPortalPlayback | null>(null);
|
||||
/**
|
||||
@@ -95,13 +107,22 @@ export class VodDetailsPlaybackService {
|
||||
session: this.externalPlayback.activeSession,
|
||||
playlistId: computed(() => this.xtreamStore.currentPlaylist()?.id),
|
||||
contentId: computed(() => this.bindings()?.vodId()),
|
||||
alsoOwns: computed(() => this.bindings()?.activeSource?.() ?? null),
|
||||
alsoOwns: computed(
|
||||
() =>
|
||||
this.externalLaunchOwner.current() ??
|
||||
this.bindings()?.activeSource?.() ??
|
||||
null
|
||||
),
|
||||
});
|
||||
|
||||
readonly matchedExternalPlayback = this.externalButton.matchedSession;
|
||||
readonly externalPrimaryLabel = this.externalButton.primaryLabel;
|
||||
readonly externalPrimaryIcon = this.externalButton.primaryIcon;
|
||||
readonly isExternalLaunchPending = this.externalButton.isLaunchPending;
|
||||
readonly isExternalLaunchPending = computed(
|
||||
() =>
|
||||
this.externalLaunchGeneration() !== null ||
|
||||
this.externalButton.isLaunchPending()
|
||||
);
|
||||
readonly isExternalStopAction = this.externalButton.isStopAction;
|
||||
readonly externalPrimaryButtonState = this.externalButton.buttonState;
|
||||
readonly vodPlaybackProgress = computed(() =>
|
||||
@@ -177,23 +198,22 @@ export class VodDetailsPlaybackService {
|
||||
this.bindings.set(bindings);
|
||||
}
|
||||
|
||||
playVod(vodItem: XtreamVodDetails | null): void {
|
||||
async playVod(vodItem: XtreamVodDetails | null): Promise<boolean> {
|
||||
if (!vodItem) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
const source = resolveXtreamVodPlaybackSource(vodItem);
|
||||
if (!source) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
const playlist = this.xtreamStore.currentPlaylist();
|
||||
if (!playlist) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
const presentation = resolveXtreamVodPlaybackPresentation(vodItem);
|
||||
this.addToRecentlyViewed();
|
||||
const streamUrl = this.xtreamStore.constructVodStreamUrl(vodItem);
|
||||
const routeVodId = this.bindings()?.vodId();
|
||||
const id =
|
||||
@@ -217,26 +237,25 @@ export class VodDetailsPlaybackService {
|
||||
contentInfo,
|
||||
};
|
||||
|
||||
this.startPlayback(playback);
|
||||
return await this.startPlayback(playback);
|
||||
}
|
||||
|
||||
resumeVod(vodItem: XtreamVodDetails | null): void {
|
||||
async resumeVod(vodItem: XtreamVodDetails | null): Promise<boolean> {
|
||||
if (!vodItem) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
const source = resolveXtreamVodPlaybackSource(vodItem);
|
||||
if (!source) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
const playlist = this.xtreamStore.currentPlaylist();
|
||||
if (!playlist) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
const presentation = resolveXtreamVodPlaybackPresentation(vodItem);
|
||||
this.addToRecentlyViewed();
|
||||
// Master's sparse-details fallback: a provider that omits the route
|
||||
// id still has the stream id on the resolved source.
|
||||
const routeVodId = this.bindings()?.vodId();
|
||||
@@ -265,7 +284,7 @@ export class VodDetailsPlaybackService {
|
||||
contentInfo,
|
||||
};
|
||||
|
||||
this.startPlayback(playback);
|
||||
return await this.startPlayback(playback);
|
||||
}
|
||||
|
||||
onPrimaryAction(vodItem: XtreamVodDetails | null): void {
|
||||
@@ -274,22 +293,20 @@ export class VodDetailsPlaybackService {
|
||||
}
|
||||
|
||||
if (this.isExternalStopAction()) {
|
||||
void this.stopExternalPlayback();
|
||||
void this.stopExternalPlayback().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.hasPlaybackPosition()) {
|
||||
this.resumeVod(vodItem);
|
||||
void this.resumeVod(vodItem);
|
||||
return;
|
||||
}
|
||||
|
||||
this.playVod(vodItem);
|
||||
void this.playVod(vodItem);
|
||||
}
|
||||
|
||||
async stopExternalPlayback(): Promise<void> {
|
||||
await this.externalPlayback.closeSession(
|
||||
this.matchedExternalPlayback()
|
||||
);
|
||||
stopExternalPlayback(): Promise<void> {
|
||||
return this.externalPlayback.closeSession(this.matchedExternalPlayback());
|
||||
}
|
||||
|
||||
formatPosition(): string {
|
||||
@@ -324,12 +341,20 @@ export class VodDetailsPlaybackService {
|
||||
}
|
||||
|
||||
handleExternalFallbackRequest(request: PlaybackFallbackRequest): void {
|
||||
const routeIdentity = this.externalLaunchOwner.captureRoute();
|
||||
this.bindings()?.supersedePendingSwitch();
|
||||
const generation = ++this.startGeneration;
|
||||
this.claimExternalLaunch(request.playback, generation);
|
||||
const launch = this.portalPlayer.openExternalPlayback(
|
||||
request.playback,
|
||||
request.player
|
||||
);
|
||||
request.trackLaunch(launch);
|
||||
void launch;
|
||||
void this.settleExternalLaunch(
|
||||
generation,
|
||||
() => this.externalLaunchOwner.ownsRoute(routeIdentity),
|
||||
launch
|
||||
);
|
||||
}
|
||||
|
||||
async loadPosition(playlistId: string, vodId: number): Promise<void> {
|
||||
@@ -377,27 +402,40 @@ export class VodDetailsPlaybackService {
|
||||
* What we last launched externally, remembered independently of the
|
||||
* controller's active source.
|
||||
*
|
||||
* `matchedExternalPlayback` cannot answer this during a switch: the
|
||||
* controller marks the DESTINATION active before playback is handed over,
|
||||
* so by the time we get here the running process no longer looks like
|
||||
* ours and would be left playing beside its replacement.
|
||||
* Kept independently of the controller so a refresh or an overlapping
|
||||
* handoff cannot make the exact process this page launched look foreign
|
||||
* before its teardown has been confirmed. Its route owner prevents a
|
||||
* reused component from attributing that process to a different movie.
|
||||
*/
|
||||
private launchedExternally: PlayerContentInfo | null = null;
|
||||
private launchedExternallyGeneration = 0;
|
||||
private readonly externalLaunchGeneration = signal<number | null>(null);
|
||||
|
||||
async startResolvedPlayback(
|
||||
playback: ResolvedPortalPlayback
|
||||
): Promise<void> {
|
||||
playback: ResolvedPortalPlayback,
|
||||
isCurrent: () => boolean = () => true
|
||||
): Promise<boolean> {
|
||||
if (this.externalLaunchGeneration() !== null) {
|
||||
return false;
|
||||
}
|
||||
const runningSession = runningExternalSession(
|
||||
this.externalPlayback.activeSession(),
|
||||
this.externalLaunchOwner.retained(),
|
||||
this.matchedExternalPlayback()
|
||||
);
|
||||
// A still-opening process has no exact closer yet. Denying this
|
||||
// replacement must not supersede that launch generation, or its late
|
||||
// successful result would be closed even though nothing replaced it.
|
||||
if (runningSession && !runningSession.canClose) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const generation = ++this.startGeneration;
|
||||
|
||||
// A switch REPLACES what is playing. With MPV or VLC and instance
|
||||
// reuse off, the backend spawns a second detached player otherwise —
|
||||
// both sources keep running and Stop owns only the newer one.
|
||||
await closeRunningExternalSession(
|
||||
runningExternalSession(
|
||||
this.externalPlayback.activeSession(),
|
||||
this.launchedExternally,
|
||||
this.matchedExternalPlayback()
|
||||
),
|
||||
const previousPlayerClosed = await closeRunningExternalSession(
|
||||
runningSession,
|
||||
(session) => this.externalPlayback.closeSession(session),
|
||||
(message, error) => this.logger.warn(message, error)
|
||||
);
|
||||
@@ -406,30 +444,90 @@ export class VodDetailsPlaybackService {
|
||||
// reach this line too: both would have seen the same session, closed
|
||||
// it once, and then launched independently — two detached players
|
||||
// again, the older one holding a source the user has moved on from.
|
||||
if (generation !== this.startGeneration) {
|
||||
return;
|
||||
if (
|
||||
!previousPlayerClosed ||
|
||||
generation !== this.startGeneration ||
|
||||
!isCurrent()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Same movie, different source: still a view.
|
||||
this.addToRecentlyViewed();
|
||||
this.startPlayback(playback);
|
||||
return await this.applyPlayback(playback, isCurrent);
|
||||
}
|
||||
|
||||
private startPlayback(playback: ResolvedPortalPlayback): void {
|
||||
private startPlayback(playback: ResolvedPortalPlayback): Promise<boolean> {
|
||||
return startRouteOwnedPlayback(this.externalLaunchOwner, (isCurrent) =>
|
||||
this.startResolvedPlayback(playback, isCurrent)
|
||||
);
|
||||
}
|
||||
|
||||
private async applyPlayback(
|
||||
playback: ResolvedPortalPlayback,
|
||||
isCurrent: () => boolean = () => true
|
||||
): Promise<boolean> {
|
||||
// EVERY start claims the generation, not just the switch path. Play,
|
||||
// Resume and Restart reach here directly, and a switch still waiting
|
||||
// on its `closeSession` would otherwise pass the check afterwards and
|
||||
// launch on top of what the user just chose.
|
||||
this.startGeneration++;
|
||||
const generation = ++this.startGeneration;
|
||||
this.positionWriter.reset();
|
||||
if (this.portalPlayer.isEmbeddedPlayer()) {
|
||||
this.inlinePlayback.set(playback);
|
||||
this.launchedExternally = null;
|
||||
return;
|
||||
this.externalLaunchOwner.clear();
|
||||
this.externalLaunchGeneration.set(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
this.closeInlinePlayer();
|
||||
this.launchedExternally = playback.contentInfo ?? null;
|
||||
void this.portalPlayer.openResolvedPlayback(playback, true);
|
||||
this.claimExternalLaunch(playback, generation);
|
||||
const launch = this.portalPlayer.openResolvedPlayback(playback, true);
|
||||
return await this.settleExternalLaunch(
|
||||
generation,
|
||||
isCurrent,
|
||||
launch
|
||||
);
|
||||
}
|
||||
|
||||
private claimExternalLaunch(
|
||||
playback: ResolvedPortalPlayback,
|
||||
generation: number
|
||||
): void {
|
||||
this.externalLaunchOwner.set(playback.contentInfo);
|
||||
this.launchedExternallyGeneration = generation;
|
||||
this.externalLaunchGeneration.set(generation);
|
||||
}
|
||||
|
||||
private async settleExternalLaunch(
|
||||
generation: number,
|
||||
isCurrent: () => boolean,
|
||||
launch: Promise<ExternalPlayerSession | void>
|
||||
): Promise<boolean> {
|
||||
return await settleOwnedExternalLaunch({
|
||||
launch,
|
||||
owns: () => generation === this.startGeneration && isCurrent(),
|
||||
close: (session) => this.externalPlayback.closeSession(session),
|
||||
warnCloseFailure: (error) =>
|
||||
this.logger.warn(
|
||||
'Closing a superseded external player failed.',
|
||||
error
|
||||
),
|
||||
clearPending: () => this.clearExternalLaunchPending(generation),
|
||||
clearOwnership: () =>
|
||||
this.clearExternalLaunchOwnership(generation),
|
||||
});
|
||||
}
|
||||
|
||||
private clearExternalLaunchOwnership(generation: number): void {
|
||||
if (this.launchedExternallyGeneration === generation) {
|
||||
this.externalLaunchOwner.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private clearExternalLaunchPending(generation: number): void {
|
||||
if (this.externalLaunchGeneration() === generation) {
|
||||
this.externalLaunchGeneration.set(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,7 +112,7 @@ describe('VodDetailsRouteComponent — source caption', () => {
|
||||
expect(component.activeSourceCaption()).toBeNull();
|
||||
});
|
||||
|
||||
it('waits for the next stream to start after Play is pressed again', () => {
|
||||
it('waits for the next stream to start after Play is pressed again', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
const component = fixture.componentInstance;
|
||||
const playback = fixture.debugElement.injector.get(
|
||||
@@ -131,8 +131,12 @@ describe('VodDetailsRouteComponent — source caption', () => {
|
||||
|
||||
// Restart keeps the same host mounted, so without clearing the latch
|
||||
// the caption would carry the previous stream's claim into the new one.
|
||||
component.playVod({
|
||||
movie_data: { stream_id: 650020, name: 'Example' },
|
||||
await component.playVod({
|
||||
movie_data: {
|
||||
stream_id: 650020,
|
||||
name: 'Example',
|
||||
container_extension: 'mkv',
|
||||
},
|
||||
} as never);
|
||||
expect(playback.inlinePlayback()).not.toBeNull();
|
||||
expect(component.activeSourceCaption()).toBeNull();
|
||||
@@ -159,10 +163,12 @@ describe('VodDetailsRouteComponent — source caption', () => {
|
||||
// The exact callback `switchToSource` invokes once it has resolved a
|
||||
// new source. Standing up the resolver here would test the host, not
|
||||
// the route's half of the seam.
|
||||
(
|
||||
await (
|
||||
component.multiSource as unknown as {
|
||||
bindings: {
|
||||
startPlayback: (playback: ResolvedPortalPlayback) => void;
|
||||
startPlayback: (
|
||||
playback: ResolvedPortalPlayback
|
||||
) => Promise<boolean>;
|
||||
};
|
||||
}
|
||||
).bindings.startPlayback({
|
||||
@@ -170,9 +176,6 @@ describe('VodDetailsRouteComponent — source caption', () => {
|
||||
title: 'Example',
|
||||
startTime: 3,
|
||||
});
|
||||
// Replacing a running external player is a round-trip, so the handoff
|
||||
// yields once before the new playback is mounted.
|
||||
await Promise.resolve();
|
||||
|
||||
expect(playback.inlinePlayback()?.streamUrl).toBe(
|
||||
'http://example.com/alt.mkv'
|
||||
|
||||
@@ -100,11 +100,61 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
expect(component.isExternalStopAction()).toBe(true);
|
||||
});
|
||||
|
||||
it('drops the carried position when Restart starts from the beginning', () => {
|
||||
it('wires diagnostic fallback acceptance to source-switch supersession', () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
const component = fixture.componentInstance;
|
||||
const supersede = jest.spyOn(
|
||||
component.multiSource,
|
||||
'supersedePendingSwitch'
|
||||
);
|
||||
const launched = {
|
||||
id: 'diagnostic-session',
|
||||
player: 'mpv' as const,
|
||||
status: 'opened' as const,
|
||||
title: 'Example',
|
||||
streamUrl: 'https://example.com/movie.mkv',
|
||||
startedAt: '2026-08-09T00:00:00.000Z',
|
||||
updatedAt: '2026-08-09T00:00:01.000Z',
|
||||
canClose: true,
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 650020,
|
||||
contentType: 'vod' as const,
|
||||
},
|
||||
};
|
||||
const launch = Promise.resolve(launched);
|
||||
stubs.openExternalPlayback.mockReturnValueOnce(launch);
|
||||
|
||||
component.handleExternalFallbackRequest({
|
||||
player: 'mpv',
|
||||
playback: {
|
||||
streamUrl: launched.streamUrl,
|
||||
title: launched.title,
|
||||
contentInfo: launched.contentInfo,
|
||||
},
|
||||
diagnostic: {},
|
||||
trackLaunch: jest.fn(),
|
||||
} as never);
|
||||
|
||||
expect(supersede).toHaveBeenCalledTimes(1);
|
||||
expect(supersede.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
stubs.openExternalPlayback.mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the carried position when Restart starts from the beginning', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
stubs.isEmbeddedPlayer.mockReturnValue(true);
|
||||
const component = fixture.componentInstance;
|
||||
const reported = jest.spyOn(component.multiSource, 'reportPosition');
|
||||
|
||||
component.playVod({} as XtreamVodDetails);
|
||||
await component.playVod({
|
||||
movie_data: {
|
||||
stream_id: 650020,
|
||||
name: 'Example',
|
||||
container_extension: 'mkv',
|
||||
},
|
||||
} as never);
|
||||
|
||||
// The controller still holds whatever this page was seeded with, and
|
||||
// a failure before the first timeupdate would resolve the next source
|
||||
@@ -112,6 +162,44 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
expect(reported).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
it('keeps the previous source state when its external close fails', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
activeSession.set({
|
||||
id: 'previous-session',
|
||||
player: 'mpv',
|
||||
status: 'playing',
|
||||
title: 'Previous source',
|
||||
streamUrl: 'https://example.com/previous.mkv',
|
||||
startedAt: '2026-08-08T00:00:00.000Z',
|
||||
updatedAt: '2026-08-08T00:00:00.000Z',
|
||||
canClose: true,
|
||||
contentInfo: {
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 650020,
|
||||
contentType: 'vod',
|
||||
},
|
||||
});
|
||||
closeSession.mockRejectedValueOnce(new Error('close ipc failed'));
|
||||
const component = fixture.componentInstance;
|
||||
const markRouteSourceActive = jest.spyOn(
|
||||
component.multiSource,
|
||||
'markRouteSourceActive'
|
||||
);
|
||||
const beginPlayback = jest.spyOn(component.msUi, 'beginPlayback');
|
||||
|
||||
await component.playVod({
|
||||
movie_data: {
|
||||
stream_id: 650020,
|
||||
name: 'Example',
|
||||
container_extension: 'mkv',
|
||||
},
|
||||
} as never);
|
||||
|
||||
expect(markRouteSourceActive).not.toHaveBeenCalled();
|
||||
expect(beginPlayback).not.toHaveBeenCalled();
|
||||
expect(stubs.openResolvedPlayback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops the external player when the button says Stop', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
downloadsAvailable.set(true);
|
||||
@@ -235,6 +323,34 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
expect(stubs.openResolvedPlayback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('guards Restart and provider actions before external IPC settles', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
stubs.openResolvedPlayback.mockReturnValue(new Promise(() => undefined));
|
||||
const component = fixture.componentInstance;
|
||||
const item = {
|
||||
movie_data: {
|
||||
stream_id: 650020,
|
||||
name: 'Example',
|
||||
container_extension: 'mp4',
|
||||
},
|
||||
} as never;
|
||||
|
||||
void component.restartVod(item);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 20 && stubs.openResolvedPlayback.mock.calls.length === 0;
|
||||
attempt += 1
|
||||
) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve));
|
||||
}
|
||||
expect(component.isExternalLaunchPending()).toBe(true);
|
||||
await component.restartVod(item);
|
||||
await component.playFromProviderSource(item);
|
||||
|
||||
expect(component.isExternalLaunchPending()).toBe(true);
|
||||
expect(stubs.openResolvedPlayback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not let the provider secondary bypass a pending external launch', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
activeSession.set({
|
||||
@@ -492,6 +608,7 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
|
||||
it('replaces an alternative’s timecode when Resume starts the route copy', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
stubs.isEmbeddedPlayer.mockReturnValue(true);
|
||||
const component = fixture.componentInstance;
|
||||
const playback = fixture.debugElement.injector.get(
|
||||
VodDetailsPlaybackService
|
||||
@@ -510,7 +627,7 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
// ROUTE copy has to overwrite it, or a failure before the first
|
||||
// timeupdate resolves the next source at a position from another copy.
|
||||
component.multiSource.reportPosition(4200);
|
||||
component.resumeVod({
|
||||
await component.resumeVod({
|
||||
movie_data: {
|
||||
stream_id: 650020,
|
||||
name: 'Example',
|
||||
@@ -544,8 +661,9 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
expect(reported).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('takes the route wrappers when the primary button falls through', () => {
|
||||
it('takes the route wrappers when the primary button falls through', async () => {
|
||||
currentPlaylist.set({ id: 'playlist-1' });
|
||||
stubs.isEmbeddedPlayer.mockReturnValue(true);
|
||||
const component = fixture.componentInstance;
|
||||
withActiveSource('playlist-1', 650020);
|
||||
jest.spyOn(component.multiSource, 'playPinnedSource').mockResolvedValue(
|
||||
@@ -555,7 +673,7 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
|
||||
// Reaching the service directly would skip the bookkeeping a route
|
||||
// start needs — the controller would keep an alternative's timecode.
|
||||
void component.onPrimaryAction({
|
||||
await component.onPrimaryAction({
|
||||
movie_data: {
|
||||
stream_id: 650020,
|
||||
name: 'Example',
|
||||
@@ -563,9 +681,7 @@ describe('VodDetailsRouteComponent — playback actions', () => {
|
||||
},
|
||||
} as never);
|
||||
|
||||
return Promise.resolve().then(() => {
|
||||
expect(reported).toHaveBeenCalledWith(0);
|
||||
});
|
||||
expect(reported).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
it('offers no resume point for a pinned copy watched through', async () => {
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
<button
|
||||
class="play-btn play-btn--restart"
|
||||
(click)="restartVod(playableItem)"
|
||||
[disabled]="isExternalLaunchPending()"
|
||||
>
|
||||
<mat-icon>replay</mat-icon>
|
||||
{{ 'XTREAM.RESTART' | translate }}
|
||||
@@ -119,6 +120,7 @@
|
||||
type="button"
|
||||
class="icon-action-btn"
|
||||
(click)="playFromProviderSource(playableItem)"
|
||||
[disabled]="isExternalLaunchPending()"
|
||||
[matTooltip]="
|
||||
'PORTALS.MULTI_SOURCE.PLAY_FROM_SOURCE'
|
||||
| translate
|
||||
|
||||
@@ -370,6 +370,8 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
vodId: this.selectedVodId,
|
||||
vodInfo: this.selectedVodInfo,
|
||||
activeSource: this.msUi.activeAlternativeSource,
|
||||
supersedePendingSwitch: () =>
|
||||
this.multiSource.supersedePendingSwitch(),
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
@@ -396,16 +398,21 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
this.multiSource.bind({
|
||||
// Route every switch through the same inline-vs-external fork a
|
||||
// normal Play uses, so the two paths cannot drift apart.
|
||||
startPlayback: (playback) => {
|
||||
// A switch mounts a DIFFERENT stream in the same host, so the
|
||||
// evidence that the previous one was playing says nothing
|
||||
// about this one — without clearing it the caption and the
|
||||
// badge would claim the new source while it is still opening.
|
||||
this.msUi.reset();
|
||||
void this.playback.startResolvedPlayback(playback);
|
||||
startPlayback: async (playback, isCurrent) => {
|
||||
const started = await this.playback.startResolvedPlayback(
|
||||
playback,
|
||||
isCurrent
|
||||
);
|
||||
if (started) {
|
||||
// A switch mounts a DIFFERENT stream in the same host, so
|
||||
// evidence from the previous one says nothing about it.
|
||||
this.msUi.reset();
|
||||
}
|
||||
return started;
|
||||
},
|
||||
movie: this.multiSourceMovie,
|
||||
playbackLive: this.playbackLive,
|
||||
playbackStartBlocked: this.playback.isExternalLaunchPending,
|
||||
});
|
||||
|
||||
// Initializes on first render and RE-initializes when the route
|
||||
@@ -500,14 +507,20 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
this.xtreamStore.setSelectedItem(null);
|
||||
}
|
||||
|
||||
playVod(vodItem: XtreamVodDetails | null): void {
|
||||
async playVod(vodItem: XtreamVodDetails | null): Promise<boolean> {
|
||||
this.multiSource.supersedePendingSwitch();
|
||||
const started = await this.playback.playVod(vodItem);
|
||||
if (!started) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Restart means from the beginning. The controller still holds the
|
||||
// position this page was seeded with, and a failure before the first
|
||||
// timeupdate would otherwise resolve the next source back at it.
|
||||
this.multiSource.reportPosition(0);
|
||||
this.multiSource.markRouteSourceActive();
|
||||
this.msUi.beginPlayback();
|
||||
this.playback.playVod(vodItem);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -518,6 +531,10 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
* user to the route's playlist.
|
||||
*/
|
||||
async restartVod(vodItem: XtreamVodDetails | null): Promise<void> {
|
||||
if (this.isExternalLaunchPending()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.msUi.primaryIsPinnedCopy()) {
|
||||
const outcome = await this.multiSource.playPinnedSource(async () =>
|
||||
Promise.resolve(0)
|
||||
@@ -527,19 +544,25 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
this.playVod(vodItem);
|
||||
await this.playVod(vodItem);
|
||||
}
|
||||
|
||||
resumeVod(vodItem: XtreamVodDetails | null): void {
|
||||
this.multiSource.markRouteSourceActive();
|
||||
this.msUi.beginPlayback();
|
||||
async resumeVod(vodItem: XtreamVodDetails | null): Promise<boolean> {
|
||||
this.multiSource.supersedePendingSwitch();
|
||||
const started = await this.playback.resumeVod(vodItem);
|
||||
if (!started) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The controller can still hold an ALTERNATIVE's timecode. A failure
|
||||
// before the first timeupdate would otherwise resolve the next source
|
||||
// at a position that belongs to a different copy.
|
||||
this.multiSource.reportPosition(
|
||||
this.playback.routePlaybackPosition()?.positionSeconds ?? 0
|
||||
);
|
||||
this.playback.resumeVod(vodItem);
|
||||
this.multiSource.markRouteSourceActive();
|
||||
this.msUi.beginPlayback();
|
||||
return true;
|
||||
}
|
||||
|
||||
async onPrimaryAction(vodItem: XtreamVodDetails | null): Promise<void> {
|
||||
@@ -547,7 +570,11 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
// make the control do the opposite of what it says — launching a
|
||||
// second player while the first keeps running.
|
||||
if (this.playback.isExternalStopAction()) {
|
||||
await this.playback.stopExternalPlayback();
|
||||
try {
|
||||
await this.playback.stopExternalPlayback();
|
||||
} catch {
|
||||
// The dock stays visible when process teardown is unconfirmed.
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -566,7 +593,10 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
async playFromProviderSource(
|
||||
vodItem: XtreamVodDetails | null
|
||||
): Promise<void> {
|
||||
if (this.externalPrimaryButtonState() !== 'idle') {
|
||||
if (
|
||||
this.isExternalLaunchPending() ||
|
||||
this.externalPrimaryButtonState() !== 'idle'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -587,11 +617,11 @@ export class VodDetailsRouteComponent implements OnInit, OnDestroy {
|
||||
// bookkeeping a route start needs — clearing the playback evidence and
|
||||
// replacing whatever timecode an alternative left in the controller.
|
||||
if (this.playback.hasPlaybackPosition()) {
|
||||
this.resumeVod(vodItem);
|
||||
await this.resumeVod(vodItem);
|
||||
return;
|
||||
}
|
||||
|
||||
this.playVod(vodItem);
|
||||
await this.playVod(vodItem);
|
||||
}
|
||||
|
||||
stopExternalPlayback(): Promise<void> {
|
||||
|
||||
@@ -72,6 +72,7 @@ export function createVodDetailsRouteStubs() {
|
||||
closeSession: jest.fn(),
|
||||
isEmbeddedPlayer: jest.fn().mockReturnValue(false),
|
||||
openResolvedPlayback: jest.fn(),
|
||||
openExternalPlayback: jest.fn(),
|
||||
snackBarOpen: jest.fn(),
|
||||
startDownload: jest.fn().mockResolvedValue(undefined),
|
||||
locationBack: jest.fn(),
|
||||
@@ -109,6 +110,7 @@ export function resetVodDetailsRouteStubs(stubs: VodDetailsRouteStubs): void {
|
||||
stubs.isDownloading.mockReturnValue(false);
|
||||
stubs.isPausedDownload.mockReturnValue(false);
|
||||
stubs.getDownloadedFilePath.mockReturnValue(undefined);
|
||||
stubs.isEmbeddedPlayer.mockReturnValue(false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -245,6 +247,7 @@ export async function configureVodDetailsRouteTestBed(
|
||||
useValue: {
|
||||
isEmbeddedPlayer: stubs.isEmbeddedPlayer,
|
||||
openResolvedPlayback: stubs.openResolvedPlayback,
|
||||
openExternalPlayback: stubs.openExternalPlayback,
|
||||
},
|
||||
},
|
||||
{ provide: MatSnackBar, useValue: { open: stubs.snackBarOpen } },
|
||||
|
||||
+9
-1
@@ -39,6 +39,7 @@ describe('VodMultiSourceHostService — pin persistence', () => {
|
||||
// Whatever is on screen; the pin path distinguishes it from selection.
|
||||
|
||||
const playbackLive = signal(false);
|
||||
const playbackStartBlocked = signal(false);
|
||||
const vodAutoFailover = signal(false);
|
||||
const startPlayback = jest.fn();
|
||||
const discovery = { isAvailable: true, discover: jest.fn() };
|
||||
@@ -63,7 +64,9 @@ describe('VodMultiSourceHostService — pin persistence', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
startPlayback.mockResolvedValue(true);
|
||||
movie.set(null);
|
||||
playbackStartBlocked.set(false);
|
||||
vodAutoFailover.set(false);
|
||||
discovery.isAvailable = true;
|
||||
discovery.discover.mockResolvedValue({
|
||||
@@ -89,7 +92,12 @@ describe('VodMultiSourceHostService — pin persistence', () => {
|
||||
|
||||
service = TestBed.inject(VodMultiSourceHostService);
|
||||
TestBed.runInInjectionContext(() =>
|
||||
service.bind({ startPlayback, movie, playbackLive })
|
||||
service.bind({
|
||||
startPlayback,
|
||||
movie,
|
||||
playbackLive,
|
||||
playbackStartBlocked,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ describe('VodMultiSourceHostService — stale resolutions', () => {
|
||||
const {
|
||||
discovery,
|
||||
movie,
|
||||
playbackStartBlocked,
|
||||
pins,
|
||||
probes,
|
||||
resolver,
|
||||
@@ -135,10 +136,39 @@ describe('VodMultiSourceHostService — stale resolutions', () => {
|
||||
expect(startPlayback).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
streamUrl: expect.stringContaining(String(ALT_THREE.contentId)),
|
||||
})
|
||||
}),
|
||||
expect.any(Function)
|
||||
);
|
||||
});
|
||||
|
||||
it('does not supersede a pending external launch with a blocked source pick', async () => {
|
||||
await loadMovie([ALT_TWO, ALT_THREE]);
|
||||
|
||||
const firstLaunch = createDeferred<boolean>();
|
||||
startPlayback
|
||||
.mockImplementationOnce((_playback, isCurrent) => {
|
||||
playbackStartBlocked.set(true);
|
||||
return firstLaunch.promise.then((opened) => {
|
||||
playbackStartBlocked.set(false);
|
||||
return opened && isCurrent();
|
||||
});
|
||||
})
|
||||
.mockResolvedValueOnce(false);
|
||||
|
||||
const first = service.play(ALT_TWO.id);
|
||||
while (startPlayback.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
await expect(service.play(ALT_THREE.id)).resolves.toBe(false);
|
||||
expect(startPlayback).toHaveBeenCalledTimes(1);
|
||||
|
||||
firstLaunch.resolve(true);
|
||||
await expect(first).resolves.toBe(true);
|
||||
expect(rowFor(ALT_TWO.id)?.isActive).toBe(true);
|
||||
expect(rowFor(ALT_THREE.id)?.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('drops a switch whose movie was navigated away from', async () => {
|
||||
await loadMovie([ALT_TWO]);
|
||||
service.reportPosition(2538);
|
||||
|
||||
+9
-1
@@ -40,6 +40,7 @@ describe('VodMultiSourceHostService — session lifecycle', () => {
|
||||
// Whatever is on screen; the pin path distinguishes it from selection.
|
||||
|
||||
const playbackLive = signal(false);
|
||||
const playbackStartBlocked = signal(false);
|
||||
const vodAutoFailover = signal(false);
|
||||
const startPlayback = jest.fn();
|
||||
const discovery = { isAvailable: true, discover: jest.fn() };
|
||||
@@ -72,7 +73,9 @@ describe('VodMultiSourceHostService — session lifecycle', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
startPlayback.mockResolvedValue(true);
|
||||
movie.set(null);
|
||||
playbackStartBlocked.set(false);
|
||||
vodAutoFailover.set(false);
|
||||
discovery.isAvailable = true;
|
||||
discovery.discover.mockResolvedValue({
|
||||
@@ -98,7 +101,12 @@ describe('VodMultiSourceHostService — session lifecycle', () => {
|
||||
|
||||
service = TestBed.inject(VodMultiSourceHostService);
|
||||
TestBed.runInInjectionContext(() =>
|
||||
service.bind({ startPlayback, movie, playbackLive })
|
||||
service.bind({
|
||||
startPlayback,
|
||||
movie,
|
||||
playbackLive,
|
||||
playbackStartBlocked,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -122,6 +122,7 @@ export function setupVodMultiSourceHost() {
|
||||
const movie = signal<VodMultiSourceMovie | null>(null);
|
||||
/** Whatever is on screen; the pin path distinguishes it from selection. */
|
||||
const playbackLive = signal(false);
|
||||
const playbackStartBlocked = signal(false);
|
||||
const vodAutoFailover = signal(false);
|
||||
const startPlayback = jest.fn();
|
||||
const discovery = { isAvailable: true, discover: jest.fn() };
|
||||
@@ -132,6 +133,7 @@ export function setupVodMultiSourceHost() {
|
||||
const harness = {
|
||||
movie,
|
||||
playbackLive,
|
||||
playbackStartBlocked,
|
||||
vodAutoFailover,
|
||||
startPlayback,
|
||||
discovery,
|
||||
@@ -143,8 +145,10 @@ export function setupVodMultiSourceHost() {
|
||||
/** Call from `beforeEach`; returns the freshly bound service. */
|
||||
reset(): VodMultiSourceHostService {
|
||||
jest.resetAllMocks();
|
||||
startPlayback.mockResolvedValue(true);
|
||||
movie.set(null);
|
||||
playbackLive.set(false);
|
||||
playbackStartBlocked.set(false);
|
||||
vodAutoFailover.set(false);
|
||||
discovery.isAvailable = true;
|
||||
discovery.discover.mockResolvedValue({
|
||||
@@ -170,7 +174,12 @@ export function setupVodMultiSourceHost() {
|
||||
|
||||
harness.service = TestBed.inject(VodMultiSourceHostService);
|
||||
TestBed.runInInjectionContext(() =>
|
||||
harness.service.bind({ startPlayback, movie, playbackLive })
|
||||
harness.service.bind({
|
||||
startPlayback,
|
||||
movie,
|
||||
playbackLive,
|
||||
playbackStartBlocked,
|
||||
})
|
||||
);
|
||||
return harness.service;
|
||||
},
|
||||
|
||||
+58
-6
@@ -9,10 +9,7 @@ import {
|
||||
StreamProbeService,
|
||||
VodSourcePinService,
|
||||
} from '@iptvnator/services';
|
||||
import type {
|
||||
VodSourceCandidate,
|
||||
VodSourceField,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import type { VodSourceCandidate } from '@iptvnator/shared/interfaces';
|
||||
import { VodMultiSourceHostService } from './vod-multi-source-host.service';
|
||||
import type { VodMultiSourceMovie } from './vod-multi-source-identity';
|
||||
|
||||
@@ -43,6 +40,7 @@ describe('VodMultiSourceHostService', () => {
|
||||
// Whatever is on screen; the pin path distinguishes it from selection.
|
||||
|
||||
const playbackLive = signal(false);
|
||||
const playbackStartBlocked = signal(false);
|
||||
const vodAutoFailover = signal(false);
|
||||
const startPlayback = jest.fn();
|
||||
const discovery = { isAvailable: true, discover: jest.fn() };
|
||||
@@ -89,7 +87,9 @@ describe('VodMultiSourceHostService', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
startPlayback.mockResolvedValue(true);
|
||||
movie.set(null);
|
||||
playbackStartBlocked.set(false);
|
||||
vodAutoFailover.set(false);
|
||||
discovery.isAvailable = true;
|
||||
discovery.discover.mockResolvedValue({
|
||||
@@ -115,7 +115,12 @@ describe('VodMultiSourceHostService', () => {
|
||||
|
||||
service = TestBed.inject(VodMultiSourceHostService);
|
||||
TestBed.runInInjectionContext(() =>
|
||||
service.bind({ startPlayback, movie, playbackLive })
|
||||
service.bind({
|
||||
startPlayback,
|
||||
movie,
|
||||
playbackLive,
|
||||
playbackStartBlocked,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
@@ -164,10 +169,57 @@ describe('VodMultiSourceHostService', () => {
|
||||
);
|
||||
expect(startPlayback).toHaveBeenCalledTimes(1);
|
||||
expect(startPlayback).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ startTime: 2538 })
|
||||
expect.objectContaining({ startTime: 2538 }),
|
||||
expect.any(Function)
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the current source when playback rejects the handoff', async () => {
|
||||
await loadMovie([ALT_TWO]);
|
||||
startPlayback.mockResolvedValueOnce(false);
|
||||
|
||||
await expect(service.play(ALT_TWO.id)).resolves.toBe(false);
|
||||
|
||||
expect(rowFor(CURRENT_A_ID)?.isActive).toBe(true);
|
||||
expect(rowFor(ALT_TWO.id)?.isActive).toBe(false);
|
||||
expect(service.lastSwitch()).toBeNull();
|
||||
expect(service.previousSourceId()).toBeNull();
|
||||
});
|
||||
|
||||
it('does not launch a resolved source after a newer unresolvable pick', async () => {
|
||||
await loadMovie([ALT_TWO, ALT_THREE]);
|
||||
const teardown = createDeferred<void>();
|
||||
const launched: string[] = [];
|
||||
startPlayback.mockImplementationOnce(
|
||||
async (
|
||||
playback: { streamUrl: string },
|
||||
isCurrent?: () => boolean
|
||||
) => {
|
||||
await teardown.promise;
|
||||
if (isCurrent && !isCurrent()) {
|
||||
return false;
|
||||
}
|
||||
launched.push(playback.streamUrl);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
const first = service.play(ALT_TWO.id);
|
||||
while (startPlayback.mock.calls.length === 0) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
resolver.resolve.mockResolvedValueOnce(null);
|
||||
await expect(service.play(ALT_THREE.id)).resolves.toBe(false);
|
||||
|
||||
teardown.resolve();
|
||||
await expect(first).resolves.toBe(false);
|
||||
|
||||
expect(launched).toEqual([]);
|
||||
expect(rowFor(CURRENT_A_ID)?.isActive).toBe(true);
|
||||
expect(service.lastSwitch()).toBeNull();
|
||||
});
|
||||
|
||||
it('never puts a credential-bearing playlist name in the notice', async () => {
|
||||
// Users routinely name a playlist after the URL they pasted, and this
|
||||
// string goes straight into a toast over the video.
|
||||
|
||||
@@ -61,8 +61,14 @@ import {
|
||||
*/
|
||||
|
||||
export interface VodMultiSourceBindings {
|
||||
/** Applies a playback — inline swap or external launch, host's choice. */
|
||||
startPlayback: (playback: ResolvedPortalPlayback) => void;
|
||||
/**
|
||||
* Applies a playback — inline swap or external launch, host's choice.
|
||||
* False leaves the controller on its current source.
|
||||
*/
|
||||
startPlayback: (
|
||||
playback: ResolvedPortalPlayback,
|
||||
isCurrent: () => boolean
|
||||
) => Promise<boolean>;
|
||||
/** The movie on screen, or null while its identity is not yet knowable. */
|
||||
movie: Signal<VodMultiSourceMovie | null>;
|
||||
/**
|
||||
@@ -70,6 +76,12 @@ export interface VodMultiSourceBindings {
|
||||
* A pinned row stays selected after its player is closed.
|
||||
*/
|
||||
playbackLive: Signal<boolean>;
|
||||
/**
|
||||
* True while an external launch has no exact closer yet. A source pick in
|
||||
* that interval cannot safely replace the launch and must not supersede
|
||||
* the switch token that still owns it.
|
||||
*/
|
||||
playbackStartBlocked: Signal<boolean>;
|
||||
}
|
||||
|
||||
export type { VodMultiSourceSwitchNotice };
|
||||
@@ -483,13 +495,18 @@ export class VodMultiSourceHostService {
|
||||
* so an older resolution would replace what the user just asked for.
|
||||
*/
|
||||
markRouteSourceActive(): void {
|
||||
this.switchToken++;
|
||||
this.supersedePendingSwitch();
|
||||
if (this.routeSourceId) {
|
||||
this.controller.markPlaying(this.routeSourceId);
|
||||
this.publish();
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancel an older source resolution without claiming that route playback started. */
|
||||
supersedePendingSwitch(): void {
|
||||
this.switchToken++;
|
||||
}
|
||||
|
||||
/** The live position, fed ahead of the persist throttle. */
|
||||
reportPosition(seconds: number): void {
|
||||
this.controller.setResumeSeconds(seconds);
|
||||
@@ -501,7 +518,7 @@ export class VodMultiSourceHostService {
|
||||
|
||||
private switchTo(candidate: VodSourceCandidate): Promise<SwitchOutcome> {
|
||||
const bindings = this.bindings;
|
||||
if (!bindings) {
|
||||
if (!bindings || bindings.playbackStartBlocked()) {
|
||||
return Promise.resolve('superseded');
|
||||
}
|
||||
|
||||
@@ -512,7 +529,8 @@ export class VodMultiSourceHostService {
|
||||
controller: this.controller,
|
||||
resolve: (target, options) =>
|
||||
this.resolver.resolve(target, options),
|
||||
startPlayback: (playback) => bindings.startPlayback(playback),
|
||||
startPlayback: (playback, isCurrent) =>
|
||||
bindings.startPlayback(playback, isCurrent),
|
||||
isCurrent: () => this.isCurrentSwitch(session, attempt),
|
||||
setPreviousSource: (id) => this._previousSourceId.set(id),
|
||||
setNotice: (notice) => this._lastSwitch.set(notice),
|
||||
|
||||
@@ -111,7 +111,11 @@ export interface SwitchDeps {
|
||||
playback: ResolvedPortalPlayback;
|
||||
candidate: VodSourceCandidate;
|
||||
} | null>;
|
||||
startPlayback: (playback: ResolvedPortalPlayback) => void;
|
||||
/** True only when the host accepted and applied this exact handoff. */
|
||||
startPlayback: (
|
||||
playback: ResolvedPortalPlayback,
|
||||
isCurrent: () => boolean
|
||||
) => Promise<boolean>;
|
||||
/** False once a newer switch, or another movie, owns the screen. */
|
||||
isCurrent: () => boolean;
|
||||
setPreviousSource: (sourceId: string | null) => void;
|
||||
@@ -154,11 +158,21 @@ export async function switchToSource(
|
||||
return 'unresolvable';
|
||||
}
|
||||
|
||||
// Ownership must be rechecked inside the playback seam after any external
|
||||
// teardown wait but before it applies the new source. A post-launch check
|
||||
// alone can reject a stale handoff only after its player already exists.
|
||||
const started = await deps.startPlayback(resolved.playback, deps.isCurrent);
|
||||
if (!started || !deps.isCurrent()) {
|
||||
// Teardown may fail before the host can apply the replacement, or a
|
||||
// newer start may take ownership while that teardown is in flight.
|
||||
// In either case the old source remains the only truthful selection.
|
||||
return 'superseded';
|
||||
}
|
||||
|
||||
controller.updateSource(resolved.candidate);
|
||||
deps.setPreviousSource(previous?.id ?? null);
|
||||
controller.markPlaying(candidate.id);
|
||||
controller.setResumeSeconds(resumeSeconds);
|
||||
deps.startPlayback(resolved.playback);
|
||||
|
||||
deps.setNotice(
|
||||
buildSwitchNotice(
|
||||
|
||||
@@ -3,11 +3,7 @@ import { PlayerContentInfo } from './portal-playback.interface';
|
||||
export type ExternalPlayerName = 'mpv' | 'vlc';
|
||||
|
||||
export type ExternalPlayerSessionStatus =
|
||||
| 'launching'
|
||||
| 'opened'
|
||||
| 'playing'
|
||||
| 'error'
|
||||
| 'closed';
|
||||
'launching' | 'opened' | 'playing' | 'error' | 'closed';
|
||||
|
||||
export interface ExternalPlayerSession {
|
||||
id: string;
|
||||
@@ -21,4 +17,6 @@ export interface ExternalPlayerSession {
|
||||
updatedAt: string;
|
||||
error?: string;
|
||||
canClose: boolean;
|
||||
/** Exact failed replacement displaced by this restored live session. */
|
||||
restoredFromSessionId?: string;
|
||||
}
|
||||
+42
-5
@@ -63,19 +63,56 @@
|
||||
</div>
|
||||
|
||||
<div class="external-playback-dock__actions">
|
||||
@if (showActionButton()) {
|
||||
@if (showCloseAction()) {
|
||||
<button
|
||||
type="button"
|
||||
mat-button
|
||||
class="external-playback-dock__button"
|
||||
[attr.aria-label]="actionLabelKey() | translate"
|
||||
(click)="onActionClick()"
|
||||
[attr.aria-label]="
|
||||
'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_CLOSE' | translate
|
||||
"
|
||||
(click)="onCloseClick()"
|
||||
>
|
||||
<mat-icon aria-hidden="true">{{ actionIcon() }}</mat-icon>
|
||||
<mat-icon aria-hidden="true">stop_circle</mat-icon>
|
||||
@if (!compact()) {
|
||||
<span>{{ actionLabelKey() | translate }}</span>
|
||||
<span>{{
|
||||
'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_CLOSE' | translate
|
||||
}}</span>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
@if (showDismissAction()) {
|
||||
@if (compact()) {
|
||||
<button
|
||||
type="button"
|
||||
mat-icon-button
|
||||
class="external-playback-dock__button external-playback-dock__dismiss"
|
||||
[attr.aria-label]="
|
||||
'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_DISMISS' | translate
|
||||
"
|
||||
(click)="onDismissClick()"
|
||||
>
|
||||
<mat-icon aria-hidden="true">close</mat-icon>
|
||||
</button>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
mat-button
|
||||
class="external-playback-dock__button external-playback-dock__dismiss"
|
||||
[attr.aria-label]="
|
||||
'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_DISMISS' | translate
|
||||
"
|
||||
(click)="onDismissClick()"
|
||||
>
|
||||
<mat-icon aria-hidden="true">close</mat-icon>
|
||||
@if (!compact()) {
|
||||
<span>{{
|
||||
'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_DISMISS'
|
||||
| translate
|
||||
}}</span>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
+4
@@ -172,6 +172,10 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.external-playback-dock__dismiss {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.external-playback-dock {
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
|
||||
+32
@@ -146,11 +146,43 @@ describe('ExternalPlaybackDockComponent', () => {
|
||||
expect(action.nativeElement.textContent).toContain('Dismiss');
|
||||
expect(action.nativeElement.textContent).not.toContain('Retry');
|
||||
expect(action.nativeElement.getAttribute('aria-label')).toBe('Dismiss');
|
||||
expect(action.nativeElement.classList).toContain('mat-mdc-button');
|
||||
expect(action.nativeElement.classList).not.toContain(
|
||||
'mat-mdc-icon-button'
|
||||
);
|
||||
|
||||
action.nativeElement.click();
|
||||
expect(dismissSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('preserves the only stop affordance when an errored process may still be alive', () => {
|
||||
const closeSpy = jest.fn();
|
||||
const dismissSpy = jest.fn();
|
||||
component.closeClicked.subscribe(closeSpy);
|
||||
component.dismissClicked.subscribe(dismissSpy);
|
||||
fixture.componentRef.setInput('session', {
|
||||
...session,
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
const stop = fixture.debugElement.query(
|
||||
By.css('.external-playback-dock__button')
|
||||
);
|
||||
const dismiss = fixture.debugElement.query(
|
||||
By.css('.external-playback-dock__dismiss')
|
||||
);
|
||||
|
||||
expect(stop.nativeElement.textContent).toContain('Close player');
|
||||
expect(dismiss).toBeNull();
|
||||
|
||||
stop.nativeElement.click();
|
||||
expect(closeSpy).toHaveBeenCalledTimes(1);
|
||||
expect(dismissSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables the artwork button when the session has no playlist target', () => {
|
||||
const artwork = fixture.debugElement.query(
|
||||
By.css('.external-playback-dock__artwork')
|
||||
|
||||
+8
-15
@@ -104,16 +104,9 @@ export class ExternalPlaybackDockComponent {
|
||||
readonly artworkInteractive = computed(
|
||||
() => !!this.session().contentInfo?.playlistId
|
||||
);
|
||||
readonly showActionButton = computed(
|
||||
() => this.session().status === 'error' || this.session().canClose
|
||||
);
|
||||
readonly actionLabelKey = computed(() =>
|
||||
this.session().status === 'error'
|
||||
? 'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_DISMISS'
|
||||
: 'WORKSPACE.SHELL.EXTERNAL_PLAYBACK_CLOSE'
|
||||
);
|
||||
readonly actionIcon = computed(() =>
|
||||
this.session().status === 'error' ? 'close' : 'stop_circle'
|
||||
readonly showCloseAction = computed(() => this.session().canClose);
|
||||
readonly showDismissAction = computed(
|
||||
() => this.session().status === 'error' && !this.session().canClose
|
||||
);
|
||||
|
||||
constructor() {
|
||||
@@ -132,11 +125,11 @@ export class ExternalPlaybackDockComponent {
|
||||
this.artworkClicked.emit();
|
||||
}
|
||||
|
||||
onActionClick(): void {
|
||||
if (this.session().status === 'error') {
|
||||
this.dismissClicked.emit();
|
||||
return;
|
||||
}
|
||||
onCloseClick(): void {
|
||||
this.closeClicked.emit();
|
||||
}
|
||||
|
||||
onDismissClick(): void {
|
||||
this.dismissClicked.emit();
|
||||
}
|
||||
}
|
||||
@@ -251,7 +251,11 @@ export class VodDetailsComponent {
|
||||
|
||||
async onPrimaryAction(): Promise<void> {
|
||||
if (this.isExternalStopAction()) {
|
||||
await this.stopExternalPlayback();
|
||||
try {
|
||||
await this.stopExternalPlayback();
|
||||
} catch {
|
||||
// The dock stays visible when process teardown is unconfirmed.
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+32
@@ -83,6 +83,38 @@ describe('ExternalPlaybackRecoveryCoordinator', () => {
|
||||
coordinator.destroy();
|
||||
});
|
||||
|
||||
it('closes a closable error before retrying another external target', async () => {
|
||||
const previous = session({
|
||||
id: 'uncertain-process',
|
||||
status: 'error',
|
||||
error: 'Process exit was not confirmed',
|
||||
canClose: true,
|
||||
});
|
||||
const activeSession = signal<ExternalPlayerSession | null>(previous);
|
||||
const closeSession = jest.fn(async () => {
|
||||
activeSession.set({
|
||||
...previous,
|
||||
status: 'closed',
|
||||
canClose: false,
|
||||
});
|
||||
});
|
||||
const coordinator = new ExternalPlaybackRecoveryCoordinator({
|
||||
activeSession,
|
||||
visibleSession: activeSession,
|
||||
closeSession,
|
||||
dismissActiveSession: jest.fn(),
|
||||
});
|
||||
coordinator.syncSession('content-a');
|
||||
const ready = jest.fn(() => true);
|
||||
|
||||
coordinator.request('vlc', jest.fn(), ready);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(closeSession).toHaveBeenCalledWith(previous);
|
||||
expect(ready).toHaveBeenCalledTimes(1);
|
||||
coordinator.destroy();
|
||||
});
|
||||
|
||||
it('cancels an intent when launch ownership disappears during close', async () => {
|
||||
const previous = session({ id: 'previous', player: 'mpv' });
|
||||
const activeSession = signal<ExternalPlayerSession | null>(previous);
|
||||
|
||||
@@ -113,6 +113,7 @@ function isLiveExternalSession(
|
||||
return (
|
||||
session?.status === 'launching' ||
|
||||
session?.status === 'opened' ||
|
||||
session?.status === 'playing'
|
||||
session?.status === 'playing' ||
|
||||
(session?.status === 'error' && session.canClose)
|
||||
);
|
||||
}
|
||||
+11
@@ -1085,6 +1085,17 @@ describe('WorkspaceShellFacade', () => {
|
||||
expect(externalPlayback.closeSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles a rejected external-session close', async () => {
|
||||
const externalPlayback = TestBed.inject(PORTAL_EXTERNAL_PLAYBACK);
|
||||
const closeSession = externalPlayback.closeSession as jest.Mock;
|
||||
closeSession.mockRejectedValueOnce(new Error('close failed'));
|
||||
|
||||
facade.closeActiveExternalSession();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(closeSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('waits for embedded MPV support preload before opening the palette', async () => {
|
||||
const dialog = TestBed.inject(MatDialog) as unknown as {
|
||||
open: jest.Mock;
|
||||
|
||||
+3
-3
@@ -156,9 +156,9 @@ export class WorkspaceShellFacade {
|
||||
}
|
||||
|
||||
closeActiveExternalSession(): void {
|
||||
void this.externalPlayback.closeSession(
|
||||
this.externalPlayback.activeSession()
|
||||
);
|
||||
void this.externalPlayback
|
||||
.closeSession(this.externalPlayback.activeSession())
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
dismissActiveExternalSession(): void {
|
||||
|
||||
Reference in new issue
Block a user