MANUAL of new OPCODEs
by Gabriel Maldonado
g.maldonado@agora.stm.it
http://web.tiscalinet.it/G-Maldonado


THIS IS A LISTING OF ALL OPCODES IMPLEMENTED BY GABRIEL MALDONADO

Single slider control

idest midic7 ictlno, imin, imax [, ifn]
kdest midic7 ictlno, kmin, kmax [, ifn]

idest midic14 ictlno1, ictlno2, imin, imax [, ifn]
kdest midic14 ictlno1, ictlno2, kmin, kmax [, ifn]

idest midic21 ictlno1, ictlno2, ictlno3, imin, imax [, ifn]
kdest midic21 ictlno1, ictlno2, ictlno3, kmin, kmax [, ifn]

idest ctrl7 ichan, ictlno, imin, imax [,ifn]
kdest ctrl7 ichan, ictlno, kmin, kmax [,ifn]

idest ctrl14 ichan, ictlno1, ictlno2, imin, imax [,ifn]
kdest ctrl14 ichan, ictlno1, ictlno2, kmin, kmax [,ifn]

idest ctrl21 ichan, ictlno1, ictlno2, ictlno3, imin, imax [,ifn]
kdest ctrl21 ichan, ictlno1, ictlno2, ictlno3, kmin, kmax [,ifn]

DESCRIPTION

Return precise signal from a MIDI slider.

INITIALIZATION

idest - output signal
ichan - MIDI channel (1-16). In (i)ctrl14 and (i)ctrl21 all the controllers used in an opcode instance must be of the same channel
ictlno - midi controller number (1-127)
ictlno1 - most-significant byte controller number (1-127)
ictlno2 - in midic14: less-significant byte controller number (1-127); in midic21: mid-significant byte controller number (1-127)
ictlno3 - less-significant byte controller number (1-127)
imin - user-defined minimum floating-point value of output
imax - user-defined maximum floating-point value of output
ifn (optional) - table to be read when indexing is required. Table must be normalized. Output is scaled according to max and min val.

PERFORMANCE

kdest - output signal
kmin - user-defined minimum floating-point value of output
kmax - user-defined maximum floating-point value of output

midic7 (i and k rate 7 bit midi control) allows floating point 7 bit midi signal scaled with a minimum and a maximum range. They also allow optional non-interpolated table indexing.
In midic7 minimum and maximum values can be varied at krate.

midic14 (i and k-rate 14 bit midi control) does the same as the above with 14 bit precision.

midic21 (i and k rate 21 bit midi control) do the same as the above with 21 bit precision.

midic14 and midic21 can use optional interpolated table indexing. They require two or three midi controllers as input.

Warnig! Don't use (i)midicXX opcodes within a sco-activated i-statement or Csound will crash. Instruments containing (i)midicXX opcodes can be only activated by a MIDI note-on message. Use (i)ctrlXX opcodes if you need to include them in a sco-oriented instrument instead.

ctrl7, ctrl14, ctrl21 are very similar to midicXX opcodes the only differeces are:

  1. ctrlXX UGs can be included in sco-oriented instruments without Csound crashes.
  2. They need the addictional parameter ichan containing the MIDI channel of the controller.

MIDI channel is the same for all the controller used in a single (i)ctrl14 or (i)ctrl21 opcode.



Single slider control initialization

initc7 ichan, ictlno, ivalue
initc14 ichan, ictlno1, ictlno2, ivalue
initc21 ichan, ictlno1, ictlno2, ictlno3, ivalue

DESCRIPTION

Initializes MIDI controller ictlno with ivalue

INITIALIZATION

ichan - midi channel (1-16)
ictlno - controller number (initc7)
ictlno1 - MSB controller number
ictlno2 - in initc14 LSB controller number; in initc21 Medium Significant Byte controller number
ictlno3 - LSB controller number
ivalue - floating point value (must be within 0 to 1)

initc7, initc14, initc21 can be used togheter with both (i)midicXX and

(i)ctrlXX opcodes for initializing the first controllers' value.
Ivalue argument must be set with a number within 0 to 1. An error occurs if it is not.

Use the following formula to set ivalue according with (i)midicXX and (i)ctrlXX min and max range:

ivalue = (initial_value - min) / (max - min)



MIDI NOTE GENERATORS

noteon ichn, inum, ivel
noteoff ichn, inum, ivel
ondur ichn, inum, ivel, idur
ondur2 ichn, inum, ivel, idur

DESCRIPTION

send note-on and note-off messages to the MIDI OUT port.
(warning! these opcodes have been renamed in to avoid namespace pollution. Before noteon was ion, noteoff was ioff, ondur was iondur and ondur2 was iondur2).

INITIALIZATION

ichn - MIDI channel number (1-16)
inum - note number (0-127)
ivel - velocity (0-127)
idur - duration in seconds beetween noteon and relative noteoff messages

PERFORMANCE

ion (i-rate note on) and ioff (i-rate note off) are the simplest MIDI OUT opcodes.
ion sends a MIDI noteon message to MIDI OUT port, and ioff sends a noteoff message.
A ion opcode must always be follwed by an ioff with the same channel and number inside the same instrument, otherwise the note will play endlessly.

ion and ioff are useful only when introducing a timout statement to play a non zero duration MIDI note. For most purposes it is better to use iondur and iondur2.

iondur and iondur2 (i-rate note on with duration) send a note-on and a note-off MIDI message both with the same channel, number and velocity. A note-off message is sent after idur seconds are elapsed by the time iondur was activated.

iondur differs from iondur2 in that iondur truncates note duration when current instrument is deactivated by score or by realtime playing, whereas iondur2 will extend performance time of current instrument until idur seconds have elapsed.

In realtime playing it is suggested to use iondur also for undefined durations, giving a large idur value.

Any number of iondur or iondur2 opcodes can appear in the same Csound instrument, allowing chords to be played by a single instr.



STREAMS OF MIDI NOTES

moscil kchn, knum, kvel, kdur, kpause
midion kchn, knum, kvel

DESCRIPTION

Send stream of note-on and note-off messages to the MIDI OUT port.
(Note that midion opcode was previously named kon. This opocode has been renamed to avoid namespace pollution).

PERFORMANCE

kchn - MIDI channel number (1-16)
knum - note number (0-127)
kvel - velocity (0-127)
kdur - note duration in seconds
kpause - pause duration after each noteoff and before new note in seconds

moscil and kon are the most powerful MIDI OUT opcodes.

moscil (midi oscil) plays a stream of notes of kdur duration. Channel, pitch, velocity, duration and pause can be controlled at k-rate, allowing very complex algorythmically generated melodic lines.
When current instrument is deactivated, the note played by current instance of moscil is forcely truncated.

midion (before called kon i.e. k-rate note on) plays MIDI notes with current kchn, knum and kvel. These arguments can be varied at k-rate. Each time the MIDI converted value of any of these arguments changes, last MIDI note played by current instance of kon is immediately turned off and a new note with the new argument values is activated.
This opcode, as well as moscil, can generate very complex melodic textures if controlled by complex k-rate signals.

Any number of moscil or kon opcodes can appear in the same Csound instrument, allowing a counterpoint-style polyphony within a single instrument.



MIDI MESSAGES OUTPUT

outic ichn, inum, ivalue, imin, imax
outkc kchn, knum, kvalue, kmin, kmax
outic14 ichn, imsb, ilsb, ivalue, imin, imax
oukc14 kchn, kmsb, klsb, kvalue, kmin, kmax

outipb ichn, ivalue, imin, imax
outkpb kchn, kvalue, kmin, kmax
outiat ichn, ivalue, imin, imax
outkat kchn, kvalue, kmin, kmax
outipc ichn, iprog, imin, imax
outkpc kchn, kprog, kmin, kmax

outipat ichn, inotenum, ivalue, imin, imax
outkpat kchn, knotenum, kvalue, kmin, kmax

DESCRIPTION

Send a single Channel message to the MIDI OUT port.

INITIALIZATION AND PERFORMANCE

ichn, kchn - MIDI channel number (1-16)
inum, knum - controller number (0-127 for examp. 1 = ModWheel; 2 = BreathControl etc.)
ivalue, kvalue - floating point value
imin, kmin - minimum floating point value (converted in midi integer value 0)
imax, kmax - maximum floating point value (converted in midi integer value 127 (7 bit) or 16383 (14 bit))
imsb, kmsb - most significant byte controller number when using 14 bit parameters
ilsb, klsb - less significant byte controller number when using 14 bit parameters
iprog, kprog - program change number in floating point
inotenum, knotenum - MIDI note number (used in polyphonic aftertouch messages)

ioutc and koutc (i and k-rate midi controller output) send controller messages to MIDI OUT device.

ioutc14 and koutc14 (i and k-rate midi 14 bit controller output) send a pair of controller messages. These opcodes can drive 14 bit parameters on MIDI instruments that recognize them. The first control message contains the most significant byte of i(k)value argument while the second message contains the less significant byte.
i(k)msb and i(k)lsb are the number of the most and less significant controller.

ioutpb and koutpb (i and k-rate pitch bend output) send pitch bend messages.

ioutat and koutat (i and k-rate aftertouch output) send aftertouch messages.

ioutat and koutat (i and k-rate aftertouch output) send aftertouch messages.

ioutpc and koutpc (i and k-rate program change output) send program change messages.

ioutpat and koutpat (i and k-rate polyphonic aftertouch output) send polyphonic aftertouch messages. These opcodes can drive a different value of a parameter for each note currently active. They work only with MIDI instruments which recognize them.

N.B. All these opcodes can scale the i(k)value floating-point argument according with i(k)max and i(k)min values. For example, setting i(k)min = 1.0 and i(k)max = 2.0, when i(k)value argument receives a 2.0 value, the opcode will send a 127 value to MIDI OUT device, while when receiving a 1.0 it will send a 0 value.

I-rate opcodes send their message once during instrument initialization.
K-rate opcodes send a message each time the MIDI converted value of argument i(k)value changes.



MIDI REALTIME MESSAGES OUTPUT

mclock ifreq
mrtmsg imsgtype

DESCRIPTION

Send System Realtime messages to the MIDI OUT port.

INITIALIZATION

ifreq - clock message frequency rate in Hz

imsgtype - type of real-time message:

1 sends a START message (0xFA);
2 sends a CONTINUE message (0xFB);
0 sends a STOP message (0xFC);
-1 sends a SYSTEM RESET message (0xFF);
-2 sends an ACTIVE SENSING message (0xFE)

PERFORMANCE

mclock (midi clock) sends a MIDI CLOCK message (0xF8) every 1/ifreq seconds. So ifreq is the frequency rate of CLOCK messages in Hz.

mrtmsg (midi realtime message) sends a realtime message once, in init stage of current instrument. imsgtype parameter is a flag to indicate the message type (see above, in ARGUMENTS description).



DURATION EXTENSION OF MIDI NOTES

xtratim iextradur
kflag release

DESCRIPTION

Extend the duration of realtime generated events and handle their extra life.

INITIALIZATION

iextradur - additional duration of current instrument instance

PERFORMANCE

xtratim extends current MIDI-activated note duration of iextradur seconds after the corresponding note-off message has deactivated current note itself.
This opcode has no output arguments.

release outputs current note state. If current note is in the release stage (i.e. if its duration has been exetended with xtratim opcode and if it has only just deactivated), kflag output argument is set to 1, else (in sustain stage of current note) is set to 0.

These two opcodes are useful for implementing complex release-oriented envelopes.

Example:

	instr  1       ;allows complex ADSR envelope with MIDI events
inum	notnum
icps	cpsmidi
iamp	ampmidi 4000
;
;############## complex envelope section ##############
	xtratim 1       ;extra-time, i.e. release dur
krel	init    0
krel	release         ;outputs release-stage flag (0 or 1 values)
if	(krel > .5) kgoto  rel  ;if in relase-stage goto relase section
;
;************ attack and sustain section ***********
kmp1	linseg  0,.03,1,.05,1,.07,0,.08,.5,4,1,50,1 
kmp	=       kmp1*iamp
	kgoto   done
;
;************ release section **********************
rel:
kmp2	linseg  1,.3,.2,.7,0    
kmp     =       kmp1*kmp2*iamp
done:
;###################################################
;
a1      oscili  kmp, icps, 1
	out     a1
	endin



WRAPPING SIGNALS AROUND

idest wrap isig, ilow, ihigh
kdest wrap ksig, klow, khigh
adest wrap asig, klow, khigh

idest mirror isig, ilow, ihigh
kdest mirror ksig, klow, khigh
adest mirror asig, klow, khigh

DESCRIPTION

Wraps the signal in various ways (similar to limit opcode by Robin Whittle).

INITIALIZATION - PERFORMANCE

xdest - output signal
xsig - input ignal
xlow - low threshold
xhigh - high threshold

mirror "reflects" the signal that exceeds low and high thresholds.

wrap wraps-around the signal that exceeds low and high thresholds.

These opcodes are useful in several situations, such as for table indexing and for clipping and modeling irate, krate or arate signals.
wrap are also useful for wrapping-around tables data when maximum index is not a power of two (see table and tablei).
Another use of wrap is in cyclical event repeating with arbirary cycle length.



ftlen2(x)

DESCRIPTION

this function is the same as ftlen( ) but operates also with deferred-allocation function size with GEN1 and GEN22 (see them for more informations).



nsamp(x)

DESCRIPTION

This function returns the number of samples effectively loaded by GEN01 or GEN22 from a file. This function is useful when table length is a power of two (i.e. not deferred allocation is used) larger than the file sample number of the file.



ftsr(x)

DESCRIPTION

This function returns the sampling-rate of a GEN01 or GEN22 generated table. The sampling-rate is determined from the header of the original file. If the original file has not header, ftsr returns 0.



LOSCIL2

ar1 [,ar2] loscil2 xamp, kcps, ifn[, ibas] [,imod1,ibeg1,iend1] [, imod2,ibeg2,iend2]

DESCRIPTION

Read sampled sound (mono or stereo) from a table of 16-bit integer samples, with optional sustain and release looping. Uses 16-bit integer table (see GEN 22).

INITIALIZATION

See loscil for details.

PERFORMANCE

See loscil for details.

N.B.

This opcode is almost identical to loscil, the only difference is loscil2 uses 16-bit integer function table (see GEN 22) for storing samples, increasing realtime performance and reducing sample-memory consumption in half.

WARNING! You MUST use only GEN 22 to allow this opcode operates correctly!



FOF3

ar fof3 xamp, xfund, xform, koct, kband, kris, kdur, kdec, iolaps, ifna, ifnb, itotdur, kphs, kgliss

DESCRIPTION

Audio output is a succession of sinusoid bursts initiated at frequency xfund with a spectral peak at xform. For xfund above 25 Hz these bursts produce a speech-like formant with spectral characteristics determined by the k-input parameters. For lower fundamentals this generator provides a special form of granular synthesis.

fof3 is identical to fof, except that the optional arguments iphs and iform are required k-rate arguments, kphs and kgliss, allowing granular synthesis and grain glissandi.

INITIALIZATION and PERFORMANCE

see fof, fof2 and fog

N.B.

fof3 is identical to fof2, except that:

1) samples of ifna are lineary interpolated to icrease sound quality and to lower distortion
2) ifna argument must refer to a GEN22 generated table (16-bit integers stored in RAM). This halves RAM need for sample-functions.

See fof, fof2 and fog for more informations.



GEN22

Transfer data from a soundfile into a function table using 16-bit integers for storing it in RAM.

f # time size -22 filcod skiptime format channel

for more information see GEN 01.

This gen-function is almost identical to GEN01. The only difference is GEN22 can only read 16 bit integer samples in mono or stereo and stores them in RAM keeping 16-bit integer format This halves RAM need. Very useful for LONG samples.

For now GEN22 can operate only with loscil2, lposcint and fof3 opcodes . You must  always suppress normalization by using a negative GEN number, otherwise you will obtain a meaningless sequence of 1 , -1 and 0 integer values!

WARNING! The only opcodes which can use GEN22-generated functions are loscil2, lposcint and fof3. You must rescale the output of loscil2 and fof3 opcodes, when upgrading instruments written with the older opcodes (i.e. loscil and fof2) otherwise they could surpass the range limit of output.

Don’t attempt to use GEN22 with any other opcode (for now).



printk2

printk2 kvar [, numspaces]

INITIALIZATION

numspaces - number of space characters printed before the value of kvar

PERFORMANCE

kvar - signal to be printed

Derived from Robin Whittle's printk, prints a new value of kvar each time kvar changes. Useful for monitoring MIDI control changes when using sliders.

Warning! don't use this opcode with normal, continuously variant k-signals, because it can hang the computer, as the rate of printing is too fast.



lowres, lowresx

ar lowres asig, kcutoff, kresonance [,istor]

ar lowresx asig, kcutoff, kresonance [, inumlayer, istor]

Warning: lpres and lpresx have been renamed to lowres and lowresx

DESCRIPTION

lowres is a resonant lowpass filter.

lowresx is equivalent to more layer of lpres, with the same arguments, serially connected.

INITIALIZATION

inumlayer - number of elements of lpresx stack. Default value is 4. Maximum value is 10
istor - initial disposition of internal data space.

A zero value will clear the space; a non-zero value will allow previous information to remain. The default value is 0.

PERFORMANCE

ar - output signal
asig - input signal
kcutoff - filter cutoff frequency point
kresonance - resonance amount

lowres is a resonant lowpass filter derived from a Hans Mikelson´s orchestra.

This implementation is very much faster than implementing it in Csound language, and it allows kr lower than sr. kcutoff is not in cps and kresonance is not in dB, so experiment for finding best results.

lowresx is equivalent to more layer of lpres, with the same arguments, serially connected. Using a stack of more filters allows a sharper freqency cutoff. It is very faster than using more lpres instances in Csound orchestra, because only one initialization and 'k' cycle are needed at time, and the audio loop falls enterely inside the cache memory of processor.



tonex, atonex, resonx

