Sunday Declarative SC q&a / demo

I’ve been working on a new SuperCollider framework that envisions a forward-looking and I think much better way of making music with sclang, and resolves a lot of historical challenges and idiosyncracies. I am loosely calling it “declarative sclang”, but its really just building an expressive DSL that’s MORE declarative than existing patterns. As it is now, I’m actively using it to make music and experiment with syntax, so you can imagine it’s somewhere on a dusty side-road in between existing-sclang and some kind of “SuperCollider 4”-style rigorous and utopian “new language”. I’ve been keeping a contract with myself that it always be usable for actual music-making - avoiding the classic SuperCollider trap of “making frameworks instead of making sounds” - but also grounding the more abstract computer science experiments with real use-cases. It’s been incredible effective for this - I’ve used versions of this on three separate live performances or installations in the last 6 months, including one very serious and complex one.

To outline a few principles that are at the core - these are north stars, and not finished features :slight_smile:

  • User code is 1:1 with the desired outcome, not a recipe or roadmap to reach the outcome.
  • User code specifies routing, the framework handles node ordering and bus allocation (not user-space problems, and have an a priori solution)
  • Missing SynthDefs, Buffers, and Node’s (“node not found”) on the server are impossible. If something is supposed to be there, it will be there. Complex async scheduling is handled correctly, no “first run this, then run this”.
  • Objects are not isolated, they live in a shared namespace and can reference and depend on each other. References and routing are fundamental concepts.
  • Everything is (possibly) a pattern - meaning: everything has the potential to change over time.
  • Composability and modularity as core concepts: a complex graph of 10 Synths should be playable using exactly the same code as a single Synth.
  • Semantics should make important musical concepts (“phrases”, “voices”, signal chains) trivial to express without utility functions, sugar, or magic.
  • Avoid layering new design patterns on top of ones: aim for a rigorous from-scratch server interface etc that has good INTEROP with old code, rather than trying to WRAP old classes in new packaging.

I want to share some of this because it’s exciting, and also because I’d like to get some feedback from other folks in the community, since thus far this has been oriented toward my own music workflows.
So this Sunday at 16:00 CET, I’ll do a live stream where I’ll demo the features and do some actual music making with it.
Twitch stream is here: Twitch

If there’s a critical mass of people, I would do a more organized walk-through, otherwise I’ll probably just jam for a few hours and answer questions or discuss things ad hoc! If you miss it, i’ll probably do more of these so don’t sweat it.

hopefully see some of y’all there! I can also answer questions on here as well.

Here’s an example of some real, working code that represents a subset of the frameworks capabilities, but I think it demonstrates some things that are quite hard to do with vanilla SC code, or any existing frameworks:

