#lang scribble/manual
@(require (for-label racket))

@title{Pattern Guide Cookbook 03: External Control}
 Pattern control by external device@section{related}
  Tutorials/A-Practical-Guide/PG_Cookbook02_Manipulating_Patterns, Tutorials/A-Practical-Guide/PG_Cookbook04_Sending_MIDI
@section{categories}
  Streams-Patterns-Events>A-Practical-Guide

@section{section}
 Pattern control by external device

@section{subsection}
 Control of parameters by MIDI or HID

The best approach is to save an incoming value into a variable, and then use link::Classes/Pfunc:: to access the variable for each event.


@racketblock[
(
~legato = 1;
c = MIDIFunc.cc({ |value, num, chan, src|
	~legato = value.linlin(0, 127, 0.1, 2.5)
}, 1);	// 1 means modwheel
)

(
p = Pbind(
	\degree, Pwhite(-7, 12, inf),
	\dur, Pwrand([0.25, Pn(0.125, 2)], #[0.8, 0.2], inf),
	\legato, Pfunc { ~legato }	// retrieves value set by MIDI control
).play;
)

p.stop;
c.free;
::

If Pfunc ]

@racketblock[{  }:: is bothersome in the Pbind, a link::Classes/PatternProxy:: or link::Classes/Pdefn:: could also serve the purpose.

]

@racketblock[
(
~legato = PatternProxy(1);
c = MIDIFunc.cc({ |value, num, chan, src|
	~legato.source = value.linlin(0, 127, 0.1, 2.5)
}, 1);
)

(
p = Pbind(
	\degree, Pwhite(-7, 12, inf),
	\dur, Pwrand([0.25, Pn(0.125, 2)], #[0.8, 0.2], inf),
	\legato, ~legato
).play;
)

p.stop;
c.remove;
::

]
@section{subsection}
 Triggering patterns by external control

Issuing 
@racketblock[play:: to a pattern can occur in an action function for many different kinds of objects: GUI, MIDI, OSCFunc, HID actions. This allows triggering patterns from a variety of interfaces.

It's very unlikely that an action function would be triggered exactly in sync with a clock. If the pattern being played needs to run in time with other patterns, use the ]

@racketblock[quant:: argument to control its starting time (see link::Classes/Quant::).

]
@section{subsection}
 Triggering a pattern by a GUI


@racketblock[
(
var	pattern = Pbind(
		\degree, Pseries(7, Pwhite(1, 3, inf) * Prand(#[-1, 1], inf), inf).fold(0, 14)
			+ Prand(#[[0, -2, -4], [0, -3, -5], [0, -2, -5], [0, -1, -4]], inf),
		\dur, Pwrand(#[1, 0.5], #[0.8, 0.2], inf)
	),
	player, window;

window = Window.new("Pattern trigger", Rect(5, 100, 150, 100))
		// onClose is fairly important
		// without it, closing the window could leave the pattern playing
	.onClose_({ player.stop });
Button.new(window, Rect(5, 5, 140, 90))
	.states_([["Pattern GO"], ["Pattern STOP"]])
	.font_(Font.new("Helvetica", 18))
	.action_({ |button|
		if(button.value == 1 and: { player.isNil or: { player.isPlaying.not } }) {
			player = pattern.play;
		} {
			player.stop;
			button.value = 0;
		};
	});
window.front;
)

p.stop;
::

]
@section{subsection}
 Triggering a pattern by MIDI


@racketblock[
(
var	pattern = Pbind(
		\degree, Pseries(7, Pwhite(1, 3, inf) * Prand(#[-1, 1], inf), inf).fold(0, 14)
			+ Prand(#[[0, -2, -4], [0, -3, -5], [0, -2, -5], [0, -1, -4]], inf),
		\dur, Pwrand(#[1, 0.5], #[0.8, 0.2], inf)
	),
	player;

~noteOnFunc = MIDIFunc.noteOn({
	if(player.isNil or: { player.isPlaying.not }) {
		player = pattern.play;
	} {
		player.stop;
	};
// 60 limits this MIDIFunc to listen to middle-C only
// but it will pick up that note from any port, any channel
}, 60);
)

// when done
~noteOnFunc.free;
::

]
@section{subsection}
 Triggering a pattern by signal amplitude

Triggering a pattern based on audio amplitude is a bit trickier -- not because it's harder to play the pattern, but because identifying when the trigger should happen is more involved. The most straightforward way in SuperCollider is to use the link::Classes/Amplitude:: UGen to get the volume of the input signal and compare it to a threshold. Volume can fluctuate rapidly, so the 
@racketblock[releaseTime:: argument of Amplitude is set to a high value. This makes the measured amplitude fall more slowly toward the baseline, preventing triggers from being sent too close together.

The actual threshold depends on the incoming signal, so the example pops up a quick and dirty window to see the measured amplitude and set the threshold and decay accordingly. The synth listens by default to the first hardware input bus, but you can change it the following in the code to use a different input bus:

]

@racketblock[
	inbus: s.options.numOutputBusChannels
::

In this configuration, the first trigger starts the pattern and the second trigger stops it. You might want the pattern to play while the input signal is above the threshold, and stop when the signal drops to a quieter level. The comparison ]

@racketblock[amp >= thresh:: can send a trigger only when the signal goes from softer to lower, so if we want the pattern to stop when the signal becomes quiet, we need to send a trigger when crossing the threshold in both directions.

]

@racketblock[
	var	amp = Amplitude.kr(In.ar(inbus, 1), attackTime: 0.01, releaseTime: decay),
		trig = HPZ1.kr(amp >= thresh);
	SendTrig.kr(trig.abs, 1, trig);
::

link::Classes/HPZ1:: is positive if its input rises and negative if it falls. Triggering based on the absolute value, then, sends the trigger on any change. The client responding to the trigger might need to know the direction of change, so we send HPZ1's value back and the client can decide which action to take based on the sign of this value.

For this example, triggers are measured only when the signal rises above the threshold.

]

@racketblock[
(
var	pattern = Pbind(
		\degree, Pseries(7, Pwhite(1, 3, inf) * Prand(#[-1, 1], inf), inf).fold(0, 14)
			+ Prand(#[[0, -2, -4], [0, -3, -5], [0, -2, -5], [0, -1, -4]], inf),
		\dur, Pwrand(#[1, 0.5], #[0.8, 0.2], inf)
	),
	player;

// Quicky GUI to tune threshold and decay times
~w = Window("threshold setting", Rect(15, 100, 300, 100))
	.onClose_({
		~ampSynth.free;
		~ampUpdater.free;
		~oscTrigResp.free;
		player.stop;
	});
~w.view.decorator = FlowLayout(~w.view.bounds, 2@2, 2@2);
~ampView = EZSlider(~w, 295@20, "amplitude", \amp, labelWidth: 80, numberWidth: 60);
~ampView.sliderView.canFocus_(false).enabled_(false);
~ampView.numberView.canFocus_(false).enabled_(false);
StaticText(~w, 295@5).background_(Color.gray);
~threshView = EZSlider(~w, 295@30, "threshold", \amp, action: { |ez|
	~ampSynth.set(\thresh, ez.value);
}, initVal: 0.4, labelWidth: 80, numberWidth: 60);
~decayView = EZSlider(~w, 295@30, "decay", #[0.1, 100, \exp], action: { |ez|
	~ampSynth.set(\decay, ez.value);
}, initVal: 80.0, labelWidth: 80, numberWidth: 60);

~w.front;

~ampSynth = SynthDef(\ampSynth, { |inbus, thresh = 0.8, decay = 1|
	var	amp = Amplitude.kr(In.ar(inbus, 1), attackTime: 0.01, releaseTime: decay);
		// this trigger (id==0) is to update the gui only
	SendReply.kr(Impulse.kr(10), '/amp', amp);
		// this trigger gets sent only when amplitude crosses threshold
	SendReply.kr(amp >= thresh, '/amptrig');
}).play(args: [inbus: s.options.numOutputBusChannels, thresh: ~threshView.value, decay: ~decayView.value]);

~ampUpdater = OSCFunc({ |msg|
	defer { ~ampView.value = msg[3] }
}, '/amp', s.addr);

~oscTrigResp = OSCFunc({ |msg|
	if(player.isNil or: { player.isPlaying.not }) {
		player = pattern.play;
	} {
		player.stop;
	};
}, '/amptrig', s.addr);
)
::

Previous:	link::Tutorials/A-Practical-Guide/PG_Cookbook02_Manipulating_Patterns::

Next:		link::Tutorials/A-Practical-Guide/PG_Cookbook04_Sending_MIDI::
]