ar tonex asig, khp[, inumlayer, istor]

ar atonex asig, khp[, inumalayer, istor]

ar resonx asig, kcf, kbw[, inumlayer, iscl, istor]

INITALIZATION

inumlayer - number of elements of filter stack. Default value is 4. Maximum value is 10
isig - some as tone, atone and reson
istor - some as tone, atone and reson
iscl - some as reson

PERFORMANCE

ar - output signal
asig - input signal
khp - some as tone, atone
kcf - some as reson
kbw - some as reson

tonex, atonex and resonx are equivalent to more layer of tone, atone and reson, with the same arguments, serially connected.
Using a stack of more filters allows a sharper frequency cutoff.
They are very faster than using more instances in Csound orchestra of old opcodes,because only one initialization and 'k' cycle are needed at time, and the audio loop falls enterely inside the cache memory of processor.



poscil and lposcil

ar poscil xamp, xcps, ift [,iphs]
kr poscil kamp, kcps, ift [,iphs]
ar poscil3 kamp, kcps, ift [,iphs]
kr poscil3 kamp, kcps, ift [,iphs]

ar lposcil kamp, kfreqratio, kloop, kend, ift [,iphs]
ar lposcil3 kamp, kfreqratio, kloop, kend, ift [,iphs]

ar lposcint kamp, kfreqratio, kloop, kend, ift [,iphs]

(Note that poscil and lposcil opcode were previously named posc and lposc. These opocodes have been renamed to avoid namespace pollution. poscil3 and lposcil3 are cubic interpolated versions of poscil and lposcil by John Fitch).

poscil can be used with tables of non-power-of-two length

INITALIZATION

ift - function table number

iphs - initial phase (in samples)

PERFORMANCE

ar - output signal
kamp - amplitude
kcps - frequency
kfreqratio - multiply factor of table frequency (for example: 1 = original frequency, 1.5 = a fifth up , .5 = an octave down)
kloop - loop point (in samples)
kend - end loop point (in samples)

poscil (precise oscillator) is the same as oscili but allows hugely more precise frequency control (especially when using long tables and low frequency values).  It uses floating-point table indexing instead of integer math, differently by oscil and oscili. It is only a bit slower than oscili.

lposcil (loop oscillator) allows to vary in k rate the starting and ending point of a sample contained in a table. This can be useful when reading samples loop of a wavetable whose repeat speed can be varied during the performance.

lposcint is the same as lposcil, but read integer stored sample tables (GEN22) to reduce RAM memory needs.



wguide1 and wguide2

ar wguide1 asig, xfreq, kcutoff, kfeedback;
ar wguide2 asig, xfreq1, xfreq2, kcutoff1, kcutoff2, kfeedback1, kfeedback2

(Note that wguide1 and wguide2 were previously named physic1. and physic2. These opocodew have been renamed to avoid namespace pollution).

DESCRIPTION

Simple waveguide blocks (see picture)

PERFORMANCE

wguide1 is the most elemental waveguide model consisting of one delay line and one first-order lowpass filter.

wguide2 is a model of beaten plate consisting of two parallel delay lines and two first-order lowpass filters. The two feedabak lines are mixed and sent to the delay again each cycle.

asig is the input of excitation noise, xfreq the frequency (i.e. the inverse of delay time), kcutoff is the filter cutoff frequency in Hz and kfeedback is the feedback factor.

Implementing waveguide algoritms as opcodes, instead of as orc instr, allows the user to set kr different than sr, allowing better performance particulary when using real-time. (see also the block diagram included in 'physic.bmp' picture)



Trigger

kout trigger ksig, kthreshold, kmode
(previously called trig).

DESCRIPTION

informs when a krate signal crosses a threshold

PERFORMANCE

kout - output signal (a stream of zeroes with some 1)
ksig - input signal
kthreshold - trigger threshold
kmode - can be 0 , 1 or 2

Normally trigger outputs zeroes: only each time ksig crosses kthreshold trigger outputs a 1.

There are three modes of using trigger:

kmode = 0 - (down-up) trigger outputs a 1 when current value of ksig is higher than kthreshold whereas old value of ksig was equal or lower than kthreshold

kmode = 1 - (up-down) trigger outputs a 1 when current value of ksig is lower than kthreshold whereas old value of ksig was equal or higher than kthreshold

kmode = 2 - (both) trigger outputs a 1 in both the two previous cases.



midiin

kstatus, kchan, kdata1, kdata2 midiin

DESCRIPTION

Returns a generic midi message received by the midi in port

PERFORMANCE

kstatus - the type of midi message. Can be:

128 (note off),
144 (note on),
160 (polyphonic aftertouch),
176 (control change),
192 (program change),
208 (channel aftertouch),
224 (pitch bend)

or 0 if no midi message are pending in the MIDI IN buffer.

kchan - midi channel (1-16)
kdata1, kdata2 - message-dependent data values

midiin has no input arguments, because it reads at the midi in port implicitly. It works at k-rate. Normally (i.e. when no messages are pending) kstatus is zero, only each time midi data are present in the midi in buffer, kstatus is set to the type of the relative messages.



midiout

midiout kstatus, kchan, kdata1, kdata2

DESCRIPTION

sends a generic midi message to the midi out port

PERFORMANCE

kstatus - the type of midi message. Can be:

128 (note off),
144 (note on),
160 (polyphonic aftertouch),
176 (control change),
192 (program change),
208 (channel aftertouch),
224 (pitch bend)
or 0 when no midi messages must be sent to the MIDI OUT port.

kchan - midi channel (1-16)
kdata1, kdata2 - message-dependent data values

midiout has not output arguments, because it sends the message to the midi out port implicitly. It works at k-rate. It sends a midi message only when kstatus is different than zero.

Warning! Normally kstatus should be set to 0, only when the user intend to send a midi message, it can be set to the corresponding message type number.



midion2

midion2 kchn, knum, kvel, ktrig

DESCRIPTION

sends note on and off messages to the midi out port when triggered by a value different than zero.
(Note that midion2 opcode was previously named kon2. This opocode has been renamed to avoid namespace pollution).

PERFORMANCE

kchn - midi channel
knum - midi note number
kvel - note velocity
ktrig - trigger input signal (normally 0)

Similary to midion, this opcode sends note-on and note-off messages to the midi out port, but midion2 does it only when ktrig is different than zero. This opcode is thinked to work toghether with the output of the trig opcode.

-----------------------------------------------------------

nrpn

nrpn kchan, kparmnum, kparmvalue

DESCRIPTION

sends a nprn (Non Registered Parameter Number) message to the midi out port each time one of the input arguments changes.

PERFORMANCE

kchan - midi channel
kparmnum - number of NRPN parameter
kparmvalue - value of NRPN parameter

This opcode sends new message when the MIDI translated value of one of the input arguments changes. It operates at k-rate. Useful with the midi instruments that recognize NRPNs (for example with the newest sound-cards with internal midi synthesizer such as SB AWE32, AWE64, GUS etc. in which each patch parameter can be changed during the performance via NRPN)



mdelay

mdelay kstatus, kchan, kdata1, kdata2, kdelay

DESCRIPTION

A midi delay

PERFORMANCE

kstatus - status byte of midi message to be delayed
kchan - midi channel (1-16)
kdata1 - first midi data byte
kdata2 - second midi data byte
kdelay - delay time in seconds

This opcode grabs a midi message each time kstatus is different than zero and sends it to the midi out port after kdelay seconds.
This opcode is useful to implement midi delays.
More instance of this opcode can be present in the same instr with different argument values, so complex and colourful midi echoes can be implemented. Furthermore, the delay can be changed at k-rate.



loopseg, lpshold

ksig loopseg kfreq, ktrig, ktime0, kvalue0  [, ktime1, kvalue1, ... , ktimeN, kvalueN]
ksig lpshold kfreq, ktrig, ktime0, kvalue0  [, ktime1, kvalue1, ... , ktimeN, kvalueN]

DESCRIPTION

Generate control signal consisiting of linear segments delimited by two or more specified points. The entire envelope is looped at kfreq rate. Each parameter can be varied at k-rate.

INITIALISATION

No parameters at init rate.

PERFORMANCE

ksig - output signal
kfreq - repeat rate in Hz or fraction of Hz
ktrig - if nonzero retriggers the envelope from start (see trigger opcode)
ktime0...ktimeN -  times of points expessed in fraction of a cycle
kvalue0...kvalueN - values of points

loopseg opcode is similar to linseg, but the entire envelope  is looped at kfreq rate. Notice that times are not expressed in seconds but in fraction of a cycle. All parameters can be varied at k-rate. Negative frequency values are allowed, reading the envelope backward. ktime0 should be always set to 0, except if the user wants some special effect.

lpshold is similar to loopseg, but can generate only horizontal segments, i.e. holds values for each time interval placed beetween ktimeN and ktimeN+1

Example:

instr 1
k0 line 1,p3,33
k1 loopseg  .5, 0,      0,0, k0,32000, 66,5000, 100,0
....
endin

In the previous example the envelope is repeated one time each two seconds (kfreq=.5), and the duration of first segment is varied continuosly, being controlled by the output of line opcode.



expsega

asig expsega ia, idur1, ib[, idur2, ic[...]]

DESCRIPTION

An exponential segment generator operating at a-rate. This unit is almost identical to expseg, but very more precise when defining segments with very short duration (i.e. in percussive attack phase) at audio-rate.

Note that old expseg opcode does not operate correctly at audio rate when segments are shorter than a k-period.

INITIALISATION

ia - starting value. Zero is illegal.
ib, ic, etc. - value after idur1 seconds, etc. must be non-zero and must agree in sign with ia.
idur1 - duration in seconds of first segment.

A zero or negative value will cause all initialization to be skipped.

idur2, idur3, etc. - duration in seconds of subsequent segments.
A zero or negative value will terminate the initialization process with the preceding point, permitting the last-defined line or curve to be continued indefinitely in performance. The default is zero.

PERFORMANCE

These units generate control or audio signals whose values can pass through 2 or more specified points.The sum of dur values may or may not equal the instrument's performance time: a shorter performance will truncate the specified pattern, while a longer one will cause the last-defined segment to continue on in the same direction.



Perry Cook opcodes

(derived by a Michael Gogins Csound version which supports an external library of opcodes. The 'perry_toolkit.opc' file must be present in the same directory of DirectCsound executable in order to enable these opcodes)

list of opcodes:

marimba
vibraphone
agogobell
plucked
mandolin
clarinet
flute
brass
bowed
rhodes
wurlitzer
tubularbell
heavymetal
percussiveflute
hammond
fmvoices
minimoog
voiceformant

example:

ar marimba xcps, xamp, xconstatus, xcondata1, xcondata2, xmodwheel

Audio output is a physical model of the named instrument based on waveguide synthesis,

frequency modulation synthesis, or modal synthesis.

Initialization

There are no specifically initialization-time variables.

Performance

xcps - Frequency in cycles per second.
xamp - Amplitude multiplier.
xconstatus  - MIDI control message status byte. Meaning depends upon opcode, but analogous to corresponding MIDI patch.
xcondata1 -   MIDI control message data byte 1. Meaning depends upon opcode, but analogous to corresponding MIDI patch.
xcondata2 - MIDI control message data byte 2. Meaning depends upon opcode, but analogous to corresponding MIDI patch.
xmodwheel  - MIDI modulation wheel value. Meaning depends upon opcode, but analogous to corresponding MIDI patch.



marimjpff

the marimba described in the 3.47 manual by John Fitch (ranamed  to avoid name-conflict with original Perry Cook algorythms included in the external library).



Banks of sliders

slider8,  slider16,  slider32,  slider64
slider8f,  slider16f,  slider32f,  slider64f
s16b14,  s32b14

SYNTAX

k1,k2,k3,k4,k5,k6,k7,k8 slider8 ichan, ictlnum1, imin1, imax1, init1, ifn1, .... , \
ictlnum8, imin8, imax8, init8, ifn8

k1, ... , k16 slider16 ichan, ictlnum1, imin1, imax1, init1, ifn1, .... , \
ictlnum16, imin16, imax16, init16, ifn16

k1, ... , k32 slider32 ichan, ictlnum1, imin1, imax1, init1, ifn1, .... , \
ictlnum32, imin32, imax32, init32, ifn32

k1, ... , k64 slider64 ichan, ictlnum1, imin1, imax1, init1, ifn1, .... , \
ictlnum64, imin64, imax64, init64, ifn64

k1,k2,k3,k4,k5,k6,k7,k8 slider8f ichan, ictlnum1, imin1, imax1, init1, ifn1, icutoff1, .... , \
ictlnum8, imin8, imax8, init8, ifn8, icutoff8

k1, ... , k16 slider16f ichan, ictlnum1, imin1, imax1, init1, ifn1, icutoff1, .... , \
ictlnum16, imin16, imax16, init16, ifn16, icutoff16

k1, ... , k32 slider32f ichan, ictlnum1, imin1, imax1, init1, ifn1, icutoff1, .... , \
ictlnum32, imin32, imax32, init32, ifn32, icutoff32

k1, ... , k64 slider64f ichan, ictlnum1, imin1, imax1, init1, ifn1, icutoff1, .... , \
ictlnum64, imin64, imax64, init64, ifn64, icutoff64

i1, ... , i8 slider8 ichan, ictlnum1, imin1, imax1, ifn1, .... , \
ictlnum8, imin8, imax8, ifn8

i1, ... , i16 slider16 ichan, ictlnum1, imin1, imax1, ifn1, .... , \
ictlnum16, imin16, imax16, ifn16

i1, ... , i32 slider32 ichan, ictlnum1, imin1, imax1, ifn1, .... , \
ictlnum32, imin32, imax32, ifn32

i1, ... , i64 slider64 ichan, ictlnum1, imin1, imax1, ifn1, .... , \
ictlnum64, imin64, imax64, ifn64

i1, ... , i16 s16b14 ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, initvalue1, ifn1, ....., \
ictlno_msb16, ictlno_lsb16, imin16, imax16, initvalue16, ifn16

i1, ... , i16 is16b14 ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, ifn1, .......... \
ictlno_msb16, ictlno_lsb16, imin16, imax16, ifn16

i1, ... , i32 s32b14 ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, initvalue1, ifn1, ....., \
ictlno_msb32, ictlno_lsb32, imin32, imax32, initvalue32, ifn32

i1, ... , i32 s32b14 ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, ifn1, .......... \
ictlno_msb32, ictlno_lsb32, imin32, imax32, ifn32

DESCRIPTION

MIDI slider control banks

INITIALIZATION

i1 ... i64 - output values
ichan - midi channel (1-16)
ictlnum1 ... ictlnum64 - midi control number
ictlno_msb1 .... ictlno_msb32 - midi control number (most significant byte)
ictlno_lsb1 .... ictlno_lsb32 - midi control number (less significant byte)
imin1 ... imin64 - minimum values for each controller
imax1 ... imax64 - maximum values for each controller
init1 ... init64 - inital value for each controller
ifn1 ... ifn64 - function table for conversion for each controller
icutoff1 ... icutoff64 - low pass filter frequency cutoff for each controller

PERFORMANCE

k1 ... k64 - output values

isliderN, sliderN and sliderNf are banks of MIDI controller (useful together with VMCI and when using midi mixer such as KAWAI MM-16 or others for changing whatever sound parameter in realtime).

The raw midi control messages at the input port are converted to agree with iminN and imaxN, and an initial value can be set. Also an optional non-interpolated function table with a custom translation curve is allowed, useful for enabling exponential response curves.

When no function table translation is required, set the ifnN value to 0, else set ifnN to a valid function table number.

When table translation is enabled (i.e. setting ifnN value to a non-zero number referring to an already allocated function table), initN value should be set equal to iminN or imaxN value, else the initial output value will not be the same as specified in initN argument.

slider8 allows a bank of 8 different midi control message numbers, slider16 does the same with a bank of 16 controls, and so on.

sliderNf filter the signal before output for eliminating discontinuities due to the low resolution of the MIDI (7 bit); the cutoff frequency can be set separately for each controller (suggested range: .1 to 5 cps). Warning! sliderNf opcodes do not output the required initial value immediately, but only after some k-cycle because the filter slightly delays the output.

As the input and output arguments are many, you can split the line using '\' (backslash) character (new in 3.47 version) to improve the readability. Using these opcodes is quite more efficient than using the separate ones (ctrl7 and ktone) when more controllers are required.

In isliderN there is not an initial-value input argument because the output is get directly from current status of internal controller array of Csound.

isNb14 and sNb14 opcodes are the 14-bit versions of these banks of controllers.



Power of two related

powoftwo(x)
logbtwo(x)

powoftwo() function returns 2 ^ x and allows positive and negatives numbers as argument. The range of values admitted in powoftwo() is -5 to +5 allowing a precision more fine than one cent in a range of ten octaves. If a greater range of values is required, use the slower opcodes ipow, kpow and apow.

logbtwo() returns the logarithm base two of x. The range of values admitted as argument is .25 to 4 (i.e. from -2 octave to +2 octave response). This function is the inverse of powoftwo().

These functions are fast, because they read values stored in tables.
Also they are very useful when working with tuning ratios. They work at i and k-rate.

Warning! values out of range will crash Csound with an invalid memory access error.



vlowres

ar vlowres asig, kfco, kres, iord, ksep;

DESCRIPTION

a bank of filters in which freqency cutoff can be separated under user control

INITIALIZATION

iord - total nuber of filter (1 to 10)

PERFORMANCE

ar - output signal
asig - input signal
kfco - frequency cutoff (not in cps)
ksep - frequency cutoff separation for each filter

vlowres (variable resonant lowpass filter) allow a variable response curve in resonant filters. It can be thinked as a bank of lowpass resonant filters with the same resonance, serially connected. The frequency cutoff of each filter can vary with the kcutoff and ksep parameters.



flanger

ar flanger asig, adel, kfeedback, imaxd

DESCRIPTION

A user controlled flanger (see picture)

INITALIZATION

imaxd - maximum delay in seconds (needed for inital memory allocation)

