Follow the player's state while something needs it continuously: a window or panel that shows the position, a meter.
Receives the state now and at every change.
The open stream; it is stopped with the scope.
listener runs with the current state as soon as the SDK has it (one
read of the player's state right after the call), then with every
change the player sends: about ten times a second while playing, at
once when the phase, pause, speed or volume changes. Before each call
the SDK updates Player.state; after each call an update pass
runs, so View.bind functions and command states that read
plugin.player.state follow the stream: the stream is what makes the
state follow the player, while it is open.
While a stream is open the player keeps the plugin running: it is
a listener (its log names it a stream opened at main.ts:12). Open it
when the thing that shows the state appears and stop it when that goes
away; nothing of a stopped stream keeps the plugin running. A plugin
that only needs to know that something happened (a file opened, ready,
ended) uses Player.on with a source event instead, which lets
it go to standby.
Several streams may be open; each listener is called. A stream ends
with StateStream.stop, when its scope is disposed, and when the
plugin stops; it is not kept through standby. After the last one ends
plugin.player.state keeps the last snapshot and no longer follows
changes made elsewhere.
The player judges what keeps a plugin running when the plugin becomes
ready. A stream that is open then counts as it does today for a
listener held at the ready: the plugin keeps running for that run, also
after the stream stops. Open the stream after activate, when what
shows the state appears.
Errors the listener throws or rejects with go to Scope.onError, as for every handler.
A tool window shows how much of the file is left, updated as it plays. The stream starts when the window is shown and stops when the user closes it, so the plugin can go to standby afterwards.
const view = plugin.windows.create("ui/left.slint");
let feed: StateStream | undefined;
view.onClose(() => feed?.stop()); // closed: nothing keeps the plugin running
plugin.commands.add({
id: "left",
path: ["Tools", "Time Left"],
run: async () => {
await view.show();
feed?.stop(); // one stream per window, also when shown again
feed = plugin.player.stream((s) =>
view.set({ text: `${Math.round((s.duration ?? 0) - (s.position ?? 0))} s` }),
);
},
});
Listen to one event of the player, with its data as the player sent it: no state copy, no comparison.
The event's name.
Receives each event's data.
A handle that stops listening; it is disposed with the scope.
event is one of the HostEvent names ("source.state",
"window.state", "timeline.changed"…), whatever part of the plugin
API it concerns; listener gets a copy of that event's data, typed
EventPayload (source.state: the player's source state, with
rate, paused, position, stamp…). Each subscription counts as a
listener of the plugin: the player keeps the plugin running while one
exists (unless the event is one the player wakes a stopped plugin for),
and its log names where the plugin added it
(a listener added at main.ts:12). Every name and its payload:
Events.
Unlike Player.stream it does not keep the SDK's copy of the
state current: plugin.player.state does not follow it, and the
listener runs for every event, changed or not. Three events are the
exception: commands.keys, timeline.changed and appearance.changed
start the copy they keep current (plugin.commands.keys,
plugin.timeline.marks and ranges, plugin.appearance.theme and
language), which stays for the plugin's life as a copy (not a
listener: it keeps no plugin running), and the copy takes each event
before the listener runs, so the listener reads the new values there.
The listener hears only the player's events, never the copy's own first
read: take the starting value once after activation, or read the copy
in a View.bind function, which follows both. It suits pushing
values yourself (view.set from the listener) or reading a field the
SDK does not expose. Errors go to Scope.onError, as for every
handler; unlike the others, no full update pass follows it, so bound
values do not re-evaluate on every event: a write to a
Scope.state field re-runs only its readers, and
Scope.update re-runs everything.
Every event arrives from its first listener.
invalid (throws) event is not a HostEvent name, or
listener is not a function.
A tab in the adjust column shows the playback speed. The listener gets each
source.state event's data and writes the text with set; no update
pass runs and the SDK keeps no copy of the state for this.
const panel = plugin.panels.mount("adjust", "ui/speed.slint", { title: "Speed" });
plugin.player.on("source.state", (s) => panel.set({ rate: `${s.rate.toFixed(2)}×` }));
Listen to one of the player's discrete source events: a source starts to open, is ready, or ended.
The event's name.
Receives each event's data.
A handle that stops listening; it is disposed with the scope.
event is a SourceEvent name; listener gets that event's
data, typed SourceEventPayloads, with state as a
PlayerState. The events arrive from the first listener, and a
listener of one does not keep the plugin running: the player starts a
plugin in standby to deliver
them, and an event that arrives while the plugin starts waits for its
activation. source.ended with reason: "quit" reaches only a
plugin that is running when the player quits. As for every
Player.on listener, no full update pass follows it.
A plugin stores the position at which each file stopped playing. The ended source's last state comes with the event, also when another file replaced it.
const saved = plugin.storage.json("positions", {
defaults: {} as Record<string, number>,
});
plugin.player.on("source.ended", ({ state, reason }) => {
if (reason === "natural" || state.source === null) return;
saved.save({ ...saved.value, [state.source]: state.position ?? 0 });
});
Listen to one of the player's facts that changed: the video's or the audio's parameters, the audio tracks, the subtitles, the main window, the panel layout, the audio devices, or the start of the player.
The event's name.
Receives each event's data.
A handle that stops listening; it is disposed with the scope.
event is a FactEvent name; listener gets that event's data,
typed FactEventPayloads. Each is sent once per change, never as
a stream: window.changed once when a resize ends, not at every step.
The events arrive from the first listener, and a listener of one does
not keep the plugin running: the player starts a plugin in standby to
deliver them, and an event that arrives while the plugin starts waits
for its activation. Where the data carries a state the SDK keeps
(subtitles.changed, window.changed, layout.changed, and
audio.tracks.changed and audio.devices.changed for
plugin.player.state), the SDK takes it first, so the copy holds it
when the listener runs. As for every Player.on listener, no full update
pass follows it.
The plugin learns the size the video is shown at once per change (a new file, a rotation, a crop), without following the player's state.
plugin.player.on("video.reconfigured", ({ displayWidth, displayHeight }) => {
if (displayWidth > 0 && displayHeight > 0)
void plugin.window.setVideoArea({ width: displayWidth, height: displayHeight });
});
Read the state from the player now.
A command reads the newest state from the player before acting.
refresh asks the player and resolves with the new snapshot;
player.state holds it afterwards.
const state = await plugin.player.refresh();
if (state.phase === "ready") await plugin.osd.show("{} s left", [((state.duration ?? 0) - (state.position ?? 0)).toFixed(0)]);
Read the player's state and the timeline's marks and ranges once, and keep the state current after this plugin's own actions.
Resolves once the state and the timeline are read.
Call it first in activate and wait for it: plugin.player.state,
plugin.timeline.marks and plugin.timeline.ranges then hold what the
player has. Before the call state is the empty state (phase: "empty") and the lists are empty. From the call on the SDK also reads
the state again after Host.run, when a Media handle is
closed and when a stream of the plugin ends, as the player's own
controls would show it.
A second call reads nothing and resolves when the first read is in. To read the state again later, use Player.refresh.
A command shows how much of the file is left. read fetches the state
once during activation, so state is current when the command first
runs; without a stream it moves only after this plugin's own calls,
so the command asks for it again with refresh.
import type { Plugin } from "@vestra-player/sdk";
export default async function activate(plugin: Plugin) {
await plugin.player.read(); // state is current from here
plugin.commands.add({
id: "left",
path: ["Tools", "Time Left"],
enabled: plugin.when.ready, // evaluated by the player
run: async () => {
// No events: ask the player for the position now.
const { duration, position } = await plugin.player.refresh();
await plugin.osd.show("{} s left", [((duration ?? 0) - (position ?? 0)).toFixed(0)]);
},
});
}
True if nothing changed the source since state was observed.
A slow lookup for the current file is shown only if that file is still
open. isCurrent compares the snapshot taken before the work with the
SDK's newest state; it is false once the source changed in any way:
another file, a close, or a pause, seek or speed change by anyone.
const seen = plugin.player.state;
const title = await lookUpTitle(seen.source ?? "");
if (plugin.player.isCurrent(seen)) await plugin.osd.show("{}", [title]); // still the same file
Open a path or URL, replacing the current source (unless ifCurrent no
longer holds). Resolves when the host accepted the load.
It does not wait for playback: use Media.ready. paused opens
it paused; aborting signal closes it. URLs matching a registered
Resolver are resolved first, and so are local files of an
extension a file resolver claims (the source is then a stream that
plugin generates; paused reaches it).
Optionaloptions: { paused?: boolean; signal?: AbortSignal } & Conditionalreplaced (rejects) Accepted, then another source took over
before it finished (for example while a URL was still being resolved).
busy (rejects) The address needs a resolver plugin and the
player is already resolving 32 addresses.
backend (rejects) A resolver plugin handled the address or
file and failed (its message), or the resolution was cancelled or
expired.
unsupported (rejects) The player refused what a resolver
returned (for example split streams with different headers).
The file opens at its start without playing. open resolves once the
player accepted the load and returns a Media handle for that
source; ready then waits until it can play (here: until it is loaded
and paused).
const media = await plugin.player.open("/Movies/clip.mp4", { paused: true });
await media.ready(); // rejects `failed` when the file cannot be loaded
Start a source whose frames this plugin generates (the stream becomes the player's source, like Player.open).
The SDK calls frame() on the audio clock and handles prefill,
activation, pausing and acknowledgement. Frames travel over a local
connection the SDK sets up: a Unix socket on macOS and Linux, loopback
TCP with a token on Windows. Rejects with a StreamStartError
(timeout), stream, device, or replaced when another source
replaced it (or it was closed) before it ran.
The player shows a 320×240 picture the plugin renders, with silence as
its sound, as the current source. The SDK pulls frames on the audio
clock: each frame() returns one picture (RGBA bytes) and the audio
that plays with it, here 1/60 s, so the picture runs at 60 frames a
second; frame() may run several times back to back to refill the
lead. onStop tells the plugin when and why the stream ended.
const frame = new Uint8Array(320 * 240 * 4); // RGBA, reused per frame
const silence = new Float32Array(2 * 800); // 1/60 s of stereo at 48 kHz
const stream = await plugin.player.openStream({
width: 320,
height: 240,
frame: () => ({ video: render(frame), audio: silence }),
});
// `error` is null when the stream stopped normally.
stream.onStop((error) => error && plugin.osd.show(error.message));
timeout (rejects) A StreamStartError: the stream did not
start in time.
Pause or resume.
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin); nothing was done.
A "pause on lock" helper pauses the current file and does nothing when
another file was opened in between. The call acts on the current state
by default; stale means the source changed and the
pause was not applied, which is the intended outcome here.
try {
await plugin.player.setPaused(true);
} catch (error) {
if ((error as PluginError).code !== "stale") throw error; // another file now
}
Jump to seconds. After the end (phase: "ended") the player leaves
the end there and plays on, unless the end was reached while paused or
by a frame step; a seek at or past the end leaves it ended and paused.
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin); nothing was done.
Playback jumps ten seconds back, never before the start. The target is
computed from the state read now, and the seek is pinned to it
(ifCurrent), so if the user opened another file meanwhile the seek
fails with stale instead of landing in the wrong file.
const now = await plugin.player.refresh();
if (now.position !== null && now.can.seek)
await plugin.player.seek(Math.max(0, now.position - 10), { ifCurrent: now }); // seconds
Set the playback speed.
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin); nothing was done.
Playback speeds up to 1.5×, with the speed on the OSD. setRate sets
the speed directly (the player's own keys step it by 0.1 within
0.25–4); state.can.rate is false for sources that cannot change speed.
if (plugin.player.state.can.rate) {
await plugin.player.setRate(1.5);
await plugin.osd.show("Speed {}×", [1.5]);
}
Play from the start (the "replay" after the end).
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin); nothing was done.
A Replay button starts the file again from its start once it has ended.
restart plays the current source from the beginning and keeps it the
same source, so a Media handle stays current.
if (plugin.player.state.phase === "ended") await plugin.player.restart();
Close the current source.
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin); nothing was done.
After 30 minutes the open file is closed, unless the user opened another
one meanwhile. The snapshot taken when the timer started is passed as
ifCurrent, so the close applies only to that source; stale means it
was replaced.
const seen = plugin.player.state;
setTimeout(() => {
// Only the source that was open when the timer started.
plugin.player.close({ ifCurrent: seen }).catch((error: PluginError) => {
if (error.code !== "stale") plugin.osd.show("Could not close: {}", [error.code]);
});
}, 30 * 60 * 1000);
Start a drag gesture from the current state.
A drag on the plugin's seek slider becomes one gesture whose seeks never
pile up. scrub() captures the current state; the gesture's seeks are
conditional on it and on each other, and it ends on its own when
someone else changes the source.
let scrub: Scrub | null = null;
bar.on("dragStart", () => (scrub = plugin.player.scrub()));
bar.on("dragEnd", () => scrub?.end());
Device output; last write wins and volume is applied before mute.
Resolves true when this request was applied, false if superseded.
volume is 0–200.
The volume drops to 30 while the plugin's announcement plays, then
returns. Writes are "latest wins": the promise resolves true when this
write was applied and false when a newer one replaced it first, which
is not an error.
const before = plugin.player.state.volume; // 0–200
await plugin.player.setOutput({ volume: 30 });
// … the announcement …
await plugin.player.setOutput({ volume: before });
Become the sequence provider, first come first served: while another
plugin holds it (the built-in playlist registers at activation), this
one is refused with conflict (sequence-taken). That does not fail
activation: the player shows a warning (PluginInfo.warnings);
a refusal after activation goes to the scope's onError. Dispose to
stop.
The player's Next and Previous items and keys play the plugin's list.
The player calls next and previous when the user asks; canNext
and canPrevious are evaluated again after every handler the SDK runs
(and after a player state change if they read a changed field), and while they return false the player disables its items ("No next
item").
const playAt = async (at: number) => {
index = at;
await plugin.player.open(items[at]!);
};
// Called by the player's Next / Previous items, keys and buttons.
plugin.player.provideSequence({
next: () => playAt(index + 1),
previous: () => playAt(index - 1),
canNext: () => index + 1 < items.length,
canPrevious: () => index > 0,
});
Ask the provider to go forward / back. Rejects unavailable when it cannot.
The plugin's own Next button plays the next item of whichever plugin
provides the sequence (the playlist, usually). next asks the
provider, the same as the player's Next key; unavailable means there
is no next item, which the button treats as the end of the list.
try {
await plugin.player.next(); // as the player's Next key does
} catch (error) {
if ((error as PluginError).code !== "unavailable") throw error;
await plugin.osd.show("End of the list");
}
Ask the provider to go back. Rejects unavailable when it cannot.
The plugin's Previous button asks the sequence provider for the item
before the current one, like the player's PageUp. It is disabled while
state.can.previous is false, which the provider's canPrevious
decides.
plugin.commands.add({
id: "previous",
title: "Previous item",
// The provider's `canPrevious`, as the player evaluates it.
enabled: plugin.when.can("previous"),
run: () => plugin.player.previous(),
});
Codec, size, frame counts and backend of the current playback.
playback.read; video and audio are null without a source.
The OSD shows something like "h264 1920×1080". stats asks the player
for the backend's own values at that moment; video is null without
a video stream (nothing open, an audio file).
const { video } = await plugin.player.stats();
if (video) await plugin.osd.show("{} {}×{}", [video.codec ?? "?", video.width ?? 0, video.height ?? 0]);
Add an external audio file (absolute local path) to the current media and,
unless select: false, select it. Resolves with the new track (external,
not exportable). It stays until the source changes. Rejects invalid for a
bad path, unavailable without ready media, backend when it cannot load.
Optionaloptions: { select?: boolean } & ConditionalA separate audio file plays with the film instead of its own sound.
addAudioTrack attaches the file to the current media and selects it;
the track stays until another source opens.
const track = await plugin.player.addAudioTrack(dubPath); // selected too
await plugin.osd.show("Audio: {}", [track.title ?? dubPath]);
Select one of state.audioTracks by id; invalid for an unknown id.
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin).
Each press of the plugin's key moves to the next audio track of the
file. The tracks and the selected one are in state.audioTracks;
selectAudioTrack resolves with the new state.
const audioTracks = plugin.player.state.audioTracks ?? []; // null: not known yet
const at = audioTracks.findIndex((track) => track.selected);
const next = audioTracks[(at + 1) % audioTracks.length];
if (next) await plugin.player.selectAudioTrack(next.id);
One frame or to the next / previous keyframe (pauses for frames). Rejects
unsupported without moving video (audio only, cover art, a generated
stream) or when backwards needs a seekable source.
Resolves once the new position is in effect, so player.state.position
is current afterwards. One step at a time: a second call while one is
in flight rejects busy.
Optionaloptions: Conditionalunsupported (rejects) Nothing playable to step through (no
moving video: audio only, cover art, a generated stream), a backward
frame step on a source that cannot seek, or a keyframe step in either
direction on a source that cannot seek.
stale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin).
The picture advances by one frame and playback pauses. step resolves
once the new position is in effect, so state.position is current
afterwards; a second step while one is running rejects with busy.
await plugin.player.step("frame", "forward");
await plugin.osd.show("{} s", [plugin.player.state.position?.toFixed(3) ?? "?"]);
The core's first-tier relative seek (seek-backward / seek-forward,
← / →): 0.1–3600 seconds in tenths, default 5. The newest call of any
plugin wins; it reverts when that plugin stops.
keyframes: true: the step seeks (seek-backward / seek-forward,
including Host.run with seconds and the picture-in-picture skips)
land on a keyframe instead of the exact time: forward on the first keyframe
at or after position + step, backward on the last at or before position −
step, and they always move. Presses during a seek add up and continue from
where it landed; the on-screen text shows the landed time. Sources without
moving video seek exactly, and so does a step seek after the end. Player.seek, chapters, loops and
Player.step are unaffected, and so is a scrub unless it asks for
keyframes itself (Scrub.seek with keyframes: true). Omitted or
false: exact seeks, as before. seconds and keyframes are written as a
pair: the newest call sets both.
The arrow keys now jump 10 seconds and land on keyframes, which is fast on large files. The newest call of any plugin wins and is withdrawn when that plugin stops, so a plugin offering this as a setting applies it on activation.
await plugin.player.setStepSeek({ seconds: 10, keyframes: true });
The chapters of the current media (empty without media or chapters),
read on demand; sourceId tells which source they belong to.
The plugin reads the chapter titles of the current file to show them in
its panel. chapters asks the player when called; sourceId says which
source they belong to, so a reply for a file that was replaced meanwhile
can be dropped.
const { sourceId, chapters } = await plugin.player.chapters();
if (sourceId === plugin.player.state.sourceId) // still the same file
console.log(chapters.map((chapter) => chapter.title));
A-B loop: on reaching b, jump back to a (seconds, 0 ≤ a < b ≤ duration), count times (positive integer; omitted = endless); null
stops it. After the last jump back state.loop becomes null.
invalid out of range, unsupported for a source that cannot seek,
unavailable without ready media. A new source clears it.
Optionaloptions: Conditionalstale (rejects) The source changed since the state the call is
based on (another file, a close, or any pause, seek
or speed change by the user or another plugin).
The output devices present now (not the system default entry).
A submenu lists the output devices present now, with a radio mark on the
one in use. audioDevices asks the player when called (devices come and
go; audio.devices.changed says when), and when.audioDevice checks
the one in use, evaluated by the player.
// The devices present now; build the menu again when they change.
for (const device of await plugin.player.audioDevices())
plugin.commands.add({
id: `device.${device.id}`,
path: ["@audio", "Output", device.name],
radio: true,
checked: plugin.when.audioDevice(device.id),
run: () => plugin.player.setAudioDevice(device.id),
});
Play on this device while it is present, else on the system default
(null = always the default). Generated streams follow too. Kept for
this run only.
Unknown ids are accepted (state.audioOutput.active stays null); a
malformed id is invalid. Reverts to the default when this plugin
stops; save the choice yourself to restore it on activation.
The plugin plays on the device the user picked last time, or on the system default when it is not connected. The choice lasts only for this run and is withdrawn when the plugin stops, so the plugin saves it itself and sets it again on activation.
const store = plugin.storage.json("output", { defaults: { device: null as string | null } });
await plugin.player.setAudioDevice(store.value.device); // null: the system default
ReadonlystateLatest state; always newer than anything delivered before.
The newest snapshot this plugin has: from Player.read, Player.refresh, the state a source event carries and this plugin's own calls. While a Player.stream is open it follows every change the player sends.
plugin.player: playback state and controls.Call
await plugin.player.read()first inactivatewhen the plugin readsstateat start: it fillsstateonce and keeps it current after this plugin's own calls. To learn that something happened, listen to an event (Player.on) or declare a trigger; to show the state as it changes, open a Player.stream while it shows.Controls are conditional (see Conditional): they fail with
staleand do nothing when the source changed since the state you saw.Example: Open a file and wait until it plays
The file opens and the plugin learns whether it started playing within ten seconds.
openresolves once the player accepted the load and returns aMediahandle;readywaits for playback and rejects withfailed(load error),replaced(another source took over) or anAbortErrorwhen the timeout fires, which closes the media.Remarks
plugin.playeris the player's one source: what is open, its phase and position, and the controls.stateis the newest snapshot the plugin has: fromread(),refresh(), an event's data and this plugin's own calls, and while a Player.stream is open, every change. Every control is conditional: it acts on the current state (read first when no stream keepsstatecurrent) or on the one given asifCurrent, and fails withstalewhen the source changed meanwhile: another file, a close, or any pause, seek or speed change by the user or another plugin (see Conditional). The player keeps the source when a plugin stops; only the plugin's own handles (a stream, its sequence provider, its output device) are withdrawn.Player.openStream.
See
Control playback
Since
1.0.0