Developer
Log in

SDKs

C#

Every action is a typed method, every event a typed C# event, every piece of live state a typed property. .NET 8, no dependencies beyond the base class library, and trimming- and Native AOT-safe.

Install

The package is Velum.Studio.Client, for .NET 8 on Windows, macOS and Linux. It uses System.Net.WebSockets and System.Text.Json with source generation, and nothing else.

NuGet: coming soon

Until it's on NuGet, reference the project, or pack it and reference the package.

Shell
dotnet add reference path/to/sdk/csharp/src/Velum.Studio.Client/Velum.Studio.Client.csproj
# or
dotnet pack sdk/csharp/src/Velum.Studio.Client -c Release -o ./packages
dotnet add package Velum.Studio.Client --source ./packages

Quick start

C#
using Velum.Studio;

// The Studio running on this computer, found through its discovery file.
await using var studio = await VelumStudioClient.ConnectAsync(new VelumClientOptions { ClientName = "My App" });

studio.SceneChanged += (_, e) => Console.WriteLine($"On air: {e.Name}");
studio.ActivityRaid += (_, e) => Console.WriteLine($"Raid from {e.Author?.Display}: {e.Amount?.Value} viewers");

// Topics bring their state and their events; State is filled when this returns.
await studio.SubscribeAsync(TopicType.Scenes, TopicType.Activity);

var result = await studio.SceneSwitchAsync(new SceneSwitchParams { Scene = "Just Chatting" });
Console.WriteLine($"Switched to {result.Name}");

var scenes = studio.State.Scenes!;
foreach (var scene in scenes.Items.Values.OrderBy(s => s.Index))
    Console.WriteLine($"{(scene.Id == scenes.Program ? "*" : " ")} {scene.Name}");

await Task.Delay(Timeout.Infinite);

Actions

Each action in Studio's catalog is one method, named after its id, with a parameters record and a result record of its own:

Action id Method Parameters Result
scene.switch SceneSwitchAsync SceneSwitchParams SceneSwitchResult
audio.mute AudioMuteAsync AudioMuteParams AudioMuteResult
record.toggle RecordToggleAsync (none) RecordToggleResult
destination.health DestinationHealthAsync DestinationHealthParams DestinationHealth
  • Required parameters are required properties. Optional ones are nullable and left out when null, so Studio uses its default.
  • A fixed set of words is an enum: new AudioMuteParams { Input = "Mic", Mode = AudioMuteMode.Unmute }.
  • A layer can be named by its id or its per-scene number: Layer takes a string or a number.
  • Every method is named the same way from its action's id (stream.golive is StreamGoliveAsync), so a new action's method can be predicted from its id.

Why one flat method per action rather than groups (studio.Scenes.SwitchAsync)? The method, the ActionType value, the parameters and the result all share one name taken straight from the id, so there's nothing to look up, IntelliSense lists a feature's actions together (they start with the same word), and a new action lands as one more method without reshaping any group.

Every action's exact signature is in the reference.

Actions chosen at run time

For tools where people pick an action, such as a button editor or a macro builder:

C#
foreach (var info in ActionTypes.All)              // name, description, group, parameters, destructive…
    Console.WriteLine($"{info.Group}: {info.Name}");

object? result = await studio.RunAsync(ActionType.SceneNext);          // the typed result, as an object
var muted = (AudioMuteResult)(await studio.RunAsync(ActionType.AudioMute, new AudioMuteParams { Input = "Mic" }))!;

ActionTypes.All carries each parameter's type, choices topic, range, unit and default: enough to build a settings form. RunAsync("some.action", jsonObject) runs an action by id with JSON parameters, for an action newer than this SDK.

Events

Each event is its own C# event, with its own record:

C#
studio.ChatMessage += (_, e) => Console.WriteLine($"{e.Author?.Display}: {e.Text}");
studio.ActivitySupport += (_, e) => Console.WriteLine($"{e.Author?.Display} sent {e.Amount?.Display}");