(
~p = PioPlayer();

// THE DRIVER: control only, no synth — ONE event per section; it owns the harmony
~p[\driver] =
    PioType.meta.bind(
        dur:    8,
        legato: Pwhite(0.3, 1.0),
        which:  Pseq([\a, \a, \b, \c], inf),
        scale:  Pseq([
            Scale([0, 3, 7, 10, 14, 17, 21], 24),
            Scale([-1, 4, 6, 8, 14, 17, 21], 24),
        ], inf).stutter(2),
        chord:  Pseq([0, 3, -2, 5], inf),
    );

// A DEF SLOT: a graph, consumed by name — NamedOut(\wet) is a second output
~p[\pluckDef] =
    PioType.synthDef {
        var freq = \freq.kr(220),
            env  = Env.perc(0.002, \decay.kr(0.3), curve: -6).kr(doneAction: 2),
            sig  = SinOsc.ar(freq, SinOsc.ar(freq * \ratio.kr(1.414)) * \index.kr(3) * env);
        sig = Pan2.ar(sig * env * 0.5, \pan.kr(0));
        sig ==> NamedOut();
        sig ==> NamedOut(\wet);
    };

// MONO + a BUILD-time hole: `spread:` shapes the graph, .bind keys are controls
~p[\pad] =
    PioType.synthDef(mono: true, spread: 8) {
        var n   = \spread.def(2),
            env = Env.asr(2, 1, 4).kr(gate: \gate.kr(1), doneAction: 2),
            sig = Ringz.ar(
                0.1 * Crackle.ar(),
                freq: \freq.kr(110) * ((0..n - 1) * 2.5).midiratio,
                decaytime: 0.5
            ).mean;
        sig = sig - FreqShift.ar(sig, LFDNoise3.kr(1/5).range(-0.04, 0.04));
        NamedOut() <== (Splay.ar(LPF.ar(sig, \cutoff.kr(800))) * env);
    }.bind(
        octave: 5,
        scale:  PioKey(\driver, \scale),
        degree: PioKey(\driver, \chord),
        cutoff: PioLift.mod { LFDNoise3.kr(1/4).exprange(300, 9400) },
        amp:    -20.dbamp,
    );

// DISPATCH: trigger a pattern on \a, \b
~p[\arp] = 
    PioSync(\driver).filter { 
        |e| [\a, \b].includes(e[\which]) 
    }.with {
        PioType(PioKey(\pluckDef)).bind(
            octave:  5,
            scale:   ~scale,
            degree:  ~chord + Pshuf([0, 4, 1, 6, 3, 9, 2], inf), 
            dur:     if (~which == \b) { 3/4 } { 2/8 },
            index:   Pexprand(0.3, 8),
            decay:   1 * Pseq([1, 0.4, 0.6], inf), 
            amp:     0.2 * Pseq([1, 0.4, 0.6], inf),
            amp_wet: 0.1,
        )
    };

// A FORK: each event spawns a phrase, windowed to that event's dur — the meta-durs
// are the phrase lengths, and `steps` is the one setting each phrase is handed
~p[\bass] =
    PioType.fork(
        steps:  Pseq([[0, 0, 3], [0, -2, 5, 1], [0, 7], [0, 3, -2]], inf),
    )
    {                                   // runs IN the fork event: reads ~steps
        PioType(PioKey(\pluckDef)).bind(
            octave: 3,
            scale:  PioKey(\driver, \scale),
            degree: \bump.ev + PioKey(\driver, \chord) + Pseq(\steps.def, inf),
            dur:    Prand([3/4, 3/4, 1/2], inf),
            decay:  0.4,
            index:  1.2,
            amp:    0.3,
        )
    }
    .bind(
        dur:    Pseq([4, 2, 2, 8], inf),
        legato: 1,
        bump: Pwhite(-4, 24),
    );

~p[\echo] = PioType.fx { |in| in + CombC.ar(in, 1, LFDNoise3.kr(0.1).range(6/8, 6/8.1), 3) }.bind();
~p[\verb] = PioType.fx { |in| FreeVerb2.ar(in[0], in[1], 1, 0.9, 0.3) }.bind();

~p.route {
    ~bass --> ~echo;
    ~arp[\wet] --> ~verb; 
    [
        ~arp, 
        ~pad, 
        ~echo, 
        ~verb
    ] --> ~output;
}.play();
)
7 Likes

A fun discovery - the \structure type is just a way of wrapping a more complex structure (e.g. a chain of synths) as a single item. This is directly usable from user code, but is also used sometimes for cases where e.g. a single thing actually needs to expand into a few related slots (e.g. multiple parallel patterns). For example, fork in the above example (which spawns parallel patterns) is just built on top of structure.

As a sort of add-on to this today, I made \structureMap:

PioType.structureMap {
   |i|
   PioType(PioRef(\mySynth)).bind(
          degree: i
   )
}.bind(items: [0, 2, 4, 6])

You can probably guess, this just makes a structure with 4 synths, each with a different degree. This is just a minor modification of the existing feature, so all of structureMap is only ~50 lines of code. But this makes something like a midi keyboard extraordinarily easy to implement:

