skode

Hex Package HexDocs Engine Alignment BEAM Run in Livebook License: MIT

Type-safe AST, parser, and canonical serializer for Skode—the live-coding and musical command language of the Skred audio engine.

Written in pure Gleam with zero C/NIF dependencies. Runs natively on both the Erlang BEAM VM and JavaScript runtimes.


Production Applications & Dogfooding

skode is battle-tested in production across three flagship open-source audio applications:


Installation

Gleam

gleam add skode

Or in gleam.toml:

[dependencies]
skode = ">= 1.0.0 and < 2.0.0"

Elixir (mix.exs)

def deps do
  [
    {:skode, "~> 1.0.0"}
  ]
end

Erlang (rebar.config)

{deps, [
    {skode, "1.0.0"}
]}.

LFE (Lisp Flavoured Erlang)

Add to your project’s rebar.config:

{deps, [
    {skode, "1.0.0"}
]}.

Polyglot BEAM Quick Start

Because skode compiles directly to standard BEAM bytecode (.beam), all functions and tagged tuples are first-class citizens across all BEAM languages.

1. Gleam

import skode

pub fn main() {
  // Parse Skode string into a list of Chunk records
  let program = skode.parse_program("v0 w15 f440 a-6 l1; [lead] puts")

  // Construct AST programmatically
  let step = skode.Step(
    ops: [skode.Voice(0), skode.Freq(440.0), skode.Amp(-6.0), skode.Level(1.0)],
    at: 12,
  )

  // Serialize back to canonical Skode string
  let script = skode.op_to_string(step)
  // => "[v0 f440 a-6 l1] x12"
}

2. Elixir

# Parse Skode code into tagged tuples
chunks = :skode.parse_program("v0 w301 n60 l1; [bass] wt 100")

# Inspect structured chunks: [{:chunk, ops, remark}]
# Ops are tagged tuples: {:voice, 0}, {:note, 60, :none}, {:amp, -6.0}, etc.
[first_chunk | _] = chunks

# Serialize AST back to canonical Skode text
iodata = :skode.program_to_string(chunks)
# => "v0 w301 n60 l1\n[bass] wt 100"

# Check versions
"1.0.0"  = :skode.version()
"0.85.0" = :skode.pulp_version()

3. Erlang

%% Parse a Skode script binary
Chunks = skode:parse_program(<<"v0 f440 l1; [lead] puts">>),

%% Transform or inspect tagged tuples
%% Chunks = [{chunk, [{voice, 0}, {freq, 440.0}, {level, 1.0}], none}, ...]

%% Format canonically and stream over UDP to a local Skred synthesizer
SkodeBin = skode:program_to_string(Chunks),
gen_udp:send(Socket, "127.0.0.1", 7000, SkodeBin).

4. LFE (Lisp Flavoured Erlang)