And every event also arrives through one EventReceived, with its EventType and its typed record, ready to switch on:

C#
studio.EventReceived += (_, e) =>
{
    switch (e)
    {
        case SceneChangedEvent s: Console.WriteLine($"On air: {s.Name}"); break;
        case ActivityRaidEvent r: Console.WriteLine($"Raid: {r.Amount?.Value} viewers"); break;
        case ChatRowEvent row: Console.WriteLine($"{e.Type}: {row.Text}"); break;   // every chat row and activity
    }
};
  • An event comes while you follow its topic: scene.changed with TopicType.Scenes, chat with TopicType.Chat, activity with TopicType.Activity. SubscribeAsync(EventType.ActivityRaid) follows the topics that bring the events you name; EventType.ActivityRaid.Info().Topic says which.
  • Chat rows share a base. The activity events and ChatMessage all carry a chat row, so they derive from ChatRowEvent.
  • Threading. Events and state changes are raised on the connection's reading thread, in the order Studio sent them. Hand long work off to your own thread. If a handler throws, the client carries on and raises HandlerFailed.

State

Each topic's latest value is a typed property of studio.State, kept current by Studio's pushes once you subscribe, with a typed event per topic:

C#
await studio.SubscribeAsync(TopicType.Audio, TopicType.Stream);
studio.State.StreamChanged += (_, s) => Console.WriteLine($"Stream: {s.State} for {s.Seconds} s");
var mic = studio.State.Audio!.Items.Values.First(a => a.Name == "Mic");
Console.WriteLine($"Mic at {mic.VolumeDb} dB, muted: {mic.Muted}");

FetchStateAsync() reads topics once without following them. State.Changed reports any topic's change with its TopicType.

Errors

Every error Studio sends is its own exception, deriving from VelumException, with Studio's plain-English message and its ErrorCode:

C#
try
{
    await studio.StreamStopAsync(new StreamStopParams { Confirm = true });
}
catch (VelumNotFoundException e) { /* a scene, source or destination that doesn't exist */ }
catch (VelumRateLimitedException e) { await Task.Delay(e.RetryAfter ?? TimeSpan.FromSeconds(3)); }
catch (VelumException e) { Console.WriteLine($"{e.Code}: {e.Message}"); }

VelumConnectionException means Studio couldn't be reached, or the connection closed before the answer came. Every code's class is in the error reference.

Connecting

  • This computer. ConnectAsync() reads Studio's discovery file, skips entries of Studios that aren't running, and connects with the token over the velum.v1 subprotocol.
  • Several Studios. StudioDiscovery.FindRunning() lists them; pick one with InstanceName (or Port) in VelumClientOptions.
  • Reconnecting is on by default. When Studio restarts or the connection drops, the client reads the discovery file again (the port and token may have changed), reconnects, and follows the same topics again. Disconnected and Reconnected say when. See Events and reconnecting.
  • Another computer. Pair once with the QR code's link, keep the result, and connect with it from then on. The connection is TLS, trusted only when Studio's certificate has the fingerprint from the QR code:
C#
var device = await VelumStudioClient.PairAsync(PairingLink.Parse(qrText), "Studio Deck");
File.WriteAllText(path, device.ToJson());   // keep it private: the token is this device's own
await using var studio = await VelumStudioClient.ConnectAsync(new VelumClientOptions { Device = PairedDevice.FromJson(File.ReadAllText(path)) });

Versioning

StudioCatalog.Version is the catalog version the SDK was generated from; studio.Hello.CatalogVersion is the running Studio's. When Studio's is higher, it has actions this SDK doesn't: they still run through RunAsync("some.action", json), and their events arrive through UnknownNotification.

  • The package version is the generator's major version, then the catalog version (1.17.0 for catalog version 17). The informational version adds the catalog's fingerprint.
  • A word Studio adds to an enum later (a new stream state, say) reads as Unknown rather than failing, and fields Studio adds are ignored until you regenerate.