PERFORMANCE

ar - output signal
asig - input signal
adel - delay in seconds
kfeedback - feedback amount (in normal tasks this should not exceed 1, even if bigger values are allowed)

This unit is useful for generating chourses and flangers. The delay must be varied at a-rate connecting adel to an oscillator output. Also the feedback can vary at k-rate.

This opcode is implemented to allow kr different than sr (else delay could not be lower than ksmps) enhancing realtime performance. (BtW: this unit is very similar to physic1, the only difference is flanger does not have the lowpass filter. See also the block diagram in figure 'flanger.bmp').



ntrpol

ir ntrpol isig1, isig2, ipoint [, imin, imax]
kr ntrpol ksig1, ksig2, kpoint [, imin, imax]
ar ntrpol asig1, asig2, kpoint [, imin, imax]

DESCRIPTION

Calculates the weighted mean value (i.e. linear interpolation) of two input signals

INITALIZATION

imin - minimum xpoint value (optional, default 0)
imax - maximum xpoint value (optional, default 1)

PERFORMANCE

xr - output signal
xsig1, xsig2 - input signals
xpoint - interpolation point beetween the two values

nterpol opcode outputs the linear interpolation beetween two input values. xpoint is the distance of evaluation point from the first value. With the default values of imin and imax, (0 and 1) a zero value indicates no distance from the first value and the maximum distance from the second one. With a 0.5 xntrpol value will output the mean value of the two inputs, indicating the exact half point beetween xsig1 and xsig2 . A 1 value indicates the maximum distance from the first value and no distance from the second one.

The range of xpoint can be also defined with imin and imax to make easier its management.
These opcodes are useful for crossfading two signals.



GEN23

This subroutine reads numeric values from an external ascii file

f# time size -23 "filename.txt"

The numeric values contained in "filename.txt" (which indicates the complete pathname of the ascii file to be read), can be separated by spaces, tabs, newline characters or commas.
Also words that contains non-numeric characters can be used as comments since they are ignored.
All characters following ';' (comment) are ignored until next line (numbers too).



GEN24

This subroutine reads numeric values from another allocated function-table and rescales them according to the max and min values given by the user.

f# time size -24 numsource min max

numsource must be an already allocated table with the same size of this function.
This GEN is useful, for example, to eliminate the starting offset in exponential segmets allowing a real starting from zero.



GEN40

This subroutine generates a continuous random distribution function starting from the shape of a user-defined distribution histogram.

f# time size -40 shapetab

The shape of histogram must be stored in a previously defined table, in fact shapetab argument must be filled with the number of such table. Histogram shape can be generated with any other GEN routines. Since no interpolation is used when GEN40 processes the translation, it is suggested that the size of the table containing the histogram shape to be reasonably big, in order to obtain more precision (however after the processing the shaping-table can be destroyed in order to re-gain memory). It is possible to generate tables having non-power-of-two length by giving a negative value to size argument.

This subroutine is designed to be used together with Cusrnd opcode (see Cusrnd for more information).



GEN41

This subroutine generates a discrete random distribution function by giving a list of numerical pairs.

f# time size -41 value1 prob1 value2 prob2 value3 prob3 ... valueN probN

The first number of each pair is a value, and the second is the probability of that value to be choosen by a random algorithm. Even if any number can be assigned to the probability element of each pair, it is suggested to give it a percent value, in order to make it clearer for the user. It is possible to generate a table having a non-power-of-two length by giving a negative value to size argument.

This subroutine is designed to be used together with Dusrnd and urd opcodes (see Dusrnd for more information).



GEN42

This subroutine generates a random distribution function of discrete ranges of values by giving a list of groups of three numbers.

f# time size -42  min1 max1 prob1  min2 max2 prob2  min3 max3 prob3 ...  minN maxN probN

The first number of each group is a the minumum value of the first range, the second is the maximum value and the third is the probability of that an element belonging to that range of values  to be choosen by a random algorithm. Even if any number can be assigned to the probability element of each group, it is suggested to give it a percent value, in order to make it clearer for the user. It is possible to generate a table having a non-power-of-two length by giving a negative value to size argument.

This subroutine is designed to be used together with Dusrnd and urd opcodes (see Dusrnd for more information). Since both Dusrnd and urd don't use any interpolation, it is suggested to give a size reasonably big.



foscili2

ar foscili2 xamp, kcps, kcar, kmod, kndx, ifn1, ifn2 [, iphs]

INITIALISATION

ifn1 - carrier function table number. Requires a wrap-around guard point.
ifn1 - modulator function table number. Requires a wrap-around guard point.
iphs (optional) - initial phase of sampling, expressed as a fraction of a cycle (0 to 1). A negative value will cause phase initialization to be skipped. The default value is 0.

PERFORMANCE

This unit is very similar to 'foscili'. The only difference is in that the user can use two different function tables, the first for the carrier (ifn1) , the second for the modulator (ifn2).
See foscili help for more informations.



Midi Micro Tuning

cpstmid

icps cpstmid ifn

INITIALIZATION

ifn - function table containing the parameters (numgrades, interval, basefreq, basekeymidi) and the tuning ratios.

(init rate only)

This unit is similar to cpsmidi, but allows fully customized micro-tuning scales. It requires five parameters, the first ifn is the function table number of the tuning ratios, and the other parameters must be stored in the function tables itself.
The function table ifn should be generated by the GEN2 and the first four values stored in this function are:

numgrades (the number of grades of the micro-tuning scale),
interval (the frequency range covered before repeating the grade ratios, for example 2 for one octave, 1.5 for a fift etcetera), basefreq (the base frequency of the scale in cps),
basekeymidi (the midi-note-number to which to assign the basefreq unmodified).

After these four values, the user can begin to insert the tuning ratios. For example, for a standard 12-grade scale with the base-frequency of 261 cps assigned to the key-number 60, the corresponding f-statement in the score to generate the table should be:

;           numgrades    basefreq     tuning-ratios (eq.temp) .......   
;                  interval    basekeymidi       
f1 0 64 -2  12     2     261   60     1   1.059463 1.12246 1.18920 ..etc...

Another example with a 24-grade scale with a base frequency of 440 assigned to the key-number 48, and a repetition interval of 1.5:

;                  numgrades       basefreq      tuning-ratios .......   
;                          interval       basekeymidi       
f1 0 64 -2         24      1.5     440    48     1   1.01  1.02  1.03   ..etc...



call,calld,callm,callmd

call instrno, iactime, idur [,ip4,ip5,ip6,ip7,... ,ipn ]
calld instrno, iactime, idur [,ip4,ip5,ip6,ip7,... ,ipn ]
callm instrno, iactime [,ip3,ip4,ip5,ip6,ip7,... ,ipn ]
callmd instrno, iactime, idur [,ip4,ip5,ip6,ip7,... ,ipn ]

DESCRIPTION

Activate an instrument from within another instrument at performance time (subroutine call)

INITIALIZATION

instrno - instrument number to be activated
iactime - action time in seconds (should be zero when using call)
idur - duration of the note to be activated
ip3,ip4,ip5,ip6, ... ,ipn - p-fields of the instrument to be activated

PERFORMANCE

An instrument containing call (instrument call), calld (delayed instrument call), callm (MIDI-oriented instrument call) or callmd (delayed MIDI-oriented instrument call) opcodes, can activate an instance of another instrument of the same orchestra during the performance.

These opcodes can also be thinked as subroutine calls. Any number of additional init arguments (ip4,ip5,ip6 etc.) can be sent to the target instruments, in the same way of p-fields in a score note event.

More instances of call, calld, callm and callmd can co-exist in the same calling instr, so chords of more notes (played by different target instruments) can be activated by a single MIDI note-on event, as well as by a single i-statement in the score. This possibility allows the user to do several things, for example to easily implement multi-layered instruments, or tho inherit the features of an instrument by a more specialized instrument (by using this opcodes together with the parmXX and rtrnXX opcode family, see below).

A multiple inheritance of several instruments can be also implemented by using these opcodes in Csound.

The difference beetween the four opcodes concerns the activation and the duration of the target note, and is described below:

  1. call plays the target note immediately (so 'iactime' argument must be set to zero), and its duration is 'idur' seconds, even if the caller instrument is turned off beforehand or afterward. This opcode has no output and operates at i-rate only.
  2. calld can schedule the target note activation 'iactime' seconds after the caller instrument init-time. Again, the target note duration is 'idur' seconds, even if the caller instrument is turned off beforehand or afterward. This opcode has no output and operates at k-rate.
  3. callm plays the target note immediately (so iactime argument must be set to zero), but its duration is indeterminate and depends by a midi midi note-off message recognized by the caller instrument. This opcode is useful when the caller instrument is activated by MIDI. In fact in this case it is impossible to know the caller duration beforehand. Notice that it is still possible to use call and calld with a MIDI-activated caller instrument instead of callm. In that case the target notes will be simply turned off after idur seconds, whether the caller instr is turned off before or after idur seconds are elapsed or it isn't. callm has no output and operates at k-rate.
  4. callmd can schedule the target note activation iactime seconds after the caller instrument init-time. The duration of the target note is indeterminate (so 'idur' parameter is meaningless) and depends by a midi note-off message recognized by the caller instrument. The target note is not allocated until iactime seconds are elapsed. callmd has no output and operates at k-rate.

Notice that each of these opcodes makes the processing point do not return to the caller until all the target instr initialization phase has been completed.

;//////////////////////////////////////
;//////////      EXAMPLE 1    /////////
;//////////  call and calld   /////////
;//////////////////////////////////////
gifn    ftgen 1,0,1024,10,1,0,0,0,0,0,0,.5,0,0,0,0,0.2
;***************************************************
	instr   1       ;**** caller instrument ****
;***************************************************
ifreq   cpsmidi
	call   2,0,2, 2000,ifreq
	calld 2,1,4, 2000,ifreq*1.2
	calld 2,3,6, 2000,ifreq*1.77
	calld 2,5,8, 2000,ifreq*2.1
	calld 2,8,10,2000,ifreq*2.4555
	endin

;***************************************************
    instr   2       ;**** target instrument ****
;***************************************************
k1      linseg  0,p3/2,1,p3/2,0
a1       oscili  p4,p5,gifn
      out     a1*k1
   endin

;//////////////////////////////////////
;//////////     EXAMPLE 2      ////////
;////////// callm and callmd ////////
;//////////////////////////////////////

gifn    ftgen 1,0,1024,10,1,0,0,0,0,0,0,.5,0,0,0,0,0.2
;***************************************************
	instr   1       ;**** caller instrument ****
;***************************************************
iamp	ampmidi 2000
ifreq	cpsmidi
	callm  2,0,2 ,iamp,      ifreq
	callmd 2,1,4 ,iamp * .5, ifreq * 1.2
	callmd 2,3,6 ,iamp * .25,ifreq * 1.77
	callmd 2,6,8 ,iamp * .2, ifreq * 2.1
	callmd 2,8,10,iamp * .1, ifreq * 2.4555
        endin
;***************************************************
	instr   2       ;**** target instrument ****
;***************************************************
k1      linenr  1,p3/2,p3/2,.03
a1	oscili  p4,p5,gifn
	out     a1*k1
	endin



parmck, parmtk, parmca, parmta, rtrnck, rtrntk, rtrnca, rtrnta

parmck kinarg1, kinarg2, kinarg3,....kinargN
parmtk koutarg1,koutarg2,koutarg3,...koutargN
parmca ainarg1, ainarg2, ainarg3,....ainargN
parmta aoutarg1,aoutarg2,aoutarg3,...aoutargN
rtrnck koutarg1,koutarg2,koutarg3,...koutargN
rtrntk kinarg1, kinarg2, kinarg3,....kinargN
rtrnca aoutarg1,aoutarg2,aoutarg3,...aoutargN
rtrnta ainarg1, ainarg2, ainarg3,....ainargN

DESCRIPTION

These opcodes deal with a-rate and k-rate argument-signals and return signals to be sent when using subroutine calls

PERFORMANCE

kinarg1, kinarg2, kinarg3,....kinargN - k-rate input arguments
koutarg1,koutarg2,koutarg3,...koutargN - k-rate output arguments
ainarg1, ainarg2, ainarg3,....ainargN - a-rate input arguments
aoutarg1,aoutarg2,aoutarg3,...aoutargN - a-rate output arguments

This opcode family allows the user to define input and output signals to use as arguments (or parameters) and return values when calling a subroutine (together with the call opcode family).

Some k-rate examples will be presented below, the corresponding a-rate oriented opcodes can be used in the same way, the only difference is that the arguments are a-rate variables.

parmck (k-rate parameters handling to be placed in the caller instrument) and parmtk (k-rate parameters handling to be placed in the target instrument) work in pair.

The caller instrument can send several k-rate signals to the target instrument by using this couple of opcodes:

;***************************************************
	instr   1       ;**** caller instrument ****
;***************************************************
        ;**** calculating the k-rate arguments to be sent to the target instrument
karg1	oscil   ...
karg2	linen   ...
karg3	expseg  ...
karg4	linseg  ...      
        ;****   instrno   actime    dur     init-rate arguments sent to instr 2 
        call    2,        0,        3,      iarg1,iarg2,iarg3   ;*** call the target instr
	parmck  karg1,karg2,karg3,karg4     ;*** send the four signals
        .....
        endin

;***************************************************
	instr   2       ;**** target instrument ****
;***************************************************
        .....
        parmtk   k1,k2,k3,k4     ;*** receive the four signals from the caller instr
                                 ;*** using the k-rate arguments...
a1	oscil    k1,k2,k3,1
	out      a1*k4
	.....
	endin

In this case instr 1 (the caller) calls instr 2 (the target) and sends three i-rate variables (iarg1, iarg2 and iarg3 which are interpreted as p4, p5 and p6 by the target instr) and four k-rate arguments (karg1,karg2,karg3,karg4 which are interpreted by the target instrument as k1,k2,k3 and k4 local variables) to the target instrument.

IMPORTANT: Notice that, in the previous example, the k1,k2,k3 and k4 arguments of parmtk opcode are output arguments, even if they appear on the right of the opcode instead of on the left. This because Csound at the moment doesn't support a variable number of arguments at the left of the opcode.
Also you must put parmck (as well as parmca) immediately after the call opcode.

rtrnck (k-rate return values received by the caller instrument) and rtrntk (k-rate return values sent by the target instrument) work in pair. The target instrument can return several k-rate signals to the caller intrument by using these two pcodes. The following example shows this concept:

;***************************************************
	instr   1       ;**** caller instrument ****
;***************************************************
;**** calculating the k-rate arguments....
;**** to be sent to the target instrument
	....
        ;****   instrno   actime    dur     init-rate arguments sent to instr 2 
        call    2,        0,        3,      iarg1,iarg2,iarg3   ;*** call the target instr
	rtrnck  karg1,karg2,karg3,karg4 ;*** receive the return signals from the target instr
;*** using the return signals ...
a1	oscil   karg1,karg1,karg1,1
	out     a1*karg1
        .....
        endin

;***************************************************
    instr   2       ;**** target instrument ****
;***************************************************
        .....
;*** generating k-rate signals to be returned to the caller instr...
k1	oscil	...
k2	linseg	...
k3	oscil1	...
k4	expseg	....
	rtrntk	k1,k2,k3,k4  ;*** return the four signals to the caller instr
	.....
        endin

It is important to be sure that the number of arguments of the pair parmck/parmtk and rtrnck/rtrntk is the same.
Using a-rate opcodes (parmca/parmta and rtrnca/rtrnta) is almost identical.
Here is a summing-up example:

;****
;**** An example of parmck, parmca, parmtk, parmta, rtrnck,rtrnca, rtrntk and rtrnta opcodes
;****

	sr = 44100
	kr = 441
	ksmps = 100
	nchnls = 2

gifn	ftgen   1,0,1024,10 ,1 ,0,0,0,0,0,0,.1,0,0,0,0,0,.05,0,0,0,0,0,0,0,.01
gikfn	ftgen   2,0,1024,10 ,1
;***************************************************
        instr   1       ;**** caller instrument ****
;***************************************************
iamp	ampmidi 2000
ifreq	cpsmidi
a1      oscili  iamp, ifreq, gifn
a2	oscili  iamp, ifreq*1.3, gifn
a3	oscili  iamp, ifreq*1.5555, gifn
k1      oscili  1, .5, gikfn
k2	oscili  1, 1.3, gikfn
k3	oscili  1, 2.1.5555, gikfn
        xtratim 2       ;when using a-rate arguments in subroutine call,
                        ;you must be sure that the extra-time of the instrument
                        ;containing the out opcode is
                        ;grater or equal to that of the target instr
;//////// first  call /////////////
        callm	2,0,4,iamp, ifreq       ;call instr 2 as subroutine
	parmck	k1,k2,k3                ;send k-rate arguments to instr 2
	parmca	a1,a2,a3                ;send a-rate arguments to instr 2
	rtrnca	aout1,aout2             ;receive a-signals returned by the first call of instr 2
;//////// second  call /////////////
        callm	2,0,4,iamp, ifreq*2.2 ;call instr 2 as subroutine
	parmck  k3,k2,k1        ;send k-rate arguments to instr 2
	parmca  a3,a1,a2        ;send a-rate arguments to instr 2
        rtrnck  kenv            ;receive k-signals returned by the second call of instr 2
	rtrnca  aout3,aout4     ;receive a-signals returned by the second call of instr 2
        outs    (aout1+aout3)*kenv, (aout2+aout4)*kenv
        endin

;***************************************************
    instr   2       ;**** target instrument ****
;***************************************************
        parmtk  ksig,ksig2,ksig3        ;receive k-signals sent by caller arguments
	parmta  asig,asig2,asig3        ;receive a-signals sent by caller arguments
k1      linenr  1,p3/2,p3/2,.03
a1	oscili  p4*ksig,p5,gifn
a2	oscili  p4*ksig2,p5*1.5,gifn
a3	oscili  p4*ksig3,p5*1.8,gifn
	rtrntk  k1                      ;return k-signals
	rtrnta  a1+asig2+asig3, a2+a3+asig      ;return a-signals
        endin



