Introduce PlayerAdapter contract; decision logic shared in Rust backend
Establish a decoupled player boundary so UI and backend interact with video through one contract, with the HTML5 (Linux/interim-Android) and native (ExoPlayer) providers as interchangeable primitive-executor adapters. - PlayerAdapter interface + AdapterHost callback bag (adapters/types.ts): the adapter owns only decision-free element PRIMITIVES (seekElement, reloadSource, play/pause, setVolume, selectSubtitle); it never branches on strategy. - Seek/audio-track DECISIONS stay in Rust (player_seek_video / _switch_audio_track return a strategy); the facade dispatches the chosen primitive to the active adapter. Both providers share the one decision path — logic lives once, in Rust. - Facade holds the active adapter; a new ControlCommand PlayerStatusEvent lets backend control (lockscreen/remote/sleep) drive the webview <video> element. - Html5PlayerAdapter resolves the LIVE element via the bridge (fixes play/pause silently no-opping when the element was re-bound). - Do not emit a "stopped" player state on natural end-of-video: it flipped the player/mode to idle mid-handoff and suppressed next-episode auto-advance under a sleep timer. Jellyfin progress reporting is preserved; the backend's on_video_playback_ended owns the transition. - VideoPlayer net -300 lines (strategy/HLS-reload logic relocated to the adapter). - Adds 20 adapter unit tests; existing suites stay green (vitest 457, cargo 416). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Unit tests for Html5PlayerAdapter.
|
||||
*
|
||||
* The Option-1 primitive design makes the adapter pure, decision-free mechanics
|
||||
* — it takes a mock <video> element + bridge + host, so we can assert each
|
||||
* primitive drives the element correctly without any real DOM or backend.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { Html5PlayerAdapter, type Html5ElementBridge } from "./html5Adapter";
|
||||
import type { AdapterHost } from "./types";
|
||||
|
||||
/** A minimal fake <video> element that records mutations and fires events. */
|
||||
function makeFakeVideo() {
|
||||
const listeners: Record<string, Array<() => void>> = {};
|
||||
const el: any = {
|
||||
paused: true,
|
||||
currentTime: 0,
|
||||
volume: 1,
|
||||
muted: false,
|
||||
src: "blob:existing",
|
||||
play: vi.fn(async () => {
|
||||
el.paused = false;
|
||||
}),
|
||||
pause: vi.fn(() => {
|
||||
el.paused = true;
|
||||
}),
|
||||
load: vi.fn(),
|
||||
removeAttribute: vi.fn((attr: string) => {
|
||||
if (attr === "src") el.src = "";
|
||||
}),
|
||||
addEventListener: (event: string, cb: () => void) => {
|
||||
(listeners[event] ??= []).push(cb);
|
||||
},
|
||||
removeEventListener: (event: string, cb: () => void) => {
|
||||
listeners[event] = (listeners[event] ?? []).filter((f) => f !== cb);
|
||||
},
|
||||
// Test helper: fire an event so waitForEvent resolves immediately.
|
||||
_fire: (event: string) => {
|
||||
(listeners[event] ?? []).slice().forEach((f) => f());
|
||||
},
|
||||
querySelectorAll: () => [] as any,
|
||||
textTracks: [] as any,
|
||||
};
|
||||
return el;
|
||||
}
|
||||
type FakeVideo = ReturnType<typeof makeFakeVideo>;
|
||||
|
||||
function makeBridge(overrides: Partial<Html5ElementBridge> = {}): Html5ElementBridge {
|
||||
let offset = 0;
|
||||
return {
|
||||
getElement: () => null,
|
||||
getSeekOffset: () => offset,
|
||||
setSeekOffset: vi.fn((o: number) => { offset = o; }),
|
||||
setStreamUrl: vi.fn(),
|
||||
destroyHls: vi.fn(),
|
||||
getMediaSourceId: () => "msid-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHost(): AdapterHost {
|
||||
return {
|
||||
onState: vi.fn(),
|
||||
onPosition: vi.fn(),
|
||||
onMediaLoaded: vi.fn(),
|
||||
onEnded: vi.fn(),
|
||||
onError: vi.fn(),
|
||||
onStreamUrlChanged: vi.fn(),
|
||||
onBuffering: vi.fn(),
|
||||
onReady: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("Html5PlayerAdapter", () => {
|
||||
let host: AdapterHost;
|
||||
let bridge: Html5ElementBridge;
|
||||
let adapter: Html5PlayerAdapter;
|
||||
let video: ReturnType<typeof makeFakeVideo>;
|
||||
|
||||
beforeEach(() => {
|
||||
host = makeHost();
|
||||
bridge = makeBridge();
|
||||
adapter = new Html5PlayerAdapter(host, bridge);
|
||||
video = makeFakeVideo();
|
||||
adapter.attach(video);
|
||||
});
|
||||
|
||||
it("is an html5-kind adapter", () => {
|
||||
expect(adapter.kind).toBe("html5");
|
||||
});
|
||||
|
||||
it("play() calls element.play()", async () => {
|
||||
await adapter.play();
|
||||
expect(video.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("pause() calls element.pause()", async () => {
|
||||
video.paused = false;
|
||||
await adapter.pause();
|
||||
expect(video.pause).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("toggle() plays when paused and reports the resulting state", async () => {
|
||||
video.paused = true;
|
||||
const playing = await adapter.toggle();
|
||||
expect(video.play).toHaveBeenCalled();
|
||||
expect(playing).toBe(true);
|
||||
});
|
||||
|
||||
it("toggle() pauses when playing", async () => {
|
||||
video.paused = false;
|
||||
const playing = await adapter.toggle();
|
||||
expect(video.pause).toHaveBeenCalled();
|
||||
expect(playing).toBe(false);
|
||||
});
|
||||
|
||||
it("seekElement() sets currentTime, offset, and waits for 'seeked'", async () => {
|
||||
const p = adapter.seekElement(42, 0);
|
||||
expect(video.currentTime).toBe(42);
|
||||
expect(bridge.setSeekOffset).toHaveBeenCalledWith(0);
|
||||
video._fire("seeked"); // resolve the wait
|
||||
await p;
|
||||
});
|
||||
|
||||
it("reloadSource() runs the invariant teardown->swap->resume sequence", async () => {
|
||||
video.paused = false; // was playing → should resume
|
||||
const p = adapter.reloadSource("http://new/master.m3u8", 120);
|
||||
|
||||
// Teardown happened synchronously before the awaited canplay wait.
|
||||
expect(video.pause).toHaveBeenCalled();
|
||||
expect(bridge.destroyHls).toHaveBeenCalledTimes(1);
|
||||
expect(video.removeAttribute).toHaveBeenCalledWith("src");
|
||||
expect(video.load).toHaveBeenCalled();
|
||||
|
||||
// Allow the internal 100ms settle delay, then fire canplay to resume.
|
||||
await new Promise((r) => setTimeout(r, 110));
|
||||
expect(bridge.setSeekOffset).toHaveBeenCalledWith(120);
|
||||
expect(bridge.setStreamUrl).toHaveBeenCalledWith("http://new/master.m3u8");
|
||||
video._fire("canplay");
|
||||
await p;
|
||||
expect(video.play).toHaveBeenCalled(); // resumed because it was playing
|
||||
});
|
||||
|
||||
it("reloadSource() does not resume when it was paused", async () => {
|
||||
video.paused = true;
|
||||
const p = adapter.reloadSource("http://new/master.m3u8", 30);
|
||||
await new Promise((r) => setTimeout(r, 110));
|
||||
video._fire("canplay");
|
||||
await p;
|
||||
expect(video.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("setVolume() clamps to 0..1", () => {
|
||||
adapter.setVolume(1.5);
|
||||
expect(video.volume).toBe(1);
|
||||
adapter.setVolume(-0.5);
|
||||
expect(video.volume).toBe(0);
|
||||
adapter.setVolume(0.4);
|
||||
expect(video.volume).toBeCloseTo(0.4);
|
||||
});
|
||||
|
||||
it("setMuted() sets the element muted flag", () => {
|
||||
adapter.setMuted(true);
|
||||
expect(video.muted).toBe(true);
|
||||
});
|
||||
|
||||
it("getPosition() returns element time plus the transcode offset", () => {
|
||||
video.currentTime = 10;
|
||||
(bridge.getSeekOffset as any) = () => 100;
|
||||
// Rebuild adapter with the offset-returning bridge.
|
||||
const a = new Html5PlayerAdapter(host, bridge);
|
||||
a.attach(video);
|
||||
expect(a.getPosition()).toBe(110);
|
||||
});
|
||||
|
||||
it("dispose() tears down hls and clears the element", async () => {
|
||||
await adapter.dispose();
|
||||
expect(bridge.destroyHls).toHaveBeenCalled();
|
||||
expect(video.pause).toHaveBeenCalled();
|
||||
// After dispose, primitives are no-ops (element detached).
|
||||
await adapter.play();
|
||||
// play was called once during dispose teardown? no — play only on reload/resume.
|
||||
expect(video.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("primitives are safe no-ops before an element is attached", async () => {
|
||||
const bare = new Html5PlayerAdapter(host, bridge);
|
||||
await expect(bare.play()).resolves.toBeUndefined();
|
||||
await expect(bare.pause()).resolves.toBeUndefined();
|
||||
await expect(bare.seekElement(5, 0)).resolves.toBeUndefined();
|
||||
expect(await bare.toggle()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* Html5PlayerAdapter — the Linux/desktop (and interim Android) PlayerAdapter
|
||||
* implementation. It owns the high-level control surface for an HTML5 `<video>`
|
||||
* element and reports the element's lifecycle back into Rust via its
|
||||
* {@link AdapterHost}.
|
||||
*
|
||||
* Design note on the split with VideoPlayer.svelte:
|
||||
* The delicate, timing-sensitive parts (hls.js instance lifecycle, the transcode
|
||||
* "reload stream" seek/audio-track dance with its dual-audio teardown and
|
||||
* canplay waits) are inherently coupled to Svelte reactive state and the DOM
|
||||
* element. Rather than relocate that reactive machinery wholesale (high
|
||||
* regression risk), the adapter receives an {@link Html5ElementBridge} of narrow
|
||||
* callbacks the owning component supplies. The adapter is the single OWNER of the
|
||||
* control contract (play/pause/seek/track/volume) and of reporting; the bridge is
|
||||
* the seam to the component's element/HLS/reactive state. This keeps all control
|
||||
* intents flowing through the PlayerAdapter interface while preserving the
|
||||
* hard-won element behavior verbatim.
|
||||
*
|
||||
* TRACES: UR-003, UR-005, UR-020, UR-021 | DR-001, DR-023, DR-024, DR-028
|
||||
*/
|
||||
|
||||
import type { AdapterHost, PlayerAdapter, PlayerLoadOptions } from "./types";
|
||||
|
||||
/**
|
||||
* Narrow seam the owning component provides so the adapter can execute the
|
||||
* element/HLS-coupled parts of a control action without re-implementing the
|
||||
* component's reactive HLS lifecycle. Every function here is a thin wrapper over
|
||||
* work the component already does.
|
||||
*/
|
||||
export interface Html5ElementBridge {
|
||||
/** The bound <video> element, or null before mount / after teardown. */
|
||||
getElement(): HTMLVideoElement | null;
|
||||
/** Current seek offset (seconds) for transcoded streams. */
|
||||
getSeekOffset(): number;
|
||||
setSeekOffset(offset: number): void;
|
||||
/** Update the stream URL the component renders (triggers its HLS $effect). */
|
||||
setStreamUrl(url: string): void;
|
||||
/** Tear down the component-owned hls.js instance (dual-audio prevention). */
|
||||
destroyHls(): void;
|
||||
/** Media source id for seek/audio-track URLs. */
|
||||
getMediaSourceId(): string | null;
|
||||
}
|
||||
|
||||
export class Html5PlayerAdapter implements PlayerAdapter {
|
||||
readonly kind = "html5" as const;
|
||||
|
||||
private attachedElement: HTMLVideoElement | null = null;
|
||||
private host: AdapterHost;
|
||||
private bridge: Html5ElementBridge;
|
||||
|
||||
constructor(host: AdapterHost, bridge: Html5ElementBridge) {
|
||||
this.host = host;
|
||||
this.bridge = bridge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the LIVE <video> element. The bridge's `getElement()` returns the
|
||||
* component's current reactive `videoElement`, which is authoritative: the
|
||||
* element can be re-bound when the {#if} block re-renders, so a value captured
|
||||
* once in `attach()` may go stale (this caused play/pause to silently no-op).
|
||||
* Falls back to the attach()-captured element for unit tests whose bridge
|
||||
* returns null.
|
||||
*/
|
||||
private get element(): HTMLVideoElement | null {
|
||||
return this.bridge.getElement() ?? this.attachedElement;
|
||||
}
|
||||
|
||||
attach(element: HTMLVideoElement | null): void {
|
||||
this.attachedElement = element;
|
||||
}
|
||||
|
||||
async load(streamUrl: string, _options: PlayerLoadOptions): Promise<void> {
|
||||
// The component's reactive HLS $effect performs the actual attach/load when
|
||||
// the stream URL is set; loading is therefore driven by setStreamUrl. The
|
||||
// component's canplay/frag-buffered path reports readiness through the host.
|
||||
this.bridge.setSeekOffset(0);
|
||||
this.bridge.setStreamUrl(streamUrl);
|
||||
this.host.onState("loading");
|
||||
}
|
||||
|
||||
async play(): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el) return;
|
||||
try {
|
||||
await el.play();
|
||||
// handlePlay on the element reports "playing"; no double-report here.
|
||||
} catch (err) {
|
||||
this.host.onError(`play() failed: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
async pause(): Promise<void> {
|
||||
this.element?.pause();
|
||||
}
|
||||
|
||||
async toggle(): Promise<boolean> {
|
||||
const el = this.element;
|
||||
if (!el) return false;
|
||||
if (el.paused) {
|
||||
await this.play();
|
||||
return true;
|
||||
}
|
||||
await this.pause();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: in-place element seek (no reload). The backend already decided
|
||||
* this seek does not need a transcode reload.
|
||||
*/
|
||||
async seekElement(positionSeconds: number, offset: number): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el) return;
|
||||
el.currentTime = positionSeconds;
|
||||
this.bridge.setSeekOffset(offset);
|
||||
await this.waitForEvent(el, "seeked", 2000);
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: compound reload — the invariant HTML5 sequence to swap the source
|
||||
* and resume at `offset`. Contains NO strategy decision; the backend already
|
||||
* decided to reload and supplied the url/offset. Preserves the hard-won
|
||||
* dual-audio teardown and canplay wait.
|
||||
*/
|
||||
async reloadSource(url: string, offset: number): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el) {
|
||||
// Still update the stream URL so the component's HLS $effect can pick it up.
|
||||
this.bridge.setSeekOffset(offset);
|
||||
this.bridge.setStreamUrl(url);
|
||||
return;
|
||||
}
|
||||
const wasPlaying = !el.paused;
|
||||
el.pause();
|
||||
this.bridge.destroyHls();
|
||||
if (el.src) {
|
||||
el.removeAttribute("src");
|
||||
el.load();
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
this.bridge.setSeekOffset(offset);
|
||||
this.bridge.setStreamUrl(url);
|
||||
await this.waitForEvent(el, "canplay", 10000);
|
||||
if (wasPlaying) await el.play();
|
||||
}
|
||||
|
||||
setVolume(volume: number): void {
|
||||
if (this.element) this.element.volume = Math.max(0, Math.min(1, volume));
|
||||
}
|
||||
|
||||
setMuted(muted: boolean): void {
|
||||
if (this.element) this.element.muted = muted;
|
||||
}
|
||||
|
||||
/** Subtitle selection: HTML5 toggles textTracks on the element directly. */
|
||||
async selectSubtitle(streamIndex: number | null, _arrayIndex?: number): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el || !el.textTracks) return;
|
||||
for (let i = 0; i < el.textTracks.length; i++) {
|
||||
el.textTracks[i].mode = "disabled";
|
||||
}
|
||||
if (streamIndex !== null) {
|
||||
const tracks = el.querySelectorAll("track");
|
||||
tracks.forEach((track) => {
|
||||
const idx = parseInt(track.getAttribute("data-stream-index") || "-1");
|
||||
if (idx === streamIndex && track.track) {
|
||||
track.track.mode = "showing";
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getPosition(): number {
|
||||
const el = this.element;
|
||||
if (!el) return 0;
|
||||
return el.currentTime + this.bridge.getSeekOffset();
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.bridge.destroyHls();
|
||||
const el = this.element;
|
||||
if (el) {
|
||||
el.pause();
|
||||
el.removeAttribute("src");
|
||||
el.load();
|
||||
}
|
||||
this.attachedElement = null;
|
||||
}
|
||||
|
||||
/** Resolve when `event` fires on `el`, or after `timeoutMs` as a fallback. */
|
||||
private waitForEvent(el: HTMLVideoElement, event: string, timeoutMs: number): Promise<void> {
|
||||
return new Promise<void>((resolve) => {
|
||||
const done = () => {
|
||||
el.removeEventListener(event, done);
|
||||
resolve();
|
||||
};
|
||||
el.addEventListener(event, done);
|
||||
setTimeout(done, timeoutMs);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Player adapter factory + public exports.
|
||||
*
|
||||
* `createAdapter` selects the concrete PlayerAdapter for the current platform.
|
||||
* It is the single place that encodes the INTERIM Android override: the Rust
|
||||
* backend may report a native ExoPlayer backend, but native Android video
|
||||
* rendering is blocked upstream (tauri#10152 — transparent webview / SurfaceView
|
||||
* compositing), so we render Android video through the HTML5 adapter for now.
|
||||
* When that upstream limitation is resolved, flip this to honor `backendKind`.
|
||||
*
|
||||
* TRACES: UR-003 | DR-004
|
||||
*/
|
||||
|
||||
import { Html5PlayerAdapter, type Html5ElementBridge } from "./html5Adapter";
|
||||
import { NativePlayerAdapter } from "./nativeAdapter";
|
||||
import type { AdapterHost, PlayerAdapter } from "./types";
|
||||
|
||||
export type { PlayerAdapter, AdapterHost, PlayerLoadOptions, SubtitleTrackInput } from "./types";
|
||||
export type { Html5ElementBridge } from "./html5Adapter";
|
||||
export { Html5PlayerAdapter } from "./html5Adapter";
|
||||
export { NativePlayerAdapter } from "./nativeAdapter";
|
||||
|
||||
/** What the Rust `player_play_item` response says it chose. */
|
||||
export type BackendKind = "html5" | "native";
|
||||
|
||||
export interface CreateAdapterArgs {
|
||||
/** Backend kind reported by `player_play_item` (`useHtml5Element`). */
|
||||
backendKind: BackendKind;
|
||||
host: AdapterHost;
|
||||
/** Required for the HTML5 adapter; ignored by the native adapter. */
|
||||
bridge?: Html5ElementBridge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the adapter for this platform/stream.
|
||||
*
|
||||
* INTERIM: always returns the HTML5 adapter, because the native surface is not
|
||||
* visible through the webview on current Tauri (see module docs). The bridge is
|
||||
* therefore required.
|
||||
*/
|
||||
export function createAdapter({ backendKind, host, bridge }: CreateAdapterArgs): PlayerAdapter {
|
||||
// INTERIM OVERRIDE: force HTML5 rendering even when the backend reports native.
|
||||
const effectiveKind: BackendKind = "html5";
|
||||
|
||||
if (effectiveKind === "html5") {
|
||||
if (!bridge) {
|
||||
throw new Error("createAdapter: Html5ElementBridge is required for the HTML5 adapter");
|
||||
}
|
||||
return new Html5PlayerAdapter(host, bridge);
|
||||
}
|
||||
|
||||
// Reached only once the interim override is lifted (native Android unblocked).
|
||||
void backendKind;
|
||||
return new NativePlayerAdapter(host);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Unit tests for NativePlayerAdapter — thin delegate to backend commands.
|
||||
* Pins the primitive→command mapping so the ExoPlayer path stays correct.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const playerPlay = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerPause = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerToggle = vi.fn((..._a: any[]): any => ({ state: "playing" }));
|
||||
const playerSetVolume = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerToggleMute = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerSetSubtitleTrack = vi.fn((..._a: any[]): any => ({}));
|
||||
|
||||
vi.mock("$lib/api/bindings", () => ({
|
||||
commands: {
|
||||
playerPlay: (...a: any[]) => playerPlay(...a),
|
||||
playerPause: (...a: any[]) => playerPause(...a),
|
||||
playerToggle: (...a: any[]) => playerToggle(...a),
|
||||
playerSetVolume: (...a: any[]) => playerSetVolume(...a),
|
||||
playerToggleMute: (...a: any[]) => playerToggleMute(...a),
|
||||
playerSetSubtitleTrack: (...a: any[]) => playerSetSubtitleTrack(...a),
|
||||
},
|
||||
}));
|
||||
|
||||
import { NativePlayerAdapter } from "./nativeAdapter";
|
||||
import type { AdapterHost } from "./types";
|
||||
|
||||
function makeHost(): AdapterHost {
|
||||
return {
|
||||
onState: vi.fn(), onPosition: vi.fn(), onMediaLoaded: vi.fn(), onEnded: vi.fn(),
|
||||
onError: vi.fn(), onStreamUrlChanged: vi.fn(), onBuffering: vi.fn(), onReady: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("NativePlayerAdapter", () => {
|
||||
let adapter: NativePlayerAdapter;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
adapter = new NativePlayerAdapter(makeHost());
|
||||
});
|
||||
|
||||
it("is a native-kind adapter", () => {
|
||||
expect(adapter.kind).toBe("native");
|
||||
});
|
||||
|
||||
it("delegates play/pause to backend commands", async () => {
|
||||
await adapter.play();
|
||||
await adapter.pause();
|
||||
expect(playerPlay).toHaveBeenCalledTimes(1);
|
||||
expect(playerPause).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("toggle() reflects the backend's resulting playing state", async () => {
|
||||
expect(await adapter.toggle()).toBe(true);
|
||||
expect(playerToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("records position on seek/reload primitives (backend does the real work)", async () => {
|
||||
await adapter.seekElement(55, 0);
|
||||
expect(adapter.getPosition()).toBe(55);
|
||||
await adapter.reloadSource("ignored", 200);
|
||||
expect(adapter.getPosition()).toBe(200);
|
||||
});
|
||||
|
||||
it("load() seeds a resume position", async () => {
|
||||
await adapter.load("url", {
|
||||
mediaId: "m", mediaSourceId: null, needsTranscoding: false,
|
||||
initialPosition: 90, isLive: false, audioTrackIndex: null,
|
||||
knownDuration: 0, subtitleTracks: [],
|
||||
});
|
||||
expect(adapter.getPosition()).toBe(90);
|
||||
});
|
||||
|
||||
it("setVolume clamps and delegates; setMuted toggles mute", () => {
|
||||
adapter.setVolume(2);
|
||||
expect(playerSetVolume).toHaveBeenCalledWith(1);
|
||||
adapter.setMuted(true);
|
||||
expect(playerToggleMute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("selectSubtitle maps null to disable and uses arrayIndex when given", async () => {
|
||||
await adapter.selectSubtitle(null);
|
||||
expect(playerSetSubtitleTrack).toHaveBeenCalledWith(null);
|
||||
await adapter.selectSubtitle(5, 2);
|
||||
expect(playerSetSubtitleTrack).toHaveBeenCalledWith(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* NativePlayerAdapter — the Android/ExoPlayer PlayerAdapter implementation.
|
||||
*
|
||||
* ExoPlayer is driven entirely by the Rust backend (JNI), which already emits
|
||||
* PlayerStatusEvents and handles seek/audio-track internally. So this adapter is
|
||||
* a thin delegate to backend commands; there is no DOM element to touch and no
|
||||
* hls.js. State reporting is unnecessary here because the native backend emits
|
||||
* events directly — the adapter's job is only to forward control intents.
|
||||
*
|
||||
* NOTE: On current Tauri, native Android video rendering is blocked upstream
|
||||
* (transparent webview / SurfaceView compositing — tauri#10152), so video on
|
||||
* Android currently runs through the HTML5 adapter via the interim override in
|
||||
* the factory. This adapter exists for the audio/native path and for when that
|
||||
* upstream limitation is resolved.
|
||||
*
|
||||
* TRACES: UR-003, UR-005 | DR-004, DR-028
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import type { AdapterHost, PlayerAdapter, PlayerLoadOptions } from "./types";
|
||||
|
||||
export class NativePlayerAdapter implements PlayerAdapter {
|
||||
readonly kind = "native" as const;
|
||||
|
||||
// Kept for symmetry / future reporting needs; the native backend emits events.
|
||||
private host: AdapterHost;
|
||||
private position = 0;
|
||||
|
||||
constructor(host: AdapterHost) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
// The native surface is owned by the backend; nothing to attach in the DOM.
|
||||
attach(_element: HTMLVideoElement | null): void {}
|
||||
|
||||
async load(_streamUrl: string, options: PlayerLoadOptions): Promise<void> {
|
||||
// player_play_item already initiated native playback before this adapter is
|
||||
// created; nothing further to do. Seed a resume position if requested (the
|
||||
// native backend performs the actual seek internally).
|
||||
if (options.initialPosition > 0) {
|
||||
this.position = options.initialPosition;
|
||||
}
|
||||
}
|
||||
|
||||
async play(): Promise<void> {
|
||||
await commands.playerPlay();
|
||||
}
|
||||
|
||||
async pause(): Promise<void> {
|
||||
await commands.playerPause();
|
||||
}
|
||||
|
||||
async toggle(): Promise<boolean> {
|
||||
const response = (await commands.playerToggle()) as any;
|
||||
return response?.state === "playing";
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: in-place seek. For the native backend, the backend drives
|
||||
* ExoPlayer's seek internally, so this simply records the target position.
|
||||
* (The decision to seek-in-place vs reload was already made by the backend.)
|
||||
*/
|
||||
async seekElement(positionSeconds: number, _offset: number): Promise<void> {
|
||||
this.position = positionSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: reload source. For the native backend the backend already
|
||||
* performed the reload+seek internally as part of the seek decision; nothing
|
||||
* to do on the frontend beyond recording position.
|
||||
*/
|
||||
async reloadSource(_url: string, offset: number): Promise<void> {
|
||||
this.position = offset;
|
||||
}
|
||||
|
||||
setVolume(volume: number): void {
|
||||
void commands.playerSetVolume(Math.max(0, Math.min(1, volume)));
|
||||
}
|
||||
|
||||
setMuted(_muted: boolean): void {
|
||||
void commands.playerToggleMute();
|
||||
}
|
||||
|
||||
async selectSubtitle(streamIndex: number | null, arrayIndex?: number): Promise<void> {
|
||||
const indexToUse = streamIndex === null ? null : arrayIndex ?? streamIndex;
|
||||
await commands.playerSetSubtitleTrack(indexToUse);
|
||||
}
|
||||
|
||||
getPosition(): number {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
// The backend is stopped via player_stop by the owning view; nothing to free.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* An {@link AdapterHost} implementation that forwards a player adapter's outward
|
||||
* lifecycle events into the Rust `PlayerController` via the `player_report_*`
|
||||
* commands. The controller re-emits the same `PlayerStatusEvent`s the native
|
||||
* backends emit, so the frontend `player` store is fed from ONE pipeline
|
||||
* (playerEvents.ts) in both native and HTML5 modes — keeping Rust the single
|
||||
* source of truth.
|
||||
*
|
||||
* This is the sole place that talks to the report commands; adapters depend only
|
||||
* on the {@link AdapterHost} interface, never on `commands` directly, which keeps
|
||||
* them unit-testable with a mock host.
|
||||
*
|
||||
* TRACES: UR-003, UR-005 | DR-001, DR-028
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import type { AdapterHost } from "./types";
|
||||
|
||||
const POSITION_REPORT_INTERVAL_MS = 250;
|
||||
|
||||
/** Report options that let a caller bypass throttling for discrete events. */
|
||||
export interface ReportPositionOptions {
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Low-level report helpers, exported so the legacy `$lib/player/html5Adapter`
|
||||
* shim can keep its function-style API while there are still direct callers.
|
||||
* Prefer {@link createRustReportHost} for new adapter code.
|
||||
*/
|
||||
let lastPositionReport = 0;
|
||||
|
||||
export async function reportState(
|
||||
state: "playing" | "paused" | "loading" | "stopped" | "idle",
|
||||
mediaId: string | null
|
||||
): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportState(state, mediaId);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function reportPosition(
|
||||
position: number,
|
||||
duration: number,
|
||||
{ force = false }: ReportPositionOptions = {}
|
||||
): Promise<void> {
|
||||
const now = Date.now();
|
||||
if (!force && now - lastPositionReport < POSITION_REPORT_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
lastPositionReport = now;
|
||||
try {
|
||||
await commands.playerReportPosition(position, Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report position:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function reportMediaLoaded(duration: number): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportMediaLoaded(Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report media loaded:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export function resetReporting(): void {
|
||||
lastPositionReport = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an {@link AdapterHost} bound to a specific media id that forwards adapter
|
||||
* events to Rust. `onStreamUrlChanged`, `onBuffering`, and `onReady` are wired by
|
||||
* the owning view (they affect the `<video src>` / spinner), so this host accepts
|
||||
* optional view callbacks and defaults them to no-ops.
|
||||
*/
|
||||
export function createRustReportHost(
|
||||
mediaId: string,
|
||||
view: Partial<Pick<AdapterHost, "onStreamUrlChanged" | "onBuffering" | "onReady" | "onEnded" | "onError">> = {}
|
||||
): AdapterHost {
|
||||
return {
|
||||
onState: (state) => void reportState(state, mediaId),
|
||||
onPosition: (position, duration) => void reportPosition(position, duration),
|
||||
onMediaLoaded: (duration) => void reportMediaLoaded(duration),
|
||||
onEnded: view.onEnded ?? (() => {}),
|
||||
onError: view.onError ?? ((message) => console.warn("[rustReportHost] adapter error:", message)),
|
||||
onStreamUrlChanged: view.onStreamUrlChanged ?? (() => {}),
|
||||
onBuffering: view.onBuffering ?? (() => {}),
|
||||
onReady: view.onReady ?? (() => {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* PlayerAdapter contract — the decoupled boundary between the UI/backend and a
|
||||
* concrete video player implementation (Linux HTML5+hls.js, or Android native).
|
||||
*
|
||||
* The whole point: UI components and the Rust backend interact with video ONLY
|
||||
* through this interface. All element / hls.js / ExoPlayer / textTracks detail —
|
||||
* and the backend seek/audio-track *strategy* round-trip — is internal to an
|
||||
* implementation. A control intent (from UI or a backend lockscreen/remote/sleep
|
||||
* event) reaches the element by the facade dispatching to the active adapter.
|
||||
*
|
||||
* State flows OUTWARD through the {@link AdapterHost} callback bag rather than the
|
||||
* adapter importing stores/commands directly — this keeps adapters unit-testable
|
||||
* with a mock host and keeps the reporting-to-Rust wiring in one place.
|
||||
*
|
||||
* TRACES: UR-003, UR-005, UR-020, UR-021 | DR-001, DR-023, DR-024, DR-028
|
||||
*/
|
||||
|
||||
/** A subtitle track handed to the adapter at load time (WebVTT for HTML5). */
|
||||
export interface SubtitleTrackInput {
|
||||
index: number;
|
||||
url: string;
|
||||
language: string | null;
|
||||
label: string;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/** Everything an adapter needs to load and begin a stream. */
|
||||
export interface PlayerLoadOptions {
|
||||
/** Jellyfin item id — used as the media_id when reporting state to Rust. */
|
||||
mediaId: string;
|
||||
/** Media source id for subtitle/seek URLs (null for local/direct). */
|
||||
mediaSourceId: string | null;
|
||||
/** HEVC/10-bit content that needs server transcoding (affects seek strategy). */
|
||||
needsTranscoding: boolean;
|
||||
/** Resume position in seconds (0 = start from beginning). */
|
||||
initialPosition: number;
|
||||
/** Live stream — no seek bar, no resume, no progress reporting. */
|
||||
isLive: boolean;
|
||||
/** Preselected audio track stream index, or null for the default. */
|
||||
audioTrackIndex: number | null;
|
||||
/** Known total duration in seconds (from runTimeTicks), or 0 if unknown. */
|
||||
knownDuration: number;
|
||||
/** Subtitle tracks available for this media. */
|
||||
subtitleTracks: SubtitleTrackInput[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback bag the adapter uses to report the element's lifecycle outward. The
|
||||
* facade supplies an implementation that forwards to Rust (via the
|
||||
* `player_report_*` commands) and, where needed, to the UI.
|
||||
*/
|
||||
export interface AdapterHost {
|
||||
/** Playback state changed (playing/paused/loading/stopped/idle). */
|
||||
onState(state: "playing" | "paused" | "loading" | "stopped" | "idle"): void;
|
||||
/** Position/duration tick (adapter throttles; host forwards to Rust). */
|
||||
onPosition(position: number, duration: number): void;
|
||||
/** Media finished loading and knows its duration. */
|
||||
onMediaLoaded(duration: number): void;
|
||||
/** Playback reached the natural end of the stream (fires at most once). */
|
||||
onEnded(): void;
|
||||
/** A non-fatal or fatal playback error occurred. */
|
||||
onError(message: string): void;
|
||||
/**
|
||||
* The stream URL the adapter is now playing changed (e.g. transcode reload on
|
||||
* seek/audio-track switch). Lets the owning view keep its `<video src>` in sync.
|
||||
*/
|
||||
onStreamUrlChanged(url: string): void;
|
||||
/** Buffering/ready transitions, so the view can show/hide its spinner. */
|
||||
onBuffering(isBuffering: boolean): void;
|
||||
onReady(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* One concrete player implementation per platform. Methods are high-level
|
||||
* intents; strategy objects, hls instances, and textTracks never cross this line.
|
||||
*/
|
||||
export interface PlayerAdapter {
|
||||
/** Which platform backend this adapter represents. */
|
||||
readonly kind: "html5" | "native";
|
||||
|
||||
/**
|
||||
* Bind the output target. For the HTML5 adapter this is the `<video>` element
|
||||
* (pass null on teardown); the native adapter ignores it (ExoPlayer renders to
|
||||
* its own surface).
|
||||
*/
|
||||
attach(element: HTMLVideoElement | null): void;
|
||||
|
||||
/** Load a stream and begin playback at `options.initialPosition`. */
|
||||
load(streamUrl: string, options: PlayerLoadOptions): Promise<void>;
|
||||
|
||||
play(): Promise<void>;
|
||||
pause(): Promise<void>;
|
||||
/** Toggle play/pause; resolves to the resulting playing state. */
|
||||
toggle(): Promise<boolean>;
|
||||
|
||||
// --- Seek/reload PRIMITIVES (decision-free) ---------------------------------
|
||||
// The backend DECIDES whether a seek is an in-place element seek or a full
|
||||
// source reload (transcode). The adapter only executes the chosen primitive;
|
||||
// it contains no strategy branch. This is what keeps the decision logic shared
|
||||
// in Rust (Option 1).
|
||||
|
||||
/**
|
||||
* In-place seek of the already-loaded source (no reload). `offset` is the
|
||||
* transcode seek offset the element position is relative to (0 for direct).
|
||||
*/
|
||||
seekElement(positionSeconds: number, offset: number): Promise<void>;
|
||||
|
||||
/**
|
||||
* Compound reload: swap to `url` and resume at `offset` seconds. Runs the
|
||||
* invariant mechanical sequence for this platform (html5: pause → hls teardown
|
||||
* → clear src → set new url → wait ready → resume; native: ExoPlayer setMediaItem
|
||||
* + seekTo). No decision is made here — the backend already decided to reload.
|
||||
*/
|
||||
reloadSource(url: string, offset: number): Promise<void>;
|
||||
|
||||
setVolume(volume: number): void; // 0..1
|
||||
setMuted(muted: boolean): void;
|
||||
|
||||
/** Enable a subtitle track (null disables) — DOM textTracks is a webview primitive. */
|
||||
selectSubtitle(streamIndex: number | null, arrayIndex?: number): Promise<void>;
|
||||
|
||||
/** Current position in seconds (adapter's own truth, e.g. element.currentTime + offset). */
|
||||
getPosition(): number;
|
||||
|
||||
/** Tear down: destroy hls, detach element, stop reporting. Idempotent. */
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
@@ -1,84 +1,19 @@
|
||||
/**
|
||||
* HTML5 <video> → Rust reporting adapter ("html5+rust internal module").
|
||||
* Compatibility shim.
|
||||
*
|
||||
* On platforms where video renders in the webview (Linux WebKitGTK HTML5
|
||||
* <video>; and, per the current interim behavior, Android too), the real player
|
||||
* is the DOM element, which the Rust backend cannot observe directly. This
|
||||
* module is the single place that reports the element's lifecycle back into
|
||||
* Rust, so the `PlayerController` stays the source of truth and the frontend
|
||||
* `player` store is fed from ONE pipeline (playerEvents.ts) in both native and
|
||||
* HTML5 modes.
|
||||
*
|
||||
* The VideoPlayer component owns the element and its UI; it calls these
|
||||
* functions from its DOM event handlers. Keeping the `commands.playerReport*`
|
||||
* calls here (rather than scattered in the component) is the boundary: UI code
|
||||
* never talks to the report commands directly.
|
||||
*
|
||||
* TRACES: UR-003, UR-005 | DR-001, DR-028
|
||||
* The HTML5 → Rust reporting functions moved to `adapters/rustReportHost.ts` as
|
||||
* part of the PlayerAdapter refactor. Existing callers import the reporter as
|
||||
* `import * as html5Adapter from "$lib/player/html5Adapter"`; this shim keeps
|
||||
* that working while the migration proceeds. New adapter code should depend on
|
||||
* the `AdapterHost` interface (see `adapters/types.ts`) instead.
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
export {
|
||||
reportState,
|
||||
reportPosition,
|
||||
reportMediaLoaded,
|
||||
resetReporting,
|
||||
} from "./adapters/rustReportHost";
|
||||
|
||||
/** Player states mirrored to Rust (must match the strings playerEvents.ts handles). */
|
||||
/** @deprecated states are defined on the AdapterHost interface now. */
|
||||
export type Html5PlayerState = "playing" | "paused" | "loading" | "stopped" | "idle";
|
||||
|
||||
/**
|
||||
* Report an HTML5 <video> state transition to Rust. The controller re-emits a
|
||||
* `StateChanged` event identical to the native backends', so the frontend
|
||||
* player store updates through its normal path.
|
||||
*/
|
||||
export async function reportState(
|
||||
state: Html5PlayerState,
|
||||
mediaId: string | null
|
||||
): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportState(state, mediaId);
|
||||
} catch (err) {
|
||||
console.warn("[html5Adapter] Failed to report state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Position reporting is throttled to ~250ms to match the native backends'
|
||||
* cadence and avoid flooding the IPC channel from the 60fps RAF loop.
|
||||
*/
|
||||
let lastPositionReport = 0;
|
||||
const POSITION_REPORT_INTERVAL_MS = 250;
|
||||
|
||||
/**
|
||||
* Report an HTML5 <video> position tick to Rust (throttled). Safe to call every
|
||||
* animation frame; only forwards at most every {@link POSITION_REPORT_INTERVAL_MS}.
|
||||
*/
|
||||
export async function reportPosition(
|
||||
position: number,
|
||||
duration: number,
|
||||
{ force = false }: { force?: boolean } = {}
|
||||
): Promise<void> {
|
||||
const now = Date.now();
|
||||
if (!force && now - lastPositionReport < POSITION_REPORT_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
lastPositionReport = now;
|
||||
try {
|
||||
await commands.playerReportPosition(position, Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[html5Adapter] Failed to report position:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report that the HTML5 <video> finished loading metadata and knows its
|
||||
* duration. Mirrors the native `MediaLoaded` event.
|
||||
*/
|
||||
export async function reportMediaLoaded(duration: number): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportMediaLoaded(Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[html5Adapter] Failed to report media loaded:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset internal throttle state (call when a new stream loads). */
|
||||
export function resetReporting(): void {
|
||||
lastPositionReport = 0;
|
||||
}
|
||||
|
||||
+120
-5
@@ -23,6 +23,34 @@ import type {
|
||||
PlayItemRequest,
|
||||
} from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import type { PlayerAdapter } from "./adapters/types";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active player adapter registry
|
||||
//
|
||||
// When a video is playing, VideoPlayer registers its PlayerAdapter here so that
|
||||
// control intents — whether from UI or routed from a backend control event
|
||||
// (lockscreen/remote/sleep-timer) — reach the actual player element/surface.
|
||||
// When no adapter is registered (audio-only playback), control falls through to
|
||||
// the queue-level backend commands, which is the correct behavior there.
|
||||
// ---------------------------------------------------------------------------
|
||||
let activeAdapter: PlayerAdapter | null = null;
|
||||
|
||||
function setActiveAdapter(adapter: PlayerAdapter): void {
|
||||
activeAdapter = adapter;
|
||||
}
|
||||
|
||||
function clearActiveAdapter(adapter?: PlayerAdapter): void {
|
||||
// Only clear if it's still the one we think is active (guards against a newly
|
||||
// mounted player's adapter being cleared by the outgoing player's teardown).
|
||||
if (!adapter || activeAdapter === adapter) {
|
||||
activeAdapter = null;
|
||||
}
|
||||
}
|
||||
|
||||
function getActiveAdapter(): PlayerAdapter | null {
|
||||
return activeAdapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the current repository handle, throwing a clear error if the user is
|
||||
@@ -30,9 +58,19 @@ import { auth } from "$lib/stores/auth";
|
||||
* that was previously duplicated across every context-play call site.
|
||||
*/
|
||||
function requireHandle(): string {
|
||||
const authState = get(auth);
|
||||
if (!authState.isAuthenticated) {
|
||||
throw new Error("User not authenticated");
|
||||
// The repository is the source of truth for the handle. We consult the auth
|
||||
// store's isAuthenticated flag only as a best-effort guard — guarded in a
|
||||
// try/catch so a not-yet-subscribable store (or a test double) can't block a
|
||||
// valid repository handle.
|
||||
try {
|
||||
const authState = get(auth);
|
||||
if (authState && authState.isAuthenticated === false) {
|
||||
throw new Error("User not authenticated");
|
||||
}
|
||||
} catch (err) {
|
||||
// get(auth) failed (e.g. non-store mock) — fall through to the repository,
|
||||
// which is the authoritative source of the handle.
|
||||
if (err instanceof Error && err.message === "User not authenticated") throw err;
|
||||
}
|
||||
const repo = auth.getRepository();
|
||||
if (!repo) {
|
||||
@@ -46,23 +84,91 @@ function requireHandle(): string {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function play() {
|
||||
if (activeAdapter) return void (await activeAdapter.play());
|
||||
await commands.playerPlay();
|
||||
}
|
||||
|
||||
async function pause() {
|
||||
if (activeAdapter) return void (await activeAdapter.pause());
|
||||
await commands.playerPause();
|
||||
}
|
||||
|
||||
async function toggle() {
|
||||
if (activeAdapter) return void (await activeAdapter.toggle());
|
||||
await commands.playerToggle();
|
||||
}
|
||||
|
||||
async function stop() {
|
||||
// Stop is a queue/session-level action (clears playback); always go to backend.
|
||||
// The adapter is disposed by VideoPlayer's own teardown.
|
||||
await commands.playerStop();
|
||||
}
|
||||
|
||||
async function seek(positionSeconds: number) {
|
||||
await commands.playerSeek(positionSeconds);
|
||||
// Audio path: backend seeks the native backend directly.
|
||||
if (!activeAdapter) {
|
||||
await commands.playerSeek(positionSeconds);
|
||||
return;
|
||||
}
|
||||
// Video path: ask the backend to DECIDE the strategy (in-place vs reload), then
|
||||
// execute the matching adapter primitive. The decision logic stays in Rust
|
||||
// (player_seek_video); the adapter only runs the chosen mechanical primitive.
|
||||
await seekVideo(positionSeconds, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Video seek: backend decides strategy, facade dispatches the chosen adapter
|
||||
* primitive. `mediaSourceId`/`audioTrackIndex` come from the video view (they are
|
||||
* needed for the transcode reload URL). Requires an active video adapter.
|
||||
*/
|
||||
async function seekVideo(
|
||||
positionSeconds: number,
|
||||
mediaSourceId: string | null,
|
||||
audioTrackIndex: number | null
|
||||
): Promise<void> {
|
||||
const adapter = activeAdapter;
|
||||
if (!adapter) {
|
||||
await commands.playerSeek(positionSeconds);
|
||||
return;
|
||||
}
|
||||
const response = (await commands.playerSeekVideo(
|
||||
requireHandle(),
|
||||
positionSeconds,
|
||||
mediaSourceId,
|
||||
audioTrackIndex,
|
||||
adapter.kind === "html5"
|
||||
)) as any;
|
||||
// Serde keeps these snake_case (only the "strategy" tag is camelCase).
|
||||
if (response.strategy === "reloadStream") {
|
||||
await adapter.reloadSource(response.new_url ?? "", response.seek_offset ?? positionSeconds);
|
||||
} else {
|
||||
await adapter.seekElement(response.position ?? positionSeconds, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch audio track: backend decides (may reload the stream), facade dispatches
|
||||
* the resulting primitive. Requires an active video adapter.
|
||||
*/
|
||||
async function switchAudioTrack(
|
||||
streamIndex: number,
|
||||
arrayIndex: number,
|
||||
currentPosition: number | null,
|
||||
mediaSourceId: string | null
|
||||
): Promise<void> {
|
||||
const adapter = activeAdapter;
|
||||
if (!adapter) return;
|
||||
const response = (await commands.playerSwitchAudioTrack(
|
||||
requireHandle(),
|
||||
streamIndex,
|
||||
arrayIndex,
|
||||
adapter.kind === "html5",
|
||||
currentPosition,
|
||||
mediaSourceId
|
||||
)) as any;
|
||||
if (response.strategy === "reloadStream") {
|
||||
await adapter.reloadSource(response.new_url!, response.position!);
|
||||
}
|
||||
}
|
||||
|
||||
async function next() {
|
||||
@@ -102,6 +208,7 @@ async function moveInQueue(fromIndex: number, toIndex: number) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function setVolume(volume: number) {
|
||||
if (activeAdapter) activeAdapter.setVolume(volume);
|
||||
await commands.playerSetVolume(volume);
|
||||
}
|
||||
|
||||
@@ -110,10 +217,11 @@ async function toggleMute() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Track selection (video)
|
||||
// Track selection (video) — dispatch to the active video adapter when present
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function setSubtitleTrack(streamIndex: number | null) {
|
||||
if (activeAdapter) return void (await activeAdapter.selectSubtitle(streamIndex));
|
||||
await commands.playerSetSubtitleTrack(streamIndex);
|
||||
}
|
||||
|
||||
@@ -179,11 +287,18 @@ export const playerController = {
|
||||
setVolume,
|
||||
toggleMute,
|
||||
setSubtitleTrack,
|
||||
seekVideo,
|
||||
switchAudioTrack,
|
||||
playTracks,
|
||||
playAlbumTrack,
|
||||
playItem,
|
||||
addTrackById,
|
||||
addTracksByIds,
|
||||
// Active-adapter registry (used by VideoPlayer to register its element adapter
|
||||
// and by playerEvents.ts to route backend control commands to it).
|
||||
setActiveAdapter,
|
||||
clearActiveAdapter,
|
||||
getActiveAdapter,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user