A complete example

A console app that lists scenes, switches them from the keyboard, and prints chat and activity as it happens. This is the SDK's own sample, copied here when the site is built:

C#sdk/csharp/samples/Velum.Studio.Sample/Program.cs
// SPDX-License-Identifier: MIT
// A small console app: connect to the Velum Studio running on this
// computer, list its scenes, react to scene changes and chat as they
// happen, and switch scenes from the keyboard.
//
//   dotnet run --project samples/Velum.Studio.Sample
//   dotnet run --project samples/Velum.Studio.Sample -- "Velum Studio (2)"   (another instance)

using System;
using System.Linq;
using System.Threading.Tasks;
using Velum.Studio;

var options = new VelumClientOptions { ClientName = "Sample console", InstanceName = args.FirstOrDefault() };
VelumStudioClient studio;
try
{
    studio = await VelumStudioClient.ConnectAsync(options);
}
catch (VelumConnectionException e)
{
    Console.Error.WriteLine($"Couldn't reach Velum Studio: {e.Message}");
    return 1;
}

await using (studio)
{
    Console.WriteLine($"Connected to {studio.Hello.InstanceName} {studio.Hello.Version} (catalog {studio.Hello.CatalogVersion}; this SDK knows {StudioCatalog.Version}).");

    studio.SceneChanged += (_, e) => Console.WriteLine($"On air: {e.Name}");
    studio.ChatMessage += (_, e) => Console.WriteLine($"[{e.Platform.ToWire()}] {e.Author?.Display}: {e.Text}");
    studio.EventReceived += (_, e) =>
    {
        // Every activity is a chat row under its own event type.
        if (e is ChatRowEvent row && e.Type != EventType.ChatMessage)
        {
            Console.WriteLine($"{e.Type}: {row.Text}");
        }
    };
    studio.Disconnected += (_, e) => Console.WriteLine($"Disconnected ({e.Reason}){(e.Reconnecting ? "; reconnecting…" : "")}");
    studio.Reconnected += (_, h) => Console.WriteLine($"Reconnected to {h.InstanceName}.");
    studio.HandlerFailed += (_, e) => Console.Error.WriteLine(e);

    await studio.SubscribeAsync(TopicType.Scenes, TopicType.Chat, TopicType.Activity, TopicType.Stream);
    await studio.FetchStateAsync([TopicType.Scenes, TopicType.Stream]);

    while (true)
    {
        var scenes = studio.State.Scenes!.Items.Values.OrderBy(s => s.Index).ToList();
        Console.WriteLine();
        for (var i = 0; i < scenes.Count; i++)
        {
            var mark = scenes[i].Id == studio.State.Scenes.Program ? "*" : " ";
            Console.WriteLine($" {mark} {i + 1}. {scenes[i].Name}");
        }
        Console.WriteLine($"Stream: {studio.State.Stream?.State.ToWire()}. Type a number to put that scene on air, or q to quit.");
        var line = await Task.Run(Console.ReadLine);
        if (line is null || line.Trim() == "q")
        {
            return 0;
        }
        if (int.TryParse(line, out var n) && n >= 1 && n <= scenes.Count)
        {
            try
            {
                var r = await studio.SceneSwitchAsync(new SceneSwitchParams { Scene = scenes[n - 1].Id });
                Console.WriteLine($"Switched to {r.Name}.");
            }
            catch (VelumException e)
            {
                Console.WriteLine($"Studio said: {e.Message} ({e.Code})");
            }
        }
    }
}
Shell
dotnet run --project samples/Velum.Studio.Sample
dotnet run --project samples/Velum.Studio.Sample -- "Velum Studio (2)"   # another instance

The sample sets IsAotCompatible; publish it with -p:PublishAot=true and it builds without a warning.

to open · ↑ ↓ to move · Esc to close