fout, foutk, fouti, foutir, fiopen

fout   "ifilename", iformat, aout1 [, aout2, aout3,.... ,aoutN]
foutk   "ifilename", iformat, kout1 [, kout2, kout3,....,koutN]
fouti   ihandle, iformat, iflag, iout1 [, iout2, iout3,....,ioutN]
foutir   ihandle, iformat, iflag, iout1 [, iout2, iout3,....,ioutN]
ihandle  fiopen  "ifilename",imode

DESCRIPTION

fout, foutk, fouti and foutir output N audio, k or i-rate signals to a specified file of N channels.
fiopen
can be used to open a file in one of the specified modes.

INITIALIZATION

ifilename - a double-quote delimited string file name
iformat - a flag to choose output file format:
for fout and foutk only:
0 - 32-bit floating point samples without header (binary PCM multichannel file)
1 - 16-bit integers without header (binary PCM multichannel file)
2 - 16-bit integers with .wav type header (Microsoft WAV mono or stereo file)

for fouti and foutir only:
0 - floating point in text format
1 - 32-bit floating point in binary format

iflag - choose the mode of writing to the ascii file (valid only in ascii mode; in binary mode iflag has no meaning, but it must be present anyway).
iflag can be a value choosen among the following:
0 - line of text without instrument prefix
1 - line of text with instrument prefix (see below)
2 - reset the time of instrument prefixes to zero (to be used only in some particular cases. See below)

iout,... ioutN - values to be written to the file.

imode - choose the mode of opening the file.
imode can be a value choosen among the following:
0 - open a text file for writing
1 - open a text file for reading
2 - open a binary file for writing
3 - open a binary file for reading

PERFORMANCE

aout1,... aoutN - signals to be written to the file.
kout1,...koutN - signals to be written to the file.

fout (file output) writes samples of audio signals to a file with any number of channels. Channel number depends by the number of aoutN variables (i.e. a mono signal with only an a-rate argument, a stereo signal with two a-rate arguments etc.) Maximum number of channels is fixed to 64.
More fout opcodes can be present in the same instrument, referring to different files.
Notice that, differently by out, outs and outq, fout does not zeroes the audio variable, so you must provide a zeroing after calling fout if poliphony is used. You can use incr and clear opcodes for this task.

foutk operates in the same way of fout, but with k-rate signals. iformat can be set only to 0 or 1.

fouti and foutir write i-rate values to a file. The main use of these opcodes is to generate a score file during a realtime session. For this purpose the user should set iformat to 0 (text file output) and iflag to 1, which enable the output of a prefix consisting of the following strings:

i num  actiontime duration

before the values of iout1...ioutN arguments. Prefix is referring to instrument number, action time and duration of current note.

The difference of fouti and foutir is that,  in the case of fouti, when iflag is set to 1, the duration of the first opcode is undefined (so it is replaced by a dot ) wheras in the case of foutir is defined at the end of note, so the corresponding text line is written only at the end of the current note (in order to recognize its duration). The corresponding file is linked by the ihandle value generated by fiopen opcode (see below). So fouti and foutir can be used to generate a Csound score while playing  a realtime session.

fiopen  opens a file to be used by the foutX opcodes. It must be defined externally by any instruments, in the header section.
It returns a number ihandle, which is univocally referring to the opened file.

Notice that fout and foutk can use both a string containing a file pathname or a handle-number generated by fiopen, wheras in the case of fouti and foutir, the target file can be only specified by means of a handle-number.



fin, fink, fini

fin  "ifilename", iskipframes, iformat, ain1 [, ain2, ain3,.... ,ainN]
fink  "ifilename", iskipframes, iformat, kin1 [, kin2, kin3,.... ,kinN]
fini  "ifilename", iskipframes, iformat, in1 [, in2, in3,.... ,inN]

DESCRIPTION

read signals from a file (at a, k, and i-rate)

INITIALIZATION

ifilename - input file name (can be a string or a handle number generated by fiopen)
iskipframes - number of frames to skip at the start (every frame contains a sample of each channel)
iformat - a number specifying the input file format:
for fin and fink:
0 -  32 bit floating points without header
1 - 16 bit integers without header

for fini:
0 - floating points in text format (loop; see below)
1 - floating points in text format (no loop; see below)
2 - 32 bit floating points in binary format (no loop)

fin (file input) is the complement of fout: it reads a multi channel file to generate audio rate signals. At present time no header is supported for file format. The user must be sure that the number of channel of the input file is the same of the number of ainX arguments

fink is the same as fin, but operates at k-rate.

fini is the complement of fouti and foutir, it reads the  values each time the corresponding instrument note is activated.
When iformat is set to 0, if the end of file is reached the file pointer is zeroed, restarting the scanning from the beginning.
When iformat is set to 1 or 2 no loop is enabled, so at the end of file the corresponding variables will be filled with zeroes.



vincr, clear

vincr  asig, aincr
clear avar1 [,avar2, avar3,...,avarN]

DESCRIPTION

vincr increments an audio variable of another signal, i.e. accumulates output.
clear zeroes a list of audio signals.

PERFORMANCE

asig - audio variable to be incremented
aincr - incrementation signal
avar1 [,avar2, avar3,...,avarN] - signals to be zeroed

vincr (variable increment) and clear are thinked to be used togheter. vincr stores the result of the sum of two audio variables into the first variable itself (which is thinked to be used as accumulator in case of polyphony). The accumulator-variable can be used for output signal by means of fout opcode. After the disk writing operation, the accumulator-variable should be set to zero by means of clear opcode (or it will explode).



fold

ar fold asig, kincr

DESCRIPTION

Adds artificial foldover to an audio signal

PERFORMANCE

asig - input signal
kincr - amount of foldover expressed in multiple of sampling rate. Must be >= 1

fold is an opcode which creates artificial foldover.  For example, when kincr is equal to 1 with sr=44100, no foldover is added, when kincr is set to 2 the foldover is equivalent to a downsampling to 22050, when it is set to 4 to 11025 etc. Fractional values of kincr are possible, allowing a continuous variation of foldover amount. This can be used for a wide range of special effects.

EXAMPLE:

	instr	1
kfreq line 1,p3,200
a1 oscili 10000, 100, 1
k1 init 8.5
a1 fold a1, kfreq
out a1
endin



resony

ar    resony     asig, kbf, kbw, inum, ksep [, iscl, istor]

DESCRIPTION

A bank of second-order bandpass filters, connected in parallel.

INITIALIZATION

inum - number of filters.
iscl - coded scaling factor for resonators. A value of 1 signifies a peak response factor of 1, i.e. all frequencies other than kcf are attenuated in accordance with the (normalized) response curve. A value of 2 raises the response factor so that its overall RMS value equals 1. (This intended equalization of input and output power assumes all frequencies are physically present; hence it is most applicable to white noise.) A zero value signifies no scaling of the signal, leaving that to some later adjustment (e.g. see balance). The default value is 0.
istor - initial disposition of internal data space. Since filtering incorporates a feedback loop of previous output, the initial status of the storage space used is significant. A zero value will clear the space; a non-zero value will allow previous information to remain. The default value is 0.

PERFORMANCE

asig - audio input signal
kbf - base frequency, i.e. center frequency of lowest filter in Hz
kbw - bandwidth in Hz
ksep - separation of the center frequency of filters in octaves

resony is a bank of second-order bandpass filters, with k-rate variant frequency separation, base frequency and bandwidth, connected in parallel (i.e. the resulting signal is a mixing of the output of each filter). The center frequency of each filter depends of kbf and ksep variables. The maximum number of filters is set to 100.

EXAMPLE:

asig, kbf, kbw, inum, ksep [, iscl, istor]

In this example the global variable gk1 modifies kbf, gk2 modifies  kbw, gk3  inum, gk4 ksep and gk5 the main volume.

	instr	1
a1	soundin "myfile.aif"
a2	resony	a1,   gk1 , gk2 ,i(gk3),gk4 ,2	
	out	a2 * gk5 
	endin



cpuprc

 cpuprc instrnum, ipercent

DESCRIPTION

Set the cpu processing-time percent usage of an instrument in order to avoid buffer underrun in realtime performances.

INITIALIZATION

instrnum - instrument number
ipercent - percent of cpu processing-time to assign

cpuprc is an opcode that enables a sort of polyphony theshold. The user must set ipercent value for each instrument he want to activate in realtime. Assumnig that the total theorical processing time of the cpu of the computer is 100%, this percent value can only be defined empirically, because there are too many factors that contribute to limit realtime polyphony in different computers. For example if ipercent is set to 5% for instrument 1, the maximum number of voices that can be allocated in realtime, can be 20 (as 5% X 20 = 100%). If the user attempts to play a further note while the 20 previous notes are still playing, Csound inhibits the allocation of that note and will display the following warning message:

  can't allocate last note because it exceeds 100% of cpu time

ipercent can be expressed also as a fractional value.

