1 title:: Writing Unit Generators
2 summary:: Get started with writing unit generators
6 section:: How Unit Generator plug-ins work.
8 The server loads unit generator plug-ins when it starts up. Unit Generator plug-ins are dynamically loaded libraries
9 written in C++. Each library may contain one or multiple unit generator definitions. A plug-in can also define things
10 other than unit generators such as buffer fill ("/b_gen") commands. Plug-ins are loaded during the startup of the
11 synthesis server. Therefore the server will have to be restarted after (re-)compiling the plugin.
14 section:: The Entry Point
16 When the library is loaded the server calls a function in the library, which is defined by the code::PluginLoad()::
17 macro. This entry point has two responsibilities:
20 ## It needs to store the passed in pointer to the InterfaceTable in a global variable.
21 ## It registers the unit generators.
24 Unit Generators are defined by calling a function in the InterfaceTable and passing it the name of the unit generator,
25 the size of its C data struct, and pointers to functions for constructing and destructing it. There are 4 macros, which
26 can be used to simplify the process.
29 ## DefineSimpleUnit || Define a `simple' unit generator
30 ## DefineDtorUnit || Define a unit generator with a descructor
31 ## DefineSimpleCantAliasUnit || Define a `simple' unit generator, whose input and output buffers cannot alias
32 ## DefineDtorCantAliasUnit || Define a unit generator with a destructor, whose input and output buffers cannot alias
35 These macros depend on a specific naming convention:
37 ## The unit generator struct is named like the plug-in.
38 ## The unit generator constructor is named code::PluginName_Ctor::
39 ## The unit generator destructor is named code::PluginName_Dtor::
43 section:: A Simple Unit Generator Plugin
45 Unit generator plugins require two parts: A C++ part, which implements the server-side code that is loaded as a
46 dynamically loaded library, and an SCLang class, that is required to build the link::Classes/SynthDef::. The following
47 example implements a simple Sawtooth oscillator
49 subsection:: C++-side Definition of Unit Generators
51 The following code shows the C++ source of a simple unit generator.
54 #include "SC_Plugin.h"
56 // InterfaceTable contains pointers to functions in the host (server).
57 static InterfaceTable *ft;
59 // declare struct to hold unit generator state
60 struct MySaw : public Unit
62 double mPhase; // phase of the oscillator, from -1 to 1.
63 float mFreqMul; // a constant for multiplying frequency
66 // declare unit generator functions
67 static void MySaw_next_a(MySaw *unit, int inNumSamples);
68 static void MySaw_next_k(MySaw *unit, int inNumSamples);
69 static void MySaw_Ctor(MySaw* unit);
72 //////////////////////////////////////////////////////////////////
74 // Ctor is called to initialize the unit generator.
75 // It only executes once.
77 // A Ctor usually does 3 things.
78 // 1. set the calculation function.
79 // 2. initialize the unit generator state variables.
80 // 3. calculate one sample of output.
81 void MySaw_Ctor(MySaw* unit)
83 // 1. set the calculation function.
84 if (INRATE(0) == calc_FullRate) {
85 // if the frequency argument is audio rate
86 SETCALC(MySaw_next_a);
88 // if the frequency argument is control rate (or a scalar).
89 SETCALC(MySaw_next_k);
92 // 2. initialize the unit generator state variables.
93 // initialize a constant for multiplying the frequency
94 unit->mFreqMul = 2.0 * SAMPLEDUR;
95 // get initial phase of oscillator
96 unit->mPhase = IN0(1);
98 // 3. calculate one sample of output.
99 MySaw_next_k(unit, 1);
103 //////////////////////////////////////////////////////////////////
105 // The calculation function executes once per control period
106 // which is typically 64 samples.
108 // calculation function for an audio rate frequency argument
109 void MySaw_next_a(MySaw *unit, int inNumSamples)
111 // get the pointer to the output buffer
114 // get the pointer to the input buffer
117 // get phase and freqmul constant from struct and store it in a
119 // The optimizer will cause them to be loaded it into a register.
120 float freqmul = unit->mFreqMul;
121 double phase = unit->mPhase;
123 // perform a loop for the number of samples in the control period.
124 // If this unit is audio rate then inNumSamples will be 64 or whatever
125 // the block size is. If this unit is control rate then inNumSamples will
127 for (int i=0; i < inNumSamples; ++i)
129 // out must be written last for in place operation
131 phase += freq[i] * freqmul;
133 // these if statements wrap the phase a +1 or -1.
134 if (phase >= 1.f) phase -= 2.f;
135 else if (phase <= -1.f) phase += 2.f;
141 // store the phase back to the struct
142 unit->mPhase = phase;
145 //////////////////////////////////////////////////////////////////
147 // calculation function for a control rate frequency argument
148 void MySaw_next_k(MySaw *unit, int inNumSamples)
150 // get the pointer to the output buffer
153 // freq is control rate, so calculate it once.
154 float freq = IN0(0) * unit->mFreqMul;
156 // get phase from struct and store it in a local variable.
157 // The optimizer will cause it to be loaded it into a register.
158 double phase = unit->mPhase;
160 // since the frequency is not changing then we can simplify the loops
161 // by separating the cases of positive or negative frequencies.
162 // This will make them run faster because there is less code inside the loop.
164 // positive frequencies
165 for (int i=0; i < inNumSamples; ++i)
169 if (phase >= 1.f) phase -= 2.f;
172 // negative frequencies
173 for (int i=0; i < inNumSamples; ++i)
177 if (phase <= -1.f) phase += 2.f;
181 // store the phase back to the struct
182 unit->mPhase = phase;
186 // the entry point is called by the host when the plug-in is loaded
189 // InterfaceTable *inTable implicitly given as argument to the load function
190 ft = inTable; // store pointer to InterfaceTable
192 DefineSimpleUnit(MySaw);
196 subsection:: SCLang-side Definition of Unit Generators
198 SuperCollider requires an SCLang class in order to build SynthDefs.
200 The arguments to the MySaw UGen are code::freq:: and code::iphase::. The code::multiNew:: method handles multi channel
201 expansion. The code::madd:: method provides support for the mul and add arguments. It will create a MulAdd UGen if
202 necessary. You could write the class without mul and add arguments, but providing them makes it more convenient for the
203 user. See link::WritingClasses:: for details on writing sclang classes.
206 // without mul and add.
208 *ar { arg freq = 440.0, iphase = 0.0;
209 ^this.multiNew('audio', freq, iphase)
211 *kr { arg freq = 440.0, iphase = 0.0;
212 ^this.multiNew('control', freq, iphase)
217 subsection:: Building Unit Generator Plugins
219 The most portable way to build plugins is using cmake footnote::http://www.cmake.org::, a cross-platform build
220 system. In order build the example with cmake, the following code should go into a code::CMakeLists.txt:: file.
223 cmake_minimum_required (VERSION 2.8)
226 include_directories(${SC_PATH}/include/plugin_interface)
227 include_directories(${SC_PATH}/include/common)
228 include_directories(${SC_PATH}/external_libraries/libsndfile/)
230 set(CMAKE_SHARED_MODULE_PREFIX "")
232 set(CMAKE_SHARED_MODULE_SUFFIX ".scx")
235 add_library(MySaw MODULE MySaw.cpp)
239 section:: Coding Guidelines
241 Unit generator plugins are called from the real-time context, which means that special care needs to be taken in order
242 to avoid audio dropouts.
245 ## Memory Allocation || Do not allocate memory from the OS via code::malloc:: / code::free:: or code::new::/ code::delete::.
246 Instead you should use the real-time memory allocator via code::RTAlloc:: / code::RTFree::.
247 ## STL Containers || It is generally not recommended to use STL containers, since they internally allocate memory. The only
248 way the STL containers can be used is by providing an Allocator, which maps to the allocating functions of
250 ## Blocking API Calls || Unit generators should not call any code, which could block the execution of the current thread. In
251 particular, system calls should be avoided. If synchronization with other threads is required, this has to be
252 done in a lock-free manner.
256 section:: Thread Safety
258 There are two different implementations of the SuperCollider server. strong::scsynth:: is the traditional server and
259 strong::supernova:: is a new implementation with support for multi-processor audio synthesis. Since the plugins in
260 strong::supernova:: can be called at the same time from multiple threads, write access to global data structures needs
264 ## Shared Global Data Structures || Unit generators should not share data structures, which are written to. While it it safe to use
265 global data structures for read-only purposes (e.g. different unit generators could use the same constant wavetable),
266 the data structures that are modified by the unit generators should not be shared among different instances.
268 ## Resource Locking || SuperCollider's buffers and busses are global data structures, and access needs to be synchronized.
269 This is done internally by using reader-writer spinlocks. This is done by using the code::ACQUIRE_::, code::RELEASE_::, and
270 code::LOCK_:: macros, which are defined in SC_Unit.h.
273 subsection:: Deadlock Prevention
275 In order to prevent deadlocks, a simple deadlock prevention scheme is implemented, based on the following constraints.
278 ## Lock resources only when required: few unit generators actually require the access to more than one resource at the same time.
279 The main exception of this rule are the FFT Chain ugens, which access multiple buffers at the same time. There is no known unit
280 generator, which accesses both buffers and busses at the same time.
281 ## Acquire reader locks if possible. Since multiple ugens can acquire a reader lock to the same resource at the same time, their
282 use reduces contention.
283 ## Resources have to be acquired in a well-defined order: busses should be acquired before buffers and resources with a high index
284 should be acquired before resources with a low index.