@vestra-player/sdk - v1.11.3
    Preparing search index...

    Example: Signal generator

    This walkthrough builds a plugin that generates its own video and audio and plays them in Vestra Player like any other source: colour bars and a 1 kHz sine tone. It is about 110 lines of TypeScript in one file, with no window. Along the way it covers how Player.openStream pulls frames from a plugin, how a frame's pixels are laid out, how many audio samples go with each picture, how to keep a tone smooth across frames, and how to stop a stream.

    The complete, tested source is in examples/signal-generator. Every code block on this page is taken from those files, so it always matches the code that CI checks and tests.

    Generated streams with openStream (the player pulls frame()) · the RGBA frame layout · audio samples per video frame (48000 / fps, carrying the fraction) · a phase-continuous sine · stopping a stream.

    Control playback teaches opening and following a source; generated streams are Player.openStream.

    Colour bars from the signal generator

    • Open ▸ Signal generator in the player's own Open menu starts a generated source: seven colour bars at 640×360 and 29.97 frames per second, with a 1 kHz tone at −12 dBFS on both channels.
    • The menu item has a check mark while the stream runs. Choosing it again stops the stream, and the player goes back to its empty state.

    You should know the basics from Hello: the manifest, activate and commands.

    Usually the player plays a file: it decodes the picture and the sound and keeps them in step. A generated source has no file. The plugin calls openStream with a frame size and a frame() function, and the player plays whatever frame() returns. To the user it is a source like any other: it replaces what was playing, play/pause works, and opening a file replaces it in turn.

    The plugin does not push frames on a timer of its own. The player pulls them: the SDK calls frame() whenever the player needs more.

    • frame() is never called twice at the same time, and not at all while the player is paused.
    • It is paced by the audio clock. The SDK keeps a little audio queued ahead of the sound card (about 50 ms). Regularly, several times per frame, it checks how much the sound card has played and calls frame() as many times in a row as it takes to fill the queue again: two or three calls back to back are normal, so do not time anything by the gap between calls.
    • It is synchronous: it cannot await, so everything it needs must already be in memory. If it is slow, the sound drops out.

    Each call returns one picture and the audio that plays while that picture is on screen. The stream's timeline is its audio: the player plays the samples at 48 000 per second and shows each picture when the audio reaches it. A frame that carries 1600 samples therefore lasts 1600 / 48 000 s = 1/30 s. The number of samples per frame is the frame rate; there is no separate setting.

    examples/signal-generator/
      manifest.json                   id
      main.ts                         the picture, the tone, frame(), start and stop, the command
      main-b.ts, main-c.ts            the command, start and stop in styles B and C
      tests/signal-generator.test.ts  tests of frame() and of the stream on the in-memory test host
      package.json                    the SDK as a dev dependency, and the npm scripts
    
    {
    "id": "examples.signal-generator",
    "version": "1.0.0",
    "apiVersion": "vestra/1",
    "entry": "main.ts",
    "minPlayerVersion": "0.9.0",
    "name": "Signal Generator",
    "author": "Vestra Player SDK examples",
    "punchline": "Colour bars and a 1 kHz test tone generated by a plugin",
    "description": "Open ▸ Signal generator plays colour bars with a 1 kHz sine tone that the plugin generates itself. Choose it again to stop.\nSDK example: Player.openStream.",
    "tags": ["example", "test signal", "audio", "video"],
    "sourceUrl": "https://github.com/vestrasys/vestra-player-sdk/tree/main/examples/signal-generator",
    "license": "Apache-2.0"
    }

    await plugin.player.read(), first in activate, lets the stream read the player's state when it stops, to check that it is still the current source before closing it, so it never closes a file the user opened in the meantime.

    The display fields (name, punchline, description, …) are what the plugin manager and the store show.

    import type { Plugin, Stream, StreamFrame } from "@vestra-player/sdk";

    export const WIDTH = 640;
    export const HEIGHT = 360;
    /** 29.97 fps, the NTSC frame rate: 48000 / FPS is not a whole number. */
    export const FPS = 30000 / 1001;
    /** Every stream's audio is 48 kHz stereo, 32-bit float. */
    const SAMPLE_RATE = 48000;
    const FREQUENCY = 1000; // Hz
    const LEVEL = 0.25; // amplitude, −12 dBFS
    • 640×360 is plenty for a test picture: the player scales it to the window. A frame may be at most 4 MiB, so 1280×720 is the largest 16:9 size.
    • FPS is 29.97, the NTSC rate, on purpose: 48 000 / 29.97 = 1601.6 samples is not a whole number, which is the interesting case (see frame()). At 25 or 30 fps the division is exact.
    • A stream's audio is always 48 kHz, stereo, 32-bit float; the plugin cannot choose another rate.
    • LEVEL is the tone's amplitude. Samples must stay within −1…1: a sample outside that range, or one that is not a number, ends the stream with the code invalid.
    /** Seven vertical 75 % colour bars as RGBA bytes, row by row from the top left. */
    function colourBars(): Uint8Array {
    const colours: [number, number, number][] = [
    [191, 191, 191], // grey
    [191, 191, 0], // yellow
    [0, 191, 191], // cyan
    [0, 191, 0], // green
    [191, 0, 191], // magenta
    [191, 0, 0], // red
    [0, 0, 191], // blue
    ];
    const pixels = new Uint8Array(WIDTH * HEIGHT * 4);
    for (let y = 0; y < HEIGHT; y++) {
    for (let x = 0; x < WIDTH; x++) {
    const [r, g, b] = colours[Math.floor((x * 7) / WIDTH)]!;
    const i = (y * WIDTH + x) * 4; // the first byte of pixel (x, y)
    pixels[i] = r;
    pixels[i + 1] = g;
    pixels[i + 2] = b;
    pixels[i + 3] = 255; // alpha: opaque
    }
    }
    return pixels;
    }

    A frame's picture is a Uint8Array of exactly width × height × 4 bytes: red, green, blue and alpha for each pixel, row by row, starting at the top left. So pixel (x, y) starts at byte (y × width + x) × 4:

    • x * 7 / WIDTH picks the bar: the first 1/7 of every row is grey, the last 1/7 blue.
    • The values are 75 % (191 of 255), as in the classic SMPTE test bars.
    • Alpha 255 means opaque. The player shows the picture as it is.

    The bars never change, so they are drawn once when the module loads.

    const video = colourBars(); // the picture never changes: draw it once
    /** Room for the longest frame: 1602 stereo samples. */
    const audio = new Float32Array(2 * Math.ceil(SAMPLE_RATE / FPS));
    let owed = 0; // the fraction of a sample carried over to the next frame
    let phase = 0; // position in the current sine cycle, 0 ≤ phase < 1

    /** The `frame` callback of openStream: one picture and its audio. */
    export function frame(): StreamFrame {
    // 48000 / 29.97 = 1601.6 samples: 1601 or 1602, never drifting.
    owed += SAMPLE_RATE / FPS;
    const samples = Math.floor(owed);
    owed -= samples;

    for (let i = 0; i < samples; i++) {
    const value = LEVEL * Math.sin(2 * Math.PI * phase);
    audio[2 * i] = value; // left
    audio[2 * i + 1] = value; // right
    phase += FREQUENCY / SAMPLE_RATE;
    if (phase >= 1) phase -= 1;
    }
    return { video, audio: audio.subarray(0, 2 * samples) };
    }

    This is the function the player calls for every frame. Three things happen in it.

    How many samples. 48 000 / 29.97 = 1601.6. Rounding every frame down to 1601 would make the sound run 0.6 samples short per frame, about 1.3 seconds per hour, and the picture would drift away from it. Instead, owed accumulates the exact amount, the frame takes the whole samples, and the fraction is carried to the next frame:

    Frame owed before Samples Carried
    0 1601.6 1601 0.6
    1 1602.2 1602 0.2
    2 1601.8 1601 0.8
    3 1602.4 1602 0.4

    The frames alternate between 1601 and 1602 samples, and the total never differs from the exact time by more than one sample, however long the stream runs.

    The sine, phase-continuous. The obvious formula, sin(2π × frequency × t), needs the time t, and it makes every frame start the wave from scratch unless t is tracked exactly. Instead the code keeps a phase: the position inside the current cycle, from 0 up to (not including) 1.

    • The sample is LEVEL × sin(2π × phase).
    • After each sample, the phase advances by FREQUENCY / SAMPLE_RATE: at 1 kHz that is 1/48 of a cycle, so a cycle takes 48 samples.
    • At 1 the phase wraps back to 0, so the number never grows and never loses precision.

    phase lives outside frame(), so each frame continues exactly where the previous one ended. That matters: a frame of 1601.6 samples holds 33.37 cycles, not a whole number, so a wave restarted at every frame would jump, and a jump in a waveform is heard as a click, 30 times a second. With the phase it is one smooth tone. The same trick keeps the tone smooth when the frequency changes (see Try next).

    Interleaved stereo. The audio is one Float32Array with the channels alternating: audio[2 * i] is the left sample of sample frame i, audio[2 * i + 1] the right one. Its length is twice the number of samples.

    Reusing the buffers. frame() returns the same video array every time, and audio is a view into one buffer allocated up front, big enough for the longest frame (1602 stereo samples). That is safe: the SDK copies each frame before it calls frame() again. Allocating new arrays 30 times a second would work too, but it gives the garbage collector work, and a long collection pause is heard as a dropout.

    export default async function activate(plugin: Plugin) {
    await plugin.player.read(); // the player's state and timeline, read once
    let stream: Stream | undefined; // the running stream
    let starting = false;

    async function start() {
    starting = true;
    try {
    stream = await plugin.player.openStream({
    width: WIDTH,
    height: HEIGHT,
    frame, // the player calls it whenever it needs the next frame
    });
    // Another source replaced the stream, or it failed.
    stream.onStop(() => (stream = undefined));
    } finally {
    starting = false;
    }
    }

    async function stop() {
    const running = stream;
    stream = undefined;
    await running?.stop();
    }
    • openStream({ width, height, frame }) resolves once the stream plays. Before that, the SDK has set up a local connection to the player, called frame() a few times to fill the first buffers, and asked the player to make the stream its source. It rejects if that fails, for example with device when the audio output is not ready, or timeout after 10 seconds; the error then goes to the plugin log.
    • starting covers the moment between the call and its result, so that choosing the command twice quickly does not start two streams.
    • onStop is called when the stream ends without the plugin stopping it: the user opened a file, or the stream failed (its argument is then the error). The plugin just forgets the stream, and the menu's check mark goes away. It is not called for the plugin's own stop().
    • stop() forgets the stream first, then calls stream.stop(). That closes the source if it is still the player's source, then the frame connection, then the producer. In that order the player sees an ordinary "closed" source rather than a playback failure. If another source already replaced the stream, stop() leaves that source alone.

    When the plugin is disabled or the player quits, the SDK stops the stream the same way: it belongs to plugin.

    plugin.commands.add({
    id: "signal-generator",
    path: ["@open", "Signal generator"], // the player's Open menu, in any language
    checked: () => stream !== undefined,
    run: () => {
    if (starting) return;
    return stream ? stop() : start();
    },
    });
    • path: ["@open", "Signal generator"] puts the item in the player's own Open menu. Paths merge by their English keys in every interface language, so ["Open", …] reaches the same menu; the id form @open names the built-in menu explicitly (Menu paths).
    • checked is a function. The SDK calls it again after every handler and every onStop, and updates the check mark when the result changes.
    • run starts the stream when there is none and stops it when there is one. It returns the promise so that a failure reaches the plugin log.

    main.ts is the main version, in style A (Tutorial): the check mark is a function, and the SDK's update passes evaluate it after every handler and every onStop. Two more entry files hold the same plugin in the other styles; point the manifest's entry at one to run it. Everything except the command and the start and stop functions is imported from main.ts.

    Style B (main-b.ts): the check mark is a value that the plugin sets when the stream starts and stops. The command never takes part in an update pass, and set sends this command's state alone.

    const command = plugin.commands.add({
    id: "signal-generator",
    path: ["@open", "Signal generator"],
    checked: false, // a value: no update pass evaluates this command
    run: () => {
    if (starting) return;
    return stream ? stop() : start();
    },
    });
    async function start() {
    starting = true;
    try {
    stream = await plugin.player.openStream({
    width: WIDTH,
    height: HEIGHT,
    frame,
    });
    command.set({ checked: true }); // sends this command's state, nothing else
    stream.onStop(() => {
    stream = undefined;
    command.set({ checked: false });
    });
    } finally {
    starting = false;
    }
    }

    async function stop() {
    const running = stream;
    stream = undefined;
    command.set({ checked: false });
    await running?.stop();
    }

    Style C (main-c.ts): the command is registered from the player's own declaration with plugin.wire.commands.register, and each change of the check mark is one commands.update that the plugin sends with update. Experimental: the declaration's fields are the player's and change with its versions.

    const command = plugin.wire.commands.register({
    id: "signal-generator",
    // The player's declaration, as `commands.register` takes it.
    declaration: {
    title: "Signal generator",
    path: ["@open", "Signal generator"],
    order: 0,
    group: "domain",
    radio: false,
    bindings: [],
    focus: null,
    repeat: false,
    },
    state: { checked: false },
    run: () => {
    if (starting) return;
    return stream ? stop() : start();
    },
    });

    The stream itself is the same in all three: openStream is a primitive that every style calls the same way. The tests run the start-and-stop test against each entry file.

    import assert from "node:assert/strict";
    import test from "node:test";
    import { startPlugin, TestHost } from "@vestra-player/sdk/testing";
    import activate, { FPS, HEIGHT, WIDTH, frame } from "../main.ts";
    import activateB from "../main-b.ts";
    import activateC from "../main-c.ts";

    test("a frame is RGBA colour bars and 1601 or 1602 stereo samples", () => {
    const { video } = frame();
    assert.equal(video.length, WIDTH * HEIGHT * 4);
    assert.deepEqual([...video.subarray(0, 4)], [191, 191, 191, 255]); // grey
    const last = video.length - 4; // bottom right: blue
    assert.deepEqual([...video.subarray(last)], [0, 0, 191, 255]);

    // 300 frames are 10.01 s: the audio stays within one sample of that.
    let total = 0;
    for (let n = 0; n < 300; n++) {
    const samples = frame().audio.length / 2;
    assert.ok(samples === 1601 || samples === 1602);
    total += samples;
    }
    assert.ok(Math.abs(total - (300 * 48000) / FPS) <= 1);
    });

    test("the sine continues smoothly from one frame to the next", () => {
    // The largest step a 1 kHz sine at amplitude 0.25 takes between samples.
    const maxStep = 0.25 * 2 * Math.PI * (1000 / 48000);
    let previous = frame().audio.at(-2)!; // the last left sample
    for (let n = 0; n < 10; n++) {
    const { audio } = frame();
    for (let i = 0; i < audio.length; i += 2) {
    assert.ok(Math.abs(audio[i]! - previous) <= maxStep + 1e-6);
    assert.equal(audio[i + 1], audio[i], "left = right");
    previous = audio[i]!;
    }
    }
    });

    /** Poll until `predicate()` holds: a stream starts and stops on timers. */
    async function until(predicate: () => boolean) {
    const deadline = Date.now() + 3000;
    while (!predicate()) {
    if (Date.now() > deadline) throw new Error("timed out");
    await new Promise((resolve) => setTimeout(resolve, 5));
    }
    }

    // The same behaviour from each entry file: style A (main.ts), B and C.
    for (const [style, entry] of [
    ["A", activate],
    ["B", activateB],
    ["C", activateC],
    ] as const)
    test(`Open ▸ Signal generator starts the stream; choosing it again stops it (style ${style})`, async () => {
    const host = new TestHost();
    // Windows has no Unix sockets: the frames travel over loopback TCP there.
    if (process.platform === "win32") host.producerTransport = "tcp";
    const { stop } = await startPlugin(entry, {
    directory: new URL("..", import.meta.url), // reads manifest.json
    host,
    });
    const command = () => host.command("signal-generator");
    const keepsRunning = () => host.keepsRunning;
    try {
    await host.settle();
    assert.deepEqual(keepsRunning(), [], "idle until the stream starts");
    const { declaration } = command();
    assert.deepEqual("path" in declaration && declaration.path, [
    "@open",
    "Signal generator",
    ]);

    await command().run();
    await until(() => command().state.checked === true);
    assert.equal(host.source.kind, "producer");

    await command().run();
    const producer = host.producers.get(1)!;
    await until(() => producer.released);
    assert.equal(producer.droppedWhileSelected, false, "source closed first");
    assert.equal(host.source.phase, "empty");
    assert.equal(command().state.checked, false);
    assert.deepEqual(keepsRunning(), []);
    } finally {
    await stop();
    }
    });
    • The first two tests call frame() directly, with no player: the picture's size and colours, the 1601/1602 sample counts and their total, and that no step between two neighbouring samples is larger than a clean 1 kHz sine allows, across frame boundaries too.
    • The others run the plugin against TestHost, once per entry file, the SDK's in-memory player. It speaks the real protocol, including the frame connection, so the SDK's start-up and stop sequence run unchanged. host.producers.get(1) is the player's end of the stream: released says the plugin let go of it, and droppedWhileSelected would be true if the connection had closed while the stream was still the player's source.
    • A stream runs on timers, so the test polls with until() instead of relying on host.settle().

    In the SDK repository, build the SDK once (npm ci at the root), then:

    cd examples/signal-generator
    npm install
    npm run check # manifest rules and a strict type check
    npm test

    Start the player with --plugin <path to examples/signal-generator>: it runs main.ts directly, with no build step. Choose Open ▸ Signal generator: the bars appear and the tone plays. Pause and resume: picture and sound stop and continue together. Choose the command again: the player returns to its empty state. npm run pack builds examples.signal-generator-1.0.0.vxp, the file users install.

    1. A frequency slider. Add a tool window with one Slider (see Blur) and make FREQUENCY a variable that its callback changes. The next frame() uses the new value; because the phase continues, the pitch glides without a click.
    2. Movement. Draw a white bar whose position depends on a frame counter. A dropped or repeated frame then shows as a jump.
    3. Show why it stopped. Call plugin.osd.show(error.message) in onStop when error is not null.