;; Parse Skode binary into AST chunks
(set chunks (: skode parse_program #"v0 n60 l1"))

;; Serialize AST chunks back to Skode string
(set code (: skode program_to_string chunks))

;; Access engine alignment version
(set pulp-ver (: skode pulp_version))

5. erlua (Lua on the BEAM)

If you run Lua scripts inside the Erlang VM via erlua:

-- Access the compiled Erlang module
local skode = erlang.skode

-- Parse Skode script
local chunks = skode.parse_program("v0 w301 n60 l1")

-- Re-serialize canonical Skode
local text = skode.program_to_string(chunks)
print("Generated Skode: " .. text)

BEAM Data Mapping Reference

Gleam’s algebraic data types map to straightforward Erlang tagged tuples:

Gleam AST TypeErlang / Elixir Tuple Representation
Chunk(ops, remark){chunk, OpsList, None | {some, <<"comment">>}}
Voice(0){voice, 0}
Note(60, None){note, 60, none}
Note(60, Some(12.5)){note, 60, {some, 12.5}}
Freq(440.0){freq, 440.0}
Amp(-6.0){amp, -6.0}
Level(1.0){level, 1.0}
Glide(0.02, None){glide, 0.02, none}
Glide(0.0, None) (bare g){glide, 0.0, none}
Step(ops, 12){step, OpsList, 12}
Generic(Command(atom, ...)){generic, {command, <<"atom">>, Args, Array, String}}

Engine State Domain Models

In addition to the raw wire-protocol parser and AST, skode provides structured, typed domain models for managing synthesizer state in UI editors (like Lustre) and distributed BEAM processes:

Example: Reactive Voice & Master Volume Diffs (for Lustre / LiveView)

import skode/global
import skode/voice

pub fn demo() {
  // 1. Create default voice 0
  let v0 = voice.default(0)

  // 2. Tweak cutoff in UI (e.g. slider moves to 1250 Hz)
  let v1 = voice.Voice(..v0, filter: voice.Filter(..v0.filter, cutoff_hz: 1250.0))

  // 3. Compute surgical delta command to stream to engine
  voice.diff_skode(v0, v1)
  // => ["v0 k1250"]

  // 4. Adjust Master Volume (V)
  let g0 = global.default()
  let g1 = global.set_master_volume_db(g0, -3.5)
  global.diff_skode(g0, g1)
  // => ["V -3.5"]
}

Web Voice Editor & Live Synthesis

skode includes an interactive browser-based sound design editor built with Lustre and powered directly by an embedded WebAssembly build of the Skred audio engine.

Running the Editor Locally

make serve

This compiles the Lustre JavaScript application, bundles the WASM synthesis engine, and starts a local web server at http://localhost:8000.


Zero-Latency Browser Audio for BEAM Developers

For BEAM developers (Gleam, Elixir/Phoenix, Erlang) building web applications, streaming raw PCM audio over WebSockets or wrestling with stateful audio DOM components often leads to latency, jitter, and dropped frames.

The Skode + Pulp WASM model flips this entirely:

“BEAM Computes, Browser Plays”
Your BEAM backend manages game state, user interactions, generative music, or collaborative chords. Instead of streaming megabytes of heavy audio, it pushes tiny, human-readable Skode commands (a few bytes: "v0 w1 f440 a-6 T"). The browser’s embedded WebAssembly DSP engine synthesizes the sound locally at 44.1 kHz with zero network lag and zero server audio load.

1. Pure Gleam / Lustre Frontend (The 2-Line Pattern)

If your frontend is built with Gleam or Lustre, triggering real-time synthesis requires zero FFI boilerplate:

import skode/transport/wasm

pub fn play_sound() {
  // 1. Boots the DSP loop on first user click/touch
  let assert Ok(Nil) = wasm.start_default()

  // 2. Play an analog lead, drum hit, or sequence locally
  let assert Ok(Nil) = wasm.send_text("v0 w1 f440 a-6 T")
}

2. Phoenix / Elixir (The Frictionless Event Pattern)

Forget heavy, fragile LiveView audio components. Use a clean, fire-and-forget event pattern that never fights the DOM:

On the Server (page_live.ex, Channels, or Controller):

# Send sound effects, notifications, or musical chords as tiny strings:
push_event(socket, "skode", %{cmd: "v0 n60 T v1 n64 T v2 n67 T"})

In the Browser (app.js):

// 3 lines in your app.js: listen and play locally
window.addEventListener("phx:skode", (e) => {
  window.Module?.ccall("skred_command", "number", ["string"], [e.detail.cmd]);
});

3. Plain HTML & JavaScript (No Framework Required)

Drop the bundled runtime (skred_api.js + skred_api.wasm) into any static website, game, or presentation:

<!DOCTYPE html>
<html>
<head>
  <script src="skred_api.js"></script>
</head>
<body>
  <button id="btn">Play 440 Hz Saw</button>

  <script>
    document.getElementById("btn").addEventListener("click", () => {
      // Boot audio on first user gesture
      if (!window._started) {
        Module._skred_start(128, 16, 0);
        window._started = true;
      }
      // Send any Skode commands
      Module.ccall("skred_command", "number", ["string"], ["v0 w1 f440 a-6 T"]);
    });
  </script>
</body>
</html>

4. Interactive Livebook (Zero Server Audio Dependencies)

Run in Livebook

Run synthesis directly inside Livebook without installing any native audio drivers, ALSA, or C libraries on your Livebook host:

# 1. Start the client-side WebAssembly widget
audio = SkodeAudio.new()

# 2. Trigger chords, sequences, and sweeps from Elixir cells
SkodeAudio.play(audio, """
v0 w1 f220.00 a-6 T
v1 w1 f277.18 a-6 T
v2 w1 f329.63 a-6 T
""")

Open notebooks/skode_wasm.livemd in Livebook or click the badge above to explore polyphony, low-pass filter sweeps, algorithmic sequencing, and SID chiptune voices.


Engine Transports

skode provides zero-friction transports for interacting directly with Pulp’s mini-skred engine across different runtime environments:

1. UDP Transport (BEAM: Gleam / Elixir / Erlang)

Streams commands to mini-skred over UDP (port 7000 by default, enabled via SKRED_UDP=ON in Pulp). Zero native dependencies, complete crash isolation, and distributed across local or network machines.

import skode
import skode/transport/udp

pub fn main() {
  // Open ephemeral client socket
  let assert Ok(sock) = udp.open()

  // Stream raw commands
  let assert Ok(Nil) = udp.send(sock, "v0 w1 f440 a-6 T")

  // Or send structured AST programs
  let program = skode.parse_program("v0 f880 T; [lead] puts")
  let assert Ok(Nil) = udp.send_program_default(sock, program)

  udp.close(sock)
}

In Elixir:

{:ok, sock} = :skode@transport@udp.open()
:ok = :skode@transport@udp.send(sock, "v0 f440 a-6 T")
:skode@transport@udp.close(sock)

2. Erlang Port Subprocess Transport (BEAM)

Launches and supervises mini-skred directly as an external OS process over stdin/stdout lines, allowing standard OTP supervisors to monitor its lifecycle and restart on failure:

import skode/transport/port

pub fn main() {
  let assert Ok(p) = port.spawn_default()
  let assert Ok(Nil) = port.send_text(p, "v0 n60 l1")
  port.close(p)
}

3. WebAssembly Transport (JavaScript / Browser / Lustre)

Directly calls the native C DSP engine compiled to WebAssembly (skred_api.js + skred_api.wasm) in browser and Web Audio environments:

import skode/transport/wasm

pub fn play() {
  case wasm.is_available() {
    True -> {
      let assert Ok(Nil) = wasm.start_default()
      let assert Ok(Nil) = wasm.send_text("v0 n60 T")
    }
    False -> Nil
  }
}

Publishing to Hex.pm

To publish a release to Hex.pm:

# 1. Verify tests pass on both Erlang and JavaScript targets
gleam test --target erlang
gleam test --target javascript

# 2. Build and preview HexDocs
gleam docs build

# 3. Publish to Hex.pm
gleam publish

License

MIT License · Copyright (c) 2026 Joseph Ellis Stewart / Octetta (LICENSE)

✨ Search Document