~p[\keyboard] = PioType.meta.bind(
   items: {
     var keys = ();
     Pfunc {
         |e|
         e[\midinote] !? {  
          keys[e[\midinote]] = if (e[\gate] == 1) {
             e
          }
     }
   }.()
);

~p[\synth] = PioType.structureMap {
   |midi|
   PioType(PioRef(\mySynth)).bind(
          midinote: midi[\midinote],
          amp: midi[\velocity] / 127.0
   )
}.bind() <> PioSync(\keyboard)

This is all that’s needed for a fully functioning midi keyboard implementation - it feels quite elegant this way, i can’t really see many ways to simplify this without adding sugar or utility functions etc.

Some notes:

  • the inner structure items are patterns, so a MIDI note that triggers a sequence of events is the same code as a single note. This wouldn’t get aftertouch info, but its a fairly small jump to add that functionality.
  • PioSync will wake the slot when the referenced thing is updated - this doesn’t currently happen for individual line-item value references, though maybe this works in the future.
2 Likes

I’ll just demo some things here as I work with them, maybe people will be interested in following along.

Every “slot” in the Pio system (temporary name…) is loosely a set of consistent server resources, a single synth or a group of similar synths that can be treated as a single entity. These exist in a flat namespace:

~p[\synth1] = PioType(PioRef(\synth1Def)).bind();
~p[\synth2] = PioType(PioRef(\synth1Def)).bind();

There are also three fundamental structural concepts, e.g. things that encode multi-slot structures. More complex things can be derives from these three. These are still in flux, so partly this is an exercise in how much I can narrow these down:

Fork: Distribute events flowing into ONE slot into several sibling slots. Some examples:

  • A single event in one slot is forked to a phrase in another slot (recursive phrasing)
  • Incoming events are forked on a midinote value to one voice-slot per note
PioType.fork {
    // one of these patterns is forked in place of every incoming event
    PioType(PioRef(\pingDef)).bind(degree: \base.ev(0) + Pseq([0, 2, 4, 7], inf), dur: 1/4, amp: 0.1)
}.bind(
    base:    Pseq([0, 2, 4, 7], inf),
    dur:     4,
    legato:  1.5,
);

Structure: Expand events from one slot into a nested structure of slots, e.g. slot A actually encodes a chain like B->C->D. Structure children are hidden, and outputs from the structure are chose explicitly.

PioType.structureDef {
    (
        voice: PioType(PioRef(\pluck)).bind(
            degree: \root.ev(0) + Pseq([0, 2, 4, 7], inf),
            dur:    1/4,
        ),
        fx:    PioType(PioRef(\echo)).bind(in: PioRef(\voice, \out), dur: 1),
        \: (out: PioRef(\fx, \out)),
    )
}.bind(root: Pseq([0, 2, 3], inf), dur: 4)

Lift: An inline slot description is lifted to a sibling slot, and connected automatically… This allows e.g. modulators and lfo’s to be declared inline.

PioType(PioRef(\synth)).bind(
    // transformed into synth.cutoff and referenced
    cutoff: PioLift.mod { LFDNoise3.kr(1/6).range(0.25, 0.7) },
);

These can be composed in nice ways. For example, this can mean basic synth playback:

PioType(PioRef(\synth)).bind(
    dur: 1,
    degree: Pseq([0, 1, 2], inf)
);

But if \synth is a fork + structure, then this plays a structure of multiple synths AS IF they were a regular single polysynth:

~p[\synth] = PioType.fork {
    PioType.structureDef {(
        voice: PioType(PioRef(\voice)).bind(),
        fx:    PioType(PioRef(\echo)).bind(),
        \: (out: PioRef(\fx, \out)),
    )}
};

This gets me to something I’ve been experimenting with: lifts inside of SynthDef functions. If a lift just means “create this as a sibling and then patch its output back in”, then we can also do this from inside a SynthDef function. We imagine a structureSynthDef type that’s a structure, but also passes in a context object that provides a lift function, and compiles the function a SynthDef. Then you can do something like this:

PioType.structureSynthDef {
    |ctx|
    var voices = ctx.lift(\voices) { 
        PioType.synthDef {
            (SinOsc.ar(\freq.kr) * Env.perc(0.005, 0.3).kr(doneAction: 2) ! 2) ==> NamedOut()
        }.bind(
            dur: 2,
            degree: Pseq([1, 2, 3, 4], inf),
            legato: 1.4
        )
    };
    var delaySettings = ctx.lift(\delaySettings) {
        PioType.meta.bind(
            dur: Prand([3, 6], inf) / 8,
            delay: Pseq([0.25, 0.5, 0.75], inf),
            decay: Pseq([1, 2, 3], inf),
        )
    };
    voices = voices + CombC.ar(voices, 
        delayTime: delaySettings[\delay], 
        decay: delaySettings[\decay],
        axDelayTime: 10
    );

    voices * Env.asr.gate(\gate.kr(1), doneAction: 2) ==> NamedOut();
};

This creates a structure with three slots: a voices slot (with a polyphonic synth playing), a delaySettings slot (with delay parameters), and an implicit output slot for the final audio signal. It does this by using the normal SynthDef syntax - ctx.lift simply does the existing lift operation for the contents, then returns a NamedControl to the SynthDef and keep track of the routing for later.

We have to do a few tricky things for more complex routing scenarios, e.g. if we want to SEND audio to a lifted slot, but this is in principle possible - maybe a syntax like this?

ctx.lift(\voices, cutoff: SinOsc.ar(1/8).exprange(100, 2000)) {
    LPF.ar(
        SinOsc.ar(\freq.kr),
        \cutoff.kr
    ) 
    * Env.perc(0.005, 0.3).kr(doneAction: 2)
    ==> NamedOut();
}

The reverse is also possible: synthdef fragments can be passed in from the outside, and fused into a single SynthDef. A simple version of this that current works is something like:

PioType.synthDef(
   fragment: { SinOsc.ar(100) },
) {
    var sig = \fragment.def.value;
}

But with a little plumbing, full SynthDefs could be composed also:

PioType.synthDef(
   osc: PioType.synthDef {
        (SinOsc.ar(\freq.kr) * Env.perc(0.005, 0.3).kr(doneAction: 2) ! 2) ==> NamedOut()
   },
   fx: PioType(PioRef(\delay))
) {
    var sig = \osc.def(
         freq: \freq.kr
    )[\out];
    sig = \fx.def(in: sig, delayTime: 1/4);
}
2 Likes

I saw this thread pop up and wasn’t able to make the livestream – just wanted to say that this looks very very cool. It’s such an unfamiliar way of thinking (and I’m burdened by a couple decades of usage patterns) that I haven’t come anywhere near to wrapping my head around it, but I can see the point. My ddwPlug quark takes a step in the direction of improved patchability, but is a bit specific to my use cases. This is broader and much more general.

Just wanted to take a moment to recognize that :+1::+1:

hjh

1 Like

thx james!

Part of the process is coming up with a sort of minimum number of concepts that it takes to generate most of the graph constructions you would want on a SuperCollider server, or musically in general. I’ve been through a lot of refinement and it HAS actually clarified a lot. I think probably its a bit obscure now, but at least for me where building things is almost universally simpler and clearer once I can wrap my head around how to combine concepts.

An interesting thing I’ve been working out with this reactive slot system…

Reactive systems often have wall clock / logical time, plus another layer of time, where operations can be ordered within a single logical time wake-up. For various reasons I’m trying to AVOID this, and instead have a model where every slot has a single deterministic output state - I dont want to re-run parts of the graph multiple times for a single logical time, for various reasons.

This creates a problem with non-value events, e.g. things that can happen multiple times per clock-wake-up. The most obvious case is something like hitting three midi notes at the same time - you might receive three MIDI events, and (for example) two CC events at the same time. There’s no “standard” way to resolve a queue of 3x events and 2x events. You can run each through the system once, but it can create a ton of consistency issues, not to mention increases the number of updates from 1x to 6x. I’ve been trying to stick to a model where events that happen at one logical time get processed by a slot in a batch. If it has multiple queue inputs (3x and 2x), the slot decides what makes semantics sense. It can, for example, have an event output that contains some number of new events OR it can resolve the input events into a single value-state (e.g. for incoming CC messages, the value is probably simply the last received value).

Orthogonal issue (this comes back around, I promise…): I think I posted elsewhere about moving toward an explicit syntax for multichannel expansion in patterns. Currently, patterns multichannel expand along the first level of an arrayed value, so in: Pseq([1, 2, [3, 4]]) the third value expands to 2 voices. This makes it difficult to interleave if you have any array-like things as DATA, which leads to the annoying pattern of double-wrapping or Ref-wrapping: freqRange: Pseq([[[120, 4500], ...]) / Pseq([[120, 4500], …])`. This reads… bad: its very hard to see “nesting level” of arrays at a glance.

I experimented with an explicit expansion syntax - since expansions are a sort of structural operations thats different than data arrays, it makes sense to call these out explicitly. So:

Pseq([1, 2, Ex[3, 4]])

This is very easy to get working, and you get all kinds of nice nesting and explicitness. For example, non-array voice structures are easy: Pseq([Ex(a: 120, b: 320)]) (the equivalent of “flop” on this gives you a dictionary).

It occurred to me that it might ALSO be interesting to have time-axis expansion, Tx - in fact, Pseq sort of ends up being an equivalent - you might also write:

Tx[1, 2, Ex[3, 4]]

It turns out you can do some interesting things when expanding across two axes like this, but at least in some initial play it resolves more ambiguities than it creates. For example, these are pretty naturally equivalent:

(degree: Ex[0, Tx[3, 5, 7]]);
(degree: Tx[Ex[0, 3], Ex[0, 5], Ex[0, 7]]);

And in fact, you can write basically the same equivalence with the pattern system, using Pseq and Ptuple.

It turns out that time axis expansion actually provides a really nice solution to the original problem I was talking about - that is, how to handle multiple-events-at-a-time. What if we consider each edge between slots, at least potentially, a Tx and Ex structure - that is, something that implicitly has a time and voice axis. Then, the midi note case looks like this:

Tx[note45, note47, note51]

These come in as a single input with a shape - this is more or less exactly as we might handle voice expanded edges from a slot:

(
   degree: Ex[0, 2, 5]
)

This is one object, and there are good reason to treat it that was in lots of cases - but implicitly its 3 along the voice axis.

This provides a nice family of solutions for common audio event processing problems. So ofc, CC controls just flatten the Tx axis to the last value. Midi notes would swap the time axis for a voice axis, so:

Tx[note45, note47, note51]

becomes:

Ex(45: note, 47: note, 51: note)

(its not QUITE a simple as this, but I think its helpful to see that this case is sort-of solved with a basic transform like this)

Because this kind of axis expansion is implicit, you dont need to ACTUALLY expand until you need to get specific values of the overall structure. This is great because you can have something like this:

(
   octave: PioKey(\control, \octave),
   degree: Ex.newFrom(100.collect { rrand(5, 5.5) });
}

A bank of 100 detuned oscillators can be tracked as a single slot, with one graph edge (pointing to control → octave), rather than 100 edges.

I’ve been thinking of time axis expansion, Tx, purely in terms of representing multiple events at a single logical time - but I’m also wondering whether the gap between a regular Stream of values e.g. from a Pseq, and a scheduled stream of values, is just remapping along the Tx axis - so:

(
   value: Tx[1, 2, 3, 4],
   time: Tx[0, 0.1, 0.2, 0.3],
)

Becomes something like:

Tx(0: 1, 0.1: 2, 0.2: 3, 0.3: 4)

So the way a normal Event stream is actually read is something like: “remap the Tx axis according to the running sum of the \dur key”.

I’m not sure how valuable this is as a representation. But, having “time expansion” as an equivalent to voice expansion (e.g. one event that describes three note played at one time, vs three notes played offset in time, should be essentially the same) was something I hoped i could solve in an elegant way in this system, and this IS starting to feel more possible.

I’d also note that this might solve something ELSE interesting…

If we imagine that one value can actually be a collection of values along the Tx time axis, why not imagine that these values can be along a time axis that isn’t instantaneous? If our midi nodes were spaced in time, the we can imagine something like:

Tx(
   0.5: Ex(56: note),
   1.5: Ex(58: note),
   3.2: Ex(59: note),
)

We can treat this time-structure as a unitary value, and perform operations on it. For example, we can stretch it out in time by expanding the Tx axis. In a basic thought experiment way, then: what happens in a reactive system if we have a knob connected to the “stretch the time axis” parameter, and we turn the knob up or down?

There’s actually a really good solution to this, i think. If each note has a duration, then the time points are actually ranges, where outside of that range the voice is nil. So, what you really get is something like:

Tx(
   0.5: Ex(56: note), // 56 starts
   1.5: Ex(56: note, 58: note), // 58 starts
   3.2: Ex(58: note, 59: note), // 56 ends
)

So, stretching the time axis by turning the knob just gives us a different note map. In practice, this would mean that the “natural” behavior would be that notes just turn on/off depending on where along the Tx axis you happen to be after the stretch. This would work more or less naturally (adding/removing slots like this is already the core semantic move, so we get that for free). This would need the ability to reschedule slots, which is not available yet, but also a pretty straightforward concept.