In order to avoid audio buffer underruns, it is suggested to set the maximum number of voices a bit below the real processing power of the computer, because sometimes an instrument can require more processing time than normal (for example, if the instrument contains an oscillator which reads a table that doesn't fit in cache memory, it will be slower than normal; also, any concurrent program which run in multitasking, can subtract more processing power in some cases, less power in other cases etc.)

At start, all instruments are set to a default value of ipercent = 0.0%  (i.e. zero processing time or rather infinite cpu processing-speed). This setting is OK for deferred-time sessions.

All instances of cpuprc must be defined in the header section, not in the instrument body.

example:

sr=44100
kr=441
ksmps=100
nchnls=2

cpuprc  1,  2.5           ;** set instr 1 to 2.5%   of processor power, i.e. maximum 40 voices (2.5% X 40 = 100%)
cpuprc  2,  33.333    ;** set  instr 2 to 33.333% of processor power, i.e. maximum 3 voices (33.333% X 3 = 100%)  

instr 1
...body...
endin

instr 2
....body...
endin



tab, tabw

ir tab_i indx, ifn[, ixmode]
kr tab kndx, ifn[, ixmode]
ar tab xndx, ifn[, ixmode]

tabw_i isig, indx, ifn [,ixmode]
tabw ksig, kndx, ifn [,ixmode]
tabw asig, andx, ifn [,ixmode]

DESCRIPTION

Fast table opcodes. Faster than table and tablew because don't allow wrap-around and limit and don't check index validity. Have been implemented in order to provide fast access to arrays. Support non-power of two tables (can be generated by any GEN function by giving a negative length value).

INITIALIZATION

ifn - table number

ixmode (optional; default = 0) -  ==0 - xndx and ixoff ranges match the length of the table.
                                                         !=0 - xndx and ixoff have a 0 to 1 range.
isig - input value to write

indx - table index

PERFORMANCE

asig, ksig  - input signal to write
andx, kndx - table index

tab and tabw opcodes are similar to table and tablew, but are faster and support tables having non-power-of-two length.

Special care of index value must be taken into account. Index values out of the table allocated space will crash Csound.



random, randomi, radomh 

ir random imin, imax
kr random kmin, kmax
ar random  kmin,kmax

kout randomi kmin, kmax, kcps
aout randomi kmin, kmax, acps

kout randomh kmin, kmax, kcps
aout randomh kmin, kmax, acps

DESCRIPTION

Output is a controlled pseudo-random number series between min and max

INITIALIZATION

imin - minimum range limit
imax - maximum range limit

PERFORMANCE

kmin - minimum range limit
kmax - maximum range limit

kcps, acps - rate of random break-point generation

random opcode is similar to linrand and trirand but allows the user to set arbitrary minimum and maximum values.

randomi is similar to randi but allows the user to set arbitrary minimum and maximum values.

randomh is similar to randh but allows the user to set arbitrary minimum and maximum values.

The Xcps parameters of randomh and randomi permit the user to specify that new random numbers are to be generated at a rate less than the sampling or control frequencies. randomh will hold each new number for the period of the specified cycle; randomi will produce straightline interpolation between each new number and the next. See also randi and randh.

All these opcodes use a custom, high-speed 31-bit random number generator. For all these opcodes, use seed opcode to give a new random-generation seed.



duserrnd, cuserrnd

iout duserrnd itableNum
kout duserrnd ktableNum
aout duserrnd atableNum

iout = urd(itableNum)
kout = urd(ktableNum)
aout = urd(atableNum)

iout cuserrnd imin, imax, itableNum
kout cuserrnd kmin, kmax, ktableNum
aout cuserrnd amin, amax, atableNum

DESCRIPTION

Output is a controlled pseudo-random number series. In these cases, the random distributions are created by the user.

INITIALIZATION

itableNum - number of table containing the random-distribution function. Such table is generated by the user. See GEN40, GEN41 and GEN42. The table length doesn't need to be a power of 2

imin - minimum range limit
imax - maximum range limit

PERFORMANCE

ktableNum - number of table containing the random-distribution function. Such table is generated by the user. See GEN40, GEN41 and GEN42. The table length doesn't need to be a power of 2

kmin - minimum range limit
kmax - maximum range limit

duserrnd (discrete user-defined-distribution random generator) generates random values according to a discrete random distribution created by the user. The user can create the discrete distribution histogram by using GEN41. In order to create that table, the user has to define an arbitrary amount of number pairs, the first number of each pair representing a value and the second representing its probability (see GEN41 for more details). urd is the same opcode as duserrnd, but can be used in function fashion. When used  as a function, the rate of generation depends by the rate type of input variable XtableNum. In this case it can be embedded into any formula. Table number can be varied at k-rate, allowing to change the distribution histogram during the performance of a single note. duserrnd is designed be used in algorithmic music generation.

duserrnd can also be used to generate values following a set of ranges of probabilities by using distribution functions generated by GEN42 (See GEN 42 for more details). In this case, in order to simulate continuous ranges, the length of table XtableNum should be reasonably big, as duserrnd doesn't interpolate beetween table elements.

cuserrnd (continuous user-defined-distribution random generator)  generates random values according to a continuous random distribution created by the user. In this case the shape of the distribution histogram can be drawn or generated by any GEN routine. The table containing the shape of such histogram must then be translated to a distribution function by means of GEN40 (see GEN40 for more details). Then such function must be assigned to the XtableNum  argument of cuserrnd. The output range can then be rescaled according to the Xmin and Xmax arguments. cuserrnd linearly interpolates beetween table elements, so it is not recommended for discrete distributions (GEN41 and GEN42).

For a tutorial about random distribution histograms and functions see:

D. Lorrain. "A panoply of stochastic cannons". In C. Roads, ed. 1989. Music machine. Cambridge, Massachusetts: MIT press, pp. 351 - 379.



vibrato, vibr, jitter, jitter2

kout vibrato kAverageAmp, kAverageFreq, kRandAmountAmp, kRandAmountFreq, kAmpMinRate, kAmpMaxRate, kcpsMinRate, kcpsMaxRate, ifn [, iphs]

kout vibr kAverageAmp, kAverageFreq, ifn

kout jitter kamp, kcpsMin, kcpsMax
kout jitter2 ktotamp, kamp1, kcps1, kamp2, kcps2, kamp3, kcps3

DESCRIPTION

These opcode are designed to make sounds more natural to hearing. vibrato and vibr generates a vibrato-like signal containing some user-controlled randomness in amplitude and frequency; jitter and jitter2 produces some deviation to be summed to constant signals to make them more "analog-like" and natural.

INITIALIZATION

ifn - number of vibrato table. It normally contains a sine or a triangle wave.

iphs (optional) - initial phase of table, expressed as a fraction of a cycle (0 to 1). A negative value will cause phase initialization to be skipped. The default value is 0.

PERFORMANCE

kAverageAmp - average amplitude value of vibrato
kAverageFreq - average frequency value of vibrato (in cps)
kRandAmountAmp - amount of random amplitude deviation
kRandAmountFreq - amount of random frequency deviation
kAmpMinRate - minimum frequency of random amplitude deviation segments (in cps)
kAmpMaxRate - maximum frequency of random amplitude deviation segments (in cps)
kcpsMinRate - minimum frequency of random frequency deviation segments (in cps)
kcpsMaxRate - maximum frequency of random frequency deviation segments (in cps)

kamp - amplitude of jitter deviation
kcpsMin -  minimum speed of random frequency variations (expressed in cps)
kcpsMax - maximum speed of random frequency variations (expressed in cps)

ktotamp - resulting amplitude of jitter2
kamp1 - amplitude of the first jitter component
kcps1 - speed of random variation of the first jitter component (expressed in cps)
kamp2 - amplitude of the second jitter component
kcps2 - speed of random variation of the second jitter component (expressed in cps)
kamp3 - amplitude of the third jitter component
kcps3 - speed of random variation of the third jitter component (expressed in cps)

vibrato outputs a natural-sounding user-controllable vibrato. The concept is to randomly vary both frequency and amplitude of the oscillator generating the vibrato, in order to simulate the irregularities of a real vibrato. In order to have a total control of these random variations, several input arguments are present. Random variations are obtained by two separated segmented lines, the first controlling amplitude deviations, the second the frequency deviations. Average duration of each segment of each line can be shortened or enlarged by the arguments kAmpMinRate, kAmpMaxRate, kcpsMinRate, kcpsMaxRate, and the deviation from the average amplitude and frequency values can be independently adjusted by means of  kRandAmountAmp and kRandAmountFreq.

vibr is an easier-to-use version of vibrato. It has the same generation-engine of vibrato, but the parameters corresponding to missing input arguments are hard-coded to default values.

jitter generates a segmented line whose segments are randomly generated inside the +kamp and -kamp interval. Duration of each segment is a random value generated according to kcpsmin and kcpsmax values.

jitter2 also generates a segmented line such as jitter, but in this case the result is similar to the sum of three randi opcodes, each one with a different amplitude and frequency value (see randi for more details), that can be varied at k-rate. Different effects can be obtained by varying the input arguments.

jitter and jitter2 can be used to make more natural and "analog-sounding" some static, dull sound. For best results, It is suggested to keep their amplitude moderate.



SoundFont2-related opcodes

ifilhandle sfload "filename"
sfplist ifilhandle
sfilist ifilhandle
sfpassign istartindex, ifilhandle
ipreindex sfpreset iprog, ibank, ifilhandle, ipreindex

a1, a2 sfplay ivel, inotnum, xamp, xfreq, ipreindex [, iflag]
a1 sfplaym ivel, inotnum, xamp, xfreq, ipreindex [, iflag]

a1, a2 sfinstr ivel, inotnum, xamp, xfreq, instrNum, ifilhandle [, iflag]
a1 sfinstrm ivel, inotnum, xamp, xfreq, instrNum, ifilhandle [, iflag]

a1, a2 sfplay3 ivel, inotnum, xamp, xfreq, ipreindex [, iflag]
a1 sfplay3m ivel, inotnum, xamp, xfreq, ipreindex [, iflag]

a1, a2 sfinstr3 ivel, inotnum, xamp, xfreq, instrNum, ifilhandle [, iflag]
a1 sfinstr3m ivel, inotnum, xamp, xfreq, instrNum, ifilhandle [, iflag]

DESCRIPTION

Csound now supports SoundFont2 format. These opcodes allow to manage the sample-structure of SoundFont2 files.

INITIALIZATION

filename - name of the SoundFont2 file (complete pathname). You must use "/" to separate directories even under Windows. It must be typed within double-quotes.
ifilhandle - unique number generated by sfload opcode to be used as an identifier of a SoundFont2 file, since several SoundFont2 files can be loaded and activated at the same time.
istartindex - starting preset index set by the user in bulk preset assignments (see below).
ipreindex - preset index
iprog - program number of a bank of presets of a SoundFont2 file
ibank - number of a specific bank of a SoundFont2 file
ivel - velocity value
inotnum - note number value
iflag - flag regarding the behaviour of xfreq (see below).
instrNum -  number of an instrument of a SoundFont2 file.

PERFORMANCE

xamp - amplitude correction factor
xfreq - frequency value or frequency correction factor (depending by iflag, see below)

SoundFont2 is a widespread standard which allow to embed banks of wavetable-based sounds into a binary file. In order to understand the usage of these opcodes, the user must know some notion about SF2 format. So a brief description of this format follows.

The SoundFont2 format is made by generator and modulator objects. All current Csound opcodes regarding SF2 support generator section only, so we will only deal with the generator-related structure of SF2 format,  omitting the modulators.

There are several levels of generators having a hierarchical structure. The most basic kind of generator object is a sample. Samples can or can't be be looped and are associated to a MIDI note number, called base-key. When a sample is associated  with a range of MIDI note numbers, with a range of velocities, with a transposition (coarse and fine tuning), with a scale tuning, and with a level scaling factor, such sample makes up a split. A set of splits, together with a name, makes up an instrument. When an instrument is associated with a key range, with a velocity range, with a level scaling factor, and with a transposition, it makes up a layer. A set of layers, together with a name, makes up a preset. Presets are normally the final sound-generating structures ready for the user. They generate sound according to the settings of their lower-level components. Here is a picture of that structure:


Both sample data and structure data is embedded in the same SoundFont2 binary file. A single SF2 file can contain up to a maximum of 128 banks of 128 preset programs, for a total of 16384 presets each one. Maximum number of layers, instruments, splits and samples is not defined, and probably is only limited by the computer memory.

sfload opcode loads an entire SF2 file in memory. It returns a file handle to be used by other opcodes. Several instances of sfload can placed in the header section of an orchestra, allowing to work with more-than-one SF2 files at the same time.

sfplist prints a list of all presets of a previously loaded SF2 file to the console.

sfilist prints a list of all instruments of a previously loaded SF2 file to the console.

sfpassign assigns all presets of a previously loaded SF2 file to a sequence of progressive index numbers, to be used later with the opcodes sfplay and sfplaym. The user can enstabilish the first index number by setting startindex argument. Any number of sfpassign instances can be placed in the header section of an orchestra, each one assigning presets belonging to different SF2 files. The user must take care that preset index numbers of different SF2 files don't cross themselves.

sfpreset assigns an existing preset of a previously-loaded SF2 file to an index number, to be used later with the opcodes sfplay and sfplaym. The user must previously know the program and the bank numbers of the preset in order to fill the corresponding arguments. Any number of sfpreset instances can be placed in the header section of an orchestra, each one assigning a different preset belonging to the same (or different) SF2 file to different index numbers.

sfplay plays a preset generating a stereo sound. ivel argument doesn't directly affect output amplitude, but informs sfplay opcode about what sample has to be choosen in multi-sample velocity-splitted presets. inotnum argument sets the frequency of the output when iflag = 0.  When iflag == 1, inotnum doesn't directly affect the frequency of the output (see below). Adjustment of amplitude can be done by varying the xamp argument, that actually is a multiplier factor. xfreq argument have a two different behaviour depending by the value of iflag argument:

  1. when iflag = 0 (or missing as this value is the default) xfreq  argument is a multiplier of a the default frequency assigned by SF2 preset to the inotenum value. This can correct the default frequency (for example to obtain vibrato or some other frequency -shift effect).

  2. when iflag = 1 xfreq argument should contain the actual frequency of the output sound in cps. This allow the user to use any kind of micro-tuning based scales. However this flag is designed to work correctly only with presets tuned to the default equal temerament. Don't try to use this flag value with preset already having non-standard tunings or with drum-kit-based presets, since unespected results could occurr.

Notice that both xamp and xfreq arguments can contain k-rate signals as well as a-rate signals, but the user must be sure that both arguments are filled with variables of the same rate, or sfplay will not work correctly.
The user must be sure that ipreindex argument is filled with a number containing a previously assigned preset, otherwise Csound will crash.

sfplaym opcode is a mono version of sfplay. It should be used with mono preset, or with the stereo presets in wich stereo output is not required, because is a bit faster than sfplay.

sfinstr plays an SF2 instrument instead of a preset (an SF2 instrument is the base of a preset layer). instrnum argument contains the instrument number, and the user must be sure that such number belongs to an existent instrument of a determinate soundfont bank. Notice that both xamp and xfreq arguments can contain k-rate signals as well as a-rate signals, but, also in this case, the user must be sure that both arguments are filled with variables of the same rate, or sfinstr will not work correctly.

sfinstrm plays is a mono version of sfinstr. This is the fastest opcode of the SF2 family.

sfplay3, sfplay3m, sfinstr, sfinstr3m are cubic-interpolation versions of previous opcodes. Difference of sound-quality is noticeable specially in bass-frequency-transposed samples. In high-freq-transposed samples the difference is less noticeable, and I suggest to use linear-interpolation versions, because they are faster.

These Csound opcodes only handle sampling structure of SF2 files, because support of modulator objects (amplitude envelopes, frequency modulation, filter envelopes and modulation) is very basic and trivial in SF2 standard; so, adding any kind of modulation or processing to the sample data is completely left to the Csound user, bypassing all  restrictions forced by the SF2 standard.



Sequence-related opcodes

ktrig seqtime ktime_unit, kstart, kloop, initndx, kfn_times

ktrig seqtime2 ktrig_in, ktime_unit, kstart, kloop, kinitndx, kfn_times

trigseq  ktrig_in,  kstart,  kloop, initndx,  kfn_values, kout1 [, kout2, kout3, ....,  koutN]

DESCRIPTION

Handle timed-sequences of groups of values stored into tables.

INITIALIZATION

initndx - initial index

PERFORMANCE

kinitndx - reinit starting index
ktrig - output trigger signal
ktime_unit  - unit of measure of time, related to seconds.
kstart - start index of looped section
kloop - end index of looped section
kfn_times - number of table containing a sequence of times
kfn_values - numer of a table containing a sequence of groups of values
ktrig_in - input tirgger signal
kout1 [, kout2, kout3, ....,  koutN] - output values

These opcodes handle timed-sequences of groups of values stored into tables.

seqtime generates a trigger signal (a sequence of impulses, see also trigger opcode), according to the values stored in kfn_times table. This table should contain a series of delta-times (i.e. times beetween to adiacent events). The time units stored into table are expressed in seconds, but can be rescaled by means of ktime_unit argument. The table can be filled with GEN02 or by means of an external text-file containing numbers, with GEN23. It is possible to start the sequence from a value different than the first, by assigning to initndx an index different than zero (which corresponds to the first value of the table). Normally the sequence is looped, and the start and end of loop can be adjusted by modifying kstart and kloop arguments. User must be sure that values of these arguments (as well as initndx) correspond to valid table numbers,  otherwise Csound will crash (because no range-checking is implementeted). It is possible to disable loop (one-shot mode) by assigning the same value both to kstart and kloop arguments. In this case, the last read element will be the one corresponding to the value of such arguments. Table can be read backward by assigning a negative kloop value. It is possible to trigger two events almost at the same time (actually separated by a k-cycle) by giving a zero value to the corresponding delta-time. First element contained in the table should be zero, if the user intend to  send a trigger impulse it immediately after  the orchestra instrument containing seqtime opcode.

seqtime2 is similar to seqtime, the difference is that when ktrig_in contains a non-zero value, current index is reset to kinitndx value. kinitndx can be varied at performance time.

trigseq accepts a trigger signal (ktrig_in) as input and outputs group of values (contained into kfn_values table) each time ktrig_in assumes a non-zero value. Each time a group of values is triggered, table pointer is advanced of a number of positions corresponding to the number of group-elements, in order to point to the next group of values. The number of elements of groups is determined by the number of koutX arguments. It is possible to start the sequence from a value different than the first, by assigning to initndx an index different than zero (which corresponds to the first value of the table). Normally the sequence is looped, and the start and end of loop can be adjusted by modifying kstart and kloop arguments. User must be sure that values of these arguments (as well as initndx) correspond to valid table numbers,  otherwise Csound will crash (because no range-checking is implementeted). It is possible to disable loop (one-shot mode) by assigning the same value both to kstart and kloop arguments. In this case, the last read element will be the one corresponding to the value of such arguments. Table can be read backward by assigning a negative kloop value.

Notice that trigseq output arguments are placed at the left of the opcode name, differently from usual (this style is already used in other opcodes using undefined lists of output arguments such as fin).

trigseq is designed to be used together with seqtime or trigger opcodes.

Example:

	instr	1
icps	cpsmidi
iamp	ampmidi	5000
ktrig	seqtime	1,       1,          10,      0,   1
trigseq	ktrig, 0, 10, 0, 2, kdur, kampratio, kfreqratio
	schedkwhen	ktrig, -1, -1, 2, 0, kdur, kampratio*iamp, kfreqratio*icps
	endin



Random Curve Generators

kr jspline kamp, kcpsMin, kcpsMax
ar jspline xamp, kcpsMin, kcpsMax

kr rspline krangeMin, krangeMax, kcpsMin, kcpsMax
ar rspline xrangeMin, xrangeMax, kcpsMin, kcpsMax

DESCRIPTION

Generate random spline curves

INITIALIZATION

no init args

PERFORMANCE

kr, ar - output signal
xrangeMin, xrangeMax - range of values of random-generated points
kcpsMin, kcpsMax -  range of point-generation rate. Min and max limits are expressed in cps.
xamp - amplitude factor

jspline (jitter-spline generator) generates a smooth curve based on random points generated at [cpsMin, cpsMax] rate.  This opcode is similar to randomi or randi or jitter, but segments are not stright lines, but cubic spline curves. Output value range is approximately > -xamp and < xamp. Actually, real range could be a bit greater, because of interpolating curves beetween each pair of random-points.

rspline (random-spline-curve generator) is similar to jspline but output range is defined by means of two limit values. Also in this case, real output range could be a bit greater of range values, because of interpolating curves beetween each pair of random-points.

At present time generated curves are quite smooth when cpsMin is not too different from cpsMax. When cpsMin-cpsMax interval is big, some little discontinuity could occurr, but it should not be a problem in most cases. Maybe the algorithm will be improved in next versions.

These opcodes are better than jitter when user wants to "naturalize" or "analogize" digital sounds. They could be used also in algorithmic composition, to generate smooth random melodic lines when used together with samphold opcode.



Tables of Vectors

vtablei  indx, ifn, interp, ixmode, iout1 [, iout2, iout3, .... , ioutN ]
vtablek  kndx, kfn, kinterp, ixmode, kout1 [, kout2, kout3, .... , koutN ]
vtablea  andx, kfn, kinterp, ixmode, aout1 [, aout2, aout3, .... , aoutN ]

vtabi  indx, ifn, iout1 [, iout2, iout3, .... , ioutN ]
vtabk  kndx, ifn, kout1 [, kout2, kout3, .... , koutN ]
vtaba   andx, ifn, aout1 [, aout2, aout3, .... , aoutN ]

vtablewi  indx, ifn, ixmode, inarg1 [, inarg2, inarg3 , .... , inargN ]
vtablewk  kndx, kfn, ixmode, kinarg1 [, kinarg2, kinarg3 , .... , kinargN ]
vtablewa  andx, kfn, ixmode, ainarg1 [, ainarg2, ainarg3 , .... , ainargN ]

vtabwi   indx, ifn, inarg1 [, inarg2, inarg3 , .... , inargN ]
vtabwk  kndx, ifn, kinarg1 [, kinarg2, kinarg3 , .... , kinargN ]
vtabwa  andx, ifn, ainarg1 [, ainarg2, ainarg3 , .... , ainargN ]

DESCRIPTION

Access to table of vectors

INITIALIZATION and PERFORMANCE

ixmode -  index data mode. The default value is 0.
                == 0 index is treated as a raw table location,
                == 1 index is normalized (0 to 1).

ifn, kfn - table number

indx, kndx, andx - Index into f-table, either a positive number range matching the table length (ixmode = 0) or a 0 to 1 range (ixmode != 0).

iout1...ioutN, kout1,,,koutN, aout1...aoutN - output vectors

kinterp - interpolation flag: 0 -> non-interpolation , non-zero -> interpolation activated

inarg1...inargN, kinarg1...kinargN, ainarg1...ainargN - input vectors

These opocodes support read/write access to arrays of vectors (or arrays of arrays).

These opcodes are useful in all cases in which one needs to access sets of values associated to unique indexes (for example, multi-channel samples, STFT bin frames, spectral formants, p-field based scores etc.) . The number of elements of each vector frame is automatically determined by the number of outN or inargN arguments, and must remain fixed for all indexes of each table.

vtable (vector table) family of opcodes allows the user to switch beetween interpolated or non-interpolated output at k-rate by means of kinterp argument.

vtable allows also to switch the table number at k-rate (but this is possible only when vector frames of each used table have the same number of elements, otherwise unpredictable results could occurr), as well as to choose indexing style (raw or normalized, see  also ixmode argument of table opcode ).

Notice that no wrap nor limit mode is implemented.  So, if  an index attempt to access to a zone not allocated by the table, Csound will probably crash. However this drawback can be easily avoided by using wrap or limit opcodes applied to indexes before using vtable, in order to correct eventual out-of-range values.

Notice that vtable output arguments are placed at the left of the opcode name, differently from usual (this style is already used in other opcodes using undefined lists of output arguments such as fin or trigseq).

vtablew family allows to write vectors frames into tables. It allows to switch the table number at k-rate (but vector frames of each used table must have the same number of elements), as well as to choose indexing style (raw or normalized, see  also argument ixmode in table opcode).

vtab family is similar to vtable, but is much faster because interpolation is not available, table number cannot be changed after initialization, and only raw indexing is supported.

vtabw family is similar to vtablew, but is much faster because interpolation is not available, table number cannot be changed after initialization,  and only raw indexing is supported.



Common Musical Converters

octave(x)
semitone(x)
cent(x)
db(x)

DESCRIPTION

Convert musical logarithmic units into multipliers. Useful to easily managing common musical unit of measure.

INITIALIZATION and PERFORMANCE

x - input value (can be at any rate).

All these functions convert a logarithmic value to be used in multiplication. Standard musical unit of measure are supported:

octave intervals
semitone intervals
cent intervals
decibels

The argument within the parentheses may be a further expression. These are really value converters with a special function of manipulating musical data.

for exampe, if one wants to rise the amplitude of  asig of 6 decibel it is sufficient the following line

asig = asig * db(6)

Also negative values are allowed, for example, if one has to transpose a frequency signal kfreq down of 7 semitones:

kfreq = kfreq * semitone(-7)



Glissando Generators

kr lineto ksig, ktime
kr tlineto ksig, ktime, ktrig

DESCRIPTION

Generate glissandos starting from a control signal.

PERFORMANCE

kr - output signal
ksig - input signal
ktime - time length of glissando in seconds
ktrig - trigger signal

lineto adds glissando (i.e. stright lines) to a stepped input signal (for example, produced by randh or randomh). It generates a stright line starting from previous step value, reaching the new step value in ktime seconds. When the new step value is reached, such value is holded until a new step occurs. Be sure that ktime argument value is smaller than the time elapsed beetween two consecutive steps of the original signal, otherwise discontinuities will occurr in output signal.

tlineto is similar to lineto, but can be applied to any kind of signal (not only stepped signals), without producing discontinuities. Last value of each segment is sampled and holded from input signal each time ktrig value is set to a nonzero value. Normally ktrig signal consists of a sequence of zeroes (see trigger opcode).



Converting Bitmap Image Data to Control Signals

iwidth, iheight, ibpp bmopen ifilno, ifn

kr, kg, kb, ka  bmtable kx, ky, ifn
kr, kg, kb, ka  bmtablei kx, ky, ifn

kr, kg, kb, ka bmoscil ktrig, kxinc, kyinc, ktrig_xphreset, ktrig_yphreset, kxphs, kyphs, ifn
kr, kg, kb, ka bmoscili ktrig, kxinc, kyinc, ktrig_xphreset, ktrig_yphreset, kxphs, kyphs, ifn

khue, ksat, kval, klum rgb2hsvl kr, kg, kb
ihue, isat, ival, ilum rgb2hsvl_i ir, ig, ib

bmscan kx, ihorLines, ifn, istartLine, ifnR, ifnG, ifnB
bmscani kx, ihorLines, ifn, istartLine, ifnR, ifnG, ifnB

DESCRIPTION

Generate control signals by scanning bitmap image data.

INITIALIZATION

iwidth - image width
iheight - image height
ibpp - image bit per pixel
ifilno - character-string denoting the file name of the source image.
ifn - an integer number chosen by the user, used as identifier of loaded image
ihue, isat, ival, ilum - hue, saturation, value and luminance of current RGB data.
ir, ig, ib - RGB components of a pixel.
ihorLines - distance between horizontal lines of bitmap image to scan. Minimum value is 1 maximum value is the vertical pixel size of the image
istartLine - horizontal line to start with. Minimum is 0 (lowest horizontal line), maximum is the vertical size of the image in pixel, minus one.
ifnR, ifnG, ifnB - numbers of output tables. Each table contains a vector with the single color component (Red, Green or Blue) of all horizontal scanned lines.

PERFORMANCE

kx - horizontal phase value
ky - vertical phase value
kr, kg, kb,ka - control signals containing the red, green, blue  and alpha components of current pixel of the image.
ktrig - trigger signal: when this signal is nonzero, forces the corresponding opcode to evaluate a new phase value, basing on kxinc
kxinc, kyinc - horizontal and vertical phase increments. When ktrig is nonzero, new phase values are evaluated.
ktrig_xphreset,  ktrig_yphreset - when non-zero set current phase value to current value of kxphs and kyphs.
kxphs, kyphs - control signals used to reset current horizontal and vertical phases when ktrig_xphreset and ktrig_yphreset are non-zero.
khue, ksat, kval, klum - hue, saturation, value and luminance of current RGB data.
kr, kg, kb - RGB components of a pixel

These opcodes allow to convert bitmap image data to control signals, which can then be used to control any synthesis parameter of Csound instruments.

bmopen read a  bitmap image file and stores it into memory. User should provide a unique identifier of the image (an integer number to be put in ifn argument) to access it with the other bitmap-oriented opcodes later. bmopen outputs information about opened image (width, height and bit per pixels). At present time the following image formats are supported:

Windows Bitmap (.BMP)
Tagged Image File Format (.TIF)
Jpeg - Jfif Compliant (.JPG)
Truevision Targa (.TGA)
Portable Network Graphics (.PNG)
Zsoft Paintbrush (.PCX)
Macintosh PICT (.PCT)
Encapsulated Postscript Bitmap (.EPS)

Even if JPEG format is provided, it is not recommended to use files encoded with destructive compression algorithm, because this could provide distorsion of generated signals.

bmtable returns red, green, blue and alpha values of the pixel pointed by the kx and ky coordinates of the picture ihandle.

bmtablei is identical to bmtable, but linear interpolation is provided when giving fractional coordinate values, whereas bmtable truncates any fractional value.

bmoscil is a sort of a two-dimensional oscillator applied to bitmap picture ihandle. Frequency/period of both horizontal and vertical domain can be independently set and varied during performance by means of kxinc (horizontal phase increment) and kyinc (vertical phase increment), that express the number of pixel  that horizontal and vertical phases have to advance. Notice that the phases are incremented only when ktrig is set to non-zero values, allowing rhythmic effects. Phase increments can be fractional. Also, phases can be reinitialized, according to kxphs and kyphs when two other triggers (ktrig_xphreset, ktrig_yphreset) are set to non-zero values.

bmoscili is identical to bmoscil, except linear interpolation is provided for output.

rgb2hsvl and rgb2hsvl_i convert input RGB data to hue, saturation, value and luminance data. rgb2hsvl works at k-rate, rgb2hsvl_i at init-rate (luminance is different from value in that, while the last one expresses the maximum value between red, green, blue components of a given pixel, luminance expresses the sum of red, green and blue components).

bmscan conception is similar to bmtable, but, instead of outputting scalar signals, it outputs vectors of RGB data, that are directly stored into tables. bmscan only accepts the horizontal coordinates as input (kx), because several vertical values aligned to the same horizontal position are stored in the output tables (ifnR, ifnG, ifnB) at the same time. These tables must be allocated before using bmscan opcode, by using a GEN routine, for example GEN02. ihandle is the bitmap image identifier, ihorLines determines the distance beween horizontal scanned lines (if it is set to 1, all adjacent lines are scanned), values greater than one allow to hop any number of lines. istartLine allows to start with a line different from the bottom line (value 0). bmscan is designed to operate together with opcodes accepting vectorial signals as input (such as, for example, adsynt or adsynt2, whose input are tables containing variant amplitudes and frequencies provided to control a bank of oscillators).

bmscani is identical to bmscan, exept that linear interpolation is provided for horizontal lines.

All these opcodes are intended to be applied to hand-made images (that in this case would be a sort of graphical score), as well as to algorithmically generated images (Fractals, Cellular Automata, etc.). Notice that color black is treated as zero level, were amplitude increases when the values of each component increase.



Trigger Metronome

ktrig metro kfreq [, initphase]

DESCRIPTION

Generate a metronomic signal to be used in any circumstance an isochronous trigger is needed.

INITIALIZATION

initphase - initial phase value (in the 0 to 1 range)

PERFORMANCE

ktrig - output trigger signal
kfreq - frequency of trigger bangs in cps

metro is a simple opcode that outputs a sequence of isochronous bangs (that is 1 values) each 1/kfreq seconds. Trigger signals can be used in any circumstance, mainly to temporize realtime algorithmic compositional structures.



Mandelbrot Set

kiter, koutrig mandel ktrig, kx, ky, kmaxIter

DESCRIPTION

Returns the number of iterations corresponding to a given point of complex plane by applying the Mandelbrot set formula.

PERFORMANCE

kiter- number of iterations
koutrig - output trigger signal
ktrig - input trigger signal
kx, ky - coordinates of a given point belonging to the complex plane
kmaxIter - maximum iterations allowed

mandel is an opocode that allows to use the Mandelbrot set formula to generate an output that can be applied to any musical (or non-musical) parameter. It has two output arguements, kiter, that contains the iteration number of a given point, and koutrig, that generates a trigger bang each time kiter changes. A new number of iterations is evaluated only when ktrig is set to a non-zero value. User have to set the coordinates of the complex plane inside kx and ky arguments, while kmaxIter contains the maximum number of iteration the user intend to use. Output values, that are integer numbers, can be mapped in any sorts of ways by the composer.



Micro Tuning

cpstun, cpstuni

kcps cpstun ktrig, kindex, kfn
icps cpstuni index, ifn

INITIALIZATION

icps - return value in cps
index - an integer number denoting an index of given scale
ifn - function table containing the parameters (numgrades, interval, basefreq, basekeymidi) and the tuning ratios.

PERFORMANCE

kcps - return value in cps
ktrig - a trigger signal used to trigger the evaluation
kindex - an integer number denoting an index of given scale
kfn - function table containing the parameters (numgrades, interval, basefreq, basekeymidi) and the tuning ratios.

These opcodes are similar to cpstmid, but work even without MIDI.

cpstun works at k-rate, while cpstuni at init-rate. They allow fully customized micro-tuning scales. They requires a function table number containing the tuning ratios, and the other parameters stored in the function tables itself.

kindex and index arguments express the grade of given scale to be converted in cps. They should be integer numbers, any eventual decimal part will be truncated. In cpstun, a new value is evaluated only when ktrig contains a non-zero value.
The function table ifn (or kfn) should be generated by GEN2 and the first four values stored in this function are parameters that express:

numgrades (the number of grades of the micro-tuning scale),
interval (the frequency range covered before repeating the grade ratios, for example 2 for one octave, 1.5 for a fifth etcetera), basefreq (the base frequency of the scale in cps),
basekey (the integer index of the scale to which to assign basefreq unmodified).

After these four values, the user can begin to insert the tuning ratios. For example, for a standard 12-grade scale with the base-frequency of 261 cps assigned to the key-number 60, the corresponding f-statement in the score to generate the table should be:

;           numgrades    basefreq     tuning-ratios (eq.temp) .......   
;                  interval    basekey       
f1 0 64 -2  12     2     261   60     1   1.059463 1.12246 1.18920 ..etc...

Another example with a 24-grade scale with a base frequency of 440 assigned to the key-number 48, and a repetition interval of 1.5:

;                  numgrades       basefreq      tuning-ratios .......   
;                          interval       basekey       
f1 0 64 -2         24      1.5     440    48     1   1.01  1.02  1.03   ..etc...



Operations Between a Vectorial and a Scalar Signal

vadd, vmult, vpow, vexp

vadd ifn, kval, ielements
vmult ifn, kval, ielements
vpow ifn, kval, ielements
vexp ifn, kval, ielements

DESCRIPTION

Perform numerical operations between a vectorial control signal and a scalar control signal

INITIALIZATION

ifn - number of the table hosting the vectorial signal to be processed
ielements - number of elements of the vector

PERFORMANCE

kval - scalar operand to be processed

These opcodes perform numeric operations between a vectorial control signal (hosted by the table ifn), and a scalar signal (kval).
Result is a new vector that overrides old values of ifn.
All these opcodes work at k-rate.

vadd adds kval operand to each elements of the vector contained in the table ifn.

vmult multiply each elements of the vector contained in the table ifn by kval operand.

vpow rises each elements of the vector contained in the table ifn to kval power.

vexp rises kval to each element contained in the table ifn.

In all previous opcodes, resulting vectors are stored in ifn, overriding the intial vectors. If you want to keep initial vector, use vcopy opcode to copy it in another table.

All these operators are designed to be used together with other opcodes that operate with vectorial signals such as bmscan, vcella, adsynt, adsynt2 etc.



Operations Between Two Vectorial Signals

vaddv ifn1, ifn2, ielements
vsubv ifn1, ifn2, ielements
vmultv ifn1, ifn2, ielements
vdivv ifn1, ifn2, ielements
vpowv ifn1, ifn2, ielements
vexpv ifn1, ifn2, ielements
vcopy ifn1, ifn2, ielements
vmap ifn1, ifn2, ielements

DESCRIPTION

Performs numerical operations between two vectorial control signals

INITIALIZATION

ifn1 - number of the table hosting the first vector to be processed
ifn2 - number of the table hosting the second vector to be processed
ielements - number of elements of the two vectors

These opcodes perform operations between two vectorial control signals, that is, each element of the first vector is processed (only) with the corresponding element of the other vector. Each vectorial signal is hosted by a table (ifn1 and ifn2). The number of elements contained in both vectors must be the same.

Result is a new vectorial control signal that overrides old values of ifn1. If you want to keep old ifn1 vector, use vcopy opcode to copy it in another table.
All these opcodes work at k-rate.

vaddv adds each element of ifn1 to the corresponding element of ifn2.

vsubv subtracts each element of ifn2 from the corresponding element of ifn2.

vmultv multiply each element of ifn1 by the corresponding element of ifn2.

vdivv divide each element of ifn1 by the corresponding element of ifn2.

vpowv rises each element of ifn1 to the corresponding element of ifn2.

vexpv rises each element of ifn2 to the corresponding element of ifn1.

vcopy copies ifn2 to ifn1. Useful to keep old vector values, by storing them in another table.

vmap maps elements of ifn1 according to the values of table ifn2. Elements of ifn1 are treated as indexes of table ifn2, so element values of ifn1 must not exceed the length of ifn2 table otherwise a Csound crash due to an illegal memory access error will occurr. Elements of ifn1 are treated as integers, so any fractional part will be truncated.

All these operators are designed to be used together with other opcodes that operate with vectorial signals such as bmscan, vcella, adsynt, adsynt2 etc.



Limiting and Wrapping Vectorial Signals

vlimit ifn, kmin, kmax, ielements
vwrap ifn, kmin, kmax, ielements
vmirror ifn, kmin, kmax, ielements

DESCRIPTION

Limit or wrap elements of vectorial control signals.

INITIALIZATION

ifn - number of the table hosting the vector to be processed
ielements - number of elements of the vector

PERFORMANCE

kmin - minimum threshold value
kmax - maximum threshold value

vlimit set lower and upper limits on each element of the vector they process.

vwrap wraps around each element of corresponding vector if it exceeds low or high thresholds.

vmirror 'reflects' each element of corresponding vector if it exceeds low or high thresholds.

These opcodes are similar to limit, wrap and mirror, but operate with a vectorial signal instead of with a scalar signal.

Result overrides old values of ifn1, if these are out of min/max interval. If you want to keep input vector, use vcopy opcode to copy it in another table.

All these operators are designed to be used together with other opcodes that operate with vectorial signals such as bmscan, vcella, adsynt, adsynt2 etc.



Vectorial Envelope Generators

vlinseg ifnout, ielements, ifn1, idur1, ifn2 [, idur2, ifn3 [...]]
vexpseg ifnout, ielements, ifn1, idur1, ifn2 [, idur2, ifn3 [...]]

DESCRIPTION

Generate linear or exponential vectorial segments

INITIALIZATION

ifnout - number of table hosting output vectorial signal
ifn1 - starting vector
ifn2, ifn3, etc. - vector after idur1 seconds
idur1 - duration in seconds of first segment.
dur2, idur3, etc. - duration in seconds of subsequent segments.
ielements - number of elements of vectors.

These opcodes are similar to linseg and expseg, but operate with vectorial signals instead of with scalar signals.

output is a vectorial control signal hosted by ifnout (that must be previously allocated), while each break-point of the envelope is actually a vector of values. All break-points must contain the same number of elements (ielements).

All these operators are designed to be used together with other opcodes that operate with vectorial signals such as bmscan, vcella, adsynt, adsynt2 etc.



Vectorial Random Signal Generator

vrandh ifn, krange, kcps, ielements
vrandi ifn, krange, kcps, ielements

DESCRIPTION

Generate a sort of 'vectorial band-limited noise'

INITIALIZATION

ifn - number of the table containing the output vector
ielements - number of elements of output vector.

PERFORMANCE

krange - range of random elements (from -krange to krange)
kcps - rate of generated elements in cycles per seconds

These opcodes are similar to randh and randi, but operate with vectors instead of with scalar values.

The output is a vector contained in ifn (that must be previously allocated).

All these operators are designed to be used together with other opocdes that operate with vector such as bmscan, adsynt etc.



Vectorial Control-rate Delay Paths

vport ifn, khtime, ielements [, ifnInit]
vecdelay ifn, ifnIn, ifnDel, ielements, imaxdel [, iskip]

DESCRIPTION

Generate a sort of 'vectorial' delay or portamento

INITIALIZATION

ifn - number of the table containing the output vector
ifnIn - number of the table containing the input vector
ifnDel - number of the table containing a vector whose elements contain delay values in seconds
ifnInit (optional) - number of the table containing a vector whose elements contain intial portamento values.
ielements - number of elements of vectors.
imaxdel - Maximum value of delay in seconds.
iskip (optional) - initial disposition of delay-loop data space (see reson). The default value is 0.

PERFORMANCE

khtime - time for output to reach halfway to input.

vport is similar to port, but operates with vectorial signals, istead of with scalar signals. Each vector element is treated as an indipendent control signal. Input vector input and output vectors are placed in the same table and output vector overrides input vector. If you want to keep input vector, use vcopy opcode to copy it in another table.

vecdelay is similar to vdelay, but it works at k-rate and, instead of delaying a single signal, it delays a vector. ifnIn is the input vector of signals, ifn is the output vector of signals, and ifnDel is a vector containing delay times for each element, expressed in seconds. Elements of ifnDel can be updated at k-rate. Each single delay can be different from that of the other elements, and can vary at k-rate. imaxdel sets the maximum delay allowed for all elements of ifnDel.



K-rate Variable Time Delay

kr, vdelayk ksig, kdel, imaxdel [, iskip]

DESCRIPTION

Variable delay applied to a k-rate signal

INITIALIZATION

imaxdel - maximum value of delay in seconds.
iskip (optional) - Skip initialization if present and non zero.

PERFORMANCE

kr - delayed output signal
ksig - input signal
kdel - delay time in seconds can be varied at k-rate

vdelayk is similar to vdelay, but works at k-rate. It is designed to delay control signals, to be used, for example, in algorithmic composition.



Cellular Automata

vcella ktrig, kreinit, ioutFunc, initStateFunc, iRuleFunc, ielements, irulelen [, iradius]

DESCRIPTION

Unidimensional Cellular Automata applied to Csound vectors

INITIALIZATION

ioutFunc - number of the table where the state of each cell is stored
initStateFunc - number of a table containig the inital states of each cell
iRuleFunc - number of a lookup table containing the rules
ielements - total number of cells
irulelen - total number of rules
iradius (optional) - radius of Cellular Automata. At present time CA radius can be 1 or 2 (1 is the default)

PERFORMANCE

ktrig - trigger signal. Each time it is non-zero, a new generation of cells is evaluated
kreinit - trigger signal. Each time it is non-zero, state of all cells is forced to be that of initStateFunc.

vcella supports unidimensional cellular automata, where the state of each cell is stored in ioutFunc. So ioutFunc is a vector containing current state of each cell. This variant vector can be used together with any other vector-based opcode, such as adsynt, vmap, vpowv etc.

initStateFunc is an input vector containing the inital value of the row of cells, while iRuleFunc is an input vector containing the rules in the form of a lookup table. Notice that initStateFunc and iRuleFunc can be updated during the performance by means of other vector-based opcodes (for example vcopy) in order to force to change rules and status at performance time.

A new generation of cells is evaluated each time ktrig contains a non-zero value. Also the status of all cells can be forced to assume the status corresponding to the contents of initStateFunc each time kreinit contains a non-zero value.

Radius of CA algorithm can be 1 or 2 (optional iradius arguement).



Table-Controlled Oscillator Bank

ar adsynt2 kamp, kcps, iwfn, ifreqfn, iampfn, icnt[, iphs]

Performs additive synthesis with an arbitrary number of partials, not necessarily harmonic (see adsynt for detailed manual).

INITIALIZATION

iwfn - table containing a waveform, usually a sine. Table values are not interpolated for performance reasons, so larger tables provide better quality.

ifreqfn - table containing frequency values for each partial. ifreqfn may contain initial frequency values for each partial, but is usually used for generating parameters at runtime with tablew. Frequencies must be relative to kcps. Size must be at least icnt.

iampfn - table containing amplitude values for each partial. iampfn may contain initial amplitude values for each partial, but is usually used for generating parameters at runtime with tablew. Amplitudes must be relative to kamp. Size must be at least icnt.

icnt - number of partials to be generated

iphs - initial phase of each oscillator, if iphs = -1, initialization is skipped. If iphs > 1, all phases will be initialized with a random value.

PERFORMANCE

kamp - amplitude of note.

kcps - base frequency of note. Partial frequencies will be relative to kcps.

adsynt2 is identical to adsynt (by Peter Neubäcker), except it provides linear interpolation for amplitude envelopes of each partial. It is a bit slower than adsynt, but interpolation higly improves sound quality in fast amplitude envelope transients when kr < sr (i.e. when ksmps > 1). No interpolation is provided for pitch envelopes, since in this case sound quality degradation is not so evident even with high values of ksmps. It is not recommended when kr=sr, in this case adsynt is better (since it is faster).

adsynt2 is designed to be used together with bmscan, bmscani, vectorial generators, operators and modifiers, vcella, etc.



Widgets and GUI controllers

Widgets allow to design a custom Grafic User Interface to control an orchestra in real-time. They are derived from the open-source library FLTK (Fast Light Tool Kit). Such library is one of the fastest graphic libraries available, supports OpenGL and should be source compatible with different platforms (Windows, Linux, Unix and Mac OS) The subset of FLTK implemented in Csound provides the following types of objects:

Containers are widgets that contain other widgets, such as panels, windows etc. Csound provides the following container objects:

The most useful objects are named valuators. These objects allow the user to vary synthesis parameter values in realtime. Csound provides the following valuator objects:

There are other widgets that are not valuators nor containers:

Also there are some other opcodes useful to modify the widget apparence:

At last, there are three important opcodes that allowing the following actions:

Here is an example preview of Csound code for a window containing a valuator. Notice that all opcodes are init-rate and must be called only once per session. The best way to use them is to place them in the header section of an orchestra, externally to any instrument (even if placing them inside an instrument is not prohibited, unpredictable results can occur if that instrument is called more than once). Each container are made up of a couple of opcodes, the first indicating the start of the container block, the last indicating the end of that container block. Some container blocks can be nested, but they must not be crossed. After defining all containers, widget thread must be run, by using the special FLrun opcode, that takes no arguments.For example to create a window, the following Csound code is needed:

;********************
sr=48000
kr=480
ksmps=100
nchnls=1

;*** It is recommended to put almost all GUI code in the 
;*** header section of an orchestra

	FLpanel		"Panel1",450,550 ;***** start of container
; some widgets should contained here
	FLpanel_end	;***** end of container
	
	FLrun		;***** runs the widget thread, it is always required!
instr 1
;put some synthesis code here
endin
;*********************

The previous code simply creates a panel (an empty window because no widgets are defined inside the container).

The following example creates two panels and inserts a slider inside each of them:

;******************************
sr=48000
kr=480
ksmps=100
nchnls=1

	FLpanel		"Panel1",450,550,100,100 ;***** start of container
gk1,iha	FLslider	"FLslider 1", 500, 1000, 2 ,1, ih1, 300,15, 20,50
	FLpanel_end	;***** end of container
	
	FLpanel		"Panel1",450,550,100,100 ;***** start of container
gk2,ihb	FLslider	"FLslider 2", 100, 200, 2 ,1, ih2, 300,15, 20,50
	FLpanel_end	;***** end of container

	FLrun		;***** runs the widget thread, it is always required!
instr 1
;put some synthesis code here
; gk1 and gk2 variables that contain the output of valuator 
; widgets previously defined, can be used inside any instrument
endin
;*******************************

All widget opcodes are init-rate opcodes, even if valuators output k-rate variables. This happens because an independent thread is run, based on a callback mechanism which consumes very few processing resources, since there is not need of polling (differently from other MIDI based controller opcodes). So you can use any number of windows and valuators without degrading the realtime performance.

Since FLTK tookit is still in evolution process, opcode syntax provided in Csound could be modified in future version, causing some incompatibilities between orchestras of a determinate version. However it should not be hard to modify early orchestras in order to make them compatible with later versions.

For more information see following sections.

Containers

FLpanel  "label", iwidth, iheight, ix, iy [, iborder]
FLpanel_end

FLscroll   iwidth, iheight, ix, iy
FLscroll_end

FLtabs   iwidth, iheight, ix, iy
FLtabs_end

FLgroup  "label", iwidth, iheight, ix, iy [, iborder]
FLgroup_end

FLpack  iwidth, iheight, ix, iy
FLpack_end

INITIALIZATION

label - a double-quoted string  containing the title of the windows or a label
iwidth - width of the widget in pixels
iheight - heigth of the widget in pixels
ix - horizontal position of the upper left corner of the widget (in pixels)
iy - vertical position of the upper left corner of the widget (in pixels)
iborder - border type of the container. It is expressed by means of an integer number choosen from the following:

0 - no border
1 - down box border
2 - up box border
3 - engraved border
4 - embossed border
5 - black line border
6 - thin down border
7 - thin up border

if the integer number doesn't match any of the previous values, no border is provided as default.

PERFORMANCE

There are no k-rate arguments in containers.

Containers are useful to format the graphic apparence of the widgets. The most important container is FLpanel, that actually creates a window, that can be filled with other containers and/or valuators or other kinds of widgets.

FLpanel creates a window. It must be followed by the opcode FLpanel_end when all widgets internal to it are declared. For example:

	FLpanel 	"PanelPluto",450,550,100,100 ;***** start of container
gk1,ih1	FLslider	"FLslider 1", 500, 1000, 2 ,1, -1, 300,15, 20,50
gk2,ih2 FLslider	"FLslider 2", 300, 5000, 2 ,3, -1, 300,15, 20,100
gk3,ih3	FLslider	"FLslider 3", 350, 1000, 2 ,5, -1, 300,15, 20,150
gk4,ih4	FLslider	"FLslider 4", 250, 5000, 1 ,11,-1, 300,30, 20,200
	FLpanel_end	;***** end of container
	

will output the following result:

[Image]

FLscroll adds scroll bars to an area. Normally you must set arguments iwidth, iheight, ix, iy equal to that of the parent window or other parent container. For example the following code:

	FLpanel 	"PanelPluto",400,300,100,100
	FLscroll	400,300,0,0
gk1,ih1	FLslider	"FLslider 1", 500, 1000, 2 ,1, -1, 300,15, 20,50
gk2,ih2	FLslider	"FLslider 2", 300, 5000, 2 ,3, -1, 300,15, 20,100
gk3,ih3	FLslider	"FLslider 3", 350, 1000, 2 ,5, -1, 300,15, 20,150
gk4,ih4	FLslider	"FLslider 4", 250, 5000, 1 ,11,-1, 300,30, 20,200
	FLscroll_end
	FLpanel_end

will show scroll bars, when the main window size is reduced:

[Image]

FLtabs is the "file card tabs" interface that allows useful to display several areas containing widgets in the same windows, alternatively.

[Image]

It must be used together with FLgroup, another container that groups child widgets.

The following example code:

	FLpanel	"Panel1",450,550,100,100
	FLscroll	450,550,0,0
	FLtabs	400,550, 5,5
	FLgroup	"sliders",380,500, 10,40,1
gk1,ihs	FLslider	"FLslider 1", 500, 1000, 2 ,1, -1, 300,15, 20,50
gk2,ihs	FLslider	"FLslider 2", 300, 5000, 2 ,3, -1, 300,15, 20,100
gk3,ihs	FLslider	"FLslider 3", 350, 1000, 2 ,5, -1, 300,15, 20,150
gk4,ihs	FLslider	"FLslider 4", 250, 5000, 1 ,11, -1, 300,30, 20,200
gk5,ihs	FLslider	"FLslider 5", 220, 8000, 2 ,1, -1, 300,15, 20,250
gk6,ihs	FLslider	"FLslider 6", 1, 5000, 1 ,13, -1, 300,15, 20,300
gk7,ihs	FLslider	"FLslider 7", 870, 5000, 1 ,15, -1, 300,30, 20,350
gk8,ihs	FLslider	"FLslider 8", 20, 20000, 2 ,6, -1, 30,400, 350,50
	FLgroup_end

	FLgroup	"rollers",380,500, 10,30,2
gk1,ihr	FLroller	"FLroller 1", 50, 1000,.1,2 ,1 ,-1, 200,22, 20,50
gk2,ihr	FLroller	"FLroller 2", 80, 5000,1,2 ,1 ,-1, 200,22, 20,100
gk3,ihr	FLroller	"FLroller 3", 50, 1000,.1,2 ,1 ,-1, 200,22, 20,150
gk4,ihr	FLroller	"FLroller 4", 80, 5000,1,2 ,1 ,-1, 200,22, 20,200
gk5,ihr	FLroller	"FLroller 5", 50, 1000,.1,2 ,1 ,-1, 200,22, 20,250
gk6,ihr	FLroller	"FLroller 6", 80, 5000,1,2 ,1 ,-1, 200,22, 20,300
gk7,ihr	FLroller	"FLroller 7",50, 5000,1,1 ,2 ,-1, 30,300, 280,50
	FLgroup_end

	FLgroup	"joysticks",380,500, 10,40,3
gk1,gk2,ihj1,ihj2 FLjoy	"FLjoy", 50, 18000, 50, 18000,2,2,-1,-1,300,300,30,60
	FLgroup_end

	FLtabs_end
	FLscroll_end
	FLpanel_end

...will produce the following result:

[Image][Image][Image]

...each picture shows a different tab selection of the same windows.

FLpack provide the functionality of compressing and aligning widgets.

The following example:

	FLpanel	"Panel1",450,300,100,100
	FLpack	400,300, 10,40
gk1,ihs1	FLslider	"FLslider 1", 500, 1000, 2 ,1, -1, 300,15, 20,50
gk2,ihs2	FLslider	"FLslider 2", 300, 5000, 2 ,3, -1, 300,15, 20,100
gk3,ihs3	FLslider	"FLslider 3", 350, 1000, 2 ,5, -1, 300,15, 20,150
gk4,ihs4	FLslider	"FLslider 4", 250, 5000, 1 ,11, -1, 300,30, 20,200
gk5,ihs5	FLslider	"FLslider 5", 220, 8000, 2 ,1, -1, 300,15, 20,250
gk6,ihs6	FLslider	"FLslider 6", 1, 5000, 1 ,13, -1, 300,15, 20,300
gk7,ihs7	FLslider	"FLslider 7", 870, 5000, 1 ,15, -1, 300,30, 20,350
	FLpack_end
	FLpanel_end

...will produce this result, when resizing the window:

[Image]

Valuators

kout, ihandle FLslider  "label", imin, imax, iexp, itype, idisp, iwidth, iheight, ix, iy
kout, ihandle FLknob  "label", imin, imax, iexp, itype, idisp, iwidth, ix, iy
kout, ihandle FLroller  "label", imin, imax, istep, iexp, itype, idisp, iwidth, iheight, ix, iy
kout, ihandle FLtext  "label", imin, imax, istep, itype, iwidth, iheight, ix, iy
koutx, kouty, ihandlex, ihandley  FLjoy  "label", iminx, imaxx, iminy, imaxy, iexpx, iexpy, idispx, idispy, iwidth, iheight, ix, iy
kout, ihandle FLcount  "label", imin, imax, istep1, istep2, itype, iwidth, iheight, ix, iy, iopcode [, kp1, kp2, kp3, ...., kpN]

INITIALIZATION

ihandle -  handle value (an integer number) that univocally references to corresponding valuator, used by further opcodes that changes some valuator's properties. It is automatically set by the corresponding valuator.
label - a double-quoted string containing  some user-provided text, placed near corresponding valuator
imin, iminx, iminy - minumum value of output range
imax, imaxx, imaxy -maximum value of output range
iexp - an integer numeber denoting the behaviuor of valuator: 0 -> valuator output is linear; -1 -> valuator output is exponential; all other positive numbers indicate the number of an existing table that is used for indexing. Linear interpolation is provided in table indexing. A negative table number suppresses interpolation.
itype - an integer number denoting the apparence of the valuator. Its meaning is different for different types of valuator (see below for details)
idisp, idispx, idispy - a handle value that was output from a previous instance of the FLvalue opcode (see later), to display current value of current valuator in FLvalue widget itself. Otherwise (i.e. if the user don't want to use this feature that displays current values), it must be set to a negative number by the user.
iwidth - width of valuator
iheght - height of valuator
ix and iy - horizontal  and vertical positions of upper left corner of the valuator, relative to the upper left corner of corresponding window, expressed in pixels
istep - a floating-point number indicating the increment of valuator value corresponding to of each mouse click
istep1, istep2 - similar to istep, correspond the coarse and fine increment, used in FLcount valuator
iopcode - ascii code indicating the score opcode to be scheduled. At present time the only opcode to be scheduled is the score "i" statement. So only the ascii value of this opcode (105) is valid. A zero value set the defaut of "i" opcode (so at present you can set this argument either to 0 or to 105 ,achieving the same result).

PERFORMANCE

kout - output value
kp1, kp2, ..., kpN - arguments of the activated instruments (see below)

All valuators ouput their current values in the kout variable, and ihandle that is used in some cases by further opcodes (such as FLsetVal, see in a later section).

FLslider opcode puts a slider into the corresponding container. itype argument can be set to the following values:

1 - shows a horizontal fill slider [Image]
2 - a vertical fill slider
3 - a horizontal engraved slider [Image]
4 - a vertical engraved slider
5 - a horizontal nice slider [Image]
6 - a vertical nice slider

FLknob puts a knob in the corresponding container. itype argument can be set to the following values:

1 - a 3-D knob [Image]
2 - a pie-like knob[Image]
3 - a clock-like knob [Image]
4 - a flat knob [Image]

FLroller is a sort of knob, but put trasversally: [Image]. istep argument allow the user to arbitrally slow roller's motion, enabling arbitrary precision.
itype
argument can be set to the following values:

1 - horizontal roller
2 - vertical roller

FLtext allow the user to modify a parameter value by directly typing it into a text field: [Image]. Value can also be modified by clicking on it and dragging the mouse horizontally. istep argument allow the user to arbitrally set the response on mouse dragging. 
itype argument can be set to the following values:

1 - normal behaviour
2 - dragging operation is suppressed, instead it will appear two arrow buttons. A mouse click on one of these buttons can increase/decrease the output value
3 - text editing is suppressed, only mouse dragging modify output value.

FLjoy is a squared area that allows the user to modify two output values at the same time, it acts like a joystick.

FLcount allows to increase/decrease value with mouse clicks on corresponding arrow buttons: [Image]. There are two kind of arrow buttons, for larger and smaller steps. Notice that FLcount not only outputs a value and a handle, but can also activate (schedule) an instrument provided by the user each time a button is pressed. P-fields of the activated instrument are kp1 (instrument number), kp2 (action time), kp3 (duration) and so on with user p-fields. If iopcode argument is set to a negative number, no instrument is activated, so this feature is optional.

Other Widgets

kout, ihandle   FLbutton  "label", ion, ioff, itype, iwidth, iheight, ix, iy,
kout, ihandle   FLbutBank   itype, inumx, inumy, iwidth, iheight, ix, iy, iopcode [, kp1, kp2, kp3, kp4, kp5, ...., kpN]
ihandle  Flbox  "label", itype, ifont, isize, iwidth, iheight, ix, iy
ihandle  FLvalue "label", iwidth, iheight, ix, iy
FLprintk itime, kval, idisp
FLprintk2  kval, idisp

INTIALIZATION

ihandle - handle value (an integer number) that univocally references to corresponding widget, used by further opcodes that modify some widget's properties (see next section). It is automatically output by the corresponding widget, and must not set by the user
label - a double-quoted string containing some user-provided text, placed near corresponding widget
ion -  value output when the button is checked
ioff - value output when the button is unchecked
itype - an integer number denoting the apparence of the widget. Its meaning is different for different types of widget (see below for details)
inumx -  number of buttons in each row of the bank
inmuy - numebr of buttons in each column of the bank
iwidth - width of widget
iheght - height of widget
ix and iy - horizontal and vertical positions of upper left corner of the valuator, relative to the upper left corner of corresponding window, expressed in pixels
ifont - an integer number denoting the font of FLbox
isize - size of the font
itime - How much time in seconds is to elapse between updating display.

PERFORMANCE

kout - output value
kp1, kp2, ..., kpN - arguments of the activated instruments (see below)
kval - k-rate signal to be displayed

FLbutton opcode creates a button. Several kind of buttons are possible, according to the value of itype argument:

1 - normal button: [Image]
2 - light button: [Image]
3 - check button: [Image]
4 - round button: [Image]

Buttons of type 2, 3 and 4 also output (kout argument) the value contained in ion argument when checked, and that contained in ioff arguement, when unchecked.
By adding 10 to itype argument (i.e. by setting 11 for type 1, 12 for type 2, 13 for type 3 and 14 for type 4) it is possible to skip button values when setting snapshots (see later section).

FLbutBank opcode creates a bank of buttons. For example, the following line:

  gkButton,ihb1	FLbutBank	12, 8,8,  380,180, 50,350,  0,7,0,0,5000,6000

will create the this bank: [Image]
A click to a button checks that button, and eventually uncheck a previous checked button belonging to the same bank. So the behaviour is always that of radio-buttons. Notice that each button is labeled with a progressive number.  kout argument is filled with that number when corresponding button is checked.
FLbutBank not only outputs a value, but can also activate (or schedule) an instrument provided by the user each time a button is pressed. If iopcode argument is set to a negative number, no instrument is activated, so this feature is optional. In order to activate an instrument, iopcode must be set to 0 or to 105 (the ascii code of character "i", referring to the i score opcode). P-fields of the activated instrument are kp1 (instrument number), kp2 (action time), kp3 (duration) and so on with user p-fields.
itype argument sets the type of buttons identically to FLbutton opcode (see above).
FLbutBank
is very useful to retreive snapshots.

FLbox is useful to show some text in a window. The text is bounded by a box, whose aspect depends on itype argument. The following values are legal for itype:

1 - flat box
2 - up box
3 - down box
4 - thin up box
5 - thin down box
6 - engraved box
7 - embossed box
8 - border box
9 - shadow box
10 - rounded box
11 - rounded box with shadow
12 - rounded flat box
13 - rounded up box
14 - rounded down box
15 - diamond up box
16 - diamond down box
17 - oval box
18 - oval shadow box
19 - oval flat box

ifont argument set the font type. The following values are legal for ifont:

1 - helvetica (same as arial under Windows)
2 - helvetica bold
3 - helvetica italic
4 - helvetica bold italic
5 - courier
6 - courier bold
7 - courier italic
8 - courier bold italic
9 - times
10 - times bold
11 - times italic
12 - times bold italic
13 - symbol
14 - screen
15 - screen bold
16 - dingbats

FLvalue shows current values of a valuator in a text field. It outputs ihandle that can then be used as idisp argument of a valuator (see previous section). In such a way, the values of that valuator will diamically be shown in the text field.

FLprintk is similar to printk, but shows values of a k-rate signal into a text field instead of showing that in the console. idisp argument must be filled with the ihandle return value of a previous FLvalue opcode. While FLvalue should be placed in the header section of an orchestra, inside an FLpanel/FLpanel_end block, FLprintk must be placed inside an instrument to operate correctly.

FLprintk2 is similar to FLprintk, but shows kvar value only each time it changes. Useful for monitoring MIDI control changes when using sliders.

Modifying Widget Apparence

FLcolor  ired1, igreen1, iblue1, ired2, igreen2, iblue2
FLlabel  isize, ifont, ialign, ired, igreen, iblue

FLsetVal_i   ivalue, ihandle
FLsetVal   ktrig, kvalue, ihandle   (not implemented yet)
FLsetColor   ired, igreen, iblue,  ihandle
FLsetColor2  ired, igreen, iblue,  ihandle
FLsetTextSize  isize, ihandle
FLsetTextColor    ired, igreen, iblue,  ihandle
FLsetFont   ifont, ihandle
FLsetTextType   itype, ihandle
FLsetText  "itext", ihandle
FLsetSize  iwidth, iheight, ihandle
FLsetPosition  ix, iy, ihandle
FLhide  ihandle  
FLshow  ihandle
FLsetBox  itype, ihandle
FLsetAlign  ialign, ihandle

INITIALIZATION

ihandle - an integer number (used as unique identifier) taken from the output of a previusly located widget opcode (which corresponds to the target widget), in order to univocally identify its reference when modifying its apparence with this class of opcodes. User must not set ihandle value directly, otherwise a Csound crash will occur.
ired, igreen, iblue - a color of the target widget. It can be the first color, second color or font color, according to the opcode. The range for each RGB component is 0-255
ialign - sets the alignment of the label text of widgets
ifont - sets the the font type of the label of a widget
ired1, igreen1, iblue1 - first color of the target widget. The range for each RGB component is 0-255
ired2, igreen2, iblue2 - second color (selection color) of the target widget. The range for each RGB component is 0-255
isize - size of the font of the target widget. Normal values are in the order of 15. Greater numbers enlarge font size, while smaller numbers reduce it.
iwidth - width of the target widget
iheght - height of the target widget
ix and iy - horizontal and vertical positions of upper left corner of the target widget, relative to the upper left corner of corresponding window, expressed in pixels
itype - an integer number that modify the apparence of the target widget. Its meaning is different for different opcodes (see below for details)
itext - a double-quoted string denoting the text of the label of the widget.

PERFORMANCE

ktrig, kvalue - not implemented yet

These opcodes modify the apparence of other widgets. There are two types of such opcodes, those that don't contain ihandle argument, that affect all subsequently declared widgets, and those without ihandle, which affect only a target widget previously defined.

FLcolor sets the primary and secondary (selection) colors to values given by the user. This opcode affects (almost) all widgets defined next its location. User can put several instances of FLcolor in front of each widget he intend to modify. However, to modify a particular widget, it is better to use the opcode belonging to the second type (i.e. those containing ihandle argument, see below). FLcolor is designed to modify the colors of a group of related widget, that assume the same colors. The influence of FLcolor on next widgets can be turned off by setting -1 as the only argument of the opcode.

FLlabel modifies a set of parameters related to the text label apparence of a widget, i.e.  size, font, alignment and color of corresponding text. This opcode affects (almost) all widgets defined next its location. User can put several instances of FLlabel in front of each widget he intend to modify. However, to modify a particular widget, it is better to use the opcode belonging to the second type (i.e. those containing ihandle argument, see below).  The influence of FLlabel on next widgets can be turned off by setting -1 as the only argument of the opcode itself. FLlabel is designed to modify text attributes of a group of related widget.
Legal values for ifont argument are:

1 - helvetica (same as arial under Windows)
2 - helvetica bold
3 - helvetica italic
4 - helvetica bold italic
5 - courier
6 - courier bold
7 - courier italic
8 - courier bold italic
9 - times
10 - times bold
11 - times italic
12 - times bold italic
13 - symbol
14 - screen
15 - screen bold
16 - dingbats

Legal values for ialign argument are:

1 - align center
2 - align top
3 - align bottom
4 - align left
5 - align right
6 - align top-left
7 - align top-right
8 - align bottom-left
9 - align bottom-right

FLsetVal_i  forces the value of a valuator to a number provided by the user. This can be useful to set the initial values or to reset/update widget values for some special task. If the valuator has some graphic apparence related to position of its pointer (for example in a slider), it affect also pointer position. This and all following opcodes belong to the second type of modifiers, since they contain ihandle argument. So they affect only a single widget.

FLsetVal is almost identical to FLsetVal_i, except it operates at k-rate, and it affects target valuator only when ktrig is set to a non-zero value.

FLsetColor sets the primary color of the target widget.

FLsetColor2 sets the secondary (or selection) color of the target widget.

FLsetTextSize sets the size of the text label of the target widget.

FLsetTextColor sets the color of the text label of the target widget.

FLsetFont sets the font type of the target widget. See above for legal ifont values.

FLsetTextType sets some attributes related to the fonts of the text label of the target widget.
In this case, legal values of itype are:

0 - normal label
1 - no label (hides the text)
2 - symbol label
3 - shadow label
4 - engraved label
5- embossed label
6- bitmap label (not implemented yet)
7- pixmap label (not implemented yet)
8- image label (not implemented yet)
9- multi label (not implemented yet)
10- free-type label (not implemented yet)

FLsetText sets the label of the target widget to the double-quoted text string provided with itext argument.

FLsetSize resize the target widget (not the size of the text), according to iwidth and iheight arguments.

FLsetPosition sets the position of the target widget according to ix and iy arguments. Their values corrspond to the upper left corner of the widget and are relative to the upper left corner of the window that contain the widget.

FLhide hides target widget, making it invisible.

FLshow restore the visibility of a previously hidden widget.

FLsetBox set the apparence of a box surrounding the target widget. Legal values for itype argument are:

1 - flat box
2 - up box
3 - down box
4 - thin up box
5 - thin down box
6 - engraved box
7 - embossed box
8 - border box
9 - shadow box
10 - rounded box
11 - rounded box with shadow
12 - rounded flat box
13 - rounded up box
14 - rounded down box
15 - diamond up box
16 - diamond down box
17 - oval box
18 - oval shadow box
19 - oval flat box

FLsetAlign sets the text alignment of the label of the target widget. See above for legal ialign values.

General Widget-related Opcodes

FLrun

inumSnap, inumVal   FLsetsnap   index [, ifn]
inumSnap FLgetsnap index

FLsavesnap "filename"
FLloadsnap "filename"

INITIALIZATION

inumSnap - current number of snapshots
inumVal - number of valuators (whose value is stored in a snapshot) present in current orchestra
ifn - optional argument referring to an already allocated table, to store values of a snapshot.
index - a number referring univocally to a snapshot. Several snapshots can be stored in the same bank.
filename - a double-quoted string corresponding to a file to store or load a bank of snapshots

FLrun opcode must be located at the end of all widget declarations. It has no arguments, and its purpose is to start the thread related to widgets. Widgets would not operate if FLrun is missing.

FLsetsnap opcode stores current status of all valuators present in the orchestra into a snapshot. Any number of snapshots can be stored in current bank. Banks  are structures that only exist in memory, there are no other reference to them other that they can be accessed by FLsetsnap, FLsavesnap, FLloadsnap and FLgetsnap opcodes. Only a single bank can be present in memory. If ifn argument (optional) refers to an already allocated and valid table, the snapshot will be stored in the table, instead of in the bank. So that table can be accessed from other Csound opcodes. index argument univocally refers to a determinate snapshot. If the value of index refers to a previously stored snapshot, all its old values will be replaced with current ones. If index refers to a snapshot that doesn't exist, a new snapshot will be created. If index value is not adjacent with that of a previously created snapshot, some empty snapshots will be created (for example, if location with index 0 contains the only and unique snapshot present in a bank, and the user stores a new snapshot using index 5, all locations between 1 and 4 will automatically contain empty snapshots). Empty snapshots don't contain any data and are neutral. FLsetsnap outputs current number of snapshots (inumSnap argument) and the total number of values stored in each snapshot (inumVal), that is equal to the number of valuators present in the orchestra.

FLgetsnap retreives a previously stored snapshot. index argument univocally must refer to an already existent snapshot. If index argument refers to an empty snapshot or to a snapshot that doesn't exist, no action is done. FLsetsnap outputs current number of snapshots (inumSnap argument).

FLsavesnap saves all snapshots currently created into a file whose name is filename. Since the file is a text file, snapshot values can also be edited manually, by means of a text editor. The format of data stored in the file is the following (at present time, this could be changed in next Csound version):

----------- 0 -----------
FLvalue 0 0 1 0 ""
FLvalue 0 0 1 0 ""
FLvalue 0 0 1 0 ""
FLslider 331.946 80 5000 -1 "frequency of the first oscillator"
FLslider 385.923 80 5000 -1 "frequency of the second ocillator"
FLslider 80 80 5000 -1 "frequency of the third ocillator"
FLcount 0 0 10 0 "this index must point to the location number where snaphsot is stored"
FLbutton 0 0 1 0 "Store snapshot to current index"
FLbutton 0 0 1 0 "Save snapshot bank to disk"
FLbutton 0 0 1 0 "Load snapshot bank from disk"
FLbox 0 0 1 0 ""
----------- 1 -----------
FLvalue 0 0 1 0 ""
FLvalue 0 0 1 0 ""
FLvalue 0 0 1 0 ""
FLslider 819.72 80 5000 -1 "frequency of the first oscillator"
FLslider 385.923 80 5000 -1 "frequency of the second ocillator"
FLslider 80 80 5000 -1 "frequency of the third ocillator"
FLcount 1 0 10 0 "this index must point to the location number where snaphsot is stored"
FLbutton 0 0 1 0 "Store snapshot to current index"
FLbutton 0 0 1 0 "Save snapshot bank to disk"
FLbutton 0 0 1 0 "Load snapshot bank from disk"
FLbox 0 0 1 0 ""
----------- 2 -----------
..... etc...
----------- 3 -----------
..... etc...
---------------------------

As you can see, each shapshot contain several lines. Each snapshot is separated from previous and next snapshot by a line of this kind: "----------- snapshot Num -----------". Then there are several line containing data. Each of these lines corresponds to a widget. The first field of each line is an unquoted string containing opcode name corresponding to that widget. Second field is a number that expresses current value of a snapshot. In current version this is the only field that can be modified manually. The third and fourth fields shows minimum and maximum values allowed for that valuator. Fifth field is a special number that indicates if the valuator is linear (value 0), exponential (value -1), or is indexed by a table interpolating values (negative table numbers) or non-interpolating (positive table numbers). Last field is a quoted string with the label of the widget. Last line of the file is always "---------------------------".
Note that FLvalue and FLbox are not valuators, and their values are fixed, cannot be modified.

FLloadsnap loads all snapshots contained in filename into current orchestra.



SCORE OPCODES

LOOPS

{ - start of a loop

} - end of a loop

Syntax:

{  num NN

   ...... body........

}

Score loops are a very powerful tool. Derived by repeats (r opcode), they allow to define any parameter, and the score events inside the loop are not separated by a section termination in each iteration. So it is possible to implement overlapping loops. Loops can be nested. The syntax is similar to that of the repeats: the macro $NN is incremented in each iteration (notice that, differently from repeats, it starts with a zero value); num argument must be set to the number of iterations.

NB: exponential ramp symbol has been changed to '(' or ')' in order to allow curly-brace characters to be used for loops.

EXAMPLE:

{ 10 nn
	i1	[$nn/2]  .5  [$Line(10' $nn ' 10000' 4000)]  [$Line(10'$nn'440'110)]
	{ 5 bb
		i1 [$nn/2+$bb/10] .1 [(1+$nn/4)*$Line(10 ' $bb' 2000' 500)] [$Line(10'  $bb' 400' 600)]
	}
}


SCORE TABLES

F - score function tables

Syntax:

F p1 p2 p3 p4 ...

This causes a GEN subroutine to place values in a stored function table for use by instruments.

N.B. In this case the function tables are created before score processing, differently from f statement. The syntax and the gen routines used by F opcode are identical to those of f statement. Tables created by F opcode are intended to be used together with T score arithmetic operator (see below).


NESTED MACROS (new syntax)

Now macros can be nested (both in orchestra and score), that is a  previously defined macro can be called from inside another macro definition. When using nested macros, it is recommended to use different names for arguments in the caller and in the target macros to avoid  unpredictable conflicts.
To enable this feature I had to do a small change in macro argument syntax: instead of using a '#' character, an apostrophe character is required in order to separate macro arguments:

OLD SYNTAX:

#define  PLUTO(mikey#minnie#donald)#....body....#         ; old macro definition

$PLUTO(1#2#3)        ;old macro call

NEW SYNTAX (nested macros):

#define  PLUTO( mikey '  minnie '  donald ) # ....body.... #       ; new macro definition

;nested macro definition. Notice that the argument names are changed
#define PIPPO( mik ' min ' don) #      
     $PLUTO( 2*$mik '  2+$min '  3 )
     $PLUTO( 5 '   8 '   1 )            
     $PLUTO( $mik,$min,3 )      
     $PLUTO( 1 '   2 '  $don )        
     $PLUTO( 4 '   5 '   6 )            
# ;end of macro
$PIPPO( 1' 5' 8 )   ; macro call

It is now possible to comment macros (before it generated errors):

;$PIPPO(1'2'3)

 or

/*
$PIPPO(1'2'3)
*/

Comments (both old assebler style ';' and new C-language style '/* ...  */') are handled in a special way in macros. Inside macro body you are allowed to put only old style comments ( ';'). If you intend to suppress an entire macro without erasing it physically, you can comment it using C-style comments externally  ('/* ...  */').

Maximum number of macro arguments has been raised to 200 (before 5)

N.B. underscore character '_'  has a special purpose in macros (it allows to define prefixes or suffixes  of words in macro body). Don't use underscore character in macro names or in macro arguments (or errors will occurr). You are allowed to use underscore in the body of macros in any case, instead.


SCORE MACRO ARITHMETIC INFIX OPERATORS

SCORE TABLES

T - retrieves a value from a score function table.

syntax:

(TabNum T  TabIndex)

TabNum - table number
TabIndex - absolute index of table element.

N.B. the unusual infix syntax can be transformed into a more familiar syntax by means of macros:

#define Table(tabnum'index) # (($tabnum) T ($index)) #

so you can call the $Table( ) macro with the classic function call syntax:

$Table(num' element)


RANDOM NUMBER OPERATOR

R - retrieves a  pseudo random value

syntax:

(amp  R  seed)

The operand amp is an amplitude factor that sets the range of random values from zero to amp itself.
The operand seed allows the user to change the initial seed of the pseudo random sequence. When seed is set to a non-zero value, R operator sets the seed, while with seed = 0 it returns a normal random value. When seed is set to -1 the seed of pseudo random sequence is obtained by the current timer value of the computer, allowing a different pseudo random sequence each time Csound is run.

N.B. the unusual infix syntax can be transformed into a more familiar syntax by means of macros:

#define RndSeed(seed) # (1 R ($seed)) #
#define Rand(min'max) # ( ($min) + ((($max)-($min)) R 0)  ) #

In these examples $RndSeed( ) macro sets the seed, while $Rand( ) retrives a random value inside the  min-max interval.


POWER OPERATOR

^  - retrieves the power

syntax:

(a  ^  b)

raises number a to the b power

Here are two example of macros very useful when using loops or repeats:

#define Expon(stepnum ' var ' a' b) # ( ($a) *(((($b)/($a))^(1/(($steps)-1)))^($var))  ) #
#define Expon1(stepnum ' var ' a' b) # ( ($a) *(((($b)/($a))^(1/(($steps)-1)))^($var-1)) ) #

Notice that macro $Expon is provided for loops (where macro index $var starts from zero), while $Expon1 is thought for repeats, where $var starts from 1.

For reasons of completeness  here are the  corresponding linear macros:

#define  Line(steps 'var'a'b) # ( ($a) +  (($b)-($a))*(($var))/(($steps)-1)  ) #
#define  Line1(steps'var'a'b) # ( ($a) +  (($b)-($a))*(($var-1))/(($steps)-1)  ) #

MODULUS OPERATOR

% - modulus operator

syntax:

(a  %  b)

retrives a MOD b