Copyright: Possibly maintained by rasmuse@hem.passagen.se


Manuals for the PC versions of Csound

Csound addresses	 copyright

csound manual 	   quick reference

Getting started

installation for DOS/Windows

Recent additions to Csound

changes to Bath versions 3.xx

CSOUND.EXE

csound command line flags

Csound utility programs

soundfile analysis, mixing, and more


Contents of the full set of CsHlp3xx.hlp RTF files:

CONTENTS.RTF: Contents; Contents of the RTF files (hidden)

CsMain.rtf:; CSOUND.EXE usage & flags; Utility programs usage & flags; Adding your own modules to Csound; OPDS data struct (popup for the previous); Csound addresses; Copyright notices; John Fitchs file CHANGELOG.CSOUND; Earlier changelog (up to and including v3.36) with the note on PC realtime.

Qref.rtf: Quick reference.

Tutors.rtf: Csound manual top (contents & preface); Csound introduction; Csound nomenclature; Orchestra statement types; Directories & files; Constants & variables; Orchestra header statements; Instrument design tutorial; Example instruments 1-13 (individual entries); fof tutorial ; Standard numeric score; Preprocessing of standard num scores; Score statements f, i, a, t, s, e (individual entries); SCOT tutorial.

SigMods.rtf: SIGNAL MODIFIERS linen linenr envlpx follow ipow kpow apow port tone atone reson areson lpread lpreson lpfreson convolve rms gain balance downsamp upsamp interp integ diff samphold delayr delayw delay delay deltap deltapi comb alpass reverb butterhp butterlp butterbp butterbr vdelay multitap reverb

FFTbased.rtf: adsyn pvoc, pvoc, pvadd, pvread pvbufread pvcross tableseg tablexseg vpvoc, cross2, lpread lpreson lpfreson, lpslot lpinterpol, convolve

SPECTRAL DATA TYPES (octdown noctdft), spectrum, specaddm specdiff specscal spechist specfilt, specptrk specsum specdisp.

SigGens.rtf: SIGNAL GENERATORS line expon linseg linseg expseg phasor [table] tablei oscil oscil1i oscil oscili foscil foscili loscil doscil buzz gbuzz fof fof2 fog fof3 grain granule pluck rand randh randi linrand trirand exprand bexprnd cauchy pcauchy poisson gauss weibull beta unirand

SigGens2.rtf: SIGNAL GENERATORS (newer) adsr xadsr madsr mxadsr, sndwarp-st wgpluck wgpluck2 repluck, wgbow wgbrass wgflute, agogobel marimba vibes, shaker, wguide1-2, fmtbell fmrhode fmwurlie fmmetal fmb3fmpercfl, fmvoice, moog, mandol, voice, lfo, vco, planet.

CSSYNTAX.RTF: Rest of opcodes (see top of file for details)

GENS.RTF: GENS overview; GEN f-statement parameters (individual entries)

CsNew.rtf Bath update notices 3.44 and up, Bath update notice 3.20

CSRW.RTF: Overview; Table read ugens; Table write overview; Writing into an ftable; Determine an ftable location; Mix two ftables; Copy an ftable; Read/write sequential ftable locations; The ZAK system; ZAK space allocation; Read/write ZAK space; ZAK signal modulation; Clear ZAK space; Read time during perf; k-rate printing; k-rate signal filters; 31-bit noise programmers note; New 31-bit uniform random ugen.


©Contents: Quick Reference


Csound Quick reference
A CSOUND QUICK REFERENCE

CONTENTS

Value Converters

Pitch Converters

Signal Display and output

Sensing & Control

Time reading ugens

Program Control

MIDI Support

Instrument Control

Function Table Control

Table Manipulation Overview

GEN Routines Overview

Signal Generators

Signal Modifiers

Operations Using Soundfile Analysis Data

Operations Using Spectral Data Types

Sound Input & Output

The Zak system

Note: In the quick-ref, nr is used to indicate that a parameter can operate at i- and k-rate, or at k- and a-rate. The argument type xr indicates that a parameter can operate at i- and k- and a-rate. To abbreviate the opcode list, opcode names are occasionally violated by supplying an n or an x for the initial rate-type letter. (-re)

VALUE CONVERTERS

(Back to contents)

int(x)  	(init- or control-rate args only)

frac(x)	"     "

dbamp(x)	"     "

i(x)	     (control-rate arg; only)

abs(x) 	       (no rate restriction)

exp(x)	"     "

log(x)	"     "

log10(x)	"     "

sqrt(x)	"     "

sin(x)	"     "

cos(x)	"     "

ampdb(x)	"     "

sininv(x)	"     "

sinh(x)   	"     "

cosinv(x)	"     "

cosh(x)	"     "

taninv(x)	"     "

tanh(x)  	"     "

taninv2(x, y)   	"     "

xr	pow	iarg, kpow

PITCH CONVERTERS

(Back to contents)

octpch(pch)	(init- or control-rate args only)

pchoct(oct)   	"     "

cpspch(pch)  	"     "

octcps(cps)   	"     "

cpsoct(oct)	       (no rate restriction)

Tuning opcodes:

icps	cps2pch	ipch, iequal

icps	cpsxpch	ipch, iequal, irepeat, ibase

SIGNAL DISPLAY AND FILE OUTPUT

(Back to contents)

dispfft 	xsig, iprd, iwsiz [,iwtyp] [,idbouti] [,wtflg]

display	xsig, iprd [,iwtflg]

print  	iarg [,iarg,...]

printk 	itime, kval [, ispace]

printk2	kval [,ispace]

printks	"txtstring", itime, kval1, kval2, kval3, kval4

k1	readk 	ifilname, iformat, iprd [, interp]

k1,k2	readk2 	ifilname, iformat, iprd [, interp]

k1,k2,k3	readk3 	ifilname, iformat, iprd [, interp]

k1,…, k4	readk4 	ifilname, iformat, iprd [, interp]

dumpk	ksig, ifilname, iformat, iprd

dumpk2	ksig1, ksig2, ifilname, iformat, iprd

dumpk3	ksig1, ksig2, ksig3, ifilname, iformat, iprd

dumpk4	ksig1, ksig2, ksig3, ksig4, ifilname, iformat, iprd

SENSING & CONTROL

(Back to contents)

ktemp	tempest	kin, iprd, imindur, imemdur, ihp,ithresh, ihtim, ixfdbak, istartempo, ifn [,idisprd, itweek]

kx, ky	xyin	iprd, ixmin, ixmax, iymin, iymax [,ixinit, iyinit]

tempo	ktempo, istartempo

TIME READING

(Back to contents)

nr	timek

nr	times

kr	instimek

kr	instimes

PROGRAM CONTROL

(Back to contents)

Jumps:	igoto	label

tigoto	label

kgoto	label

goto	label

if ia  R ib	igoto	label

if ka R kb	kgoto	label

if ia  R ib	goto	label

timout 	istrt, idur, label

Reinitialisation:

reinit	label

rigoto	label

rireturn

MIDI SUPPORT

(Back to contents)

Generic MIDI input and output:

kstatus, kchan, kdata1, kdata2 \

midiin

midiout 	kstatus, kchan, kdata1, kdata2

MIDI converters

ival	notnum

ival	veloc

icps	cpsmidi

icps	cpsmidib

kcps	cpsmidib	[irange]

kval	cpstmid	ifn

ioct	octmidi

ioct	octmidib

koct	octmidib	[irange]

ipch	pchmidi

ipch	pchmidib

kpch	pchmidib	[irange]

iamp	ampmidi	iscal[, ifn]

kaft	aftouch	iscal

kchpr	chpress	iscal

kbend	pchbend	iscal

nval	midictrl	inum [, initial]

MIDI controller input:

initc7/14/21	ichan, ictlno, ivalue

ndest	midic7/14/21  ictlno, nmin, nmax [, ifn]

ndest	ctrl7/14/21	ichan, ictlno, nmin, nmax [,ifn]

nval	chanctrl	ichan, ictlno [,ilow,ihigh]

kbend	pchbend	[ilow, ihigh]

MIDI slider bank controller input:

k1,...,kN	sliderN 	ichan, ictlnum1, imin1, imax1, init1, ifn1, .... , ictlnumN, iminN, imaxN, initN, ifnN

k1,...,kN	sliderNf 	ichan, ictlnum1, imin1, imax1, init1, ifn1, icutoff1, .... , ictlnumN, iminN, imaxN, initN, ifnN, icutoffN

i1,...,iN	sliderN 	ichan, ictlnum1, imin1, imax1, ifn1, .... , ictlnumN, iminN, imaxN, ifnN

k1,...,kN	sNb14 	ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, initvalue1, ifn1, ...., ictlno_msbN, ictlno_lsbN, iminN, imaxN, initvalueN, ifnN

i1,...,iN	sNb14 	ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, ifn1, ...., ictlno_msbN, ictlno_lsbN, iminN, imaxN, ifnN

MIDI note output:

noteon   	ichn, inum, ivel

noteoff	ichn, inum, ivel

ondur	ichn, inum, ivel, idur

ondur2	ichn, inum, ivel, idur

moscil	kchn, knum, kvel, kdur, kpause

midion   	kchn, knum, kvel

midion2	kchn, knum, kvel, ktrig

Output MIDI channel messages:

outic(14)	ichn, inum, ivalue, imin, imax

outkc(14)	kchn, knum, 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

Output MIDI system realtime messages:

mclock	ifreq

mrtmsg	imsgtype

Misc MIDI output messages:

nrpn	kchan, kparmnum, kparmvalu

midiout	kstatus, kchan, kdata1, kdata2

Extend MIDI events:

xtratim	 iextradur

kflag	release

INSTRUMENT CONTROL

(Back to contents)

turnon	insno[,itime]

ihold

turnoff

schedule	inst, iwhen, idur, ....

schedwhen	ktrigger, kinst, kwhen, kdur, ....

FUNCTION TABLE CONTROL

(Back to contents)

Table manipulation overview

Get information about function tables:

iafno	ftgen	ifno,itime,isize, igen, iarga[,...iargz]

ftlen(x)	        (init-rate args only)

ftlptim(x)	        (init-rate args only)

ftsr(x) 	        (init-rate args only)

nsamp(x)	        (init-rate args only)

kr	tablekt	kndx, kfn [, ixmode] [,ixoff] [,iwrap]

ar	tableikt	andx, kfn [, ixmode] [,ixoff] [,iwrap]

nr	tableng	nfn

Read/write function tables:

tableiw	isig, indx, ifn [,ixmode] [,ixoff] [,iwgmode]

tablew	ksig, kndx, ifn [,ixmode] [,ixoff] [,iwgmode]

tablew	asig, andx, ifn [,ixmode] [,ixoff] [,iwgmode]

tablewk	ksig, kndx, kfn [,ixmode] [,ixoff] [,iwgmode]

tablewkt	asig, andx, kfn [,ixmode] [,ixoff] [,iwgmode]

ar	tablera	kfn, kstart, koff

kstart	tablewa	kfn, asig, koff

tableigpw	ifn

tablegpw	kfn

tablecopy	kdft, ksft

tableicopy	idft, isft

tablemix	kdft, kdoff, klen, ks1ft, ks1off, ks1g, ks2ft, ks2off, ks2g

tableimix	idft, idoff, ilen, is1ft, is1off, is1g, is2ft, is2off, is2g

SIGNAL GENERATORS

(Back to contents)

Linear signal generators:

nr	line   	ia, idur1, ib

nr	expon	ia, idur1, ib

nr	linseg	ia, idur1, ib [,idur2, ic[…]]

nr	expseg	ia, idur1, ib [,idur2, ic[…]]

nr	linsegr	ia, idur1, ib [,idur2, ic[…]], irel, iz

nr	expsegr	Ia, Idur1, Ib [,Idur2, Ic[...]], Irel, iz

nr	adsr	iatt, idec, islev, irel[, idelay]

nr	xadsr	iatt, idec, islev, irel[, idelay]

nr	madsr	iatt, idec, islev, irel[, idelay]

nr	mxadsr	iatt, idec, islev, irel[, idelay]

Phase generator:

nr	phasor	kcps [,iphs]

Table access:

xr	table  	indx, ifn [,ixmode] [,ixoff] [,iwrap]

xr	tablei 	indx, ifn [,ixmode] [,ixoff] [,iwrap]

xr	table3 	indx, ifn [,ixmode] [,ixoff] [,iwrap]

kr	oscil1  	idel, kamp, idur, ifn

kr	oscil1i  	idel, kamp, idur, ifn

ar	osciln	kamp, ifrq, ifn, itimes

nr	oscil  	xamp, xcps, ifn [,iphs]

nr	oscili  	xamp, xcps, ifn [,iphs]

nr	oscil3  	xamp, xcps, ifn [,iphs]

ar	foscil  	xamp, xcps, xcar, xmod, kndx, ifn [,iphs]

ar	foscili  	xamp, xcps, xcar, xmod, kndx, ifn [,iphs]

kr	lfo    	kamp, kcps[, itype]

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

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

nr	poscil 	kamp, kcps, ift [,iphs]

nr	lposcil 	kamp, kfreqratio, kloop, kend, ift [,iphs]

Buzzers:

ar	buzz	xamp, xcps, knh, ifn [,iphs]

ar	gbuzz	xamp, xcps, knh, kih, kr, ifn [,iphs]

Granular synthesis:

ar	fof    	xamp, xfund, xform, koct, kband, kris, kdur, kdec, iolaps, ifna, ifnb, itotdur [,iphs] [,ifmode]

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

ar	fog   	xamp, xdens, xtrans, xspd, koct, kband, kris, kdur, kdec, iolaps, ifna, ifnb, itotdur[, iphs][, itmode]

ar	grain	xamp, xpitch, xdens, kampoff, kpitchoff, kgdur, igfn, iwfn, imgdur

ar	granule	xamp, ivoice, iratio, imode, ithd, ifn, ipshift, igskip, igskip_os, ilength, kgap, igap_os, kgsize, igsize_os, iatt, idec [,iseed] [,ipitch1] [,ipitch2] [,ipitch3] [,ipitch4] [,ifnenv]

Time-streching:

ar [,acmp]	sndwarp	xamp, xtimewarp, xresample, ifn1, ibeg, iwsize, irandw, ioverlap, ifn2, [itimemode]

ar1, ar2 [, acmp1, acmp2] \

sndwarpst	xamp, xtimewarp, xresample, ifn1, ibeg, iwsize, irandw, ioverlap, ifn2, itimemode

Waveguide physical modeling:

ar	wguide1	asig, kfreq, kcutoff, kfeedback;

ar	wguide2	asig, kfreq1, kfreq2, kcutoff1, kcutoff2, kfeedback1, kfeedback2

ar	pluck	kamp, kcps, icps, ifn, imeth [,iparm1, iparm2]

ar	wgpluck

ar	wgpluck2	iplk, xamp, icps, kpick, krefl

ar	repluck	iplk, xamp, icps, kpick, krefl, axcite

ar	wgbow	kamp, kfreq, kpres, kratio, kvibf, kvamp, ifn[, iminfreq]

ar	wgbrass	kamp, kfreq, kliptens, idetk, kvibf, kvamp, ifn[, iminfreq]

ar	wgclar	kamp, kfreq, kstiff, iatt, idetk, kngain, kvibf, kvamp, ifn[, iminfreq]

ar	wgflute	kamp, kfreq, kjet, iatt, idetk, kngain, kvibf, kvamp, ifn[, iminfreq]

More physical models:

ar	gogobel	kamp, kfreq, ihrd, ipos, imp, kvibf, kvamp, ivibfn

ar	marimba	kamp, kfreq, ihrd, ipos, imp, kvibf, kvamp, ivibfn, idec

ar	vibes	kamp, kfreq, ihrd, ipos, imp, kvibf, kvamp, ivibfn, idec

ar	shaker	kamp, kfreq, kbeans, kdamp, knum, ktimes[, idecay]

4-operator FM instruments:

ar	fmtbell	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmrhode	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmwurlie	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmmetal	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmb3	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmpercfl	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmvoice	kamp, kfreq, kvowel, ktilt, kvibamt, kvibrate, ifn1, ifn2, ifn3, ifn4, ivibfn

Emulation/simulation instruments:

ar	moog	kamp, kfreq, kfiltq, kfiltrate, kvibf, kvamp, iafn, iwfn, ivfn

ar	vco 	kamp, kfqc, iwave, kpw, isine, imaxd

ar	mandol	kamp, kfreq, kpluck, kdetune, kgain, ksize, ifn[, iminfreq]

ar	voice	kamp, kfreq, kphoneme, kform, kvibf, kvamp, ifn, ivfn

ax,ay,az	planet 	kmass1, kmass2, ksep, ix, iy, iz, ivx, ivy, ivz, idelta, ifriction

Random generators (uniform distribution):

nr	rand	xamp [,iseed, iuse31]

nr	randh	kamp, kcps [,iseed, iuse31]

nr	randi	kamp, kcps [,iseed, iuse31]

rnd(x)

birnd(x)

Random generators (various distributions):

xr	linrand	krange

xr	trirand	krange

xr	exprand	krange

xr	bexprnd	krange

xr	cauchy	kalpha

xr	pcauchy	kalpha

xr	poisson	klambda

xr	gauss	krange

xr	weibull	ksigma, ktau

xr	betarand	krange, kalpha, kbeta

xr	unirand	krange

SIGNAL MODIFIERS

(Back to contents)

Gain units:

kr	rms   	asig [,ihp, istor]

ar	gain	asig, krms [,ihp, istor]

ar	balance	asig, acomp [,ihp, istor]

ar	dam	ain, kthresh, icomp1, icomp2, irtme, iftme

Signal limiters:

xr	limit	xsig, xlow, xhigh

xr	wrap	xsig, xlow, xhigh

xr	mirror	xsig, xlow, xhigh

Notification:

kout	trigger	ksig, kthreshold, kmode

Envelope lines:

nr	linen	kamp, irise, idur, idec

nr	linenr	kamp, irise, idec, iatdec

nr	envlpx	kamp, irise, idur, idec, ifn, iatss, iatdec [,ixmod]

ar	follow	asig, idt

nr	adsr	iatt, idec, islev, irel[, idelay]

nr	madsr	iatt, idec, islev, irel[, idelay]

Interpolator:

xr	ntrpol	xsig1, xsig2, kpoint [, imin, imax]

Standard filters:

kr	port	ksig, ihtim [,isig]

ar	tone	asig, khp [,istor]

ar	atone	asig, khp [,istor]

ar	reson	asig, kcf, kbw [,iscl, istor]

ar	areson	asig, kcf, kbw [,iscl, istor]

ar	tonex	asig, khp[, inumlayer, istor]

ar	atonex	asig, khp[, inumalayer, istor]

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

ar	butterhp	asig, kfreq

ar	butterlp	asig, kfreq

ar	butterbp	asig, kfreq, kband

ar	butterbr	asig, kfreq, kband

ar	filter2	asig, iM,iN,ib0,ib1,..., ibM,ia1,ia2,...,iaN

kr	kfilter2	ksig, iM,iN,ib0,ib1,...,ibM,ia1,ia2,...,iaN

ar	zfilter2	asig, kdamp,kfreq,iM,iN,ib0,ib1,...,ibM,ia1,ia2,...,iaN

Specialised filters:

ar	dcblock	asig [, igain]

ar	nlfilt	ain, ka, kb, kd, kL, kC

ar	pareq 	asig, kc, iv, iq, imode

ar	streson 	asig, kfr, ifdbgain

ar	lowres	asig, kcutoff, kresonance [,istor]

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

ar	vlowres	asig, kcutoff, kresonance, iord, ksep;

ar	biquad	asig, kb0, kb1, kb2, ka0, ka1, ka2 [, iskip, iskipinit]

ar	moogvcf	asig, xfco, xres [, iscale]

ar	rezzy	asig, xfco, xres [, imode]

Sample level operators:

kr	downsamp	asig [,iwlen]

ar	upsamp	ksig

ar	interp	ksig [,istor]

kr	integ	ksig [,istor]

ar	integ	asig [,istor]

kr	diff 	ksig [,istor]

ar	diff 	asig [,istor]

kr	samphold	xsig, kgate [,ival, ivstor]

ar 	samphold	asig, xgate [,ival, ivstor]

Delays:

ar	delayr	idlt [,istor]

ar	delayw	asig

ar	delay	asig, idlt [,istor]

ar	delay1	asig [,istor]

ar	deltap	kdlt

ar 	deltapi	xdlt

ar 	deltap3	xdlt

ar 	deltapn	xnumsamps

ar	multitap	asig, itime1, igain1, itime2, igain2 . . .

ar	vdelay	asig, adel, imaxdel

ar	vdelay3	asig, adel, imaxdel

Reverbs:

ar	comb	asig, krvt, ilpt [,istor]

ar	alpass	asig, krvt, ilpt [,istor]

ar	reverb	asig, krvt [,istor]

ar	nreverb	asig, ktime, khdif

ar	reverb2	asig, ktime, khdif

Special effects:

ar	harmon	asig,kestfrq,kmaxvar, kgenfrq1, kgenfrq2, imode, iminfrq, iprd

ar	flanger	asig, adel, kfeedback, imaxd

aout	distort1 	asig [, kpregain, kpostgain, kshape1, kshape2 ]

FFT-based morphing synthesis:

asig	cross2	ain1, ain2, ilen, iovl, iwin, kbias

OPERATIONS USING SOUNDFILE ANALYSIS DATA

(Back to contents)

Based on Heterodyne analysis:

HETRO.EXE - Fourier analysis for adsyn generator

ar	adsyn	kamod, kfmod, ksmod, ifilcod

Based on Phase vocoder analysis:

PVANAL.EXE - Fourier analysis for phase vocoder generators

ar	pvoc	ktimpnt, kfmod, ifilcod [,ispecwp]

ar	pvadd	ktimpnt, kfmod, ifile, ifn, ibins [, ibinoffset, ibinincr]

kfrq,kamp	pvread	ktimpnt, ifile, ibin

pvbufread	ktimpnt, ifile

ar	pvinterp	ktimpnt, kfmod, ifile, kfreqscale1, kfreqscale2, kampscale1, kampscale2, kfreqinterp, kampinterp

ar	pvcross	ktimpnt, kfmod, ifile, kamp1, kamp2, [ispecwp]

tableseg	ifn1, idur1, ifn2[, idur2, ifn3[...]]

tablexseg	ifn1, idur1, ifn2[, idur2, ifn3[...]]

ar	vpvoc	ktimpnt, kfmod, ifile, [ispecwp]

Based on Linear predictive coding (LPC):

LPANAL.EXE - Linear predictive analysis for lpread/lpreson generators

krmsr, krmso, kerr, kcps \

lpread	ktimpnt, ifilcod[, inpoles][,ifrmrate]

ar	lpreson	asig

ar	lpfreson	asig, kfrqratio

lpslot	islot

lpinterpol	islot1,islot2,kmix

Using single Fourier analysis frame:

CVANAL.EXE - Impulse response fourier analysis for convolve operator

ar1[,...[,ar4]]] convolve	ain, ifilcod, ichan

OPERATIONS USING SPECTRAL DATA TYPES

(Back to contents)

Overview

wsig	spectrum	xsig, iprd, iocts, ifrqs, iq[,ihann, idbout, idsprd, idsinrs]

wsig	specaddm 	wsig1, wsig2[, imul2]

wsig	specdiff 	wsigin

wsig	specscal 	wsigin, ifscale, ifthresh

wsig	spechist 	wsigin

wsig	specfilt 	wsigin, ifhtim

koct	specptrk 	wsig, inptls, irolloff, iodd[, interp, ifprd, iwtflg]

ksum	specsum 	wsig[, interp]

specdisp 	wsig, iprd[, iwtflg]

SOUND INPUT & OUTPUT

(Back to contents)

Sound input:

 a1 	in

a1, a2	ins

a1,...,a4	inq

 a1	soundin	ifilcod [,iskptim] [,iformat]

a1, a2	soundin	ifilcod [,iskptim] [,iformat]

a1,...,a4	soundin	ifilcod [,iskptim] [,iformat]

a1[,a2[,a3,a4]] diskin	ifilcod, kpitch [,iskiptim][, iwraparound] [,iformat]

Sound output:

out	asig

outs	asig1, asig2

outs1	asig

outs2	asig

outq	asig1, asig2, asig3, asig4

outq1	asig

outq2	asig

outq3	asig

outq4	asig

Panning and 3-D sound:

a1,...,a4	pan	asig, kx, ky, ifn [,imode] [,offset]

aL, aR	hrtfer	asig, kAz, kElev, "HRTFcompact"

a1,..., a4	space	asig, ifn, ktime, kreverbsend [,kx, ky]

a1,..., a4	spsend

kr	spdist	ifn, ktime, [,kx, ky]

a1,... , a4	locsig	asig, kdegree, kdistance, kreverbsend

a1,..., a4	locsend

THE ZAK SYSTEM

(Back to contents)

ZAK System Overview

Allocating Zak space:

zakinit	isizea, isizek

Zak read/write operations:

ir	zir	indx

kr	zkr	kndx

ar	zar	kndx

ar	zarg	kndx, kgain

ziw	isig, indx

zkw	ksig, kndx

zaw	asig, kndx

zkcl	kfirst, klast

zacl	kfirst, klast

Zak signal modulation:

ziwm	isig, indx [,imix]

zkwm	ksig, kndx [,imix]

zawm	asig, kndx [,imix]

kr	zkmod	ksig, kzkmod

ar	zamod	asig, kzamod


ïºContents: Bath Csound update notices, detailed from 3.44 and up;

3.48 stuff: dcblock, pvadd, locsig, locsend, space, spsend, spdist

3.47 stuff: ftgen, poscil, NEW STRING PHYSICAL MODELS wgpluck (?) wgpluck2 repluck

More 3.47 stuff: harmon, cross2, dam, turnon,

3.46: sndwarp, Tuning opcodes; 3-D sound opcode; Non-linear filter opcode; New LPC analysis format and opcodes  Bath update notice 3.20 (the ugens from 3.20 have been integrated into CSSYNTAX.RTF):

(ftlen2( ), nsamp( ), ftsr( ), loscil2, fof3, GEN22)???


Version 3.x upgrades
Csound version 3.x upgrades

Overview of changes during 96 -- 98

The following changes concern the official Bath/Montreal Csound release, maintained by John Fitch.

A host of new opcodes have been added -- contributed by several developers -- and many bugs weeded out.

This release extends the original Barry Vercoe MIT release version 3.0 (1992).

Contents

Version 3.52 upgrade

Version 3.51 upgrade

Version 3.50 upgrade

Version 3.49 upgrade

Version 3.48 upgrade

Version 3.47 upgrade

Version 3.46 upgrade

Version 3.45 upgrade

Version 3.44 upgrade

Version 3.20 upgrade

Earlier upgrades


Version 3.52 upgrade   v 3.51. Back to upgrade index.

These are the release notes for version 3.52.  This is a collection of bug fixes from 3.51, and some major opcode renaming to avoid clashes between variables and opcodes

Language Changes

In score arithmetic , operators % (for remainder) and ^ allowed.

The use of {} for exponential score ramps is duplicated by ( and ).  This is so we can withdraw { and } soon, so they can be used for section brackets.

New Opcodes

High precision oscillators: poscil, poscil3 (with cubic interpolation);

High precision looping oscillators lposcil and lposcil3.

The opcode kreadN has been implemented, and simultaneously renamed to readk, readk2, readk3 and readk4.  The interpolation argument is currently ignored while I think about it. The code has not been tested so may fail.

Opcode changes

biquad has an additional optional argument to skip reinitialisation, so smooth transitions can be made.

distort1 changes so all but first argument are optional.

This release also saw another name-changing party:

opcodes islider8, islider16, islider32 renamed slider8 /slider16/slider32

ilimit renamed limit

itimes/itimek renamed times /timek

All itable.... opcodes renamed tablei...

imidic... renamed midic ...

ictrl... renamed ctrl ...

ion, ioff renamed noteon, noteoff

iout..., kout... renamed outi ..., outk...

agogobel renamed gogobel

iondur, iondur2 renamed ondur, ondur2

isNb14 renamed sNb14

kreadN renamed readkN

Bug Fixes

AIFF files with Author, Annotation and Copyright chunks read correctly

Extending the number of GOTOs and LABELS had two independent bugs which wuld usually lead to a segmentation error.  Fixed

Some uses of [] could give a memory error, now fixed

tonex, atonex and resonx corrected when reinit is skipped.  This might help avoid some clicks.


Version 3.51 upgrade   v 3.50. v 3.52. Back to upgrade index.

This is mainly a small number of bug fixes from 3.50, but rather significant ones. (Notes merged with those for version 3.511 release.)

Language changes

Comments (beginning with semicolon or # character) allowed in the unified file format.

Winsound can use .csd unified/project files in orchestra field of the main dialog.

New opcodes

envlpxr -- inadvertently lost; exponential, MIDI controlled envelope.

xadsr -- ADSR opcode with exponential lines rather than linear.

mxadsr -- ADSR with exponential curves and MIDI sensitive to release.

Bug Fixes

- Use of C-style comment /* ... */ now works both in orchestra and in score .

- Another attempt to get backslash line continuation in orchestra working.

- wgbow -- the pitch control was all wrong and has been rewritten.  Also the bow slope had been removed; now restored.

- oscil3 at k-rate was totally wrong; fixed

Version 3.511 adds the following bugfixes:

- constant values for arate ^ operator

- noise error in spectrum fixed (2pi was wrong).

- sndwarp fix for some platforms.

- new diskin fix.

- ADSR fixed in midi case.

- wgflute

- distort1 now compiled correctly (gave a spurious null iopadr mesage)

- cpsmidib etc in k-rate case fixed.

In version 3.511 there was also some source code restructuring.


Version 3.50 upgrade   v 3.49. v 3.51. Back to upgrade index.

Language changes

It is now possible to keep all Csound code for a project - as well as the command line - in a single text file, using the new HTML-style unified file format.

If a file .csoundrc exists, it is read to set parameters first, which still can be overridden. More under the unified file format section.

Rising to a power is available in expressions with the ^ operator. Use with some caution as it is not sure that the precedence is correct. (NB: New in version 3.493)

There is now a modulus-like % operator (which is not limited to working with integers).

New 31-bit random option in rand, randi, randh (NB: New in version 3.492-3).

moogvcf and rezzy can accept a-rate parameters, moogvcf takes an optional scaling factor, and rezzy takes an optional normalization value. biquad also has an additional optional argument, which if non-zero skips initialisation.

foscil/foscili can now accept a-rate parameters.

If an out opcode is used which is inconsistent with the declared nchnls, Csound now attempts to correct to the correct one, which will not necessarily be correct. (NB: New in version 3.492)

New opcodes

schedule and schedwhen -- Insert new instrument events from orchestra code(!). (NB: New in version 3.491)

Some synthesizing and filter opcodes by Hans Mikelson: vco , planet , distort1, pareq (Implementation of Zoelzer's Parametric Equalizer Filters), and deltapn

lfo -- Low Frequency Oscillator with 6 shapes. (NB: New in version 3.491).

String resonator streson by V.Lazzarini (NB: New in version 3.494).

A number of new MIDI opcodes by G. Maldonado: midion2, midiin, midiout, nrpn, cpstmid, and MIDI slider bank controler input.

pctrlinit and dpctrlinit by the same author (not documented yet).

There is a set of old opcodes reimplemented by John ffitch to use cubic interpolation internally, for HiFi audio quality: oscil3 , loscil3 , table3 , deltap3 , vdelay3. Note that foscil3 and itable3 were also announced, but they are not in the sources.

Opcode changes, bug fixes and revisions

Name changes: kdump1-4 now dumpk1-4, kon renamed midion, kfilter2 renamed filter2.

hetro had a wrong constant which would give rise to a little noise.


Version 3.49 upgrade   v 3.48. v 3.50. Back to upgrade index.

Language changes

1.  Digits allowed in macro names except at start.

2.  New ramp functions in score introduced by { and } give ramps driven by expon rather than line. The ramp function ~ gives a random value (uniform distribution) in range on the ramp.

4.  v statement in scores for local textual varying of time.

5.  b statement in score to reset the clock.

New opcodes

A number of new filter opcodes: lowres, lowresx and vlowres -- lowpass resonant filters; tonex atonex resonx -- more multiple filters; and biquad, moogvcf and rezzy.

Actions on large amplitudes: mirror, wrap.

ntrpol -- interpolation

trigger  goes off when a krate variable crosses a threshold.

spectrum -- calculate wsig variables (DFTs) for the spectral opcodes.

wguide1, wguide2 -- primitive wave guides

adsr and madsr -- classical ADSR envelopes

ftsr(x)  get sample rate of a f-table created by GEN01 or GEN22

GEN23 -- read a table of numbers

envlpxr code included -- omitted by mistake earlier.

flanger a user controlled flanger (Gabriel Maldanado NB: New in version 3.484)

dcblock, a DC Blocking filter (NB: New in version 3.481)

Opcode changes and revisions

voscili opcode removed as it did not work well and the functionality exists elsewhere.

Skip initialisation in physical model instruments if lowest frequency is negative (for legato sounds).

Bug fixes in cross2, wgflute, diskin and soundin.

aftouch had wrong arguments, shaker had an argument removed which was not used.

Arguments to specptrk and specdisp now agree with manual.

Manual news (this WinHelp file only)

Since there have been name changes in Csound (names have been removed, not just added) there is now a new entry: NAME CHANGES, under which old reserved names may be listed. This will be on the relevant page, between the DESCRIPTION and the INITIALISATION or PERFORMANCE entries. These names will be removed from the index of the help file at some suitable time.

The old names are returned to public namespace and may be used for variable names (although this will not always be a good idea) - re

Other changes

1.  -J command line option selects IRCAM format in the same way as -W and A.

2.  AIFC supported at least for floats.

3.  Allow Mac, Unix or PC files to be read on other platforms.

4.  Scot (score translator) removed.

Lots of bug fixes and betterments, eg

- MIDI control message PROGRAM_TYPE recognised

- \ for line continuation rewritten, improved recognition of # at start of line.

- corrected use of [] in scores.

- use of large instrument numbers now correct.

- Included files in orchestra use a pathname look-up.

-  -z command line option now reports the public opcode names rather than the internal.

- Increase number of arguments to about 800 (still not dynamic).

- Removed a large number of 'namespace polution' (as announced in 3.485).

- Ouput file null is thrown away (ie no sound file generated).


Version 3.48 upgrade   v 3.47. v 3.49. Back to upgrade index.

Language changes

1.  Name changes of several opcodes beginning with a, k, i (eg kgauss, agauss, igauss now all named gauss)  this frees up some Csound variable name space.

2.  Macros in orchestra and in scores (NB: These were beset by bugs, most of which were fixed by v 3.484)

3.  New r statement to repeat sections in scores

4.  #include statement available in orchestra and in score

5.  /* */ comments allowed in orchestra and score. (Does not work properly yet -re)

6.  Underscores _ allowed as part of a word.  Words case sensitive (capitals allowed in names).

7.  Limited evaluation of expressions in the score

8.  Treat backslash character \ at end of line as continuation in orchestra. (Does not work properly yet -re)

New Opcodes

flanger a user controlled flanger (Gabriel Maldonado NB: New in version 3.484)

dcblock (NB: New in version 3.481)

pvadd (Richard Karpen)

locsig, locsend, space, spsend, spdist for locating sound. (Richard Karpen)

xyin implemented in Windows

taninv2(x, y) (equivalent to atan2 in C language)

printk2 which prints when a k-value changes (Gabriel Maldanado)

Other Changes

Two news in the command line options:

Pipes allowed in -L inputs, using a | as the first character of the filename' argument

-H2, -H3 and -H4 options to display heartbeat in a different way.  -H1 is equivalent to -H and -H0 is equivalent to no -H option. The Heartbeat option in Winsounds Extras dialog also reflects this

Further:

Code merge with the Mills (Berry/Ingalls/Madole) PowerPC port (NB: New in version 3.484)

WAV format now supports floating point samples correctly. (Richard Dobson)

AIFC floating point format implemented (NB: New in version 3.484)

Removal of limit on orchestra size (ARGSPACE and ORTEXT problems)

Write permissions of the output soundfile could be wrong on Windows.

Opcode Fixes

reverb2 was tuned to one particular sampling rate.  Replaced by nreverb opcode (the two names both refer to the new version). (Richard Karpen)

The opcodes asin, acos and atan renamed as sininv, cosinv and taninv so as to avoid name-space polution.

wgbow, wgflute and wgbrass fixed in various ways

Fixes in fof2 and fog (Ekman) (fog still broken, but fixed in 3.481. My fault -re)

shaker used to ignore kfrequency; now fixed. one unused argument was also removed (NB: In version 3.484)

Removed voscili, as it did not work well and gave little new functionality,

Windows GUI Changes

Output device selectable by menu (Richard Dobson).  No equivalent code for input yet.

Reading MIDI files fixed in interface


Version 3.47 upgrade   v 3.46. v 3.48. Back to upgrade index.

Language changes

1.  Comments allowed in score in more places.

2.  Maximum number of an instrument is dynamic, and expands as needed.

3.  Removed limit on number of labels.

4.  Introduced ^ syntax (for exponential expressions) in score files.

5.  Two new GENs, numbered GEN25 and GEN27

6.  No limit to number of partials in HETRO.EXE and adsyn

Some handy additions

Opcodes to find out function table size (ftlen)  and loop time (ftlptim).

Random generating functions i/krnd(x), i/kbirnd(x)

Allow instrument trigger from orchestra file: turnon

Allow function table creation in orchestra file: ftgen

MIDI opcodes

A number of new opcodes for MIDI in/out were added (most are by Gabriel Maldonado) They allow the following activities:

Assign MIDI instrument to a Csound instrument massign (new orc file header statement)

MIDI controller input - allows MIDI controllers to control Csound instrument variables.

MIDI output of single notes, note streams, channel messages, or System Realtime messages

Envelopes for MIDI notes

Extend duration of MIDI notes

New signal generators:

New string physical models: repluck wgpluck2 wgpluck

Waveguide physical models: wgclar, wgflute, wgbow, wgbrass

Percussion physical models: marimba, vibes, agogobel, shaker,

4-operator FM instruments: fmbell, fmrhode, fmwurlie, fmmetal, fmb3, fmpercfl, fmvoice

More synthetic instruments: moog, mandol, voice

Harmonizer opcode harmon

A simplified loscil unit doscil

An oscil1 variant which cycles n times through a ftable: osciln

New value converters: acos(x) asin(x) atan(x) cosh(x) sinh(x) tanh(x)

(A pulse oscillator poscil was announced, but was not included in the exe)

New signal modifiers

General filter design ugens filter2 kfilter2 zfilter2

Morphing audio crossfade synth

Compressor/expander unit dam

Revised opcodes

The following opcodes have had their specification changed, generally in a compatible way. Usually to add scale factors and the like:

midictrl	pchbend	linseg	printks	veloc

Opcode fixes

a)	Some fixes in fog

b)	Internal tidying in granule

c)	Documentation is now available for the opcodes kread/2/3/4 and kdump/2/3/4,

d)	Fix problem with tables 300, 600, 900,...

Other changes

ksmps constrained to be integer

Additional features on Windows GUI to includes access to orchestra and score editing and post-calculation soundfile editing.

Revised realtime audio on Windows (again!)

Emacs orchestra mode expanded for new opcodes, and fixed a little


Version 3.46 upgrade   v 3.45. v 3.47. Back to upgrade index.

a)	Changes in a number of MIDI converters (ipchmidib, ioctmidib, icpsmidib, kpchmidib, koctmidib, kcpsmidib, midictrl) to add additional optional argument, mainly for scaled pitchbend; also new opcode midictrlsc (Mike Berry). (The last is however missing from the actual exe)

b)	New opcode, diskin. Like soundin except allows variable rate of reading sound file. (Mike Berry)

c)	Improved pvoc with optional last argument (Richard Karpen)

d)	Most of Robin Whittle's opcodes included. This includes opcodes for writing into ftables, the zak system which more or less simulates array variables, krate variable printout and more.

e)	New granular synthesis opcode fog from Michael Clarke (still needs a little tweaking)

f)	Bug and functionality fixes:

Defaults for sr/kr/ksmps such that one can omit one.

Defaults if all omitted: sr = 44100, kr = 4410, ksmps = 10 (CD style)

Number of tables is no longer fixed, but expands as required.

Fixes to -o dac on Windows95

Fixed cscore main program for dribble files.

Missing endin now noticed.

Negative p3 in score no longer confuses other references to that note in the score (JPff/RWD)

Correction of opcode listing (-z command line flag)

Correction of hrtfer code on PCs and other machines with that byte order.

Corrected writing to log file on PC (mega dyslexia!)

Large number of bug fixes; mainly minor and to do with igoto (many people).

Attempt to fix LINUX precision problem in large table sizes etc


Version 3.45 upgrade   v 3.44. v 3.46. Back to upgrade index.

a)	An additional optional argument has been added to all the Butterworth filters, vdelay, and reverb2, which if non-zero skips the initialisation stage. (This is in keeping with earlier filter opcodes - re)

b)	Adjusted sndwarp to give (optional) stereo, and added new opcode sndwarpst

c)	Added fof2 opcode (partly nonfunctional in this version; fixed in 3.46 - re)

d)	Added new opcode unirand to complete the random generators (by Robin Whittle).

e)	Allow command line arguments written together like -m6W

f)	New command line flag -z to give a list of opcodes. -z0 or -z prints a list; -z1 prints a list with answer/argument descriptions. (Broken in this version, fixed in 3.46 - re)

g)	Bug and functionality fixes:

Adjust writing of scores to allow longer tables (as described by Richard Karpen).

Return code corrected after no graphics.


Version 3.44 upgrade   v 3.20. v 3.45. Back to upgrade index.

a) Phase Vocoder Opcodes:

ktableseg, ktablexseg, voscili, vpvoc, pvread, pvcross, pvbufread, pvinterp

b) Tuning Opcodes:	cps2pch, cpsxpch

c) 3-D Sound Opcode:	hrtfer (did not work for PC in this release; fixed in 3.46)

d) Time Stretching Opcode:	sndwarp

e) Non-linear Filter Opcode:	nlfilt

f) New format for LPC analysis:

Allows for pole stabilisation, and two new opcodes,

lpslot, lpinterp

for interpolation between different analyses

g) Bug Fixes:

Reading of numbers in Event reading fixed

Comments allowed after e in scores

Obscure bad case in opening files

Minor bug in vdelay fixed

h) Permanent Graphs (Fabio Bertolotti):

A new option (-G) on the csound command line ensures that the graphs are saved as a

PostScript file, with the same name as the soundfile with .eps as the extention.

This has been in use by teachers for a while.

h) Code Changes (PC):

Improvements in output to Multimedia-implemented DAC

Recognise file names starting with a: etc.

Non-stop feature in Windows

and a number of internal code improvements which I doubt you care about.


Version 3.20 upgrade   v 3.44. Back to upgrade index.

This distribution included a granular texture generator grain, a new set of butterworth filters, a new variable delay, a multitap delay, a new reverb (reverb2), an envelope follower, various noise generators, a power function generator and two gen routines, GEN20 and GEN21.

All of the above additions were designed by Paris Smaragdis between May and December 1994, under the supervision of Dr. Richard Boulanger.

The documentation was written on 20 December 1994 by Paris Smaragdis, Berklee College of Music.

Internet: psmaragdis@aol.com

Earlier upgrades

The upgrades to Csound version 3.0 (originally released from MIT in 1992) included the new opcodes granule and convolve.


Contents: Info popup entries; Introductory notes for PC users; Installing Csound on PC; Csound addresses; Copyright notices; John Fitchs file CHANGELOG.CSOUND; Earlier changelog (up to and including v3.36) with the note on PC realtime.


i-time, k-rate, a-rate
a-rate, k-rate, i-time

For speed reasons, Csound has two internal loops, one at audio rate (sr) for generating sample and one at a slower rate (kr).  The slower rate allows the program to use control variables (e.g. envelopes) without spending the time to recalculate them at every sample. The names of variables for Csound unit generators must always be preceded by a letter which indicates the rate of updating is used for that variable. Valid prefixes are a, k, i.

i-time is for init time. This is not properly a rate, it is for setting a variable to an initial value before an instrument begins playing. Csound makes an initial pass through each instrument in the orchestra, to set up all necessary data before actually beginning to generate any sound.

a-rate means audio rate, ie generated soundfile (or output sound) sample rate. Sample rate in a digital sound file decides the sound quality. Common values are: 44100 Hz (CD rate), 22050 Hz (usually ok when testing an instrument), or 8000 Hz (like web .au files - only good for speech). See also Nyquist.

k-rate means "Control" rate. The ear cannot detect most musical changes (like pitch change) at a very high rate. Csound saves computing time by updating many variables at a slower rate. For most purposes 1/10th or even 1/100th of audio rate will do fine. At lower rates the stepping in the variable changes will be too annoying. For outputting MIDI events, you can even go down to 1/200th audio rate. The control rate is set in the orchestra file header with the variable kr, or at the Csound command line with the flag -k.

See also the introductory notes on Csound variables


Environment variables
Environment variables: Environment variables are strings which are stored centrally by the operating system (DOS/Win/Unix). They may be defined in one place (under DOS/Windows by using the set command), but programs are guaranteed to have access to them regardless of where they are located in the hard disk directory system. The Csound environment variables are SADIR, SFDIR, SSDIR, SFOUTYP and CSNOSTOP. See also Installing Csound for DOS/Windows.


CSNOSTOP (Environment variable)
CSNOSTOP - Environment variable.  In the John Fitch Bath Csound version there is a pause before and after each graph.  This can be turned off if the environment variable CSNOSTOP is set to YES. Under DOS/Windows you set it at the command line or in a batch file with:

set CSNOSTOP=YES


SADIR, SFDIR, SSDIR (Environment variables)
SADIR, SFDIR, SSDIR - Environment variables for Csound input and output files. The rules for these are:

Soundfiles being written are placed in SFDIR (if it exists), else the current directory.

Soundfiles for reading are sought in the current directory, then SSDIR, then SFDIR.

Analysis control files for reading are sought in the current directory, then SADIR.

NOTE: Windows 95 long file names work, but they must not contain spaces or non-ANSI (non-English) letters. DOS names always work.

See also Installing Csound for DOS/Windows.


SFOUTYP
SFOUTYP - Environment variable.  In the John Fitch Bath Csound version you get WAV sound files either by using the -W command line flag, or by setting SFOUTYP to WAV. Under DOS/Windows you set it at the command line or in a batch file with:

set SFOUTYP=WAV


Chebyshev functions (description)
Chebyshev functions: Functions used for controlling waveshaping. Waveshaping will usually just produce fairly uninteresting noise unless you use these functions. See GEN13 and perhaps ACCCI examples Group 40.


Fast Fourier Transform (description)
Fast Fourier Transform (FFT): (anyone?)


FIR filters and IIR filters (description)
FIR filters and IIR filters: FIR means Finite Impulse Response, while IIR means Infinite Impulse Response.  Anyone?


Filter response (description)
Frequency response and Impulse response of filters:

The Frequency response says how a filter changes the amplitude of low and high frequencies of an input sound (measured for white noise).

The Impulse response says how the filter reacts over time to a very short white noise burst (analog: a firecracker or start pistol shot; digital: one sample) followed by silence. Since any acoustical environment (like a church, or your bath-room) can be viewed as a filter, this is useful to describe the reverb characteristics of a room.

In technical terms, the frequency response of the filter is the fourier transform of the impulse response. It is the same response, but expressed as a frequency spectrum of the impulse response. This, in turn, means that you can measure the frequency response of the room and take the inverse Fourier transform to get the impulse response. This is good for practical purposes since a start pistol shot (etc) has very low energy, and will yield a recording with a horrible signal to noise ratio.

Conversely, the coefficients of an FIR filter are the FFT of the desired frequency response. So you can create a filter by

1) Changing the desired frequency profile

2) Calculating the FFT

3) Using the result as the filter coefficients

By using convolution CVANAL and convolve (See tutorial) you can impose the impulse response caracteristics of one sound on another. This is used eg to add reverberation to sounds.


FM synthesis (description)
Frequency Modulation (FM) synthesis: An oldish technique developed (patented) by James Chowning. The basic principle is to let the output of one oscillator (the modulator) modulate the frequency of another (the carrier). This would be like vibrato, but at much higher (audible) frequencies. It is a computationally cheap technology which easily allows rich and varying harmonic spectra, and reasonably interesting imitations of conventional instruments.


Nyquist frequency
Nyquist frequency: According to the sampling theoreme (aka the Nyquist theoreme), any frequency may be represented by sampling, with the constraint that at least two samples must be taken in each period of the frequency. The highest frequency which can theoretically be represented at all (however crudely) at a given sample rate (recording or playback), is thus half that sample rate. Eg, at 44.100 kHz sr, the highest pitch which can be represented is thus 22.050 kHz, which is above the highest pitch anyone can hear under the best conditions at any time in their life.

If you try to use (or record) higher pitches than the Nyquist frequency, they will fold over and appear as lower frequencies. Samplers and CD players therefore use filtering techniques to rid the signals of higher pitches.


RMS - Root-Mean-Square (description)
RMS - Root-Mean-Square: A method for averaging the power of a signal. Useful for estimating the amplitude envelope of a sound.


Shepard tones
Shepard Tones - Shepard tones consist of a series of octave-spaced partials (not the usual harmonic series, but rather the 1st, 2nd, 4th, 8th, 16th, 32nd... partials) whose amplitudes are determined by a bell-shaped curve.This series of partials goes all the way from the lower limits of human hearing (around 20 Hz) to the Nyquist frequency.

These have the special effect that they "wrap around" to exactly the same perceived tone when played an octave higher or lower. For example, if you play an ascending chromatic scale with a Shepard Tone, each note will sound a half step higher than the previous note, but the last note will sound exactly the same as the first note.


Filter theory (basic)
(very) basic filter theory

Snipped from some messages on the Csound mailing list

RESONANCE AND "Q"

One of the things that give analog synthesizers their distinctive sound is resonance.  This is a boost or emphasis of frequencies at the cut-off frequency (ie just before the topmost frequencies starts falling).  In the case of the Moog diode ladder filter the phase at the cut-off frequency is shifted by 180 degrees and an inverted signal is fed back into the system which results in the resonance.  With digital filters things are a bit different again.  For some implementations review the Csound mailing list archives, and look for examples at Hans Mikelsons page.

The "Q" actually stands for "Quality" and is defined as the ratio of the center frequency of a filter to the band width, i.e., Q = CF/BW, where CF and BW are specified in Hz:

                   Center freq

Q  =  -----------------------------------------

         Hi cutoff - Lo cutoff freqs

It's a more musically useful (or intuitive) parameter than the band width itself, because as the center frequency is swept over the full frequency range, the width of the band must change proportionally in order for the quality of the filter to sound the same. A high Q means a relatively narrow band width (i.e., BW is a small value in Hz, compared to the CF). This results in a sharp peak in the frequency response at the CF; the sharper the peak (as we will see: the higher the order of the filter), the greater the "resonance" at that point in the spectrum.

FILTER "ORDER"

The order of an analog filter corresponds to the order of the differential equation which describes the filter.  A first order filter has one pole and has a roll off of 6 db/octave. (This means roughly that the perceived amplitude of frequencies above the top frequency of the filter falls to half each octave.)  Each order adds another 6 db (ie the frequencies are cut off twice as sharply, the filter is more precise, and takes more processing power to compute).  An Oberheim Matrix has a 2-pole filter, so the frequency response rolls off at 12 db/octave.  A MiniMoog has a 4-pole filter that rolls off at 24 db/octave.

In other words frequencies one octave above the cut-off point of an analog filter would be attenuated (reduced in volume) 24 db with a 4-pole filter.  The frequency response is the ratio of two polynomials:

(a0+a1*x+a2*x^2...)

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

(b0+b1*x+b2*x^2...)

The biggest exponent in the polynomials is the same as the number of poles.  (Actually the a's are called zeros and the b's are called poles, but lets not get too complicated here...)

Digital filters are a bit different.  Instead of the differential equation they are based on the difference equation.  The frequency response is

(a0+a1*exp(-i*theta)+a2*exp(-i*2*theta)...)

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

(b0+b1*exp(-i*theta)+b2*exp(-i*2*theta)...)

. . .which looks to me (HM) like the zero term is an offset, and each of the other terms traces out a circle whose radius corresponds to the coefficient.  The first term would trace out a semi-circle as the frequency goes from 0 to sr/2 (the Nyquist frequency) (theta goes from 0 to pi)  The second term would complete a full circle, the third term a circle and a half etc.

The 'order' of a filter thus identifies the most delayed sample. In the equation above, the numerator gives the order of delayed input samples (giving zeroes), and the denominator gives the order of the delayed (fed back) outputs (giving the poles).

Thus, in practical terms, the higher the order of the filter, the more samples are involved in the calculation, and the greater the overall processing time.

FIR FILTERS AND IIR FILTERS

FIR means "Finite Impulse Response," while IIR means "Infinite Impulse Response."  Anyone?

See also the Convolution tutorial.

By Hans Mikelson, Russell Pinkston & Richard Dobson, snipped by rasmus ekman. Dont blame them, this is just compiled from quick emails.


Convolution, a (very) quick tutorial
A (very) quick tutorial on convolution

A filter (highpass, lowpass, bandpass, etc.) is usually characterized by its frequency response. If you put an impulse (just a 1 surrounded by zeros in the digital domain, ie one maximum amplitude sample followed by all zeroes) into a filter, the signal (or sound) you get out is called the impulse response of the filter. You can filter a signal in two ways: either run the signal through the filter, or convolve the signal with the impulse response of the filter.

Since every filter (within reason) has an impulse response, we can assume every signal (or sound) is the impulse response of some filter. When you use convolve you are using the frequency response of the entire-signal-at-once to filter the other signal. Adding silence at the front or back of the sound will not change the sound of the convolution in the least. It will only lengthen the delay. Convolution is symmetric so which signal you call the filter and which signal you call the signal makes no difference in the final output. By convention the shorter signal is usually considered the filter.

In filter parlance, the filter signal is used as an FIR filter on the other signal. When you put an impulse into an FIR filter, the impulse response lasts the length of the filter. In other words, if the filter is 1024 samples long, the impulse response will be 1024 samples long. How much is the response actually delayed? There is no precise answer but for symmetric impulse responses the mid-point is usually used. So a 1024-sample sound causes a delay of 512 samples, approximately.

Finally, the Csound opcode convolve doesn't actually do full-fledged convolution. It takes the Fast Fourier Transform of part of the signal, multiplies that FFT by the FFT of the impulse signal, takes the inverse FFT, and carefully combines the parts. It's mathematically equivalent to convolution but much, much faster in most cases.

What many people hope to do with this technology is to eg have a gong say the word "Gong" while it's ringing. convolve won't do that. You need to run an LPANAL on the word "Gong" and use the output with an lpread, then run the actual gong sound through an lpreson. Or try the recent cross2 opcode.

By Erik Spjut. Captured from the Csound mailing list by rasmus ekman


Installing Csound for PC
Installing Csound for DOS/Windows

Based on notes by John Fitch. Inflated by rasmus ekman

Contents:

Getting Started

Running Csound

See also:

Questions and answers

Realtime support

GETTING STARTED

System requirements:

Windows 95 or Windows NT, or have the Win32S system installed under Window 3.1 (See Note for Win 3.x users).

Files to get:

Present Csound version: 3.48 (April 12 1998). Get it from either of:

ftp://ftp.maths.bath.ac.uk/pub/dream

ftp://ftp.musique.umontreal.ca/pub/mirrors/dream/

There are several files to choose from. The most recent PC files are probably under the directory /newest.

file	contents

csound_new.zip	Csound.exe for MS DOS, and alll utility programs

csound_con.zip	only the most recent Csound.exe for DOS

csound_win.zip	Winsound.exe for Windows 95 (or Win32S)

csound_source.zip	Csound C source code - for programmers.

Only some of the utility programs are built into Csound/Winsound, so if you want them all, you need to get the file csound_new.zip.

Files for the sound modelling opcodes can be found on the Csound server at Bath, in the directory

ftp://ftp.maths.bath.ac.uk/pub/dream/documentation/sounds/modelling/

Manuals:

You also really need the current HTML manual (or perhaps the windows help file) to use Csound. Get them from:

ftp://ftp.maths.bath.ac.uk/pub/dream/documentation/manuals/

ftp://ftp.musique.umontreal.ca/pub/CsoundManual/

and

http://hem.passagen.se/rasmuse/Csound.htm

respectively.

Examples:

Get the ACCCI example files. They are worth your attention.

http://mars.let.uva.nl/gather/accci/index.html

There are also a number of example files in the /documentation directory at Bath

ftp://ftp.maths.bath.ac.uk/pub/dream/documentation/

Directory structure:

In order to use Csound to create music it is necessary to arrange the environment on your PC in a suitable way.

In the following we will assume that you have created a directory called C:\Csound.

Now create three subdirectories. At the DOS command line, type

mkdir  C:\ Csound\Analyses

mkdir  C:\ Csound\Bin

mkdir  C:\ Csound\Waves

- or create the folders from Explorer or File manager.

Unzip all your binary files to Csound\Bin. The Csound\Analyses directory is used for files produced by the Csound utility programs HETRO.EXE, LPANAL.EXE and PVANAL.EXE. The output soundfiles will be written to Csound\Waves (or whatever directory you like, if you specify that).

You should also similarly add a subdirectory Projects to which you copy and rename any Csound orc/sco file pairs that you create. Do this often - as soon as you lose the changes youll miss the reasonable swoosh you had 20 minutes ago.

Environment:

You are going to need extra string space for the environment variables. Add something like the following line to CONFIG.SYS:

SHELL=C:\Win95\Command\Command.com /e:1024 /p

or:

SHELL=C:\Command.com /e:1024 /p

The exact path depends on whether you find the file Command.com under C:\ or in your Windows (95) DOS folder Windows\Command (or something similar). The relevant bit is the /e:1024 switch, which increases string space from the default 256 bytes to 1024 (actually any multiple of 16 is ok, in the range 160 through 32768). If you already have a SHELL statement in CONFIG.SYS, just make sure that the /e: switch is there. You need to restart your computer for the changes to take effect.

Now set the environment variables. Add lines like the following to AUTOEXEC.BAT - with any local changes (or create a special batch file which you always run before your Csound sessions):

set PATH=%PATH%;C:\Csound\Bin

set SFDIR= C:\Csound\Waves

set SSDIR= C:\Csound\Samples

set SADIR= C:\Csound\Analyses

This will ensure that the programs are found (if you put them in Csound\Bin), and that any input soundfiles will be found (using SFDIR and/or SSDIR).  The output WAV files will be written into the directory named in the SFDIR line.

These environment variables are also used by the Winsound Windows interface, but you can easily override them with the dialogs.

RUNNING CSOUND

Csound basically wants two plain text files to generate sound. You may eg create them under Notepad or the DOS program Edit.

Call them TEST.ORC and TEST.SCO.

You may keep Test.orc and Test.sco in the Csound folder, or perhaps in the Csound\Projects folder. These files must be plain text; no formatting, so don't use some fancy word processor like WordPerfect unless you are sure that they are saved as plain text.

The files should in the end of course contain Csound orchestra code (in Test.ORC) and Csound score events notation (in Test.SCO) -- two interwoven programming languages which expose to your musical deliberation some of the most advanced sound synthesis technologies on the planet.

For a quick start, copy and paste an example from the tutorials in the help file, or copy some example files to your Csound project folder and run Csound on them. Try out the ACCCI examples. Go on for a very long time. Read a lot in the help files (all of them).

Windows 95

See separate documentation on Winsound. Basically, you will probably find your way around. Use the O and S buttons by the edit boxes to browse for your ORC and SCO files. Hit the Extra button to check the details in your command line. See also Realtime support.

DOS users

The following notes pertain to those who run Csound from the DOS command line. If you also run Windows, open a DOS box. Find your way to the Csound folder (by typing eg cd C:\Csound etc). Invoke Csound with the following line:

csound  -W -oTest.wav -g -H -m3 Test.orc Test.sco

Csound will print a lot of info to the DOS window, and perhaps (if the orc/sco files are ok) render a WAV file in your soundfile directory (or in the currently active directory if you haven't defined SFDIR as you should). You can now play the file with your favourite soundfile player.

Now change one of the values in TEST.ORC/SCO and run them again - or go on to the next tutorial/example.

The arguments -W -g etc, are documented in the topic The Csound Command Line.

DOS batch files:

If you are working under DOS, you'll soon get tired in your command line typing finger. Of course you are using DOSKEY to edit your command line (type 'doskey', then use the arrow keys to recall and edit the command line without retyping everything), but still things can be smoother.

Copy and paste the following text to a plain text file:

@echo off

set NAME=%1

if %NAME%*==* set NAME=test

if not exist %NAME%.orc set NAME=Projects\%1

csound -W -otest.wav -g -H3 -m3 %NAME%.orc %NAME%.sco

Save the file as CS.BAT or something in your Csound directory (the cs could be anything, but the .bat extension is compulsory). Now, you just type CS at the command line to run Csound on TEST.ORC and TEST.SCO.

Whats more, you can also run any file in the folder Csound\Projects (which I (re) think you should have created). Eg if you have the files Glitter.ORC and Glitter.SCO in the Csound or the Csound\Projects folder, type

CS glitter

to run Csound on those two files.

Read more about the Csound command line.


Winsound - Csound GUI for Windows

By John Ffitch - (these notes cranked out in 20 mins by re)

Winsound is Csound with a graphical user interface shell for Microsoft Windows. It has never been properly documented, but here are some notes.

Winsound is available from the normal distribution sources: At the Bath/Montreal sites, get the file csound_win.zip.

You will probably find your way around. The shell is mostly a number of dialogs which you can use to set the options for running Csound on your ORC/SCO files. Here is what you can do:

  1)	Run Csound (surprise!). Use the O and S buttons to browse for your ORC and SCO files. Use the > arrow to edit each file in the built-in Windows application Notepad (or whichever editor you associate with those file extensions).

As of Csound 3.51, .csd project files using the unified file format can also be used with Winsound: Enter the file name in the orchestra (O) field of the main dialog, and leave the score file field empty.

Set output soundfile options on the front dialog, and in the Extra dialog. The available options correspond to the mass of Csound command line flags, which are documented elsewhere.

  2)	Run Csounds built-in utility programs for soundfile analysis. Available under the Utilities button. The output from these programs can be used by several interesting opcodes.

  3)	Run Csound as a realtime synthesizer, with MIDI input and realtime output. Realtime sound output never worked under DOS, so you need Winsound to do that (or get Gabriel Maldonados Csound version). See further about realtime support.

Running Winsound

During performance Csound outputs text to the Notepad-like text window. After a performance you can browse the output, or display graphs of your ftables.  Due to its heritage Csound cannot run like other windows programs, so after each performance it must be fully restarted. This can be automated if you check the box Remain Active in the main dialog window. When you have seen the output after a run, hit enter to quit or restart Winsound.

Winsound can show graphs of your ftables. This sems not to work properly yet (version 3.48). There is a menu in the text window for browsing through the ftable graphs, if you check Full in the Graphics groupbox. Incidentally, it seems this box must be checked if you want to use the xyin opcode to control Winsound during performance.

NOTE FOR WINDOWS 3.X USERS

All current Csound binaries are 32bit programs, but will run under Windows 3.x as long as you have the Win32S code installed.  This is often distributed with machines, or compilers.  If you do not have it you will get an error message saying that the program WinSound is an NT executable.  In this case you should down load Win32S from Microsoft's ftp service (ftp.microsoft.com), or one of MSDL or CompuServe:

Win32s is available from many sources. Microsoft Personal Operating System Support Engineers support the installation of Win32s when it is obtained from any of the following sources:

 - Internet (anonymous FTP)

ftp://ftp.microsoft.com/softlib/mslfiles

Get PW1118.EXE

 - CompuServe

GO MSL

Search for PW1118.EXE

Display results and download

 - Microsoft Download Service (MSDL)

Dial (206) 936-6735 to connect to MSDL

Download PW1118.EXE


Questions and answers

Under construction. Contributions welcome.

Compiled by rasmus ekman. Contributors include at least Mike Berry, John Fitch, Matt Ingalls, Hans Mikelson, Jean Piche, Erik Spjut and Larry Troxler.

Contents:

Why function tables?

Csound variable types

Questions and answers

See also:

Getting started

Basic filter theory.

WHY FUNCTION TABLES?

The functionality of Csound components is at least as much determined by computer efficiency considerations, as by musical esthetics! Many signal generators in Csound operate not directly with mathematical formulae (like the sine function), but with lookup tables - simply because this is a so much faster way to produce data.

The GEN routines produce such tables, using various formulae, and it is more or less up to the Csound programmer (you) to find a way of using the results.

The table produced by any GEN call has a certain length which you define in the third argument to the f-statement that invokes the GEN routine. What length you decide on has no musical relevance whatsoever (except that with too short tables you may get a little worse sound quality), but it is important for how much memory Csound uses at run time. Since memory nowadays is not so very expensive, you should make tables reasonably large - for an a-rate oscillator (see oscil) at least 8192 or 16384 memory locations, if you want a good sound at 44100 samples per second.

A simple example: GEN09 will write sine values into your function table, and the table will be considered to have length 2*PI (or 360 degrees, ie a full circle, which means a full period of a sine wave), regardless of the number of memory locations it actually uses. Thus, for integer partials, you will get a number of full periods written into the table. With fractional partials, GEN09 (and its sister GEN19) will write fractionally long periods, but whatever part of the period fits into the table, fits. The rest is, so to speak, outside the table.

Now, Csound doesn't care what you try to do with your table, the GEN functions just produce it to your specification. When eg an oscil unit generator in a Csound orchestra looks up the values in the table, the table will be automatically rescaled, and read through the number of times per second that you have defined, skipping some values, or maybe reading them several times (if you use a high sample rate, a short table and a low frequency - this can be verified by looking at the resultant waveform in a standard soundfile editor; the oscili ugen will interpolate though).

Csound's internal rescaling mechanism is highly efficient, dependent on (standard) computer behaviour, and also the reason why tables MUST be of some power-of-2 length (it only becomes a little quirky when reading sound files into a table, since they tend not to conform to the pow-2 requirement).

If you are looking to use a table for a sine-wave oscillator instrument, you should thus generate only whole-number partials, and then set the pitch of the generated tone in the oscillator unit(s) which read from the table to generate sound. But you could very well use a fractional sine segment for eg panning (use length 0.25, which leaves a quarter of a sinewave inside the table) or for stranger waveforms with discontinuities.

Guard points and length of tables:

As explained above, the size of a ftable is not a musical matter. The guard point may be, however. It is an extra table point beyond the end of the table, which is used when the table reading function interpolates between values. If you give the length of the table as exactly a power of two, the guard point at the end of the table will get the same value as the first point in the table, but if you give the length of the ftable as any power of two plus one, the last value will be held. See the manual entry on score f statements.

Csound ftables are usually considered to have the virtual length 1, meaning one cycle. Indexing a table (a sine wave, or a sound file, or anything else), is done with numbers in the range 0.0 through 0.9999. . . (other numbers are in effect cropped into their fractional part). Since any table index in reality (inside Csound, in the computer's physical memory) is always an integer, the decimal fractions used in Csound orchestras will often index points "between" the real points in the table.

Tables used with oscil and similar opcodes are cycled, so it is a good idea to let the generator function copy the first value to the guard point for them - else there may be a sharp click noise each time the table goes from index 0.9999. . . and back to 0.0 (which is the same as table index 1.0, 2.0 etc). But if you are using the table as a rise or decay shape in fof or pan however, the very last point is not supposed to fade down towards the value of the first point in the table. In those cases you should therefore make the table length a power of two plus one.

(back to contents)

CSOUND VARIABLE TYPES

There are three types of variables which can be used in Csound instruments: i-time, k-rate and a-rate variables. the letters indicate the time or rate of evaluation of the variable value. See the entry on i-, k- and a-rate variables. Here follows an explanation of the reasons behind this differentiation of variables.

For speed reasons, Csound has two internal loops, one at audio rate for generating sound samples (the output sample rate is specified by the variable sr in the orchestra header), and one at a slower control rate, kr.  The slower rate allows the program to use control variables (e.g. envelopes) without spending the time to recalculate them at every sample.

Because the k-rate and a-rate are used for a loop in the program, they must be related to each other so that sr/kr is an integer. This value is called ksmps, and must also be specified in the orchestrea header (NB: this has recently been changed, you can now leave out one of the three values). They should thus satisfy the following equation in whole numbers:

sr = kr * ksmps

Usage examples:

Now well see how these values may be varied for different purposes. First the default settings:

sr = 44100

kr = 4410

ksmps = 10

This means that k-rate variables are updated every ten samples. This might be good if you are eg using k-rate variables for changing pitch over large ranges in an oscil, but it is not really necessary if you are only doing envelopes. For envelopes (and perhaps slow pitch changes), the following should be fine:

sr = 44100

kr = 441

ksmps = 100

Of course, while you are just designing and testing an instrument, you may save even more time by using a lower sample rate:

sr = 22050

kr = 315

ksmps = 70

This will also increase performance if you want to try realtime output.

Here is an extreme example:

sr = 44100

kr = 44100

ksmps = 1

Here kr = sr, meaning that k variables update every sample.  This allows some tricks with opcodes that only work at k-rate (like conditionals).

Arrays or series and some misconfusion:

Lets now clear away a potential misunderstanding, which may actually arise from a passage in the manual. Somebody at one time wanted to talk of "variables that are series." This probably springs from reading the manual entry on the different orchestra statement types. It is mentioned there that "prefixes k or a denote control (scalar) and audio (vector) values..." It should be added: "respectively" (this actually becomes apparent from the list of variable prefixes that follows, but it's still a sloppy formulation).

Now this is informative for programmers, but perhaps less so for others. It refers to the aforementioned loops in the program. Internally, Csound will work through its list of active orchestra instruments at K(ontrol) rate. At each such pass, audio (a-rate) data is generated, k-rate variables are updated (or generated), the list of active instruments is maintained, etc.

Audio rate data is generated in small blocks at each k-rate pass through an instrument. Eg inside an oscil, if sr=44100 and kr=441, then 100 samples will be generated, using the current values of k-rate variables. Such a block of (audio) data is called a vector, or an array in programming parlance. Thus if an operator takes a-rate input, it will use the values from such a data block (vector), rather than one single value, to work out its own a-rate data.

This does relate to Csound users, because sometimes you can get devious "stepping" errors in k-rate variables. Here is a nasty little trap that you would probably not expect:

andx	init	0

andx	 =	andx + 1

aout	tablei	andx, iftable

this would only work if you set sr=kr  (which is not always a bad thing) since the input to the "=" operator is copied and not changed for each ksmps buffer lenght of samples  (to fix substitute the interp operator for the "=")...

(back to contents)

QUESTIONS AND ANSWERS

Q: Has anyone made a tutorial/manual for people like me who are smart, but not MIT students?!?!

A: Csound is basic building blocks.  It is like what is underneath all digital synthesizers.  In order to use it without frustration, you need to learn how synthesizers make sound.  The best suggestion for this task is "The Computer Music Tutorial" by Curtis Roads (MIT Press).  It will set you back $50 but it is very comprehensive.  If you ever take a course in computer music, it will probably be one of the texts.

There is also a book all about Csound coming out in the summer of 1998, The Csound Book: Tutorials in Software Synthesis and Sound Design. MIT Press, edited by Richard Boulanger.

Q: Whats the difference between an opcode and a ugen? Whats a ugen anyway?

A: ugen (or sometimes UG) is short for unit generator. It means the same as opcode, which is short for operator code. Opcodes do the work in Csound instruments to generate and process signals. There are presently over 300 opcodes in Csound. Begin studying now. Try oscil and linseg for a simple start.

Q: Are variables like kamp and kvib named arbitrarily in the manual, that is, can you change the names of these variables and get the same results (kvib to kvibrato, for example)

A: Nasty answer: Why dont you try it? Nice answer: Yes.

Q: I cant get GEN01 to work. Why?

A: You have an old Csound manual, which is missing the last argument (channel). Get the fresh HTML manuals (or this help file), and look it up there.

Q: I can't get linenr to work. Why is this?

A: linenr only works for MIDI.

Q: How can I view or manipulate LPANAL or PVANAL analysis files?

A: Well get to that, er, soon.

Q: How can I do global processing, like reverb, on the output of a number of instruments?

A: See the global reverb example in the Instrument design tutorial in the manual.

Q: I have a long sustained note, and want to add an occasional pitch bend to it at various times (think electric guitar being whammied from time to time). Now I know that I can accomplish this using a suitably long linseg or the like, but is there any way that I can accomplish this in the score rather than the orc. file?

A: Use a second instrument to trigger the bends and a global variable to communicate between the two instruments.  Add this frequency to the base frequency of your instrument.

Something like:

aout	oscil	iamp, ifqc+gkfqc, 1

I think you may want to make the pitch-bending instrument lower numbered than the "guitar" instrument so that everything gets updated on time.

(back to contents)


Addresses
Csound addresses

WWW

The place to start looking for help and documentation is the Csound front page, hosted by MIT Press.

http://mitpress.mit.edu/e-books/csound/frontpage.html

BINARIES

Csound can be picked up by anonymous ftp from the following addresses:

John Fitchs (canonical/semi-official) Csound, based on the original MIT release 3.0 by Barry Vercoe, but with major enhancements and additions:

ftp://ftp.maths.bath.ac.uk/pub/dream/newest

It is mirrored at:

ftp://ftp.musique.umontreal.ca/pub/mirrors/dream/

There are versions for PC, Mac, PowerMac, Linux, Next and Atari.

Csound is usually upgraded several times a year.

Dont use!

Unfortunately there are some old versions hanging around looking like just the thing. Avoid the following:

AXCsound at Bath. This is by Michael Gogins. The version at Bath is old, so if you think it looks attractive, get the file AXCsoundAll.zip from his homepage at:

http://www.pipeline.com/~gogins/

Csound95.zip -- also at Bath. This one is plain old, dont know why its still around. Use the ones mentioned above (in the directory newest).

DOCUMENTATION

The official HTML manuals are maintained by Jean Piche and Peter J Nix. They are available from:

ftp://ftp.maths.bath.ac.uk/pub/dream/documentation/manuals/

ftp://ftp.musique.umontreal.ca/pub/

EXAMPLES

You should get some example files. The best is the ACCCI collection (Amsterdam Catalogue of Csound Computer Instruments), with commented examples.

http://mars.let.uva.nl/gather/accci/index.html

This server seems not to work presently, so try either of these:

ftp://ftp.musique.umontreal.ca/pub/mirrors/accci/index.html

http://wings.buffalo.edu/academic/department/AandL/music/pub/accci/index.html

Hans Mikelson also has several instruments on a web page which you may find interesting:

http://www.werewolf.net/~hljmm/csound/

OTHER CSOUND VERSIONS

There are a few proprietary Csound versions of interest around, notably

Gabriel Maldonado has a version called DirectCsound (an earlier version was called RTsound) which is geared towards realtime MIDI and sound output. Available for PC/Win95, PPC, Linux, SGI etc. Get it from:

http://www.agora.stm.it/G.Maldonado/home2.htm

http://www.agora.stm.it/G.Maldonado/download.htm

http://www.geocities.com/SiliconValley/Way/7041/download.htm

Michael Gogins has built a Win 95 only version with some tools for algorithmic composition. Its called Silence, and is available from:

http://www.pipeline.com/~gogins/

Note that the algorithmic tools part of the program incurs a fee of $100, if anybody but yourself should listen to the music created with it.

Gogins also has a version called ActiveX Csound (or AXCsound) which is Csound as a Windows ActiveX control. Note that the version at Bath may be outdated, so if you think it looks interesting, get it from his page.

ABOUT THIS HELP FILE:

This help file pertains to the canonical/official version available from Bath/Montreal.

File formated and perhaps maintained by rasmus ekman.

The latest version should be available from:

http://hem.passagen.se/rasmuse/Csound.htm

Contact:

rasmuse@hem.passagen.se

about errors and omissions, tutorials, installation notes or other stuff you can provide to put into it, or to get the original RTF format files.


Copyright

Copyright 1986, 1992 by the Massachusetts Institute ofTechnology.

All rights reserved.

Developed by Barry L. Vercoe at the Experimental Music Studio,Media Laboratory, M.I.T., Cambridge, Massachusetts,with partial support from the System Development Foundation and from National Science Foundation Grant # IRI-8704665.

Permission to use, copy, or modify these programs and their documentation for educational and research purposes only and without fee is hereby granted, provided that this copyright and permission notice appear on all copies and supporting documentation.

For any other uses of this software, in original or modified form, including but not limited to distribution in whole or in part, specific prior permission from M.I.T. must beobtained.

M.I.T. makes no representations about the suitability of this software for any purpose.  It is provided "as is" without express or implied warranty.

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

John Fitch

School of Mathematical Sciences

University of Bath

Bath BA2 7AY

England

Tel: +44-1225-826820

FAX: +44-1225-826492

E-mail: jpff@maths.bath.ac.uk

or  J.P.Fitch@bath.ac.uk

(also Codemist Ltd, Tel/FAX: +44-1225-837430)

The mixer, graphing and SoundBlaster support are probably my copyright, and I hereby give permission to use, copy, or modify this code for any purpose whatsoever. I would like my name to remain in there, but I do not insist.

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

Robin Whittle

Modifications and new code for tableread/write ugens and the zak system provided by Robin Whittle are provided without warranty etc. etc.

They are copyright 1995 and 1996 Robin Whittle

Use of this code for non-commercial software products is permitted, provided the source code is made freely available according to the principles of the Free Software Foundation, with this copyright notice attached.

Carefully considered and well written bug reports and suggestions are welcome at :

firstpr@ozemail.com.au

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

 Gabriel Maldonado Realtime MIDI Features for WIN95

Warning!

This program is provided without warranty of any kind.

Use it at your own risk.

The modifications for Midi Input and console text line additions are my copyright.

An optional donation of any entity to the author would be very appreciated.

My new UGs sources are public domain.

I give permission to use, copy, or modify my UGs code for any purpose. I would like my name to remain in there.

Gabriel Maldonado

via di Donna Olimpia 166

00152 Roma ITALIA

g.maldonado@agora.stm.it


ACCCI Examples - contents

This is included just to whet your appetite. Most examples come with a text file containing explanations and reading tips. Get it. Youll find the web address among the other Csound addresses.

Main Group 01: Simple Synthesis

01   Basic Instrument

10   LFO on Amplitude

11   LFO and RANDI on Amplitude

12   RANDI on Amplitude

40   LFO on Frequency

41   LFO on Frequency, RANDI Replaces Envelope

42   LFO on Frequency, Vibrato Effect

Main Group 02: Additive Synthesis, Same Units

01   Basic Instrument

13   Linear Envelope

40   LFO on Frequency

41   RANDI on Frequency

42   Frequency Transfer Functions

43   Extremely Small Frequency Offsets

44   Exponential Frequency Control

Main Group 03: Additive Synthesis, Different Units

01   Noise/Inharmonics/Fundamental

05   Noise/Inharmonics 1/Inharmonics 2

40   LFOs Modulate Frequency in Parallel

Main Group 10: Random Number Generation

01   RAND

02   RANDI

03   RANDH

Main Group 15: Karplus/Strong Algorithm

01   Pluck Decay Method 1: Simple Averaging

Main Group 20: FM Synthesis

01   Basic Design for FM Synthesis

10   Dynamic Spectral Evolution

20   Double Carrier, Dynamic Spectrum

70   Complex Wave Modulation

Main Group 33: Amplitude Modulation

01   Basic Ring Modulation with Multiplier

10   Ring Modulation of External Soundfiles

50   "Classical" Amplitude Modulation

Main Group 40: Waveshaping

01   Function Table Implementation

02   With Conditional Branch for Envelope

03   Inline Polynomial Implementation

60   Chebychev Coefficients Implementation

Main Group 43: (G)Buzz

01   Basic Instrument

21   Kratio Envelope

Main Group 45: FOF Synthesis

01   FOF Tutorial

33   Summed FOF Generators

Main Group 50: Subtractive Synthesis

01   Basic Design RESON

09   Continuous Control of Bandwidth bw

11   Continuous Control of cfq and bw

51   Spectrum Proportional to Amplitude

71   Two Constant Formant Regions

Main Group 60: Phase Vocoder

The MIT Media Lab Phase Vocoder

01   Testfiles pvanal

Testing Procedure - A Sample Session at the Terminal From Phase to Frequency

22   Ktimpnt Variations

23   Kfmod Variations

Main Group 70: Granular Synthesis

01   Sine Wave as Granular Waveform

02   External Soundfile for Granular Waveforms

Main Group 80: Other Instruments

01   Hybrid Instruments

Main Group 88: Wave Table Generation

01   Basic Design


Vocal formants table
Table of vocal formants

soprano a	 f1	 f2	 f3	 f4	 f5

freq (Hz)	800	1150	2900	3900	4950

amp (dB)	0	-6	-32	-20	-50

bw (Hz)	80	90	120	130	140

soprano e 	 f1	 f2	 f3	 f4	 f5

freq (Hz)	350	2000	2800	3600	4950

amp (dB)	0	-20	-15	-40	-56

bw (Hz)	60	100	120	150	200

soprano i	 f1	 f2	 f3	 f4	 f5

freq (Hz)	270	2140	2950	3900	4950

amp (dB)	0	-12	-26	-26	-44

bw (Hz)	60	90	100	120	120

soprano o 	 f1	 f2	 f3	 f4	 f5

freq (Hz)	450	800	2830	3800	4950

amp (dB)	0	-11	-22	-22	-50

bw (Hz)	70	80	100	130	135

soprano u	 f1	 f2	 f3	 f4	 f5

freq (Hz)	325	700	2700	3800	4950

amp (dB)	0	-16	-35	-40	-60

bw (Hz)	50	60	170	180	200

alto a	 f1	 f2	 f3	 f4	 f5

freq (Hz)	800	1150	2800	3500	4950

amp (dB)	0	-4	-20	-36	-60

bw (Hz)	80	90	120	130	140

alto e	 f1	 f2	 f3	 f4	 f5

freq (Hz)	400	1600	2700	3300	4950

amp (dB)	0	-24	-30	-35	-60

bw (Hz)	60	80	120	150	200

alto i	 f1	 f2	 f3	 f4	 f5

freq (Hz)	350	1700	2700	3700	4950

amp (dB)	0	-20	-30	-36	-60

bw (Hz)	50 	100	120 	150	200

alto o	 f1	 f2	 f3	 f4	 f5

freq (Hz)	450	800	2830	3500	4950

amp (dB)	0	-9	-16	-28	-55

bw (Hz)	70	80	100	130	135

alto u	 f1	 f2	 f3	 f4	 f5

freq (Hz)	325	700	2530	3500	4950

amp (dB)	0	-12	-30	-40	-64

bw (Hz)	50	60	170	180	200

countertenor a	 f1	 f2	 f3	 f4	 f5

freq (Hz)	660	1120	2750	3000	3350

amp (dB)	0	-6	-23	-24	-38

bw (Hz)	80	90	120	130	140

countertenor e	 f1	 f2	 f3	 f4	 f5

freq (Hz)	440	1800	2700	3000	3300

amp (dB)	0	-14	-18	-20	-20

bw (Hz)	70	80	100	120	120

countertenor i	 f1	 f2	 f3	 f4	 f5

freq (Hz)	270	1850	2900	3350	3590

amp (dB)	0	-24	-24	-36	-36

bw (Hz)	40	90	100	120	120

countertenor o	 f1	 f2	 f3	 f4	 f5

freq (Hz)	430	820	2700	3000	3300

amp (dB)	0	-10	-26	-22	-34

bw (Hz)	40	80	100	120	120

countertenor u	 f1	 f2	 f3	 f4	 f5

freq (Hz)	370	630	2750	3000	3400

amp (dB)	0	-20	-23	-30	-34

bw (Hz)	40	60 	100	120	120

tenor a	 f1	 f2	 f3	 f4	 f5

freq (Hz)	650	1080	2650	2900	3250

amp (dB)	0	-6	-7	-8	-22

bw (Hz)	80	90	120	130	140

tenor e	 f1	 f2	 f3	 f4	 f5

freq (Hz)	400	1700	2600	3200	3580

amp (dB)	0	-14	-12	-14	-20

bw (Hz)	70	80	100	120	120

tenor i	 f1	 f2	 f3	 f4	 f5

freq (Hz)	290	1870	2800	3250	3540

amp (dB)	0	-15	-18	-20	-30

bw (Hz)	40	90	100	120	120

tenor o	 f1	 f2	 f3	 f4	 f5

freq (Hz)	400	800	2600	2800	3000

amp (dB)	0	-10	-12	-12	-26

bw (Hz)	40	80	100	120	120

tenor u	 f1	 f2	 f3	 f4	 f5

freq (Hz)	350	600	2700	2900	3300

amp (dB)	0	-20	-17	-14	-26

bw (Hz)	40	60	100	120	120

bass a	 f1	 f2	 f3	 f4	 f5

freq (Hz)	600	1040	2250	2450	2750

amp (dB)	0	-7	-9	-9	-20

bw (Hz)	60	70	110	120	130

bass e	 f1	 f2	 f3	 f4	 f5

freq (Hz)	400	1620	2400	2800	3100

amp (dB)	0	-12	-9	-12	-18

bw (Hz)	40	80	100	120	120

bass i	 f1	 f2	 f3	 f4	 f5

freq (Hz)	250	1750	2600	3050	3340

amp (dB)	0	-30	-16	-22	-28

bw (Hz)	60	90	100	120	120

bass o	 f1	 f2	 f3	 f4	 f5

freq (Hz)	400	750	2400	2600	2900

amp (dB)	0	-11	-21	-20	-40

bw (Hz)	40	80	100	120	120

bass u	 f1	 f2	 f3	 f4	 f5

freq (Hz)	350	600	2400	2675	2950

amp (dB)	0	-20	-32	-28	-36

bw (Hz)	40	80	100	120	120


ïº_Contents: Csound manual top (contents & preface); Csound introduction; Csound nomenclature; The Csound command Line, New features in orchestra language, New features  in Score language; Orchestra statement types; Directories & files; Constants & variables; Orchestra header statements; Csound standard numeric score; Preprocessing of standard num scores; Score statements f, i, a, t, s, e (individual entries);


Csound manual
CSOUND MANUAL - Contents & Preface

General Overview:

Preface

Introduction

The Csound Orchestra Language:

Recent changes to the orchestra language

Orchestra Statement Types

The Orchestra Header Statements

Instrument Block Statements

Constants and Variables

The Csound Score Language:

Recent changes to the score language

The Csound Standard Numeric Score

Preprocessing Of Standard Scores

Score Statement Types

Function table generators (GENs)

The Score Translator (SCOT)

Running Csound:

Getting started

The Csound Command Line

Realtime support

Directories and Files

Tutorials:

Some Questions and Answers

Instrument Design Tutorial

Fof tutorial

Add your own modules to Csound (Advanced)

PREFACE TO THE 1992 MIT RELEASE

Realizing music by digital computer involves synthesizing audio signals with discrete points or samples that are representative of continuous waveforms. There are several ways of doing this, each affording a different manner of control. Direct synthesis generates waveforms by sampling a stored function representing a single cycle; additive synthesis generates the many partials of a complex tone, each with its own loudness envelope; subtractive synthesis begins with a complex tone and filters it. Non-linear synthesis uses frequency modulation and waveshaping to give simple signals complex characteristics, while sampling and storage of natural sound allows it to be used at will.

Since comprehensive moment-by-moment specification of sound can be tedious, control is gained in two ways: 1) from the instruments in an orchestra, and 2) from the events within a score. An orchestra is really a computer program that can produce sound, while a score is a body of data which that program can react to. Whether a rise-time characteristic is a fixed constant in an instrument, or a variable of each note in the score, depends on how the user wants to control it.

The instruments in a Csound orchestra are defined in a simple syntax that invokes complex audio processing routines. A score passed to this orchestra contains numerically coded pitch and control information, in standard numeric score format. Although many users are content with this format, higher level score processing languages are often convenient.

The programs making up the Csound system have a long history of development, beginning with the Music 4 program written at Bell Telephone Laboratories in the early 1960's by Max Mathews. That initiated the stored table concept and much of the terminology that has since enabled computer music researchers to communicate. Valuable additions were made at Princeton by the late Godfrey Winham in Music 4B; my own Music 360 (1968) was very indebted to his work. With Music 11 (1973) I took a different tack: the two distinct networks of control and audio signal processing stemmed from my intensive involvement in the preceding years in hardware synthesizer concepts and design. This division has been retained in Csound.

Because it is written entirely in C, Csound is easily installed on any machine running Unix or C. At MIT it runs on VAX/DECstations under Ultrix 4.2, on SUNs under OS 4.1, SGIs under 4.1, and on the Macintosh under ThinkC 4.0. With this single language for audio signal processing, users move easily from machine to machine.

The 1991 version included many new features. I am indebted to others for the contribution of the phase vocoder and FOF synthesis modules. That release also charted a new direction with the addition of a spectral data type, holding much promise for future development. The 1992 release is even more significant for its addition of MIDI converter and control units, enabling Csound to be run from MIDI score-files and from external MIDI keyboards. Since the newest RISC processors bring to computer music an order of magnitude more speed than did those on which it was born, researchers and composers now have access to workstations on which realtime software synthesis with sensing and control is now a reality. This is perhaps the single most important development for people working in the field. This new Csound is designed to take maximum advantage of realtime audio processing, and to encourage interactive experiments in this exciting new domain.

Barry Vercoe


CSOUND INTRODUCTION

The purpose of this section is to expose the reader to the fundamentals of designing and using computer music instruments in Csound. Only a small portion of the language will be covered here, sufficient to implement some simple instrument examples.  The sections in this primary text are arranged as a Reference manual (not a tutorial), since that is the form the user will eventually find most helpful when inventing instruments. Once the basic concepts are grasped from this beginning tutorial, the reader might let himself into the remainder of the text by locating the information presented here in the Reference entries that follow.

THE ORCHESTRA FILE

Csound runs from two basic files: an orchestra file and a score file. The orchestra file is a set of instruments that tell the computer how to synthesize sound; the score file tells the computer when. An instrument is a collection of modular statements which either generate or modify a signal; signals are represented by symbols, which can be "patched" from one module to another. For example, the following two statements will generate a 440 Hz sine tone and send it to an output channel:

asig oscil     10000, 440, 1

   out  asig

The first line sets up an oscillator whose controlling inputs are an amplitude of 10000, a frequency of 440 Hz, and a waveform number, and whose output is the audio signal asig. The second line takes the signal asig and sends it to an (implicit) output channel. The two may be encased in another pair of statements that identify the instrument as a whole:

instr 1

asig oscil     10000, 440, 1

out  asig

endin

In general, an orchestra statement in Csound consists of an action symbol followed by a set of input variables and preceded by a result symbol. Its action is to process the inputs and deposit the result where told. The meaning of the input variables depends on the action requested. The 10000 above is interpreted as an amplitude value because it occupies the first input slot of an oscil unit; 440 signifies a frequency in Hertz because that is how an oscil unit interprets its second input argument; the waveform number is taken to point indirectly to a stored function table, and before we invoke this instrument in a score we must fill function table #1 with some waveform.

The output of Csound computation is not a real audio signal, but a stream of numbers which describe such a signal. When written onto a sound file these can later be converted to sound by an independent program; for now, we will think of variables such as asig as tangible audio signals.

Let us now add some extra features to this instrument. First, we will allow the pitch of the tone to be defined as a parameter in the score. Score parameters can be represented by orchestra variables which take on their different values on successive notes. These variables are named sequentially: p1, p2, p3, ...  The first three have a fixed meaning (see the Score File below), while the remainder are assignable by the user. Those of significance here are:

p3 - duration of the current note (always in seconds).

p5 - pitch of the current note (in units agreed upon by  score and orchestra).

Thus in

asig oscil     10000, p5, 1

the oscillator will take its pitch (presumably in cps) from score parameter 5.

If the score had forwarded pitch values in units other than cycles-per-second (Hertz), then these must first be converted.  One convenient score encoding, for instance, combines pitch class representation (00 for C, 01 for C#, 02 for D, ... 11 for B) with octave representation (8. for middle C, 9. for the C above, etc.) to give pitch values such as 8.00, 9.03, 7.11. The expression

cpspch(8.09)

will convert the pitch A (above middle C) to its cps equivalent (440 Hz). Likewise, the expression

cpspch(p5)

will first read a value from p5, then convert it from octave.pitch-class units to cps. This expression could be imbedded in our orchestra statement as

asig oscil     10000, cpspch(p5), 1

to give the score-controlled frequency we sought.

Next, suppose we want to shape the amplitude of our tone with a linear rise from 0 to 10000. This can be done with a new orchestra statement

amp  line 0, p3, 10000

Here, amp will take on values that move from 0 to 10000 over time p3 (the duration of the note in seconds). The instrument will then become

instr     1

amp  line 0, p3, 10000

asig oscil     amp, cpspch(p5), 1

 	    out  asig

endin

The signal amp is not something we would expect to listen to directly. It is really a variable whose purpose is to control the amplitude of the audio oscillator. Although audio output requires fine resolution in time for good fidelity, a controlling signal often does not need that much resolution. We could use another kind of signal for this amplitude control

kamp line 0, p3, 10000

in which the result is a new kind of signal. Signal names up to this point have always begun with the letter a (signifying an audio signal); this one begins with k (for control). Control signals are identical to audio signals, differing only in their resolution in time. A control signal changes its value less often than an audio signal, and is thus faster to generate.  Using one of these, our instrument would then become

instr  1

kamp line 0, p3, 10000

asig oscil     kamp, cpspch(p5), 1

     out  asig

endin

This would likely be indistinguishable in sound from the first version, but would run a little faster. In general, instruments take constants and parameter values, and use calculations and signal processing to move first towards the generation of control signals, then finally audio signals. Remembering this flow will help you write efficient instruments with faster execution times.

We are now ready to create our first orchestra file. Type in the following orchestra using the system editor, and name it "intro.orc".

sr = 20000	; audio sampling rate is 20  kHz

kr = 500	; control rate is 500 Hz

ksmps = 40	; number of samples in a  control period (sr/kr)

nchnls = 1	; number of channels of audio  output

instr  1

kctrl     line 0, p3, 10000	; amplitude envelope

asig oscil     kctrl, cpspch(p5), 1	; audio oscillator

      out  asig	; send signal to channel 1

endin

It is seen that comments may follow a semi-colon, and extend to the end of a line. There can also be blank lines, or lines with just a comment. Once you have saved your orchestra file on disk, we can next consider the score file that will drive it.

THE SCORE FILE

The purpose of the score is to tell the instruments when to play and with what parameter values. The score has a different syntax from that of the orchestra, but similarly permits one statement per line and comments after a semicolon. The first character of a score statement is an opcode, determining an action request; the remaining data consists of numeric parameter fields (pfields) to be used by that action.

Suppose we want a sine-tone generator to play a pentatonic scale starting at C-sharp above middle-C, with notes of 1/2 second duration. We would create the following score:

;  a sine wave function table

f1 0 256 10 1

;  a pentatonic scale

i1    0   .5   0.  8.01

i1   .5    .    .    8.03

i1 1.0    .    .    8.06

i1 1.5    .    .    8.08

i1 2.0    .    .    8.10

e

The first statement creates a stored sine table. The protocol for generating wave tables is simple but powerful. Lines with opcode f interpret their parameter fields as follows:

p1 - function table number being created

p2 - creation time, or time at which the table becomes readable

p3 - table size (number of points), which must be a power of two or one greater

p4 - generating subroutine, chosen from a prescribed list.

Here the value 10 in p4 indicates a request for subroutine GEN10 to fill the table. GEN10 mixes harmonic sinusoids in phase, with relative strengths of consecutive partials given by the succeeding parameter fields. Our score requests just a single sinusoid. An alternative statement:

f1 0 256 10 1 0 3

would produce one cycle of a waveform with a third harmonic three times as strong as the first.

The i statements, or note statements, will invoke the p1 instrument at time p2, then turn it off after p3 seconds; it will pass all of its p-fields to that instrument. Individual score parameters are separated by any number of spaces or tabs; neat formatting of parameters in columns is nice but unnecessary. The dots in p-fields 3 and 4 of the last four notes invoke a carry feature, in which values are simply copied from the immediately preceding note of the same instrument. A score normally ends with an e statement.

The unit of time in a Csound score is the beat. In the absence of a Tempo statement, one beat takes one second. To double the speed of the pentatonic scale in the above score, we could either modify p2 and p3 for all the notes in the score, or simply insert the line

t 0 120

to specify a tempo of 120 beats per minute from beat 0.

Two more points should be noted. First, neither the f-statements nor the i-statements need be typed in time order; Csound will sort the score automatically before use. Second, it is permissible to play more than one note at a time with a single instrument. To play the same notes as a three-second pentatonic chord we would create the following:

;    a sine wave function

f1 0 256 10 1

;    five notes at once

   i1   0    3    0    8.01

   i1   0    .     .    8.03

   i1   0    .     .    8.06

   i1   0    .     .    8.08

   i1   0    .     .    8.10

e

Now go into the editor once more and create your own score file.  Name it "intro.sco". You may at this point want to read about how to invoke Csound and the Csound command line flags to perform your Csound score.

Suppose we next wished to introduce a small vibrato, whose rate is 1/50 the frequency of the note (i.e. A440 is to have a vibrato rate of 8.8 Hz.). To do this we will generate a control signal using a second oscillator, then add this signal to the basic frequency derived from p5. This might result in the instrument

instr   1

kamp line      0, p3, 10000

kvib oscil     2.75, cpspch(p5)/50, 1

a1   oscil     kamp, cpspch(p5)+kvib, 1

     out       a1

endin

Here there are two control signals, one controlling the amplitude and the other modifying the basic pitch of the audio oscillator.  For small vibratos, this instrument is quite practical; however it does contain a misconception worth noting. This scheme has added a sine wave deviation to the cps value of an audio oscillator. The value 2.75 determines the width of vibrato in cps, and will cause an A440 to be modified about one-tenth of one semitone in each direction (1/160 of the frequency in cps). In reality, a cps deviation produces a different musical interval above than it does below. To see this, consider an exaggerated deviation of 220 cps, which would extend a perfect 5th above A440 but a whole octave below. To be more correct, we should first convert p5 into a true decimal octave (not cps), so that an interval deviation above is equivalent to that below. In general, pitch modification is best done in true octave units rather than pitch-class or cps units, and there exists a group of pitch converters to make this task easier. The modified instrument would be

instr   1

ioct     =         octpch(p5)

kamp  line      0, p3, 10000

kvib    oscil     1/120, cpspch(p5)/50, 1

asig    oscil     kamp, cpsoct(ioct+kvib), 1

     out       asig

endin

This instrument is seen to use a third type of orchestra variable, an i-variable. The variable ioct receives its value at an initialization pass through the instrument, and does not change during the lifespan of this note. There may be many such init time calculations in an instrument. As each note in a score is encountered, the event space is allocated and the instrument is initialized by a special pre-performance pass. i-variables receive their values at this time, and any other expressions involving just constants and i-variables are evaluated. At this time also, modules such as line will set up their target values (such as beginning and end points of the line), and units such as oscil will do phase setup and other bookkeeping in preparation for performance. A full description of init-time and performance-time activities, however, must be deferred to a general consideration of the orchestra syntax.

Read more about the Csound numeric score


Csound command line
THE CSOUND COMMAND LINE

See also Csound command line flags and Csound unified file format

To request your orchestra to perform your score, type the command

csound  intro.orc  intro.sco

The resulting performance will take place in three phases:

1)	sort the score file into chronological order.  If score syntax errors are encountered they will be reported on your console. This is done by Scot, the score sorting utility.

2)	translate and load your orchestra.  The console will  signal the start of translating each instr block, and will report  any errors.  If the error messages are not immediately  meaningful, translate again with the verbose flag turned on:

csound  -v  intro.orc  intro.sco

1)	fill the wave tables and perform the score.  Information about this performance will be displayed throughout in messages  resembling

B  4.000 .. 6.000   T 3.000  TT  3.000  M    7929.    7929.

A message of this form will appear for every event in your score.  An event is defined as any change of state (as when a new note begins or an old one ends). The first two numbers refer to beats in your original score, and they delimit the current segment of sound synthesis between successive events (e.g. from beat 4 to beat 6). The second beat value is next restated in real seconds of time, and reflects the tempo of the score. That is followed by the Total Time elapsed for all sections of the score so far.  The last values on the line show the maximum amplitude of the audio signal, measured over just this segment of time, and reported separately for each channel.

Console messages are printed to assist you in following the orchestra's handling of your score. You should aim at becoming an intelligent reader of your console reports. When you begin working with longer scores and your instruments no longer cause surprises, the above detail may be excessive. You can elect to receive abbreviated messages using the -m option of the Csound command.

When your performance goes to completion, it will have created a sound file named test in your soundfile directory. If you happen to have a command line soundfile player called play you can now listen to your sound file by typing

play test

If your machine is fast enough, and your Csound module includes user access to the audio output device, you can hear your sound as it is being synthesized by using a command like

csound  -o  devaudio  intro.orc  intro.sco

See further notes about realtime support on Windows machines.


New Features in the Orchestra Language

By John ffitch April 1998  (New in Csound 3.48)

In version 3.48 macros (below) and #include statements have been incorporated into the orchestra language.  They are similar to the new features in the score language, but independent.

SIMPLE MACROS

Macros are textual replacements which are made in the orchestra as it is being read.  The macro system in Csound is a very simple one, and uses two special characters to indicate the presence of macros, the characters # and $.

To define a macro one uses the # character:

#define NAME  # replacement text#

The name of the macro can be any made from letters, upper or lower case, or digits (as of Csound 3.484 - digits were not allowed in the first version).  The replacement text is any character string (not containing a #) and can extend over more than one line. The replacement text is enclosed within the # characters, which ensures that additional characters are not inadvertently captured.

To use a macro the name is used following a $ character.  The name is terminated by the next non-letter.  If the need is to have the name without a space a period can be used to terminate the name, which is ignored.  The string $NAME. is replaced by the replacement text from the definition.  Of course the replacement text can also include macro calls.

If a macro is not required any longer it can be undefined with

#undef NAME

Example:

#define REVERB #ga = ga+a1

out a1#

instr 1

  a1	oscil

  $REVERB.

endin

instr 2

  a1	repluck

  $REVERB.

endin

This will get expanded before compilation into

instr 1

  a1	oscil

  ga = ga+a1

out a1

endin

instr 2

  a1	repluck

  ga = ga+a1

out a1

endin

This can save typing, and in the case, for example, of a general effects processing sequence, it can lead to a coherent and consistent use.

This form is limiting in at least having the variable names fixed.  An alternative would be to use the second form of the macro, described below.

NOTE: some care is needed with textual macros as they can sometimes do strange things.  They take no notice of any meaning, and so spaces are significant, which is why the definition has the replacement text surrounded by # characters, unlike that in the C programming language.

Used carefully simply macros are a powerful concept, but they can be abused.

ADVANCED MACROS

Macros can also be defined with parameters.  This can be used in more complex situations.  In order to define a macro with arguments the syntax is

#define NAME(A#B#C)  #replacement text#

Within the replacement text the arguments can be substituted by the form $A.  In fact the implementation defines the arguments as simple macros.  There may be up to 5 arguments, and the names can be any choice of letters.  Case is significant in macro names.

In use the argument form for example

#define REVERB(A) #ga = ga+$A.

out $A.#

instr 1

  a1	oscil

  $REVERB(a1)

endin

instr 2

  a2	repluck

  $REVERB(a2)

endin

which expands to:

instr 1

  a1	oscil

  ga = ga+a1

out a1

endin

instr 2

  a2	repluck

  ga = ga+a2

out a2

endin

As with the simple macros, these macros can also be undefined with

#undef NAME

#include STATEMENT

It is sometimes convenient to have the orchestra arranged in a number of files, for example with each instrument in a separate file.  This style is supported by the #include facility which is part of the macro system.  A line containing the text

#include :filename:

where the character : can be replaced by any suitable character.  For most uses the double quote symbol will probably be the most convenient.

This takes input from the named file until it ends, when input reverts to the previous input.  There is currently a limit of 20 on the depth of included files and macros.

Another suggested use of #include would be to define a set of macros which are part of the composer's style. An extreme form would be to have each instrument defines as a macro, with the instrument number as a parameter.  Then an entire orchestra could be constructed from a number of #include statements followed by macro calls.

#include :clarinet:

#include :flute:

#include :bassoon:

$CLARINET(1)

$FLUTE(2)

$BASSOON(3)

It must be stressed that these changes are at the textual level and so take no cognisance of any meaning.


New Features in the Score Language

By John ffitch April 1998  (New in Csound 3.48)

The 3.48 version of Csound introduces a number of changes in the language in which scores are presented to the system.  These are all upward compatible, and so do not require any changes in existing scores.  These changes should allow for simpler score writing, and provide an elementary alternative to the full score-generation systems.  Similar changes have been made in the orchestra language.

Contents:

Simple macros (below)

Macros with arguments

#include statement

r statement (repeat sections)

Expression evaluation

SIMPLE MACROS

Macros are textual replacements which are made in the score as it is being read.  The macro system in Csound is a very simple one, and uses two special characters to indicate the presence of macros, the characters # and $.

To define a macro one uses the # character:

#define NAME  # replacement text#

The name of the macro can be any made from letters, upper or lower case, or digits (as of Csound 3.484 - digits were not allowed in the first version).  The replacement text is any character string (not containing a #) and can extend over more than one line. The replacement text is enclosed within the # characters, which ensures that additional characters are not inadvertently captured.

To use a macro the name is used following a $ character.  The name is terminated by the next non-letter.  If the need is to have the name without a space a period can be used to terminate the name, which is  ignored.  The string $NAME. is replaced by the replacement text from the definition.  Of course the replacement text can also include macro calls.

If a macro is not required any longer it can be undefined with

#undef NAME

Example:

If a note-event has a set of p-fields which are repeated

#define ARGS # 1.01 2.33 138#

i1 0 1 8.00	1000 $ARGS

i1 0 1 8.01 	1500 $ARGS

i1 0 1 8.02	1200 $ARGS

i1 0 1 8.03	1000 $ARGS

This will get expanded before sorting into

i1 0 1 8.00	1000 1.01 2.33 138

i1 0 1 8.01 	1500 1.01 2.33 138

i1 0 1 8.02	1200 1.01 2.33 138

i1 0 1 8.03	1000 1.01 2.33 138

This can save typing and is easier to change if for example one needed to change one of the parameters.  If there were two sets of p-fields one could have a second macro (there is no real limit on the number of macros one can define).

#define ARGS1 # 1.01 2.33 138#

#define ARGS2 # 1.41 10.33 1.00#

i1 0 1 8.00	1000 $ARGS1

i1 0 1 8.01 	1500 $ARGS2

i1 0 1 8.02	1200 $ARGS1

i1 0 1 8.03	1000 $ARGS2

An alternative would be to use the second form of the macro, described below.

NOTE: Some care is needed with textual macros as they can sometimes do strange things.  They take no notice of any meaning, and so spaces are significant, which is why the definition has the replacement text surrounded by # characters, unlike that in the C programming language. Used carefully simple macros are a powerful concept, but they can be abused.

ADVANCED MACROS

Macros can also be defined with parameters.  This can be used in more complex situations.  In order to define a macro with arguments the syntax is

#define NAME(A#B#C)  #replacement text#

Within the replacement text the arguments can be substituted by the form $A.  In fact the implementation defines the arguments as simple macros.  There may be up to 5 arguments, and the names can be any choice of letters.  Case is significant in macro names.

In use the argument form for example

#define ARG(A) # 2.345   1.03   $A   234.9#

i1 0 1 8.00 1000 $ARG(2.0)

i1  + 1 8.01 1200 $ARG(3.0)

which expands to

i1 0 1 8.00 1000 2.345   1.03   2.0   234.9

i1  + 1 8.01 1200 2.345   1.03   3.0   234.9

As with the simple macros, these macros can also be undefined with

#undef NAME

Another Use For Macros

When writing a complex score it is sometimes all too easy to forget to what the various instrument numbers refer.  One can use macros to give names to the numbers.  For example

#define Flute	#i1#

#define Whoop	#i2#

$Flute.	0	10	4000	440

$Whoop.	5	1

#include STATEMENT

It is sometimes convenient to have the score in more than one file. This use is supported by the facility which is part of the macro system.  A line containing the text

#include :filename:

where the character : can be replaced by any suitable character.  For most uses the double quote symbol will probably be the most convenient.

This takes input from the named file until it ends, when input reverts to the previous input.  There is currently a limit of 20 on the depth of included files and macros.

A suggested use of #include would be to define a set of macros which are part of the composer's style.  It could also be used to provide repeated sections.

s

#include :section1:

;; Repeat that

s

#include :section1:

However there is an alternative way of doing repeats, described below.

r statement - REPEATED SECTIONS

Sections can be repeated by using #include or by editing the text.  An alternative is the new r directive in the score language.

r3	NN

starts a repeated section, which lasts until the next s, r or e directive.  The section is repeated 3 times in this example.  In order that the sections may be more flexible than simple editing, the macro NN is given the value of 1 for the first time through the section, 2 for the second, and 3 for the third.  This can be used to change p-field parameters, or indeed ignored.

Warning: because of serious problems of interaction with macro expansion, sections must start and end in the same file, and not in a macro.

EVALUATION OF EXPRESSIONS

In earlier versions of Csound the numbers presented in a score were used as given.  There are occasions when some simple evaluation would be easier.  This need is increased when there are macros.  To assist in this area the syntax of an arithmetic expressions within square brackets [ ] has been introduced.  Expressions built from the operations +, -, *, and / are allowed, together with grouping with parentheses ( ).

As of Csound 3.52, the remainder ('%') and power ('^') operators are also allowed.

The expressions can include numbers, and naturally macros whose values are numeric or arithmetic strings.  All calculations are made in floating point numbers.  Note that unary minus is not yet supported.

Example:

r3	CNT

i1	0	[0.3*$CNT.]

i1	+	[($CNT./3)+0.2]

e

As the three copies of the section have the macro $CNT. with the different values of 1, 2 and 3, this expands to

s

i1	0	0.3

i1	0.3	0.533333

s

i1	0	0.6

i1	0.6	0.866667

s

i1	0	0.9

i1	0.9	1.2

e

This is an extreme form, but the evaluation system can be used to ensure that repeated sections are subtly different.


Unified file format
Unified .csd file format

(New in Csound 3.50)

.csd is the extension of a file type introduced by Michael Gogins, which include the orchestra, the score and the command line flags in a single text file. It has now also been fitted to canonical Csound. The specifications follow.

Also, if a file .csoundrc exists, it is read to set command-line parameters first, which can be overridden.  It used the .csd form described below, so options are written as on the command line, with optional line breaks at appropriate places.  It however does not set orc/sco names (as far as i can understand it -jffitch).

As of Csound 3.51, comments (beginning with semicolon or # character) can be used in .csoundrc or in the <CsOptions> part of a .csd file. Comments can also start where an option is expected.

Finally, .csd project files can also be used with Winsound : Enter the file name in the orchestra field of the main dialog, and leave the score file field empty.

Order of precedence

As you see, there are now three places (and in some cases four) where options for Csound performance may be set. They are processed in the following order:

1) .csoundrc file

2) Command line

3) <CsOptions> tag in a .csd file

4) Orchestra header (for sr, kr, ksmps, nchnls, massign).

The last assignment of an option will override any earlier ones.

DESCRIPTION

The following example is a "csd" text file template. The format of .csd files follows the same principles as SGML, XML, or HTML. Each section of data is prefaced by a start (<...>) tag and finished with an end (</...>) tag, and sections can be nested hierarchically.

The Csound tags (boldface) are as follows, with explanatory comments (italics) and sample data:

Comments

As of Csound 3.51, lines starting with a semicolon, or with the character '#' in .csoundrc or in the <CsOptions> part of a .csd file are treated as comments.  Comments can also start where an option is expected.

<CsoundSynthesizer>

; Csound structured data file.

<CsOptions>

; Command-line options

-W   # (this is also treated as a comment)

</CsOptions>

<CsInstruments>

; Orchestra statements.

sr = 44100

kr = 441

ksmps = 100

nchnls = 2

; Instrument definitions.

; The first comment following on the same line as an instrument number is the name of the instrument.

instr 1 ;Toot1

endin

instr 2 ;Toot2

endin

</CsInstruments>

<CsScore>

; Standard Csound function ("f") statements, note ("i") statements, or comments (";").

f 1 2 3

i 1 2 3 4

</CsScore>

</CsoundSynthesizer>


ORCHESTRA STATEMENT TYPES

Contents:

Csound nomenclature

The ORC File

Syntax of the Orchestra

Labels

Expressions

Csound nomenclature

In Csound there are nine statement types, each of which provides a heading for its descriptive section:

orchestra header statements

instrument block statements

assignment statements

signal generator statements

signal modifier statements

signal display statements

program control statements (jumps & reinits)

soundfile access statements

duration control statements

Throughout this document, opcodes are indicated in boldface and their argument and result mnemonics, when mentioned in the text, are given in italics. Argument names are generally mnemonic (amp, phs), and the result is denoted the letter r. Both are preceded by a type qualifier i, k, a or x (e.g. kamp, iphs, ar). The prefix i denotes scalar values valid at note init time; prefixes k or a denote control (scalar) and audio (vector) values, modified and referenced continuously throughout performance (i.e. at every control period while the instrument is active). Arguments are used at the prefix-listed times; results are created at their listed times, then remain available for use as inputs elsewhere. The validity of inputs is defined by the following:

arguments with prefix i must be valid at Init time;

arguments with prefix k can be either control or init values (which remain valid);

arguments with prefix a must be vector inputs;

arguments with prefix x may be either vector or scalar (the compiler will distinguish).

See further i-, k- and a-rate.

All arguments, unless otherwise stated, can be expressions whose results conform to the above. Most opcodes (such as linen and oscil) can be used in more than one mode, which one being determined by the prefix of the result symbol.

THE ORC FILE

An orchestra program in Csound is comprised of orchestra header statements which set various global parameters, followed by a number of instrument blocks representing different instrument types. An instrument block, in turn, is comprised of ordinary statements that set values, control the logical flow, or invoke the various signal processing subroutines that lead to audio output.

An orchestra header statement operates once only, at orchestra setup time. It is most commonly an assignment of some value to a global reserved symbol, e.g. sr = 20000. All orchestra header statements belong to a pseudo instrument 0, an init pass of which is run prior to all other instruments at score time 0. Any ordinary statement can serve as an orchestra header statement, eg. gifreq = cpspch(8.09), provided it is an init-time only operation.

An ordinary statement runs at either init time or performance time or both. Operations which produce a result formally run at the rate of that result (that is, at init time for i-rate results; at performance time for K- and A-rate results), with the sole exception of the init opcode. Most generators and modifiers, however, produce signals that depend not only on the instantaneous value of their arguments but also on some preserved internal state. These performance-time units therefore have an implicit init-time component to set up that state. The run time of an operation which produces no result is apparent in the opcode.

Arguments are values that are sent to an operation. Most arguments will accept arithmetic expressions composed of constants, variables, reserved globals, value converters, arithmetic operations and conditional values.

SYNTAX OF THE ORCHESTRA

An orchestra statement in Csound has the format:

label:   result    opcode    argument1, argument2, ... ; comments

The label is optional and identifies the basic statement that follows as the potential target of a go-to operation (see Program control statements).  A label has no effect on the statement per se.

Csound comments

Comments are optional and are for the purpose of letting the user document his orchestra code. Comments always begin with a semicolon (;) and extend to the end of the line.

C-language style comments /* ... */

Since Csound 3.51, also /* …(anything)… */ C-style comments are allowed in orchestra and score files. This type of comments can span several lines (useful for temporarily excluding sections of text from a run). NOTE: A small bug: If a multi-line comment begins at the end of a line with orchestra code, and this code has errors, the error messages will point to the line with the end-of-comment sign (ie "... */"), not to the offending code line.

NOTE: This feature was announced in version 3.48, but not functional.

Line continuation sign \

Since Csound version 3.51, orchestra lines may be continued over two or more lines by adding a backslash character. This must be the last charactersave for white-space, or it may be followed (but of course not preceded) by a comment. NOTE: This feature was announced in version 3.48, but not functional.

Basic statements

The remainder (result, opcode, and arguments) form the basic statement. This also is optional, i.e. a line may have only a label or comment or be entirely blank. If present, the basic statement must be complete on one line. The opcode determines the operation to be performed; it usually takes some number of input values (arguments); and it usually has a result field variable to which it sends output values at some fixed rate. There are four possible rates:

1) once only, at orchestra setup time (effectively a permanent assignment);

2) once at the beginning of each note (at initialization (init) time: I-rate);

3) once every performance-time control loop (perf time control rate, or K-rate);

4) once each sound sample of every control loop (perf time audio rate, or A-rate).

EXPRESSIONS

Expressions may be composed to any depth from the components shown above. Each part of an expression is evaluated at its own proper rate. For instance, if the terms within a sub-expression all change at the control rate or slower, the sub-expression will be evaluated only at the control rate; that result might then be used in an audio-rate evaluation.

For example, in

k1 + abs(int(p5) + frac(p5) * 100/12 +  sqrt(k1))

the 100/12 would be evaluated at orch init, the p5 expressions evaluated at note i-time, and the remainder of the expression evaluated every k-period. The whole might occur in a unit generator argument position, or be part of an assignment statement .


DIRECTORIES AND FILES

Many generators and the csound command itself specify filenames to be read from or written to. These are optionally full pathnames, whose target directory is fully specified. When not fullpath, filenames are sought in several directories in order, depending on their type and on the setting of certain environment variables. The latter are optional, but they can serve to partition and organize the directories so that source files can be shared rather than duplicated in several user directories. The environment variables can define directories for soundfiles (SFDIR), sound samples (SSDIR), and sound analysis (SADIR). The search order is:

Soundfiles being written are placed in SFDIR (if it exists), else the current directory.

Soundfiles for reading are sought in the current directory, then SSDIR, then SFDIR.

Analysis control files for reading are sought in the current directory, then SADIR.


CONSTANTS AND VARIABLES

Constants are floating point numbers, such as 1, 3.14159, or -73.45. They are available continuously and do not change in value.

Variables are named cells containing numbers. They are available continuously and may be updated at one of the four update rates (setup only, i-rate, k-rate, or a-rate). i- and k-rate variables are scalars (i.e. they take on only one value at any given time) and are primarily used to store and recall controlling data, that is, data that changes at the note rate (for i-variables) or at the control rate (for k-variables). i- and k-variables are therefore useful for storing note parameter values, pitches, durations, slow-moving frequencies, vibratos, etc. a-variables, on the other hand, are arrays or vectors of information. Though renewed on the same perf-time control pass as k-variables, these array cells represent a finer resolution of time by dividing the control period into sample periods (see ksmps). A-variables are used to store and recall data changing at the audio sampling rate (e.g. output signals of oscillators, filters, etc.).

A further distinction is that between local and global variables. local variables are private to a particular instrument, and cannot be read from or written into by any other instrument. Their values are preserved, and they may carry information from pass to pass (e.g. from initialization time to performance time) within a single instrument. Local variable names begin with the letter p, i, k, or a. The same local variable name may appear in two or more different instrument blocks without conflict.

Global Variables are cells that are accessible by all instruments. The names are either like local names preceded by the letter g, or are special reserved symbols. Global variables are used for broadcasting general values, for communicating between instruments (semaphores), or for sending sound from one instrument to another (e.g. mixing prior to reverberation).

Given these distinctions, there are eight forms of local and global variables:

type	when renewable	Local	Global

reserved symbols	permanent	   --	rsymbol

score parameter fields	I-time	pnumber	    --

init variables  	I-time	iname	giname

control signals	P-time, K-rate	kname	gkname

audio signals 	P-time, A-rate	aname	ganame

where rsymbol is a special reserved symbol (e.g. sr, kr), number is a positive integer referring to a score statement pfield, and name is a string of letters and/or digits with local or global meaning. As might be inferred, score parameters are local i-variables whose values are copied from the invoking score statement just prior to the Init pass through an instrument.


ORCHESTRA HEADER STATEMENTS

sr = n1

kr = n2

ksmps = n3

nchnls = n4

massign  ichnl, insno

These statements are global value assignments, made at the beginning of an orchestra, before any instrument block is defined. Their function is to set certain reserved symbol variables that are required for performance. Once set, these reserved symbols can be used in expressions anywhere in the orchestra.

sr = (optional) - set sampling rate to n1 samples per second per channel. The default value is 44100. (The original default was 10000; this was changed in Bath/Montreal Csound 3.46)

kr = (optional) - set control rate to n2 samples per second. The default value is 4410. (The original default was 1000; this was changed in Bath/Montreal Csound 3.46)

ksmps = (optional) - set the number of samples in a Control Period to n3. This value must equal sr/kr, and it must be integer The default value is 10.

nchnls = (optional) - set number of channels of audio output to n4. (1 = mono, 2 = stereo, 4 = quadraphonic.) The default value is 1 (mono).

massign - Assign MIDI channel ichnl to Csound instrument number insno.  Somebody noted that massign can also be used inside an instrument, the assignment being made each time that instrument is called. This is however not documented, so use with caution. (New in Csound 3.47; Author Barry Vercoe)

In addition, any global variable can be initialized by an init-time assignment anywhere before the first instr statement.

All of the above assignments are run as instrument 0 (i - pass only) at the start of real performance.

Example of header assignments:

sr = 10000

kr = 500

ksmps = 20

gi1  =    sr/2. ga   init 0 gitranspose =  octpch(.0l)


INSTRUMENT BLOCK STATEMENTS

instr i, j, ...

.

.  < body

.    of

.    instrument >

.

endin

These statements delimit an instrument block. They must always occur in pairs.

instr - begin an instrument block defining instruments i, j, ...

i, j, ... must be numbers, not expressions. Any positive integer is legal, and in any order, but excessively high numbers are best avoided.

endin - end the current instrument block.

NOTE

There may be any number of instrument blocks in an orchestra.

Instruments can be defined in any order (but they will always be both initialized and performed in ascending instrument number order).

Instrument blocks cannot be nested (i.e. one block cannot contain another).


Standard numeric score
THE CSOUND STANDARD NUMERIC SCORE

A score is a data file that provides information to an orchestra about its performance.  Like an orchestra file, a score file is made up of statements in a known format.  The Csound orchestra expects to be handed a score comprised mainly of ascii numeric characters.  Although most users will prefer a higher level score language such as provided by Cscore, Scot, or another score-generating program, each resulting score must eventually appear in the format expected by the orchestra.  A Standard Numeric Score can be created and edited directly by the beginner using standard text editors; indeed, some users continue to prefer it.  The purpose of this section is to describe this format in detail.

The basic format of a standard numeric score statement is:

opcode p1 p2 p3 p4...             ;comments

The opcode is a single character, always alphabetic.  Legal opcodes are f, i, a, t, s, and e, the meanings of which are described in the following pages.  The opcode is normally the first character of a line; leading spaces or tabs will be ignored.  Spaces or tabs between the opcode and p1 are optional.

p1, p2, p3, etc...  are parameter fields (pfields).  Each contains a floating point number comprised of an optional sign, digits, and an optional decimal point.  Expressions are not permitted in Standard Score files.  pfields are separated from each other by one or more spaces or tabs, all but one space of which will be ignored.

Continuation lines are permitted.  If the first printing character of a new scoreline is not an opcode, that line will be regarded as a continuation of the pfields from the previous scoreline.

Comments in score files

Comments are optional and are for the purpose of permitting the user to document his score file.  Comments always begin with a semicolon (;) and extend to the end of the line.  Comments will not affect the pfield continuation feature.

Blank lines or comment-only lines are legal (and will be ignored).

C-language style comments /* ... */

Since Csound 3.51, also /* …(anything)… */ C-style comments are allowed in orchestra and score files. This type of comments can span several lines (useful for temporarily excluding sections of text from a run). NOTE: This feature was announced in Csound 3.48, but not functional until 3.51.

SCORE STATEMENT TYPES

There are several statement types for Csound scores:

f statement - invoke a function table generator (GEN)

i statement - instrument statements (play a note)

t statement - tempo statements

b statement - reset the clock (new in Csound 3.49)

v statement - local textual varying of time (new in Csound 3.49)

s statement - section statements

m and n statements - repeat named sections (new in Csound 3.48/49?)

r statement - repeat sections (new in Csound 3.48)

a statement - advance statements

e statement - end statements

See also score preprocessing and new features in score language for tips on how you can save typing in your score files.

Occasionally somebody will also notice (eg in the score preprocessor output file score.srt) that there exists yet another score statement type, w. This is totally different and is used internally related to t (tempo) statements.  There is no reason to understand it as it should not be used.  If you really want to know, read the Csound source code!


PREPROCESSING OF STANDARD SCORES

A Score (a collection of score statements) is divided into time-ordered sections by the s statement.  Before being read by the orchestra, a score is preprocessed one section at a time.  Each section is normally processed by 3 routines: Carry, Tempo, and Sort.  For further information, see also the example in the Instrument Design Tutorial.

See also New features in score language.

1. Carry

Within a group of consecutive i statements whose p1 whole numbers correspond, any pfield left empty will take its value from the same pfield of the preceding statement.  An empty pfield can be denoted by a single point (.) delimited by spaces.  No point is required after the last nonempty pfield.  The output of Carry preprocessing will show the carried values explicitly.  The Carry Feature is not affected by intervening comments or blank lines; it is turned off only by a non-i statement or by an i statement with unlike p1 whole number.

An additional feature is available for p2 alone.  The symbol + in p2 will be given the value of p2 + p3 from the preceding i statement.  This enables note action times to be automatically determined from the sum of preceding durations.  The + symbol can itself be carried.  It is legal only in p2.

E.g.:     the statements

i1   0     .5    100

i .  +

i

   will result in

i1   0     .5    100

i1   .5    .5    100

i1   1     .5    100

The Carry feature should be used liberally.  Its use, especially in large scores, can greatly reduce input typing and will simplify later changes.

2. Tempo

This operation time warps a score section according to the information in a t statement.  The tempo operation converts p2 (and, for i statements, p3) from original beats into real seconds, since those are the units required by the orchestra.  After time warping, score files will be seen to have orchestra-readable format demonstrated by the following:

i p1 p2beats p2seconds p3beats p3seconds p4 p5 ....

3. Sort

This routine sorts all action-time statements into chronological order by p2 value.  It also sorts coincident events into precedence order.  Whenever an f statement and an i statement have the same p2 value, the f statement will precede.  Whenever two or more i statements have the same p2 value, they will be sorted into ascending p1 value order.  If they also have the same p1 value, they will be sorted into ascending p3 value order.  Score sorting is done section by section (see s statement).  Automatic sorting implies that score statements may appear in any order within a section.

NOTE

The operations Carry, Tempo and Sort are combined in a 3-phase single pass over a score file, to produce a new file in orchestra-readable format (see the Tempo example).  Processing can be invoked either explicitly by the scsort command, or implicitly by csound which processes the score before calling the orchestra.  Source-format files and orchestra-readable files are both in ascii character form, and may be either perused or further modified by standard text editors.  Userwritten routines can be used to modify score files before or after the above processes, provided the final orchestra-readable statement format is not violated.  Sections of different formats can be sequentially batched; and sections of like format can be merged for automatic sorting.

NEXT-P AND PREVIOUS-P SYMBOLS

At the close of score preprocessing operations, three additional score features are interpreted during file writeout: next-p, previous-p, and ramping.

i statement pfields containing the symbols npx or ppx (where x is some integer) will be replaced by the appropriate pfield value found on the next i statement (or previous i statement) that has the same p1.  For example, the symbol np7 will be replaced by the value found in p7 of the next note that is to be played by this instrument. np and pp symbols are recursive and can reference other np and pp symbols which can reference others, etc.  References must eventually terminate in a real number or a ramp symbol (see below).  Closed loop references should be avoided.  np and pp symbols are illegal in p1,p2 and p3 (although they may reference these).  np and pp symbols may be Carried.  np and pp references cannot cross a Section boundary.  Any forward or backward reference to a non-existent note-statement will be given the value zero.

 E.g.:     the statements

i1   0    1    10   np4  pp5

i1   1    1    20

i1   1    1    30

will result in

i1   0    1    10   20     0

i1   1    1    20   30   20

i1   2    1    30     0   30

np and pp symbols can provide an instrument with contextual knowledge of the score, enabling it to glissando or crescendo, for instance, toward the pitch or dynamic of some future event (which may or may not be immediately adjacent).  Note that while the Carry feature will propagate np and pp through unsorted statements, the operation that interprets these symbols is acting on a time-warped and fully sorted version of the score.

RAMPING

i statement pfields containing the symbol < will be replaced by values derived from linear interpolation of a time-based ramp.  Ramps are anchored at each end by the first real number found in the same pfield of a preceding and following note played by the same instrument.

In Csound 3.49, some new ramping statements were introduced: The normal parentheses '(', ')' give values derived from an exponential rather than a linear function. The tilde symbol ~ gives random values (uniform distribution) in the range given by ramp start and end points.

NOTE: Until Csound 3.52, the wiggly parens '{' and '}' were used for exp ramping. These are now deprecated, as they are scheduled to be used as brackets for score sections.

E.g.:     the statements

i1   0    1    100

i1   1    1      <

i1   2    1      <

i1   3    1    400

i1   4    1      <

i1   5    1      0

     will result in

i1   0    1    100

i1   1    1    200

i1   2    1    300

i1   3    1    400

i1   4    1    200

i1   5    1        0

Ramps cannot cross a Section boundary.  Ramps cannot be anchored by an np or pp symbol (although they may be referenced by these).  Ramp symbols are illegal in p1, p2 and p3.  Ramp symbols may be Carried.  Note, however, that while the Carry feature will propagate ramp symbols through unsorted statements, the operation that interprets these symbols is acting on a time-warped and fully sorted version of the score.  In fact, time-based linear interpolation is based on warped score-time, so that a ramp which spans a group of accelerating notes will remain linear with respect to strict chronological time.


Function table statements
F STATEMENT (Function Table statement)

f  p1  p2  p3  p4 ...

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

(See also ftgen, function table generator orchestra file opcode- New in Csound 3.47)

PFIELDS

p1	Table number (from 1 to 200) by which the stored function will be known.

A negative number requests that the table be destroyed.

p2	Action time of function generation (or destruction) in beats.

p3	Size of function table (i.e.  number of points).

Must be a power of 2, or a power-of-2 plus 1 (see below).

Maximum table size is 16777216 (2**24) points.

p4	Number of the GEN routine to be called (see GEN ROUTINES).

A negative value will cause rescaling to be omitted.

p5	|

p6	|   Parameters whose meaning is determined by the particular GEN routine.

 .	|

 .	|

SPECIAL CONSIDERATIONS

Function tables are arrays of floating-point values.  Arrays can be of any length in powers of 2; space allocation always provides for 2**n points plus an additional guard point.  The guard point value, used during interpolated lookup, can be automatically set to reflect the table's purpose: If size is an exact power of 2, the guard point will be a copy of the first point; this is appropriate for interpolated wrap-around lookup as in oscili, etc., and should even be used for non-interpolating oscil for safe consistency.  If size is set to 2**n + 1, the guard point value automatically extends the contour of table values; this is appropriate for single-scan functions such in envlpx, oscil1, oscil1i, etc.

Table space is allocated in primary memory, along with instrument data space.  The maximum table number has a soft limit of 200;  this can be extended if required.

An existing function table can be removed by an f-statement containing a negative p1 and an appropriate action time.  A function table can also be removed by the generation of another table with the same p1.  Functions are not automatically erased at the end of a score section.

p2 action time is treated in the same way as in i statements with respect to sorting and modification by t statements.  If an f statement and an i statement have the same p2, the sorter gives the f statement precedence so that the function table will be available during note initialization.

An f 0 statement (zero p1, positive p2) may be used to create an action time with no associated action.  Such time markers are useful for padding out a score section (see s statement).


Instrument statements
I STATEMENT (Instrument or Note statement)

i  p1  p2  p3  p4  ...

This statement calls for an instrument to be made active at a specific time and for a certain duration.  The parameter field values are passed to that instrument prior to its initialization, and remain valid throughout its performance.

PFIELDS

p1	Instrument number (from 1 to 200), usually a non-negative integer.

An optional fractional part can provide an additional tag for specifying ties between particular notes of consecutive clusters.

A negative p1 (including tag) can be used to turn off a particular held' note.

p2	Starting time in arbitrary units called beats.

p3	Duration time in beats (usually positive).  A negative value will initiate a held note (see also ihold).  A zero value will invoke an initialization pass without performance (see also instr).

p4	|

p5	|   Parameters whose significance is determined by the instrument.

 .	|

 .	|

SPECIAL CONSIDERATIONS

Beats are evaluated as seconds, unless there is a t statement in this score section or a -t flag in the command line.

Starting or action times are relative to the beginning of a section (see s statement), which is assigned time 0.

Note statements within a section may be placed in any order.  Before being sent to an orchestra, unordered score statements must first be processed by Sorter, which will reorder them by ascending p2 value.  Notes with the same p2 value will be ordered by ascending p1; if the same p1, then by ascending p3.

Notes may be stacked, i.e., a single instrument can perform any number of notes simultaneously.  (The necessary copies of the instrument's data space will be allocated dynamically by the orchestra loader.)  Each note will normally turn off when its p3 duration has expired, or on receipt of a MIDI noteoff signal.  An instrument can modify its own duration either by changing its p3 value during note initialization, or by prolonging itself through the action of a linenr unit.

An instrument may be turned on and left to perform indefinitely either by giving it a negative p3 or by including an ihold in its i-time code.  If a held note is active, an i statement with matching p1 will not cause a new allocation but will take over the data space of the held note.  The new pfields (including p3) will now be in effect, and an i-time pass will be executed in which the units can either be newly initialized or allowed to continue as required for a tied note (see tigoto).  A held note may be succeeded either by another held note or by a note of finite duration.  A held note will continue to perform across section endings (see s statement).  It is halted only by turnoff or by an i statement with negative matching p1 or by an e statement.


Advance statement
A STATEMENT (Advance statement)

a	p1  p2  p3

This causes score time to be advanced by a specified amount without producing sound samples.

PFIELDS

 p1   carries no meaning.  Usually zero

 p2   Action time, in beats, at which advance is to begin.

 p3   Durational span (distance in beats) of time advance.

 p4   |

 p5   |    These carry no meaning.

  .

  .

SPECIAL CONSIDERATIONS

This statement allows the beat count within a score section to be advanced without generating intervening sound samples.  This can be of use when a score section is incomplete (the beginning or middle is missing) and the user does not wish to generate and listen to a lot of silence.

p2 action time and p3 distance are treated as in i statements, with respect to sorting and modification by t statements.

An a statement will be temporarily inserted in the score by the Score Extract feature when the extracted segment begins later than the start of a Section.  The purpose of this is to preserve the beat count and time count of the original score for the benefit of the peak amplitude messages which are reported on the user console.

Whenever an a statement is encountered by a performing orchestra, its presence and effect will be reported on the user's console.


Variation statement
V STATEMENT (Time variation)

(New in Csound 3.49)

v	warpfactor

This sets a scaling on the speed of the clock, on the textual score level. Effective until the end of the section or the next v command.

PFIELDS

p1   New scaling rate.

SPECIAL CONSIDERATIONS

Use eg for phase music, where there is 1 theme played twice simultaneously at different speeds.

As it is textual it is local, unlike the t command


Begin statement
B STATEMENT (Reset the clock)

(New in Csound 3.49)

b	clockbase

Resets the base clock for textually following events.

PFIELDS

 p1   New clock base value.

SPECIAL CONSIDERATIONS

Use it for repeated sections where you want an overlap with previous version, as it does not start a new section.  It is textual, and is expanded before sorting.


Mark and Name statements
M and N STATEMENTS (Named sections)

m	name

n	name

m - Sets a mark in the score which can be referenced by later n directives

n - repeat a named section (ie from m to end of section).

PFIELDS

 p1   name of mark

Names can contain letters and numerals.

SPECIAL CONSIDERATIONS

Designed to simplify verse+chorus structures.


Tempo statement
T STATEMENT (Tempo statement)

t	p1  p2  p3  p4  .....  (unlimited)

This statement sets the tempo and specifies the accelerations and decelerations for the current section.  This is done by converting beats into seconds.

PFIELDS

p1         	must be zero

p2         	initial tempo in beats per minute

p3, p5, p7, ...	times in beats (in non-decreasing order)

p4, p6, p8, ...	tempi for the referenced beat times

SPECIAL CONSIDERATIONS

Time and Tempo-for-that-time are given as ordered couples that define points on a "tempo vs time" graph.  (The time-axis here is in beats so is not necessarily linear.) The beat-rate of a Section can be thought of as a movement from point to point on that graph: motion between two points of equal height signifies constant tempo, while motion between two points of unequal height will cause an accelarando or ritardando accordingly.  The graph can contain discontinuities: two points given equal times but different tempi will cause an immediate tempo change.

Motion between different tempos over non-zero time is inverse linear.  That is, an accelerando between two tempos M1 and M2 proceeds by linear interpolation of the single-beat durations from 60/M1 to 60/M2.

The first tempo given must be for beat 0.

A tempo, once assigned, will remain in effect from that time-point unless influenced by a succeeding tempo, i.e.  the last specified tempo will be held to the end of the section.

A t statement applies only to the score section in which it appears.  Only one t statement is meaningful in a section; it can be placed anywhere within that section.  If a score section contains no t statement, then beats are interpreted as seconds

(i.e. with an implicit t 0 60 statement).

NOTE

If the csound command includes a -t flag, the interpreted tempo of all score t statements will be overridden by the command-line tempo.


Section statement
S STATEMENT (Section statement)

s	anything

The s statement marks the end of a section.

PFIELDS

All pfields are ignored.

SPECIAL CONSIDERATIONS

Sorting of the i, f and a statements by action time is done section by section.

Time warping for the t statement is done section by section.

All action times within a section are relative to its beginning.  A section statement establishes a new relative time of 0, but has no other reinitializing effects (e.g. stored function tables are preserved across section boundaries).

A section is considered complete when all action times and finite durations have been satisfied (i.e., the "length" of a section is determined by the last occurring action or turn-off).  A section can be extended by the use of an f 0 statement.

A section ending automatically invokes a Purge of inactive instrument and data spaces.

NOTE

Since score statements are processed section by section, the amount of memory required depends on the maximum number of score statements in a section.  Memory allocation is dynamic,  and the user will be informed as extra memory blocks are requested during score processing.

For the end of the final section of a score, the s statement is optional; the e statement may be used instead.


Repeat score sections
R STATEMENT (Repeat sections)

r	num   NN

Sections can be repeated by using #include or by editing the text.  An alternative is the new r directive in the score language.

PFIELDS

 p1   number of repetitions

 p2   name of repetition counter, which is incremented with each repetition (optional)

SPECIAL CONSIDERATIONS

r3	NN

starts a repeated section, which lasts until the next s, r or e statement.  The section is repeated 3 times in this example.  In order that the sections may be more flexible than simple editing, the macro NN is given the value of 1 for the first time through the section, 2 for the second, and 3 for the third.  This can be used to change p-field parameters, or indeed ignored.

Warning: because of serious problems of interaction with macro expansion, sections must start and end in the same file, and not in a macro.


End statement
E STATEMENT (End statement)

e	anything

This statement may be used to mark the end of the last section of the score.

PFIELDS

All pfields are ignored.

SPECIAL CONSIDERATIONS

The e statement is contextually identical to an s statement.  Additionally, the e statement terminates all signal generation (including indefinite performance) and closes all input and output files.

If an e statement occurs before the end of a score, all subsequent score lines will be ignored.

The e statement is optional in a score file yet to be sorted.  If a score file has no e statement, then Sort processing will supply one.


Contents: Adding your own modules to Csound; OPDS data struct (popup for the previous), Instrument design tutorial; Example instruments 1-13 (individual entries); fof tutorial; SCOT tutorial;


Adding your own C modules to Csound

If the existing Csound generators do not suit your needs, you can write your own modules in C and add them to the run-time system.  When you invoke Csound on an orchestra and score file, the orchestra is first read by a table-driven translator 'otran' and the instrument blocks converted to coded templates ready for loading into memory by 'oload' on request by the score reader.  To use your own C-modules within a standard orchestra you need only add an entry in otran's table and relink Csound with your own code.

[John Fitch maintains a detailed changelog in the file ChangeLog.Csound in the Bath archive.]

The translator, loader, and run-time monitor will treat your module just like any other provided you follow some conventions.  You need a structure defining the inputs, outputs and workspace, plus some initialization code and some perf-time code.  Let's put an example of these in two new files, newgen.h and newgen.c:

typedef struct {	/*  newgen.h  -  define a structure */

OPDS h;	/* required header */

float  *result, *istrt, *incr, *itime, *icontin;	/* addr outarg, inargs   */

float  curval, vincr;	/* private dataspace */

long  countdown;	/* ditto       */

}  RMP;

Now Newgen.c:

#include "cs.h"	/*  newgen.c  -  init and perf code */

#include "newgen.h"

void rampset(p)	/* at note initialization:     */

register  RMP  *p;

{

if  (*p->icontin == 0.)

p->curval = *p->istrt;	/* optionally get new start value */

p->vincr = *p->incr / esr; 	/* set s-rate increment per sec.   */

p->countdown = *p->itime * esr;	/* counter for itime seconds     */

}

void ramp(p)	/* during note performance:   */

    register  RMP  *p;

{

register float *rsltp = p->result;	/* init an output array pointer  */

register int nn = ksmps;	/* array size from orchestra */

do {

*rsltp++ = p->curval;	/* copy current value to ouput */

if (--p->countdown >= 0) 	/* for the first itime seconds, */

p->curval += p->vincr;	/*   ramp the value  */

} while (--nn);

}

Now we add this module to the translator table entry.c, under the opcode name rampt:

#include "newgen.h"

void rampset(), ramp();

/*   opcode    dspace    thread    outarg    inargs      isub       ksub     asub    */

{    "rampt",    S(RMP),       5,        "a",      "iiio",     rampset, NULL,   ramp  },

S( ) is shorthand for sizeof; the thread is an OR value of which functions are supplied -- i-time, k-rate, a-rate; and the outargs and inargs are data type declarations of the arguments for the ugen (all this is documented in entry.c).

Finally we relink Csound to include the new module.  Under Unix this means changing the Makefile in three places:

     1.  Add the name newgen.o to the variable OBJS.

     2.  Add the name newgen.h as a dependency for entry.o

     3.  Create a new dependency,  newgen.o: newgen.h

Now run 'make csound'.   If your host is a Macintosh, simply add newgen.h and newgen.c to one of the Csound segments and invoke the C compiler.

COMPILING CSOUND FOR DOS/WINDOWS

(NOTE: This section will not be updated regularly. It was valid for Csound 3.51, but will probably have changed slightly by the time you read this. -re)

Csound for Windows/DOS exists in two versions: Winsound , with an attempt at a graphical user interface (GUI), and the standard command-line version. The latter can be run as a console application in a DOS session in the Windows interface, or it can be run in a DOS-only session (in the last case it gets flat 32-bit memory by using the dos4gw library, which is included with the distribution csound_new.zip ).

John ffitch presently uses Microsoft Developer Studio (also called Visual C++, or MsDev for short) to compile the distributed executables, and it seems most other people do too. (Some time ago Watcom was used.) Now, if you also use the MS compiler, you can make use of the project files for Winsound and "consound", as the standard command-line version is called. These are MsDev project files with the file extension ".mdp", ie Winsound.mdp and consound.mdp. If you use either of those you will have all files added, invisible makefile management, compiler options and preprocessor flags set, etc etc. There is only one caveat here:

Missing files in distributed MsDev projects

Sometimes the project files lag behind the version number. In those cases some of the C code files are not added to the project, which means you will get lots of errors at link time, saying things like

blah.obj : error LNK2001: unresolved external symbol _functionName

Solution: Search in all the files for the definition of the function called "functionName" (it is decorated with an initial underscore by the compiler), and add that C-code file to the project. Any needed header files will be automatically included, of course.

Here is a list of files that were missing from the version 3.51 of consound.mdp (Winsound.mdp was updated for version 3.51):

"aifc.c" "argdecode.c" "biquad.c" "flanger.c" "lowpassr.c" "midiops3.c" "one_file.c" "pvocext.c" "schedule.c" "uggab.c"

Platform-dependent file issues

Now, if you use a different Windows/DOS compiler than MsDev, or decide to create your own project file in MsDev, you will have to add the right files by hand. By running some quick diffs, it seems the following files should NOT be included in any compilation of Csound for Windows/DOS:

Blaster.c  Cscormai.c  Decaudio.c  Decplay.c  Het_ Expo.c  Het_Impo.c  Hpplay.c  Linuxaud.c  Lpc_Expo.c  Pv_Expor.c  Pv_Impor.c  Sgiplay.c  Winbor.c  Winfg.c  Winsgi.c  Winwat.c  Winx11.c

Here are the files which should be included in Winsound but not in consound:

Control.c  Csliders.c  Cvdlg.cpp  Cwin.cpp  Hetdlg.cpp  Lpcdlg.cpp  Pvdlg.cpp  Wincwin.c  Winsound.rc

Preprocessor flags.

Csound is a multi-platform project. Lots of platform-specific code is included, which is managed by standard #ifdef's. Here are the flags you'll need:

Consound uses: _CONSOLE,  WIN32, SFIRCAM, PIPES, MACROS, RTAUDIO, MSVC

Winsound has:   WINDOWS, CWIN, WIN32, SFIRCAM, PIPES, MACROS, RTAUDIO, MSVC

So the differentiating defines for consound/winsound are the first; _CONSOLE vs WINDOWS and CWIN. The defines that marks the Windows/PC MsDev versions are MSVC and WIN32. Winsound (unfortunately) uses the Microsoft Foundation Library for window management, so to the libraries for this must be included with your compiler to build that program version.

The other flags define various features which may be available on some or all platforms.

RTAUDIO: accept "devaudio" for real-time output, and possibly "adc" for realtime audio input.

SFIRCAM: Read/write Ircam format soundfiles

PIPES: Accept piped input/output

MACROS: Use the orc/score macro system introduced in Csound  3.48

(NOTE: END of Windows/DOS-specific notes here. Continue old tutorial, with all the really useful info...)

CSOUND PROGRAMMING ISSUES

The above actions have added a new generator to the Csound language.  It is an audio-rate linear ramp function which modifies an input value at a user-defined slope for some period.  A ramp can optionally continue from the previous note's last value.  The Csound manual entry would look like:

ar   rampt     istart,  islope, itime [,  icontin]

istart - beginning value of an audio-rate linear ramp.  Optionally overridden by a continue flag.

islope - slope of ramp, expressed as the y-interval change per  second.

itime - ramp time in seconds, after which the value is held for the remainder of the note.

icontin (optional) - continue flag.  If zero, ramping will proceed from input istart .  If non-zero, ramping will proceed from the last value of the previous note.  The default value is zero.

The file newgen.h includes a one-line list of output and input parameters.  These are the ports through which the new generator will communicate with the other generators in an instrument.  Communication is by address, not value, and this is a list of pointers to floats.  There are no restrictions on names, but the input-output argument types are further defined by character strings in entry.c (inargs, outargs).   Inarg types are commonly x, a, k, and i, in the normal Csound manual conventions;  also available are o (optional, defaulting to 0), p (optional, defaulting to 1).  Outarg types include a, k, i and s (asig or ksig).  It is important that all listed argument names be assigned a corresponding argument type in entry.c.  Also, i-type args are valid only at initialization time, and other-type args are available only at perf time.  Subsequent lines in the RMP structure declare the work space needed to keep the code re-entrant.  These enable the module to be used multiple times in multiple instrument copies while preserving all data.

The file newgen.c contains two subroutines, each called with a pointer to the uniquely allocated RMP structure and its data.  The subroutines can be of three types: note initialization, k-rate signal generation, a-rate signal generation.  A module normally requires two of theseÑinitialization, and either k-rate or a-rate subroutinesÑwhich become inserted in various threaded lists of runnable tasks when an instrument is activated.  The thread-types appear in entry.c in two forms:  isub, ksub and asub names;  and a threading index which is the sum of isub=1, ksub=2, asub=4.  The code itself may reference global variables defined in cs.h and oload.c, the most useful of which are:

float     esr       	user-defined sampling rate

float     ekr       	user-defined control rate

float     ensmps 	user-defined ksmps

int        ksmps   	user-defined ksmps

int        nchnls   	user-defined nchnls

int        odebug 	command-line -v flag

int        initonly  	command-line -I flag

int        msglevel	command-line -m level

float     pi, twopi	obvious constants

float     tpidsr   	twopi / esr

float     sstrcod	special code for string arguments

FUNCTION TABLES

To access stored function tables, special help is available.  The newly defined structure should include a pointer

FUNC        *ftp; initialized by the statement

ftp = ftpfind(p->ifuncno);

where float *ifuncno is an i-type input argument containing the ftable number.  The stored table is then at ftp->ftable, and other data such as length, phase masks, cps-to-incr converters, are also accessed from this pointer.  See the FUNC structure in cs.h, the ftfind() code in fgens.c, and the code for oscset() and koscil() in ugens2.c.

ADDITIONAL SPACE

Sometimes the space requirement of a module is too large to be part of a structure (upper limit 65535 bytes), or it is dependent on an i-arg value which is not known until initialization.  Additional space can be dynamically allocated and properly managed by including the line

AUXCH      auxch;

in the defined structure (*p), then using the following style of code in the init module:

if (p->auxch.auxp == NULL)

     auxalloc(npoints * sizeof(float), &p->auxch);

The address of this auxilliary space is kept in a chain of such spaces belonging to this instrument, and is automatically managed while the instrument is being duplicated or garbage-collected during performance.  The assignment

char *auxp = p->auxch.auxp;

will find the allocated space for init-time and perf-time use.  See the LINSEG structure in ugens1.h and the code for lsgset() and klnseg() in ugens1.c.

FILE SHARING

When accessing an external file often, or doing it from multiple places, it is often efficient to read the entire file into memory.  This is accomplished by including the line

MEMFIL    *mfp;

in the defined structure (*p), then using the following style of code in the init module:

if (p->mfp == NULL)

p->mfp = ldmemfile(filname);

where char *filname is a string name of the file requested.  The data read will be found between

(char *)  p->mfp->beginp;          and       (char *) p->mfp->endp;

Loaded files do not belong to a particular instrument, but are automatically shared for multiple access.  See the ADSYN structure in ugens3.h and the code for adset() and adsyn() in ugens3.c.

STRING ARGUMENTS

To permit a quoted string input argument (float *ifilnam, say) in our defined structure (*p), assign it the argtype S in entry.c, include another member char *strarg in the structure, insert a line

TSTRARG( "rampt",  RMP)  \

in the file oload.h, and include the following code in the init module:

if (*p->ifilnam == sstrcod)

strcpy(filename, unquote(p->strarg));

See the code for adset( ) in Ugens3.c, lprdset( ) in Ugens5.c, and pvset( ) in Ugens8.c.


OPDS
OPDS  CS.H

typedef struct opds {

struct opds * nxti;

struct opds * nxtp;

SUBR	iopadr;  	/* initialisation function pointer */

SUBR	opadr;   	/* perf-time function pointer */

OPTXT	*optext;	/* opcode info */

INSDS	*insdshead;	/* MIDI input data structure */

} OPDS;


AN INSTRUMENT DESIGN TUTORIAL

By Richard Boulanger Berklee College of Music

Tutorial instruments:

Play One Note

P-Fields

Envelopes

Chorusing

Vibrato

Function Table Generators

Crossfade

Soundin

Global Stereo Reverb

Filtered Noise

Carry, Tempo and Sort

Tables & Labels

Spectral Fusion

Csound instruments are created in an "orchestra" file, and the list of notes to play is written in a separate "score" file.  Both are created using a standard word processor.  When you run Csound on a specific orchestra and score, the score is sorted and ordered in time, the orchestra is translated and loaded, the wavetables are computed and filled, and then the score is performed.  The score drives the orchestra by telling the specific instruments when and for how long to play, and what parameters to use during the course of each note event.

Unlike today's commercial hardware synthesizers, which have a limited set of oscillators, envelope generators, filters, and a fixed number of ways in which these can be interconnected, Csound's power is not limited.  If you want an instrument with hundreds of oscillators, envelope generators, and filters you just type them in.   More important is the freedom to interconnect the modules, and to interrelate the parameters which control them.  Like acoustic instruments, Csound instruments can exhibit a sensitivity to the musical context, and display a level of "musical intelligence" to which hardware synthesizers can only aspire.

Because the intent of this tutorial is to familiarize the novice with the syntax of the language, we will design several simple instruments.  You will find many instruments of the sophistication described above in various Csound directories, and a study of these will reveal Csound's real power.

The Csound orchestra file has two main parts:

1.  the "header" section  -  defining the sample rate, control rate, and number of output channels.

2.  the "instrument" section  -  in which the instruments  are designed.

THE HEADER SECTION

A Csound orchestra generates signals at two rates - an audio sample rate and a control sample rate.  Each can represent signals with frequencies no higher than half that rate, but the distinction between audio signals and sub-audio control signals is useful since it allows slower moving signals to require less compute time.  In the header below, we have specified a sample rate of 16kHz, a control rate of 1kHz, and then calculated the number of samples in each control period using the formula:  ksmps = sr / kr.

sr   =         16000

kr   =         1000

ksmps     =         16

nchnls    =         1

In Csound orchestras and scores, spacing is arbitrary.  It is important to be consistent in laying out your files, and you can use spaces to help this.  In the Tutorial Instruments shown below you will see we have adopted one convention.  The reader can choose his or her own.

THE INSTRUMENT SECTION

All instruments are numbered and are referenced thus in the score.  Csound instruments are similar to patches on a hardware synthesizer.  Each instrument consists of a set of "unit generators," or software "modules," which are "patched" together with  "i/o" blocks  - i, k, or a variables.  Unlike a hardware module, a software module has a number of variable "arguments" which the user sets to determine its behavior.  The four types of variables are:

setup only

i-rate variables, changed at the note rate

k-rate variables, changed at the control signal rate

a-rate variables, changed at the audio signal rate

ORCHESTRA STATEMENTS

Each statement occupies a single line and has the same basic format:

     result    action    arguments

To include an oscillator in our orchestra, you might specify it as follows:

a1        oscil          10000, 440, 1

The three "arguments" for this oscillator set its amplitude (10000), its frequency (440Hz), and its waveshape (1).   The output is put in i/o block "a1."   This output symbol is significant in prescribing the rate at which the oscillator should generate output - here the audio rate.  We could have named the result anything (e.g. "asig") as long as it began with the letter "a".

COMMENTS

To include text in the orchestra or score which will not be interpreted by the program, precede it with a semicolon.  This allows you to fully comment your code.  On each line, any text which follows a semicolon will be ignored by the orchestra and score translators.

WHEN THINGS SOUND WRONG

When you design your own Csound instruments you may occasionally be surprised by the results.  There will be times when you've computed a file for hours and your playback is just silence, while at other times you may get error messages which prevent the score from running, or you may hang the computer and nothing happens at all.

In general, Csound has a comprehensive error-checking facility that reports to your console at various stages of your run:  at score sorting, orchestra translation, initializing each call of every instrument, and during performance.  However, if your error was syntactically permissable, or it generated only a warning message, Csound could faithfully give you results you don't expect. Here is a list of the things you might check in your score and orchestra files:

1.  You typed the letter small L instead of the number One

2.  You forgot to precede your comment with a semi-colon

3.  You forgot an opcode or a required parameter

4.  Your amplitudes are not loud enough or they are too loud

5.  Your frequencies are not in the audio range - 20Hz to 20kHz

6.  You placed the value of one parameter in the p-field of another

7.  You left out some crucial information like a function definition

8.  You didn't meet the Gen specifications

SUGGESTIONS FOR FURTHER STUDY

Csound is such a powerful tool that we have touched on only a few of its many features and uses.  You are encouraged to take apart the instruments in this chapter, rebuild them, modify them, and  integrate the features of one into the design of another.  To understand their capabilities you should compose short etudes with each.  You may be surprised to find yourself merging these little studies into the fabric of your first Csound compositions.

The directory 'morefiles' contains examples of the classical designs of Risset and Chowning.  Detailed discussions of these instruments can be found in Charles Dodge's and Thomas Jerse's Computer Music textbook.  This text is the key to getting the most out of these instrumental models and their innovative approaches to signal processing.  Also recommended are the designs of Russell Pinkston.  They demonstrate techniques for legato phrasing, portamento, random vibrato, and random sequence generation.  His instrument representing Dx7 OpCodeª Editor/Librarian patches is a model for bringing many wonderful sounds into your orchestra.

Nothing will increase your understanding more than actually Making Music with Csound.   The best way to discover the full capability of these tools is to create your own music with them.  As you negotiate the new and uncharted terrain you will make many discoveries.  It is my hope that through Csound you discover as much about music as I have, and that this experience brings you great personal satisfaction and joy.

Richard Boulanger   -    March 1991   -  Boston, Massachusetts  -  USA

First example instrument


01 - Play one note
Toot 1: Play One Note

Back to tutorial index	Next

For this and all instrument examples below, there exist orchestra and score files in the Csound subdirectory tutorfiles that the user can run to soundtest each feature introduced.  The instrument code shown below is actually preceded by an orchestra header section similar to that shown above.  If you are running on a RISC computer, each example will likely run in realtime.  During playback (realtime or otherwise) the audio rate may automatically be modified to suit the local d-a converters.

   The first orchestra file, called toot1.orc, contains a single instrument which uses an oscil unit to play a 440Hz sine wave (defined by f1 in the score) at an amplitude of 10000.

instr 1

a1     oscil     10000, 440, 1

            out  a1

endin

Run this with its corresponding score file, toot1.sco :

 f1     0    4096 10   1    ; use "gen1" to compute a sine wave

    i1     0    4              ; run "instr 1" from time 0 for 4 seconds

 e                               ; indicate the "end" of the score

Back to tutorial index	Next


02 - P-Fields
Toot 2: "P-Fields"

Previous 	Next

The first instrument was not interesting because it could play only one note at one amplitude level.  We can make things more interesting by allowing the pitch and amplitude to be defined by parameters in the score.  Each column in the score constitutes a parameter field, numbered from the left.   The first three parameter fields of the i-statement have a reserved function:

p1 = instrument number

p2 = start time

p3 = duration

All other parameter fields are determined by the way the sound designer defines his instrument.  In the instrument below, the oscillator's amplitude argument is replaced by p4 and the frequency argument by p5.  Now we can change these values at i-time, i.e. with each note in the score.  The orchestra and score files now look like:

instr  2

a1	oscil	p4, p5, 1	; p4=amp

   out   a1	; p5=freq

endin

Score to run with this example:

  f1   0    4096 10   1                   ; sine wave

; instrument  start  duration   amp(p4)   freq(p5)

      i2               0        1              2000         880

      i2               1.5     1             4000         440

      i2               3        1             8000         220

      i2               4.5     1           16000         110

      i2               6        1           32000           55

e

Previous 	Next


03 - Envelopes
Toot 3: Envelopes

Previous	Next

Although in the second instrument we could control and vary the overall amplitude from note to note, it would be more musical if we could contour the loudness during the course of each note.  To do this we'll need to employ an additional unit generator linen, which the Csound reference manual defines as follows:

kr   linen     kamp, irise, idur, idec

ar   linen     xamp, irise, idur, idec

linen is a signal modifier, capable of computing its output at either control or audio rates.  Since we plan to use it to modify the amplitude envelope of the oscillator, we'll choose the latter version.  Three of linen's arguments expect i-rate variables.  The fourth expects in one instance a k-rate variable (or anything slower), and in the other an x-variable (meaning a-rate or anything slower).  Our linen we will get its amp from p4.

The output of the linen (k1) is patched into the kamp argument of an oscil.  This applies an envelope to the oscil.   The orchestra and score files now appear as:

instr 3

k1     linen     p4, p6, p3, p7      ; p4=amp

a1     oscil     k1, p5, 1      ; p5=freq

    out  a1             ; p6=attack time

endin                         ; p7=release time

Score to run with this example:

 f1  0  4096  10  1                        ; sine wave

; instr   start  duration  amp(p4)   freq(p5)   attack(p6)  release(p7)

   i3        0          1          10000         440           .05             .7

   i3        1.5       1          10000         440           .9               .1

   i3        3          1            5000         880           .02             .99

   i3        4.5       1            5000         880           .7               .01

   i3        6          2          20000         220           .5               .5

e

Previous	Next


04 - Chorusing
Toot 4: Chorusing

Previous	Next

Next we'll animate the basic sound by mixing it with two slightly detuned copies of itself.  We'll employ Csound's "cpspch" value converter which will allow us to specify the pitches by octave and pitch-class rather than by frequency, and we'll use the "ampdb" converter to specify loudness in dB rather than linearly.

Since we are adding the outputs of three oscillators, each with the same amplitude envelope, we'll scale the amplitude before we mix them.  Both "iscale" and "inote" are arbitrary names to make the design a bit easier to read.  Each is an i-rate variable, evaluated when the instrument is initialized.

instr 4	; toot4.orc

iamp = ampdb(p4)    	; convert decibels to linear amp

iscale = iamp * .333	; scale the amp at initialization

inote = cpspch(p5) 	; convert "octave.pitch" to cps

k1 linen     iscale, p6, p3, p7	; p4=amp

a3 oscil     k1, inote*.996, 1	; p5=freq

a2 oscil     k1, inote*1.004, 1	; p6=attack time

a1 oscil     k1, inote, 1	; p7=release time

a1 =    a1 + a2 + a3

    out  a1

endin

Score to run with this example:

f1 0 4096 10 1                                 ; sine wave

; instr  start  dur  amp(p4)  freq(p5)  attack(p6) release(p7)

   i4       0      1        75          8.04          .1               .7

   i4       1      1        70          8.02          .07             .6

   i4       2      1        75          8.00          .05             .5

   i4       3      1        70          8.02          .05             .4

   i4       4      1        85          8.04          .1               .5

   i4       5      1        80          8.04          .05             .5

   i4       6      2        90          8.04          .03            1

e

Previous	Next


05 - Vibrato
Toot 5: Vibrato

Previous	Next

To add some delayed vibrato to our chorusing instrument we use another oscillator for the vibrato and a line segment generator, linseg, as a means of controlling the delay.  linseg is a k-rate or a-rate signal generator which traces a series of straight line segments between any number of specified points.  The Csound manual describes it as:

kr	linseg	ia, idur1, ib[, idur2, ic[...]]

ar	linseg	ia, idur1, ib[, idur2, ic[...]]

Since we intend to use this to slowly scale the amount of signal coming from our vibrato oscillator, we'll choose the k-rate version.  The i-rate variables: ia, ib, ic, etc., are the values for the points.  The i-rate variables: idur1, idur2, idur3, etc., set the duration, in seconds, between segments.

instr 5	; toot5.orc

irel = .01	; set vibrato release time

idel1 = p3 - (p10 * p3)	; calculate initial delay (% of dur)

isus   = p3 - (idel1- irel)	; calculate remaining duration

iamp = ampdb(p4)

iscale = iamp * .333    	; p4=amp

inote = cpspch(p5)      	; p5=freq

k3     linseg    0, idel1, p9, isus, p9, irel, 0	; p6=attack time

k2     oscil     k3, p8, 1	; p7=release time

k1     linen     iscale, p6, p3, p7	; p8=vib rate

a3     oscil     k1, inote*.995+k2, 1	; p9=vib depth

a2     oscil     k1, inote*1.005+k2, 1	; p10=vib delay (0-1)

a1     oscil     k1, inote+k2, 1

    out  a1+a2+a3

endin

Score to run with this example:

f 1  0  4096  10  1

; instr  start  dur  amp    frq     attack  rel  vibrt  vibdpth  vibdel

   i5       0     3      86   10.00       .1      .7       7        6         .4

   i5       4     3      86   10.02       1       .2       6        6         .4

   i5       8     4      86   10.04       2      1         5        6         .4

e

Previous	Next


06 - Function generators
Toot 6: Function Generators

Previous	Next

The first character in a score statement is an opcode, determining an action request; the remaining data consists of numeric parameter fields (p-fields) to be used by that action.  So far we have been dealing with two different opcodes in our score: f and i.   i-statements, or note statements, invoke the p1 instrument at time p2 and turn it off after p3 seconds; all remaining p-fields are passed to the instrument.

F-statements, or lines with an opcode of f, invoke function-drawing subroutines called GENS (see GEN overview).  In Csound there are currently seventeen gen routines which fill wavetables in a variety of ways.  For example, GEN01 transfers data from a soundfile; GEN07 allows you to construct functions from segments of straight lines; and GEN10, which we've been using in our scores so far, generates composite waveforms made up of a weighted sum of simple sinusoids.   We have named the function "f1," invoked it at time 0, defined it to contain 512 points, and instructed GEN10 to fill that wavetable with a single sinusoid whose amplitude is 1.  GEN10 can in fact be used to approximate a variety of other waveforms, as illustrated by the following:

f1   0    2048 10   1                                  ; Sine

f2   0    2048 10   1    .5    .3   .25 .2   .167   .14  .125 .111 ; Sawtooth

f3   0    2048 10   1    0      .3    0 .2    0       .14     0   .111      ; Square

f4   0    2048 10   1    1      1     1 .7    .5      .3      .1       ; Pulse

For the opcode f, the first four p-fields are interpreted as follows:

p1 - table number - In the orchestra, you reference this table by its number.

p2 - creation time - The time at which the function is generated.

p3 - table size - Number of points in table - must be a power of 2,  or that plus 1.

p4 - generating subroutine - Which of the 17 GENS will you employ.

p5 -> p?  -  meaning determined by the particular GEN subroutine.

In the instrument and score below, we have added three additional functions to the score, and modified the orchestra so that the instrument can call them via p11.

instr 6                            ; toot6.orc

ifunc = p11                     ; select basic waveform

irel = .01                      ; set vibrato release

idel1 = p3 - (p10 * p3)         ; calculate initial delay

isus   = p3 - (idel1- irel)     ; calculate remaining dur

iamp = ampdb(p4)

iscale = iamp * .333            ; p4=amp

inote = cpspch(p5)              ; p5=freq

k3    linseg   0, idel1, p9, isus, p9, irel, 0     	; p6=attack time

k2    oscil     k3, p8, 1      	; p7=release time

k1    linen     iscale, p6, p3, p7	; p8=vib rate

a3    oscil     k1, inote*.999+k2, ifunc	; p9=vib depth

a2    oscil     k1, inote*1.001+k2, ifunc	; p10=vib delay (0-1)

a1    oscil     k1, inote+k2, ifunc

    out  a1 + a2 + a3

endin

Score to run with this example:

f1 0 2048 10 1                     	; Sine

f2 0 2048 10 1 .5 .3 .25 .2 .167 .14 .125 .111	; Sawtooth

f3 0 2048 10 1 0  .3  0   .2  0  .14  0   .111  	; Square

f4 0 2048 10 1 1 1 1 .7 .5 .3 .1	; Pulse

; ins  start   dur  amp  frq   attack  rel  vibrt  vibdpth  vibdel  waveform(f)

   i6     0      2      86   8.00    .03     .7     6          9           .8            1

   i6     3      2      86   8.02    .03     .7     6          9           .8            2

   i6     6      2      86   8.04    .03     .7     6          9           .8            3

   i6     9      3      86   8.05    .03     .7     6          9           .8            4

 e

Previous	Next


07 - Crossfading
Toot 7: Crossfade

Previous	Next

Now we will add the ability to do a linear crossfade between any two of our four basic waveforms.  We will employ our delayed vibrato scheme to regulate the speed of the crossfade.

instr 7                            ; toot7.orc

ifunc1 = p11   	; initial waveform

ifunc2 = p12          	; crossfade waveform

ifad1 = p3 - (p13 * p3)   	; calculate initial fade

ifad2 = p3 - ifad1     	; calculate remaining dur

irel = .01 	; set vibrato release

idel1 = p3 - (p10 * p3) 	; calculate initial delay

isus   = p3 - (idel1- irel) 	; calculate remaining dur

iamp = ampdb(p4)

iscale = iamp * .166  	; p4=amp

inote = cpspch(p5)  	; p5=freq

k3     linseg    0, idel1, p9, isus, p9, irel, 0    ; p6=attack time

k2     oscil     k3, p8, 1      	; p7=release time

k1     linen     iscale, p6, p3, p7 	; p8=vib rate

a6     oscil     k1, inote*.998+k2, ifunc2	; p9=vib depth

a5     oscil     k1, inote*1.002+k2, ifunc2    ; p10=vib delay (0-1)

a4     oscil     k1, inote+k2, ifunc2	; p11=initial wave

a3     oscil     k1, inote*.997+k2, ifunc1	; p12=cross wave

a2     oscil     k1, inote*1.003+k2, ifunc1	; p13=fade time

a1     oscil     k1, inote+k2, ifunc1

kfade  linseg 1, ifad1, 0, ifad2, 1

afunc1 = kfade * (a1+a2+a3)

afunc2 = (1 - kfade) * (a4+a5+a6)

    out  afunc1 + afunc2

endin

Score to run with this example:

   f1 0 2048 10 1          	; Sine

   f2 0 2048 10 1 .5 .3 .25 .2 .167 .14 .125 .111	; Sawtooth

   f3 0 2048 10 1 0  .3  0   .2  0  .14  0   .111  	; Square

   f4 0 2048 10 1 1 1 1 .7 .5 .3 .1	; Pulse

; ins  strt  dur  amp     frq     atk    rel  vibrt  vbdpt  vibdel  startwave  endwave   crosstime

   i7   0      5     96    8.07   .03     .1     5         6        .99            1               2                .1

   i7   6      5     96    8.09   .03     .1     5         6        .99            1               3                .1

   i7 12      8     96    8.07   .03     .1     5         6        .99            1               4                .1

Previous	Next


08 - Sound input
Toot 8: Soundin

Previous	Next

Now instead of continuing to enhance the same instrument, let us design a totally different one.  We'll read a soundfile into the orchestra, apply an amplitude envelope to it, and add some reverb.  To do this we will employ Csound's soundin and reverb generators.  The first is described as:

a1   soundin   ifilcod[, iskiptime][, iformat]

soundin derives its signal from a pre-existing file.  ifilcod is either the filename in double quotes, or an integer suffix (.n) to the name "soundin".  Thus the file "soundin.5" could be referenced either by the quoted name or by the integer 5.  To read from 500ms into this file we might say:

a1   soundin   "soundin.5",  .5

The Csound reverb generator is actually composed of four parallel comb filters plus two allpass filters in series.  Although we could design a variant of our own using these same primitives, the preset reverb is convenient, and simulates a natural room response via internal parameter values.  Only two arguments are required - the input (asig) and the reverb time (krvt).

ar   reverb    asig, krvt

The soundfile instrument with artificial envelope and a reverb (included directly) is as follows:

instr 8                                 ; toot8.orc

dur           =         p3

amp         =         p4

skiptime   =         p5

attack      =         p6

release    =         p7

rvbtime    =         p8

rvbgain    =         p9

kamp        linen          iamp, iattack, idur, irelease

asig        soundin   "soundin.aiff", iskiptime

arampsig    =   kamp * asig

aeffect     reverb    asig, irvbtime

arvbreturn  =   aeffect * irvbgain

    out            arampsig + arvbreturn

endin

Score to run with this example:

; ins  start     dur      amp   skip    atk    rel   rvbtime rvbgain

   i8     0        1           .3       0      .03     .1      1.5        .2

   i8     2        1           .3       0      .1       .1      1.3        .2

   i8    3.5      2.25      .3       0      .5       .1      2.1        .2

   i8    4.5      2.25      .3       0      .01     .1      1.1        .2

   i8     5        2.25      .3       .1     .01     .1      1.1        .1

e

Previous	Next


09 - Global stereo reverb
Toot 9: Global Stereo Reverb

Previous	Next

In the previous example you may have noticed the soundin source being "cut off" at ends of notes, because the reverb was inside the instrument itself.  It is better to create a companion instrument, a global reverb instrument, to which the source signal can be sent.  Let's also make this stereo.

Variables are named cells which store numbers. In Csound, they can be either local or global, are available continuously, and can be updated at one of four rates - setup, i-rate, k-rate, or a-rate.

Local Variables (which begin with the letters p, i, k, or a) are private to a particular instrument.  They cannot be read from, or written to, by any other instrument.

Global Variables are cells which are accessible by all instruments.  Three of the same four variable types are supported (i,  k, and a), but these letters are preceded by the letter g to identify them as "global."   Global variables are used for "broadcasting" general values, for communicating between instruments, and for sending sound from one instrument to another.

The reverb instr99 below receives input from instr9 via the global a-rate variable garvbsig.  Since instr9 adds into this global, several copies of instr9 can do this without losing any data.  The addition requires garvbsig to be cleared before each k-rate pass through any active instruments.  This is accomplished first with an init statement in the orchestra header, giving the reverb instrument a higher number than any other (instruments are performed in numerical order), and then clearing garvbsig within instr99 once its data has been placed into the reverb.

sr        =    18900          ; toot9.orc

kr        =    945

ksmps     =    20

nchnls    =    2              ; stereo

garvbsig  init      0         ; make zero at orch init time

instr 9

   idur        =    p3

   iamp   =    p4

   iskiptime   =    p5

   iattack     =    p6

   irelease    =    p7

   ibalance    =    p8        ; panning: 1=left, .5=center, 0=right

   irvbgain    =    p9

   kamp   linen          iamp, iattack, idur, irelease

   asig        soundin   "soundin.aiff", iskiptime

   arampsig    =         kamp * asig

          outs      arampsig * ibalance,  arampsig * (1 - ibalance)

   garvbsig    =         garvbsig + arampsig * irvbgain

endin

instr 99                 ; global reverb

   irvbtime    =    p4

   asig        reverb    garvbsig,  irvbtime ; put global signal into reverb

          outs asig, asig

   garvbsig    =    0              ; then clear it

endin

In the score we turn the global reverb on at time 0 and keep it on until irvbtime after the last note.

 ; ins     strt dur  rvbtime                  ; toot9.sco

  i99     0    9.85 2.6

; ins   start  dur     amp   skip   atk   rel   balance(0-1)   rvbsend

   i9      0      1         .5       0     .02    .1             1               .2

   i9      2      2         .5       0     .03    .1             0               .3

   i9      3.5   2.25    .5       0     .9      .1             .5              .1

   i9      4.5   2.25    .5       0   1.2      .1             0               .2

   i9      5      2.25    .5       0     .2      .1             1               .3

e

Previous	Next


10 - Filtered noise
Toot 10: Filtered Noise

Previous	Next

The following instrument uses the Csound rand unit to produce noise, and a reson unit to filter it.  The bandwidth of reson will be set at i-time, but its center frequency will be swept via a line unit through a wide range of frequencies during each note.  We add reverb as above.

 garvbsig  init      0

instr 10                      ; toot10.orc

   iattack     =    .01

   irelease    =    .2

   iwhite      =    10000

   idur        =    p3

   iamp   =    p4

   isweepstart      =    p5

   isweepend   =    p6

   ibandwidth  =    p7

   ibalance    =    p8        ; pan: 1 = left, .5 = center, 0 = right

   irvbgain    =    p9

   kamp   linen     iamp, iattack, idur, irelease

   ksweep line isweepstart, idur, isweepend

   asig        rand iwhite

   afilt       reson     asig, ksweep, ibandwidth

   arampsig    =    kamp * afilt

          outs      arampsig * ibalance, arampsig * (1 - ibalance)

   garvbsig    =    garvbsig  +  arampsig * irvbgain

endin

instr 100

    irvbtime    =    p4

    asig        reverb  garvbsig,  irvbtime

           outs      asig, asig

    garvbsig    =    0

endin

Score to run with this example:

; ins     strt      dur  rvbtime                       ; toot10.sco

   i100   0    15   1.1

   i100   15   10   5

; ins     strt      dur    amp    stswp   ndswp   bndwth   balance(0-1)  rvbsend

   i10       0       2      .05      5000        500        20              .5                  .1

   i10       3       1      .05      1500      5000        30              .5                  .1

   i10       5       2      .05        850      1100        40              .5                  .1

   i10       8       2      .05      1100      8000        50              .5                  .1

   i10       8       .5     .05      5000      1000        30              .5                  .2

   i10       9       .5     .05      1000      8000        40              .5                  .1

   i10      11      .5     .05        500      2100        50              .4                  .2

   i10      12      .5     .05      2100      1220        75              .6                  .1

   i10      13      .5     .05      1700      3500      100              .5                  .2

   i10      15      5      .01      8000        800        60              .5                  .15

e

Previous	Next


11 - Score preprocessing
Toot 11: Carry, Tempo & Sort

Previous	Next

We now use a plucked string instrument to explore some of Csound's score preprocessing capabilities.  Since the focus here is on the score, the instrument is presented without explanation.

      instr 11

          asig1     pluck     ampdb(p4)/2, p5, p5, 0, 1

          asig2     pluck     ampdb(p4)/2, p5 * 1.003,  p5 * 1.003, 0, 1

               out  asig1+asig2

     endin

The score can be divided into time-ordered sections by the S statement.  Prior to performance, each section is  processed by three routines: Carry, Tempo, and Sort.  The score toot11.sco has multiple sections containing each of the examples below, in both of the forms listed.

CARRY

The Carry feature allows a dot ("." ) in a p-field to indicate that the value is the same as above, provided the instrument is the same.  Thus the following two examples are identical:

;  ins    start   dur    amp   freq

   i11    0         1       90    200

   i11    1          .        .      300

   i11    2          .        .      400

; ins  start     dur     amp   freq

   i11    0        1       90     200

   i11    1        1       90     300

   i11    2        1       90     400

A special form of the carry feature applies to p2 only.  A "+" in p2 will be given the value of p2+p3 from the previous i statement.  The "+" can also be carried with a dot:

 ;  ins  start   dur   amp  freq

    i11    0      1       90   200

    i  .     +       .        .     300

    i  .     .        .        .     500

;  ins    start   dur   amp  freq

    i11    0       1      90    200

    i11    1       1      90    300

    i11    2       1      90    500

The carrying dot may be omitted when there are no more explicit pfields on that line:

;  ins    start dur  amp  freq

   i11      0    1     90   200

   i11      +    2

   i11

;  ins    start  dur   amp  freq

   i11      0      1     90    200

   i11      1      2     90    200

   i11      3      2     90    200

A variant of the carry feature is Ramping, which substitutes a sequence of linearly interpolated values for a ramp symbol ( < ) spanning any two values of a pfield.  Ramps work only on consecutive calls to the same instrument, and they cannot be applied to the first three p-fields.

; ins   start  dur  amp  freq

  i11     0      1    90   200

  i .       +       .     <     <

  i .       .        .     <    400

  i .       .        .     <     <

  i .       .       4    70   200

; ins   start  dur  amp  freq

  i11     0      1    90    200

  i11     1      1    85    300

  i11     2      1    80    400

  i11     3      1    75    300

  i11     4      4    70    200

TEMPO

The unit of time in a Csound score is the beat - normally one beat per second.  This can be modified by a Tempo Statement, which enables the score to be arbitrarily time-warped. Beats are converted to their equivalent in seconds during score pre-processing of each Section.  In the absence of a Tempo statement in any Section, the following tempo statement is inserted:

t   0   60

It means that at beat 0 the tempo of the Csound beat is 60 (1 beat per second).  To hear the Section at twice the speed, we have two options:  1) cut all p2 and p3 in half and adjust the start times, or 2) insert the statement  t  0  120  within the Section.

The Tempo statement can also be used to move between different tempi during the score, thus enabling ritardandi and accelerandi.  Changes are linear by beat size (see the Csound manual).  The following statement will cause the score to begin at tempo 120, slow to tempo 80 by beat 4, then accelerate to 220 by beat 7:

t    0   120   4   80    7   220

The following will produce identical soundfiles:

t  0  120       ; Double-time via Tempo

; ins   start   dur  amp  freq

  i11     0      .5     90   200

    i .     +       .       <      <

    i .      .       .       <    400

    i .      .       .       <      <

    i .      .       2     70   200

; ins    start  dur  amp  freq

  i11      0      1    90   200

    i .      +       .     <      <

    i .      .        .     <    400

    i .      .        .     <      <

    i .      .       4    70   200

The following includes an accelerando and ritard.  It should be noted, however, that the ramping feature is applied after time-warping, and is thus proportional to elapsed chronological time.  While this is perfect for amplitude ramps, frequency ramps will not result in harmonically related pitches during tempo changes.  The frequencies needed here are thus made explicit.

t     0   60   4    400  8    60   ; Time-warping via Tempo

;    ins  start   dur  amp   freq

     i11    0      1     70     200

     i .     +       .       <      500

     i .     .        .      90     800

     i .     .        .       <      500

     i .     .        .      70     200

     i .     .        .      90   1000

     i .     .        .       <      600

     i .     .        .      70     200

     i .     .       8      90     100

Three additional score features are extremely useful in Csound.   The s statement was used above to divide a score into Sections for individual pre-processing.  Since each s statement establishes a new relative time of 0, and all actions within a section are relative to that, it is convenient to develop the score one section at a time, then link the sections into a whole later.

Suppose we wish to combine the six above examples (call them toot11a - toot11f) into one score.  One way is to start with toot11a.sco, calculate its total duration and add that value to every starting time of toot11b.sco, then add the composite duration to the start times of toot11c.sco, etc.  Alternatively, we could insert an s statement between each of the sections and run the entire score.  The file toot11.sco, which contains a sequence of all of the above score examples, did just that.

The f0 statement, which creates an "action time" with no associated action, is useful in extending the duration of a section.   Two seconds of silence are added to the first two sections below.

;    ins  start     dur  amp  freq           ; toot11g.sco

     i11  0    2    90   100

     f 0  4                             ; The f0 Statement

     s                                  ; The Section Statement

     i11  0    1    90   800

     i .  +    .    .    400

     i .  .    .    .    100

     f 0  5

     s

     i11  0         4    90   50

 e

SORT

During preprocessing of a score section, all action-time statements are sorted into chronological order by p2 value.  This means that notes can be entered in any order, that you can merge files, or work on instruments as temporarily separate sections, then have them sorted automatically when you run Csound on the file.

The file below contains excerpts from this section of the rehearsal chapter and from instr6 of the tutorial, and combines them as follows:

;    ins   start  dur   amp  freq           ; toot11h.sco

       i11   0      1     70   100            ; Score Sorting

       i .     +      .       <    <

       i .     .       .       <    <

       i .     .       .      90   800

       i .     .       .      <    <

       i .     .       .      <    <

       i .     .       .     70   100

       i .     .       .     90   1000

       i .     .       .      <    <

       i .     .       .      <    <

       i .     .       .      <    <

       i .     .       .     70   <

       i .     .       8    90   50

   f1 0 2048 10 1                                                    ; Sine

   f2 0 2048 10 1 .5 .3 .25 .2 .167 .14 .125 .111    ; Sawtooth

   f3 0 2048 10 1 0  .3  0   .2  0 .14  0   .111          ; Square

   f4 0 2048 10 1 1 1 1 .7 .5 .3 .1                           ; Pulse

; instr  start  dur  amp     frq     atk   rel   vibrt  vibdpth  vibdel    waveform

   i6       0      2     86     9.00   .03    .1      6        5          .4            1

   i6       2      2     86     9.02   .03    .1      6        5          .4            2

   i6       4      2     86     9.04   .03    .1      6        5          .4            3

   i6       6      4     86     9.05   .05    .1      6        5          .4            4

Previous	Next


12 - Tables & Labels
Toot 12: Tables & Labels

Previous	Next

This is by far our most complex instrument.  In it we have designed the ability to store pitches in a table and then index them in three different ways:

1) directly,

2) via an LFO (Low Frequency Oscillator)

3) randomly (see rand).  As a means of switching between these three methods, we will use Csound's program control statements and logical and conditional operations.

instr 12

iseed     =      p8

iamp     =  ampdb(p4)

kdirect  =  p5

imeth    =  p6

ilforate  =      p7                 ; lfo and random index rate

itab       =     2

itablesize =     8

if (imeth == 1)   igoto direct

if (imeth == 2)   kgoto lfo

if (imeth == 3)   kgoto random

 direct:     kpitch    table      kdirect, itab         ; index "f2" via p5

kgoto    contin

 lfo:   kindex    phasor  ilforate

kpitch     table     kindex  *  itablesize, itab

kgoto      contin

 random: kindex    randh   int(7), ilforate, iseed

kpitch     table     abs(kindex), itab

 contin:   kamp      linseg   0, p3 * .1, iamp, p3 * .9, 0  ; amp envelope

asig        oscil     kamp, cpspch(kpitch), 1    ; audio osc

        out       asig

endin

Score to run with this orchestra:

  f1 0 2048 10 1                             ; Sine

  f2 0 8 -2  8.00 8.02 8.04 8.05 8.07 8.09 8.11 9.00   ; cpspch C major scale

; method 1 - direct index of table values

; ins   start     dur   amp  index  method  lforate   rndseed

  i12     0         .5      86       7         1            0            0

  i12     .5        .5      86       6         1            0

  i12     1         .5      86       5         1            0

  i12     1.5      .5      86       4         1            0

  i12     2         .5      86       3         1            0

  i12     2.5      .5      86       2         1            0

  i12     3         .5      86       1         1            0

  i12     3.5      .5      86       0         1            0

  i12     4         .5      86       0         1            0

  i12     4.5      .5      86       2         1            0

  i12     5         .5      86       4         1            0

  i12     5.5    2.5      86       7         1            0

s

; method 2 - lfo index of table values

; ins    start   dur  amp  index   method lforate   rndseed

  i12     0       2      86      0          2           1            0

  i12     3       2      86      0          2           2

  i12     6       2      86      0          2           4

  i12     9       2      86      0          2           8

  i12    12      2      86      0          2         16

s

; method 3 - random index of table values

; ins   start   dur  amp  index  method  rndrate  rndseed

  i12     0       2     86       0         3             2           .1

  i12     3       2     86       0         3             3           .2

  i12     6       2     86       0         3             4           .3

  i12     9       2     86       0         3             7           .4

  i12    12      2     86       0         3           11           .5

  i12    15      2     86       0         3           18           .6

  i12    18      2     86       0         3           29           .7

  i12    21      2     86       0         3           47           .8

  i12    24      2     86       0         3           76           .9

  i12    27      2     86       0         3         123           .9

  i12    30      5     86       0         3         199           .1

Previous	Next


13 - Spectral fusion
Toot 13: Spectral Fusion

Previous	Back to tutorial index

For our final instrument, we will employ three unique synthesis methods - Physical Modeling, Formant-Wave Synthesis, and  Non-linear Distortion.  Three of Csound's most powerful unit generators - pluck,  fof, and foscil, make this complex task a fairly simple one.  The Reference Manual describes these as follows:

a1    pluck   kamp, kcps, icps, ifn, imeth [, iparm1, iparm2]

pluck simulates the sound of naturally decaying plucked strings by filling a cyclic decay buffer with noise and then smoothing it over time according to one of several methods.  The unit is based on the  Karplus-Strong algorithm.

a2    fof    xamp, xfund, xform, koct, kband, kris, kdur kdec, iolaps, ifna, ifnb, itotdur[, iphs][, ifmode]

fof simulates the sound of the male voice by producing a set of harmonically related partials (a formant region) whose spectral envelope can be controlled over time.  It is a special form of granular synthesis, based on the CHANT program from IRCAM by Xavier Rodet et al.

a1    foscil   xamp, kcps, kcar, kmod, kndx, ifn [, iphs]

foscil is a composite unit which banks two oscillators in a simple FM configuration, wherein the audio-rate output of one (the "modulator") is used to modulate the frequency input of another (the "carrier.")

The plan for our instrument is to have the plucked string attack dissolve into an FM sustain which transforms into a vocal release.  The orchestra and score are as follows:

instr 13                 ; toot13.orc

amp   = ampdb(p4) / 2     ; amplitude, scaled for two sources

pluckamp   = p6           ; % of total amp, 1=dB amp as in p4

pluckdur   = p7*p3        ; % of total dur, 1=entire dur of note

pluckoff   = p3 - ipluckdur

fmamp      =  p8               ; % of total amp, 1=dB amp as in p4

fmrise     = p9*p3        ; % of total dur, 1=entire dur of note

fmdec      = p10*p3       ; % of total duration

fmoff      = p3 - (ifmrise + ifmdec)

ndex  = p11

vibdepth   = p12

vibrate    = p13

formantamp = p14               ; % of total amp, 1=dB amp as in p4

formantrise     = p15*p3       ; % of total dur, 1=entire dur of note

formantdec = p3 - iformantrise

kpluck linseg    ipluckamp, ipluckdur, 0, ipluckoff, 0

apluck1     pluck     iamp, p5, p5, 0, 1

apluck2     pluck     iamp, p5*1.003, p5*1.003, 0, 1

apluck =    kpluck * (apluck1+apluck2)

kfm         linseg    0, ifmrise, ifmamp, ifmdec, 0, ifmoff, 0

kndx   =    kfm * index

afm1   foscil    iamp, p5, 1, 2, kndx, 1

afm2   foscil    iamp, p5*1.003, 1.003, 2.003, kndx, 1

afm         =    kfm * (afm1+afm2)

kfrmnt linseg    0, iformantrise, iformantamp, iformantdec, 0

kvib        oscil     ivibdepth,ivibrate,1

afrmnt1     fof    iamp, p5+kvib, 650, 0, 40, .003, .017, .007, 4, 1, 2, p3

afrmnt2     fof    iamp, (p5*1.001)+kvib*.009, 650, 0, 40, .003,.017,.007, 10,1,2,p3

aformnt     =    kfrmnt * (afrmnt1+afrmnt2)

 	out  apluck + afm + aformnt

endin

Score to run with this orchestra

f1  0  8192  10  1            ; sine wave f2  0  2048   19  .5  1  270  1         ; sigmoid rise

;ins   strt  dur  amp   frq   plkmp   plkdr   fmp  fmris   fmdec  indx  vbdp  vbrt   frmp  fris

 i13    0     5    80    200      .8        .3       .7      .2       .35       8        1        5       3     .5

 i13    +     8    80    100       .         .4       .7      .35     .35       7        1        6       3     .7

 i13    .    13    80      50       .         .3       .7      .2       .4         6        1        4       3     .6

Previous	Back to tutorial index


FOF synthesis tutorial
A FOF Synthesis Tutorial

By J.M.Clarke University of Huddersfield

The fof synthesis generator in Csound has more parameter fields than other modules. To help the user become familiar with these parameters this tutorial will take a simple orchestra file using just one fof unit-generator and demonstrate the effect of each parameter in turn. To produce a good vocal imitation, or a sound of similar sophistication, an orchestra containing five or more fof generators is required and other refinements (use of random variation of pitch etc.) must be made. The sounds produced in these initial explorations will be much simpler and consequently less interesting but they will help to show clearly the basic elements of fof synthesis. This tutorial assumes a basic working knowledge of Csound itself. The specification of the fof unit-generator (as found in the main Csound manual) is:

ar  fof  xamp,  xfund,  xform,  koct,  kband,  kris,  kdur,  kdec,  iolaps,  ifna,  ifnb,  itotdur [, iphs] [, ifmode]

where

xamp, xfund, xform  	can receive any rate (constant, control or audio)

koct, kband, kdris, kdur, kdec 	can receive only constants or control rates

iolaps, ifna, ifnb, itotdur 	must be given a fixed value at initialization

[iphs][ifmode] 	are optional, defaulting to 0.

The following orchestra contains a simple instrument we will use for exploring each parameter in turn. On the faster machines (DECstation, SparcStation, SGI Indigo) it will run in real time.

sr = 22050

kr = 441

ksmps = 50

instr     1

a1   fof  15000, 200, 650, 0, 40, .003, .02, .007, 5, 1, 2, p3

out  a1

endin

It should be run with the following score:

f1  0  4096  10  1

f2  0  1024  19  .5  .5  270  .5

i1  0  3

e

The result is very basic. This is not surprising since we have created only one formant region (a vocal imitation would need at least five) and have no vibrato or random variation of the parameters.  By varying one parameter at a time we will help the reader learn how the unit-generator works.  Each of the following "variations" starts from the model. Parameters not specified remain as given.

xamp = amplitude

The first input parameter controls the amplitude of the generator. At present our model uses a constant amplitude, this can be changed so that the amplitude varies according to a line function:

a2   linseg    0,  p3*.3,  20000,  p3*.4,  15000,  p3*.3,  0 a1   fof  a2, ......(as before)...

The amplitude of a fof generator needs care. xamp does not necessarily indicate the maximum output, which can also depend on the rise pattern, bandwidth, and the presence of any "overlaps".

xfund = fundamental frequency

This parameter controls the pitch of the fundamental of the unit generator. Starting again from the original model this example demonstrates an exaggerated vibrato:

a2   oscil     20,  5,  1

a1   fof  15000,  200+a2,  etc........

fof synthesis produces a rapid succession of (normally) overlapping excitations or granules. The fundamental is in fact the speed at which new excitations are formed and if the fundamental is very low these excitations are heard as separate granules. In this case the fundamental is not so much a pitch as a pulse speed. The possibility of moving between pitch and pulse, between timbre and granular texture is one of the most interesting aspects of fof. For a simple demonstration try the following variation. It will be especially clear if the score note is lengthened to about 10 seconds.

a2   expseg  5,  p3*.8,  200,  p3*.2,  150 a1   fof   15000,  a2  etc........

koct = octaviation coefficient

Skipping a parameter, we come to an unusual means of controlling the fundamental: octaviation. This parameter is normally set to 0. For each unit increase in koct the fundamental pitch will drop by one octave. The change of pitch is not by the normal means of glissando, but by gradually fading out alternate excitations (leaving half the original number). Try the following (again with the longer note duration):

k1   linseg    0,  p3*.1,  0,  p3*.8,  6,  p3*.1,  6

a1   fof  15000,  200,  650,  k1  etc.........

This produces a drop of six octaves; if the note is sufficiently long you should be able to hear the fading out of alternate excitations towards the end.

xform = formant frequency;
ifmode = formant mode (0 = striated, non-0 = smooth)

The spectral output of a fof unit-generator resembles that of an impulse generator filtered by a band pass filter. It is a set of partials above a fundamental xfund with a spectral peak at the formant frequency xform.  Motion of the formant can be implemented in two ways. If ifmode = 0, data sent to xform has effect only at the start of a new excitation. That is, each excitation gets the current value of this parameter at the time of creation and holds it until the excitation ends. Successive overlapping excitations can have different formant frequencies, creating a richly varied sound. This is the mode of the original CHANT program. If ifmode is non-zero, the frequency of each excitation varies continuously with xform.  This allows glissandi of the formant frequency. To demonstrate these differences we take a very low fundamental so that the granules can be heard separately and the formant frequency is audible not as the center frequency of a "band" but as a pitch in its own right. Compare the following in which only ifmode is changed:

a2   line 400,  p3,  800

a1   fof  15000,  5,  a2,  0,  1,  .003,  .5,  .1,  3,  1,  2,  p3,  0,  0

a2   line 400,  p3,  800

a1   fof  15000,  5,  a2,  0,  1,  .003,  .5,  .1,  3,  1,  2,  p3,  0,  1

In the first case the formant frequency moves by step at the start of each excitation, whereas in the second it changes smoothly. A more subtle difference is perceived with higher fundamental frequencies. (Note that the later fof parameters were changed in this example to lengthen the excitations so that their pitch could be heard easily.)

xform also permits frequency modulation of the formant frequency. Applying FM to an already complex sound can lead to strange results, but here is a simple example:

acarr     line 400,  p3,  800

index     =    2.0

imodfr    = 400

idev       =    index * imodfr

amodsig oscil  idev, imodfr, 1

a1   fof  15000,  5,  acarr+amodsig,  0,  1,  .003,  .5,  .1,  3, 1,  2,  p3,  0,  1

kband = formant bandwidth
kris, kdur, kdec = risetime, duration and decaytime (in seconds)

These parameters control the shape and length of the fof granules. They are shaped in three segments: a rise, a middle decay, and a terminating decay. For very low fundamentals these are perceived as an amplitude envelope, but with higher fundamentals (above 30 Hz) the granules merge together and these parameters effect the timbre of the sound. Note that these four parameters influence a new granule only at the time of its initialization and are fixed for its duration; later changes will affect only subsequent granules. We begin our examination with low frequencies.

k1   line .003,  p3,  .1                          ; kris

a1   fof  15000,  2,  300,  0,  0,  k1,  .5,  .1,  2,  1,  2,  p3

Run this with a note length of 10 seconds. Notice how the attack of the envelope of the granules lengthens. The shape of this attack is determined by the forward shape of ifnb (here a sigmoid).

Now try changing kband:

k1   linseg    0,  p3,  10                             ; kband

a1   fof  15000,  2,  300,  0,  k1,  .003,  .5,  .1,  2,  1,  2,  p3

Following its rise, an excitation has a built-in exponential decay and kband determines its rate. The bigger kband the steeper the decay; zero means no decay. In the above example the successive granules had increasingly fast decays.

k1   linseg    .3,  p3,  .003

a1   fof  15000,  2,  300,  0,  0,  .003,  .4,  k1,  2,  1,  2, p3

This demonstrates the operation of kdec. Because an exponential decay never reaches zero it must be terminated gracefully. kdur is the overall duration (in seconds from the start of the excitation), and kdec is the length of the terminating decay. In the above example the terminating decay starts very early in the first granules and then becomes progressively later. Note that kband is set to zero so that only the terminating decay is evident.

In the next example the start time of the termination remains constant, but its length gets shorter:

k1   expon     .3,  p3,  .003

a1   fof  15000,  2,  300,  0,  0,  .003,  .01 + k1,  k1,  2,  1, 2,  p3

It may be surprising to find that for higher fundamentals the local envelope determines the spectral shape of the sound. Electronic and computer music has often shown how features of music we normally consider independent (such as pitch, timbre, rhythm) are in fact different aspects of the same thing. In general, the longer the local envelope segment the narrower the band of partials around that frequency. kband determines the bandwidth of the formant region at -6dB, and kris controls the skirtwidth at -40dB. Increasing kband increases the local envelope's exponential decay rate, thus shortening it and increasing the -6dbB spectral region. Increasing kris (the envelope attack time) inversely makes the -40dB spectral region smaller.

The next example changes first the bandwidth then the skirtwidth. You should be able to hear the difference.

k1   linseg    100,  p3/4,  0,  p3/4,  100,  p3/2,  100              ; kband

k2   linseg    .003,  p3/2,  .003,  p3/4,  .01,  p3/4,  .003         ; kris

a1   fof  15000,  100,  440,  0,  k1,  k2,  .02,  .007,  3,  1, 2,  p3

[In the first half of the note kris remains constant while kband broadens then narrows again. In the second half, kband is fixed while kris lengthens (narrowing the spectrum) then returns again.]

Note that kdur and kdec don't really shape the spectrum, they simply tidy up the decay so as to prevent unwanted discontinuities which would distort the sound. For vocal imitations these parameters are typically set at .017 and .007 and left unchanged. With high ("soprano") fundamentals it is possible to shorten these values and save computation time (reduce overlaps).

iolaps  = number of overlap spaces

Granules are created at the rate of the fundamental frequency, and new granules are often created before earlier ones have finished, resulting in overlaps. The number of overlaps at any one time is given by xfund * kdur. For a typical bass note the calculation might be 200 * .018 = 3.6, and for a soprano note 660 * .015 = 9.9. fof needs at least this number (rounded up) of spaces in which to operate. The number can be over-estimated at no computation cost, and at only a small space cost.  If there are insufficient overlap spaces during operation, the note will terminate.

ifna, ifnb  = stored function tables

Identification numbers of two function tables (see the fof entry in the manual proper).

itotdur  = total duration within which all granules in a note must be completed

So that incomplete granules are not cut off at the end of a note fof will not create new granules if they will not be completed by the time specified. Normally given the value "p3" (the note length), this parameter can be changed for special effect; fof will output zero after time itotdur.

iphs  = initial phase (optional, defaulting to 0).

Specifies the initial phase of the fundamental. Normally zero, but giving different fof generators different initial phases can be helpful in avoiding "zeros" in the spectrum.


SCOT: Score translation utility
SCOT: Score translator

(NOTE: SCOT was discontinued as of Csound version 3.49)

Scot is a language for describing scores in a fashion that parallels traditional music notation.  Scot is also the name of a program which translates scores written in this language into standard numeric score format so that the score can be performed by Csound.  The result of this translation is placed in a file called score.  A score file written in Scot (named file.sc, say) can be sent through the translator by the command

scot  file.sc

The resulting numeric score can then be examined for errors, edited, or performed by typing

csound  file.orc  score

Alternatively, the command

csound  file.orc  -S file.sc

would combine both processes by informing Csound of the initial score format.

Internally, a Scot score has at least three parts:  a section to define instrument names, a section to define functions, and one or more actual score sections.  It is generally advisable to keep score sections short to facilitate finding errors.  The overall layout of a Scot score has three main sections:

orchestra { .... }

functions { .... }

score { .... }

The last two sections may be repeated as many times as desired.  The functions section is also optional.  Throughout this Scot document, bear in mind that you are free to break up each of these divisions into as many lines as seem convenient, or to place a carriage return anywhere you are allowed to insert a space, including before and after the curly brackets.  Furthermore, you may use as many spaces or tabs as you need to make the score easy to read.  Scot imposes no formatting restrictions except that numbers, instrument names, and keywords (for example, orchestra) may not be broken with spaces.  You may insert comments (such as measure numbers) anywhere in the score by preceding them with a semicolon.  A semicolon causes Scot to ignore the rest of a line.

ORCHESTRA DECLARATION SECTION

The orchestra section of a Scot score serves to designate instrument names for use within the score.  This is a matter of convenience, since an orchestra knows instruments only by numbers, not names.  If you declare three instruments, such as:

     orchestra { flute=1 cello=2 trumpet=3 }

Csound will neither know nor care what you have named the note lists.  However, when you use the name $flute, Scot will know you are referring to instr 1 in the orchestra, $cello will refer to instr 2, and $trumpet will be instr 3.  You may meaningfully skip numbers or give several instruments the same number.  It is up to you to make sure that your orchestra has the correct instruments and that the association between these names and the instruments is what you intend.  There is no limit (or a very high one, at least) as to how many instruments you can declare.

FUNCTION DECLARATION SECTION

The major purpose of this division is to allow you to declare function tables for waveforms, envelopes, etc.  These functions are declared exactly as specified for Csound.  In fact, everything you type between the brackets in this section will be passed directly to the resulting numeric score with no modification, so that mistakes will not be caught by the Scot program, but rather by the subsequent performance.  You can use this section to write notes for instruments for which traditional pitch-rhythm notation is inappropriate.  The most common example would be turning on a reverb instrument.  Instruments referenced in this way need not appear in the Scot orchestra declaration.  Here is a possible function declaration:

functions {

f1 0 256 10 1 0 .5 0 .3

f2 0 256 7 0 64 1 64 .7 64 0

i9 0 -1 3           ; this turns on instr 9

}

SCORE SECTION

The Scot statements contained inside the braces of each score statement is translated into a numeric score Section (q.v.).  It is wise to keep score sections small, say seven or eight measures of five voices at a time.  This avoids overloading the system, and simplifies error checking.

The beginning of the score section is specified by typing:

     score {

Everything which follows until the braces are closed is within a single section.  Within this section you write measures of notes in traditional pitch and rhythm notation for any of the instrument names listed in your orchestra declaration. These notes may carry additional information such as slurs, ties and parameter fields.  Let us now consider the format for notes entered in a Scot score.

The first thing to do is name the instrument you want and the desired meter.  For example, to write some 4/4 measures for the cello, type:

     $cello

     !ti "4/4"

The dollar sign and exclamation point tell Scot that a special declarator follows. The time signature declarator is optional;  if present, Scot will check the number of beats in each measure for you.

PITCH AND RHYTHM

The two basic components of a note statement are the pitch and duration.  Pitch is specified using the alphabetic note name, and duration is specified using numeric characters.  Duration is indicated at the beginning of the note  as a number representing the division of a whole beat.  You may always find  the number specifying a given duration by thinking of how many times that  duration would fit in a 4/4 measure.  Also, if the duration is followed by a dot (`.')  it is increased by 50%, exactly as in traditional notation.  Some sample durations are listed below:

whole note	  1

half note           	  2

quarter note     	  4

dotted quarter note     	  4.

double dotted quarter  	  4..

half note triplet	  6

eighth note  	  8

eighth note triplet   	12

sixteenth note	16

thirty-second note       	32

Pitch is indicated next by first (optionally) specifying the register and then the note name, followed by an accidental if desired.  Normally, the "octave following" feature is in effect.  This feature causes any note named to lie within the interval of an augmented fourth of the previous note, unless a new register is chosen.  The first note you write will always be within a fourth of middle c unless you choose a different register.

For example, if the first note of an instrument part is notated g flat, the scot program assigns the pitch corresponding to the g flat below middle c.  On the other hand, if the first note is f sharp, the pitch assigned will be the f sharp above middle c.  Changes of register are indicated by a preceding apostrophe for each octave displacement upward or a preceding comma for each octave displacement downward.  Commas and apostrophes always displace the pitch by the desired number of octaves starting from that note which is within an augmented fourth of the previous pitch.

If you ever get lost, prefacing the pitch specification with an `=' returns the reference to middle c.  It is usually wise to use the equals sign in your first note statement and whenever you feel uncertain as to what the current registration is.  Let us now write two measures for the cello part, the first starting in the octave below middle c and the second repeating but starting in the octave above middle c:

$cello

!ti "4/4"

4=g 4e 4d 4c/ 4='g 4e 4d 4c

As you can see, a slash indicates a new measure and we have chosen to use the dummy middle c to indicate the new register.  A more convenient way of notating these two measures would be to type the following:

$cello

!ti "4/4"

4=g e d c/ ''g e d c

You may observe in this example that the quarter note duration carries to the following notes when the following durations are left unspecified.  Also, two apostrophes indicate an upward pitch displacement of two octaves from two g's below middle c, where the pitch would have fallen without any modification.  It is important to remember three things, then, when specifying pitches:

1)  Note pitches specified by letter name only (with or without accidental) will always fall within an interval of a fourth from the preceding pitch.

2)  These pitches can be octave displaced upward or downward by preceding the note letter with the desired number of apostrophes or commas.

3)  If you are unsure of the current register, you may begin the pitch component of the note with an equals sign which acts as a dummy middle c.

The pitch may be modified by an accidental after the note name:

     n 	natural

     #	sharp

     -  (hyphen) 	flat

     ## 	double sharp

     -- (double hyphen) 	double flat

Accidentals are carried throughout the measure just as in traditional music notation.  However, an accidental specified within a measure will hold for that note in all registers, in contrast with traditional notation.  Therefore, make sure to specify n when you no longer want an accidental applied to that pitch-class.

Pitches entered in the Scot score are translated into the appropriate octave point pitch-class value and appear as parameter p5 in the numeric score output.  This means you must design your instruments to accept p5 as pitch.

Rests are notated just like notes but using the letter r instead of a pitch name.  4r therefore indicates a quarter rest and 1r a whole rest.  Durations carry from rest to rest or to following pitches as mentioned above.

The tempo in beats per minute is specified in each section by choosing a single instrument part and using tempo statements (e.g. t=90) at the various points in the score as needed.  A quarter note is interpreted as a single beat, and tempi are interpolated between the intervening beats (see t statement).

Scot Example I

A Scot encoding of the above score might appear as follows:

 ; A BASIC Tune

orchestra { guitar=1 bass=2 }

functions  {

f1 0 512 10 1 .5 .25 .126

f2 0 256  7 1 120 1 8 0 128 1

}

score     {  ;section 1

$guitar

!ti "4/4"

4=c 8d e- f r 4='c/

8.b- 16a a- g  g- f  4e- c/

$bass

2=,,c 'a-/

g  =,c/

}

score     {  ;section 2

$guitar

!ti "4/4"

6='c r c 4..c## 16e- /

6f r f 4..f## 16b /

$bass

4=,,c 'g, c 'g/

2=a-  g /

}

The score resulting from this Scot notation is shown at the end of this chapter.

GROUPETTES

Duration numbers can have any integral value; for instance,

!time "4/4"

5cdefg/

would encode a measure of 5 in the time of 4 quarter notes.  However, specification of arbitrary rhythmic groupings in this way is at best awkward.  Instead, arbitrary portions of the score section may be enclosed in groupette brackets.  The durations of all notes inside groupette brackets will be multiplied by a fraction n/d, where the musical meaning is d in the time of n.  Assuming d and n here are integers, groupette brackets may take these several forms:

{d:n:     ....      :}   d in the time of n

{d:: ....      :}   n will be the largest power of 2 less than d

{:   ....      :}   d=3, n=2 (normal triplets)

It can be seen that the second and third form are abbreviations for the more common kinds of groupettes.  (Observe the punctuation of each form carefully.)  Groupettes may be nested to a reasonable depth.  Also, groupette factors apply only after the written duration is carried from note to note.  Thus, the following example is a correct specification for two measures of 6/8 time:

!time "6/8" 8cde {4:3: fgab :} / crc 4.c /

The notes inside the groupette are 4 in the space of 3 8th notes, and the written-8th-note duration carries normally into the next measure.  This closely parallels the way groupette brackets and note durations interact in standard notation.

SLURS AND TIES

Now that you understand part writing in the Scot language, we can start discussing more elaborate features.  Immediately following the pitch specification of each note, one may indicate a slur or a tie into the next note (assuming there is one), but not both simultaneously.  The slur is typed as a single underscore (`_') and a tie as a double underscore (`__').  Despite the surface similarity, there is a substantial difference in the effect of these modifiers.

For purposes of Scot, tied notes are notes which, although comprised of several graphic symbols, represent only a single musical event.  (Tied notes are necessary in standard music notation for several reasons, the most common being notes which span a measure line and notes with durations not specifiable with a single symbol, such as quarter note tied to a sixteenth.)  Notes which are tied together are summed by duration and output by Scot as a single event.  This means you cannot, for example, change the parameters of a note in the middle of a tie (see below).  Two or more notes may be tied together, as in the following example, which plays an f# for eleven beats:

!ti "4/4" 1 f#__ / 1 f#__ / 2. f# 4r /

By contrast, slurred notes are treated as distinct notes at the Csound level, and may be of arbitrary pitch.  The presence of a slur is reflected in parameter p4, but the slur has no other meaning beyond the interpretation of p4 by your instrument.  Since instrument design is beyond the scope of this manual, it will suffice for now to explain that the Scot program gives sets p4 to one of four values depending on the existence of a slur before and after the note in question.  This means Scot pays attention not only to the slur attached to a given note, but whether the preceding note specified a slur.  The four possibilities are as follows, where the p4 values are taken to apply to the note d':

4c  d         (no slur)       p4 = 0

4c  d_        (slur after only)    p4 = 1

4c_ d         (slur before only)   p4 = 2

4c_ d_      (before & after)       p4 = 3

PARAMETERS

The information contained in the Scot score notation we have considered so far is manifested in the output score in parameters p1 through p5 in the following way:

p1:  instrument number

p2:  initialization time of instrument

p3:  duration

p4:  slur information

p5:  pitch information in octave point pitch-class notation

Any additional parameters you may want to enter are listed in brackets as the last part of a note specification.  These parameters start with p6 and are separated from each other with spaces.  Any parameters not specified for a particular note have their value carried from the most recently specified value. You may choose to change some parameters and not others, in which case you can type a dot (`.') for parameters whose values don't change, and new values for those that do.  Alternatively, the construction N:, where N is an integer, may be used to indicate that the following parameter specifications apply to successive parameters starting with parameter N.  For example:

4e[15000 3 4 12:100 150] g_ d_[10000 . 5]    c

Here, for the first two quarter notes p6, p7, p8, p12, and p13 respectively assume the values 15000, 3, 4, 100, and 150.  The values of p9 through p11 are either unchanged, or implicitly zero if they have never been specified in the current section.  On the third quarter note, the value of p6 is changed to 10000, and the value of p8 is changed to 5.  All others are unchanged.

Normally, parameter values are treated as globals - that is, a value specification will carry to successive notes if no new value is specified.  However, if a parameter specification begins with an apostrophe, the value applies locally to the current note only, and will not carry to successive notes either horizontally or vertically (see divisi below).

PFIELD MACROS

Scot has a macro text substitution facility which operates only on the pfield specification text within brackets.  It allows control values to be specified symbolically rather than numerically.  Macro definitions appear inside brackets in the orchestra section.  A single bracketed list of macro definitions preceding the first instrument declaration defines macros which apply to all instruments.  An additional bracketed list of definitions may follow each instrument to specify macros that apply to that particular instrument.

orchestra {

     [ pp=2000 p=4000 mp=7000 mf=10000 f=20000 ff=30000

       modi = 11: w = 1 x = 2 y = 3 z = 4

       vib = "10:1 " novib = "10:0 1"

     ]

violin = 1     [ pizz = " 20:1" arco = " 20:0" ]

serpent = 3    [ ff = 25000 sfz = 'f sffz = 'ff]

}

score {

 $violin = 4c[mf modi z.y novib] d e a['f vib3] /

          8 b[pizz]c 4d[f] 2c[ff arco] /

 $serpent =, 4.c[mp modi y.x] 8b 2c /

          'g[f ], c[ff] /

}

As can be seen from this example, a macro definition consists of the macro name, which is a string of alphabetic characters, followed by an equal sign, followed by the macro value.  As usual, spaces, tabs, and newlines may be used freely.  The macro value may contain arbitrary characters, and may be quoted if spacing characters need to be included.

When a macro name is encountered in bracketed pfield lists in a score section, that name is replaced with the macro text with no additional punctuation supplied.  The macro text may itself invoke other macros, although it is a serious error for a macro to contain itself, directly or indirectly.  Since macro names are identified as strings of alphabetic characters, and no additional spaces are provided when a macro is expanded, macros may easily perform such concatenations as found in the first serpent note above, where the integer and fractional parts of a single pfield are constructed.  Also, a macro may do no more than define a symbolic pfield, as in the definition of modi.  The primary intention of macros is in fact not only to reduce the number of characters required, but also to enable symbolic definitions of parameter numbers and parameter values.  For instance, a particular instrument's interpretation of the dynamic ff can be changed merely by changing a macro value, rather than changing all occurrences of that particular value in the score.

DIVISI

Notes may be stacked on top of each other by using a back arrow (`<') between the notes of the divisi.  Each time Scot encounters a back arrow, it understands that the following note is to start at the same time as the note to the left of the back arrow. Durations, accidentals and parameters carry from left to right through the divisi.  Each time these are given new values, the notes to the right of the back arrows also take on the new values unless they are specified again.

When writing divisi you can stack compound events by enclosing them in parentheses.  Also, divisi which occur at the end of the measure must have the proper durations or the scot program will mis-interpret the measure duration length.

Scot Example II

Scot encoding:

orchestra { right=1 left=2 }

functions { f1 0 256 10 1}

score {

$right !key "-b"

; since p5 is pitch, p7 is set to the pitch of next note

!ti "2/4"

!next p5 "p7"  ;since p5 is pitch, p7 refers to pitch of next note

!next p6 "p8"  ;If p6 is vol, say, then p8 refers to vol of next note

t90

8r c[3 np5]<e<='g r c<f<a / t90 r d-<g<b r =c[5]<f<a__ /

!ti "4/4"

t80

4d_<f__<(8a g__) 4c<(8fe)<4g 4.c<f<f 8r/

$left  !key "-b"

!next p5 "p7"

!next p6 "p8"

!ti "2/4"

8=,c[3 np5] r f r/ e r f r/

!ti "4/4"

2b_[5]<(4=,b_c) 4.a<f 8r/

}

View result

Notice in this example that tempo statements occurred in instrument `right' only.  Also, all notes had p6=3 until the third measure, at which point p6 took on the value 5 for all notes. The next parameter option used is described in Additional Features.  The output score is given at the end.

ADDITIONAL FEATURES

Several options can be included in any of the individual instrument parts within a section.  A sample statement follows the description of each option.  The keyword which follows the `!' in these statements may be abbreviated to the first two characters.

Key Signatures

Any desired key signature is specified by listing the accidentals as they occur in a key signature statement.  Thereafter, all notes of that instrument part are sharpened or flattened accordingly.  For example, for the key of D, type

!key "#fc"

Accidental Following

Accidental following may be turned on or off as needed.  When turned off, accidentals no longer carry throughout the measure as in traditional notation.  This convention is sometimes used in contemporary scores.

!accidentals "off"

Octave Following

Turning off octave following indicates that pitches stay in the same absolute octave register until explicitly moved. An absolute octave starts at pitch c and ends at the b above it.  The octave middle-c-to-b is indicated with an equals sign (`=') and octave displacement is indicated with the appropriate number of commas or apostrophes.  These displacements are cummulative.  For example,

!octaves "off"      4='c g b 'c

starts at the c above middle c and ends at two c's above middle c.

Vertical Following

Turning off vertical following means that durations, register, and parameters only carry horizontally from note to note and not vertically as described in the section on divisi.

     !vertical "off"

Transposition

Any instrument part can be transposed to another key by indicating the intervalic difference between the notated key and the desired key.  This difference is always taken with reference to middle c - to transpose a whole step upward, for example, type

!transpose "d"

This indicates that the part is transposed by the interval difference between middle c and d.

Next-value and Previous-value Parameteres

In order to play a note, it is sometimes necessary for an instrument to know what value one or more parameters will have for the next note.  For instance, an instrument might be designed which glisses during the last portion of its performance (perhaps only when a slur is indicated) from its written pitch to the pitch of the next note.  This can only be done, of course, if the instrument can know what the pitch of the next note will be.

The necessary information can be provided using next-value parameters.  A next value parameter might be declared by

!next p5 "p6"

which is interpreted to mean that for the current instrument, p6 will contain the next note's p5 value. This holds true globally for all occurences of this instrument until further modifications.  If for any reason you wish to override this value, p6 may be filled in explicitly.  This is sometimes useful for the last note of a section, for which p6 will otherwise assume the p5 value for the current note.  The next-value feature is illustrated in the Scot example II.

The necessary information may also be provided using standard numeric score next-value parameters.  A parameter argument containing the symbol npx (where x is an integer) will substitute parameter number x of the following note for that instrument.  Similarly, the value of a parameter occurring during the previous note may be referenced with the symbol ppx (where x is an integer).  Details of the next- and previous-value parameter feature may be found in the Numeric Scores section.

Ramping

Pfields containing the symbol < will be replaced by values derived from linear interpolation of a time-based ramp.  Ramp endpoints are defined by the first real number found in the same pfield of a preceding and following note played by the same instrument.  Details of the ramping feature are likewise found in the Numeric Scores section.

f0 Statements

In each score section, Scot automatically produces an f0 statement with a p2 equal to the ending time of the last note or rest in the section.  Thus, dead time' at the end of a section for reverberation decay or whatever purpose may be specified musically by rests in one or more parts.  See the eighth rest at the end of Scot example II and its output score shown below.

OUTPUT SCORES

Output file score from Scot Example I.

f1 0 512 10 1 .5 .25 .126

f2 0 256  7 1 120 1 8 0 128 1

i1.01 0 1 0 8.00

i1.01 1 0.5 0 8.02

i1.01 1.5 0.5 0 8.03

i1.01 2 0.5 0 8.05

i1.01 3 1 0 9.00

i1.01 4 0.75 0 8.10

i1.01 4.75 0.25 0 8.09

i1.01 5 0.25 0 8.08

i1.01 5.25 0.25 0 8.07

i1.01 5.5 0.25 0 8.06

i1.01 5.75 0.25 0 8.05

i1.01 6 1 0 8.03

i1.01 7 1 0 8.00

i2.01 0 2 0 6.00

i2.01 2 2 0 6.08

i2.01 4 2 0 6.07

i2.01 6 2 0 7.00

t0 60

f0 8

s

i1.01 0 0.6667 0 9.00

i1.01 1.3333 0.6667 0 9.00

i1.01 2 1.75 0 9.02

i1.01 3.75 0.25 0 9.03

i1.01 4 0.6667 0 9.05

i1.01 5.3333 0.6667 0 9.05

i1.01 6 1.75 0 9.07

i1.01 7.75 0.25 0 9.09

i2.01 0 1 0 6.00

i2.01 1 1 0 6.07

i2.01 2 1 0 6.00

i2.01 3 1 0 6.07

i2.01 4 2 0 7.08

i2.01 6 2 0 7.07

t0 60

f0 8

s

Back

Output file score from Scot Example II.

f1 0 256 10 1

c r1 n 7 5

c r1 n 8 6

i1.01 0.5000 0.5000 0 8.00 3 8.00 3

i1.02 0.5000 0.5000 0 8.04 3 8.05 3

i1.03 0.5000 0.5000 0 8.07 3 8.09 3

i1.01 1.5000 0.5000 0 8.00 3 8.01 3

i1.02 1.5000 0.5000 0 8.05 3 8.07 3

i1.03 1.5000 0.5000 0 8.09 3 8.10 3

i1.01 2.5000 0.5000 0 8.01 3 8.00 5

i1.02 2.5000 0.5000 0 8.07 3 8.05 5

i1.03 2.5000 0.5000 0 8.10 3 8.09 5

i1.01 3.5000 0.5000 0 8.00 5 8.02 5

i1.02 3.5000 0.5000 0 8.05 5 8.05 5

i1.01 4.0000 1.0000 1 8.02 5 8.00 5

i1.03 3.5000 1.0000 0 8.09 5 8.07 5

i1.01 5.0000 1.0000 2 8.00 5 8.00 5

i1.02 4.0000 1.5000 0 8.05 5 8.04 5

i1.02 5.5000 0.5000 0 8.04 5 8.05 5

i1.03 4.5000 1.5000 0 8.07 5 8.05 5

i1.01 6.0000 1.5000 0 8.00 5 8.00 5

i1.02 6.0000 1.5000 0 8.05 5 8.05 5

i1.03 6.0000 1.5000 0 8.05 5 8.05 5

c r2 n 7 5

c r2 n 8 6

i2.01 0.0000 0.5000 0 7.00 3 7.05 3

i2.01 1.0000 0.5000 0 7.05 3 7.04 3

i2.01 2.0000 0.5000 0 7.04 3 7.05 3

i2.01 3.0000 0.5000 0 7.05 3 7.10 5

i2.01 4.0000 2.0000 1 7.10 5 7.09 5

i2.02 4.0000 1.0000 1 6.10 5 7.00 5

i2.02 5.0000 1.0000 2 7.00 5 7.05 5

i2.01 6.0000 1.5000 2 7.09 5 7.09 5

i2.02 6.0000 1.5000 0 7.05 5 7.05 5

t0 60 0.0000 90.0000 2.0000 90.0000 4.0000 80.0000 4.0000 90.0000

f0 8.0000

s

e

Back


Contents: Quick reference; CSOUND.EXE flags, Realtime support; UTILITY PROGRAMS hetro lpanal pvanal cvanal sndinfo mixer scale mkgraph envext xtrctor scsort


CSOUND.EXE

Digital audio processing and sound synthesis.

Detailed info about command line flags.

Realtime output.

The Csound program is an environment in which a score file (or some external event sequence like MIDI events) can invoke an orchestra file of arbitrarily complex signal-processing "instruments" to produce sound. A number of command line flags set the level of displays and console reports, specify I/0 filenames and sample formats, and declare the nature of realtime sensing and control.

Here is the format for invoking Csound:

csound [flags] orchfile scorefile

PROPRIETARY FLAGS

After some confusion, it has been decided that platform- (or proprietary build) specific flags shall be preceded by a plus sign, eg '-+J'. The flags documented here are those which are available for the official Bath Csound version. If you use any of the proprietary version, you must look at the documentation to get information about flags.  For Windows, earlier versions of Maldonado's RTCsound et al has included several diverging flags. Here is some old documentation for those, but note that his recent versions conform to the new standard!

FLAGS

   Basic options:

-i fnam	sound input filename (if fnam is devaudio or adc use directly (See Winsound 3.47 note below))

-o fnam	sound output filename (if fnam is devaudio or dac use directly)

(New in Winsound 3.47) The output form devaudio0, devaudio1,.. or adc0, adc1,... can be used to select which of many audio devices are to be used. (devaudio1 would refer to device 1 etc).  The form devaudio refers to device zero.

-r N	orchestra srate override

-k N	orchestra krate override

-b N	sample frames (or -kprds) per software sound I/O buffer

-B N	samples per hardware sound I/O buffer

-+<anything>	Proprietary or platform-specific flag (not Bath Csound). Consult documentation for that version

   Output soundfile options:

-A	create an AIFF format output soundfile

-J	create an IRCAM format output soundfile (New in Csound 3.49)

-W	create a WAV format output soundfile

-h	no header on output soundfile

-8	8-bit unsigned char sound samples

-c	8-bit signed_char sound samples

-a	alaw sound samples

-u	ulaw sound samples

-s	short_int sound samples

-l	long_int sound samples

-f	float sound samples (New in Csound 3.47) floats also supported for WAV files

-R	continually rewrite header while writing soundfile (WAV/AIFF)

-n	no sound onto disk

-D	defer GEN01 soundfile loads until performance time

   MIDI options:

-M dnam	read MIDI realtime events from device 'dnam' (must be sbmidi)

-F fnam  	read MIDIfile event stream from file 'fnam'

-T	terminate the performance when miditrack is done

   Score options::

-x fnam	extract from score.srt using extract file fnam

-t N     	use uninterpreted beats of the score, initially at tempo N

-L dnam	read Line-oriented realtime score events from device 'dnam'

dnam can be a pipe if the first character of dnam is a bar '|' (New in Csound 3.48)

-C	use Cscore processing of scorefile

   Display options:

-v	verbose orch translation

-m N	tty message level. Sum of: 1=note amps, 2=out-of-range msg,

   	                                          4=warnings, 8=SoundBlaster messages

-d	suppress all displays

-g	suppress graphics, use ascii displays

-G	suppress graphics, output Postcript file (New in Csound 3.44)

-H [N]	print a heartbeat character at each soundfile write. (N option new in Csound 3.48)

-N	notify (ring the bell) when score or miditrack is done

-z [N]	List available opcodes in this version (New in Csound 3.45)

-- fname	output to log file fnam

   Alternate functionality:

-U unam [...]	run utility program unam

-I	 I-time only orch run

   Deprecated flags:

-S	score is in Scot format (REMOVED in Csound 3.49)

-P N	MIDI sustain pedal threshold (0 - 128) (NB: deprecated!)

Flags may appear anywhere in the command line, either separately or bundled together. A flag taking a Name or Number will find it in that argument, or in the immediately subsequent one. The following are thus equivalent commands:

csound  -nm3  orchname  -Sxxfilename  scorename

csound  -n  -m  3  orchname  -x  xfilename  -S scorename

All flags and names are optional. The default flags are:

csound -s -otest -b1024 -B1024 -m7 -P128 orchname scorename

If scorename is omitted, there are two default options:

1) 	if realtime input is expected (-L, -M or -F), a dummy scorefile is substituted consisting of the single statement 'f 0 3600' (i.e. listen for real-time input for one hour);

2) 	else csound uses the previously processed score.srt in the current directory.

DETAILED COMMAND LINE FLAG NOTES

Csound reports on the various stages of score and orchestra processing as it goes, doing various syntax and error checks along the way. Once the actual performance has begun, any error messages will derive from either the instrument loader or the unit generators themselves. A csound command may include any rational combination of the following flag arguments, with default values as described below.

Basic options:

   -i isfname

Input soundfile name. If not a full pathname, the file will be sought first in the current directory, then in that given by the environment variable SSDIR (if defined), then by SFDIR. The name stdin will cause audio to be read from standard input. If realtime audio is enabled, the name devaudio will request sound from the host audio input device.

   -o osfname

Output soundfile name. If not a full pathname, the soundfile will be placed in the directory given by the environment variable SFDIR (if defined), else in the current directory. The name stdout will cause audio to be written to standard output. If no name is given, the default name will be test. If realtime audio is enabled, the name devaudio will send to the host audio output device.  Also for Windows, the output form devaudio0, devaudio1,.. or adc0, adc1,... can be used to select which of your audio devices are to be used. (devaudio1 would refer to device 1 etc).  The form devaudio refers to device zero.

   -b number

Number of audio sample-frames per soundio software buffer. Large is efficient, but small will reduce audio I/O delay. The default is 1024. In realtime performance, Csound waits on audio I/O on number boundaries. It also processes audio (and polls for other input like MIDI) on orchestra ksmps boundaries. The two can be made synchronous. For convenience, if number = -N (is negative) the effective value is ksmps * N (audio synchronous with k-period boundaries). With N small (e.g. 1) polling is then frequent and also locked to fixed DAC sample boundaries.

   -B number

Number of audio sample-frames held in the DAC hardware buffer. This is a threshold on which software audio I/O (above) will wait before returning. A small number reduces audio I/O delay; but the value is often hardware limited, and small values will risk data lates. The default is 1024.

Output soundfile options:

   -A

Write an AIFF output soundfile. Restricts the soundfile data formats to c, s, l, or f.

   -W

Write a WAV output soundfile. Restricts the soundfile data formats to 8 or s.

   -J

Write a IRCAM format output soundfile.

   -h

No header on output soundfile. Don't write a file header, just raw binary samples.

   { -8, -c, -a, -u, -s, -l, -f}

Audio sample format of the output soundfile. One of:

8	8-bit unsigned character

c	8-bit signed character

a	8-bit a-law

u	8-bit u-law

s	short integer

l	long integer

f	single-precision float (not playable, but can be read by -i, soundin and GEN01)

   -n

No sound. Do all processing, but bypass writing of sound to disk. This flag does not change the execution in any other way. Useful when doing realtime output. (NOTE: In Winsound this does not hold. Soundfile output must be enabled. -re)

MIDI options:

   -M devname

Read MIDI events from device devname.

   -F mfname

Read MIDI events from midifile mfname.

   -T

Terminate the performance when miditrack is done.

Score options:

   -x xfile

Extract a portion of the sorted score score.srt, according to xfile ( see XTRCTOR).

   -t number

Use the uninterpreted beats of score.srt for this performance, and set the initial tempo at number beats per minute. When this flag is set, the tempo of score performance is also controllable from within the orchestra ( see the tempo unit).

   -L devname

Read Line-oriented realtime score events from device devname. The name stdin will permit score events to be typed at your terminal, or piped from another process. Each line-event is terminated by a carriage-return. Events are coded just like those in a standard numeric score , except that an event with p2=0 will be performed immediately, and an event with p2=T will be performed T seconds after arrival. Events can arrive at any time, and in any order. The score carry feature is legal here, as are held notes (p3 negative) and string arguments, but ramps and pp or np references are not.

(New in Csound 3.44) If the first character of devname is a bar | then devname is taken to be the name of a pipe.

Display options:

   -v

Verbose translate and run. Prints details of orch translation and performance, enabling errors to be more clearly located.

   -m number

Message level for standard (terminal) output. Takes the sum of 4 print control flags, turned on by the following values: 1 = note amplitude messages, 2 = samples out of range message, 4 = warning messages, and 8 = soundblaster error messages. The default value is m7 (all Csound messages on).

   -d

Suppress all displays.

   -g

Recast graphic displays into ascii characters, suitable for any terminal.

   -H number

Print a heartbeat character at each soundfile write (console version only). The number argument was introduced in In Bath version 3.48:

-H or -H1 generates a 'rotating line' progress report.

-H2 generates a . (dot) every time a buffer is written.

-H3 reports the size in seconds of output sound.

-H4 sounds a bell for every buffer of the output written.

   -N

Notify (ring the bell) when score or miditrack is done.

   -z number

List all available opcodes. -z0 (default) uses short format, names only, while -z1 outputs both opcode names and the data type of all arguments in short form, eg:

foscil    a       xkkkkio

Alternate functionality:

   -U

Invoke Utility preprocessing programs: sndinfo, hetro, lpanal, pvanal et al.

   -I

I-time only. Allocate and initialize all instruments as per the score, but skip all P-time processing (no k-signals or a-signals, and thus no amplitudes and no sound). Provides a fast validity check of the score p-fields and orchestra i-variables.

Deprecated flags:

   -S

Interpret scorename as a Scot file and create a standard score file (named "score") from it, then sort and perform that. (NOTE: The Scot format was reported as removed in Csound 3.49. Still seems to be in sources though -re).

   -P number

Set MIDI sustain pedal threshold (0 - 128). The official switch value of 64 is normally too low, and is more realistic above 100. The default value of 128 will block all pedal info.


Csound Realtime support

From various release notes

Today (1998) it is possible to use Csound as a realtime instrument, and many of the recent changes are geared towards this goal. Here are some notes on how you can go about it with Winsound, or using Gabriel Maldonados proprietary version.

Notes for the standard (Bath/Montreal) Csound distribution

Csound (on a 386 and up) will recognise the output file called devaudio as an attempt to use a sound card for direct output (SoundBlaster or compatible).  This never worked out for DOS, so there is no realtime support for DOS.

Winsound however (in the file csound_win.zip on the Bath/Montreal servers) can use the Windows sound subsystem. In Winsound you set the Csound execution flags by text- or checkboxes in the interface (some are under the Extras dialog) Here are some tips:

•	Set Output file name to devaudio (-odevaudio). Also for Windows, the output form devaudio0, devaudio1,.. or adc0, adc1,... can be used to select which of your audio devices are to be used. (devaudio1 would refer to device 1 etc).  The form devaudio refers to device zero.

•	Use only 16-bit (default) or Unsigned 8-bit (-8 flag) output with soundblaster compatible sound cards.

Signed 8-bit (-c flag) does not work.

•	In the Extra dialog you can set sample rate/krate overrides for your orchestras. Note that the ksmps value in the orchestra must be valid, if it is given in the ORC file. For this reason it seems like a good idea not to have the sr/kr/ksmps header values in the ORC files, but always to set them on the command line, or in Winsound interface, depending on how you want to run the file. you must specify a sample rate in the orc that the sound card can support, otherwise you will get an "incompatible sample rate" error.  Subdivisions of 44100  (22050, 11025) are usually safe.

To control Winsound by mouse, use the xyin opcode

There are a few more command line flags, -L, -M and -F which are relevant for realtime input:

-L dnam	read Line-oriented realtime score events from device 'dnam'

-M dnam	read MIDI realtime events from device 'dnam' (must be sbmidi)

-F fnam  	read MIDIfile event stream from file 'fnam'


Csound utility programs

There are a number of separate soundfile or other (mostly spectral / FFT) data processing tools designed for use with Csound. Most of these are available in two forms: As standalone command-line DOS or console programs; and as built-in commands available directly in Csound/Winsound. See general usage notes below.

Spectral analysis programs:

HETRO - Fourier analysis for the Csound adsyn generator.

LPANAL - Linear predictive analysis for direct resynthesis or for spectral interpolation.

PVANAL - Fourier analysis for the Csound pvoc and pvread (et al) generators.

CVANAL - Impulse response fourier analysis for convolve operator.

Mixing, soundfile information, envelopes etc:

SNDINFO - Information about soundfiles

*MIXER.EXE - Mix up to 20 sound files

*SCALE.EXE - Scale a soundfile

*MKGRAPH.EXE - Utility to create envelopes for MIXER and SCALE

*ENVEXT.EXE - Create an envelope file from a sound

*XTRCTOR.EXE - Extract parts of a soundfile

*SCSORT.EXE - Standalone score sorting utility

(NOTE: Programs marked with * are not built into Csound/Winsound, they are only available as stand-alone command line / DOS utilities, in the distribution file csound_new.zip)

OVERVIEW

The Csound Utilities are soundfile preprocessing programs that return information on a soundfile or create some analyzed version of it for use by certain Csound generators.  Though different in goals, they share a common soundfile access mechanism and are describable as a set.  The soundfile utility programs (except as noted above) can be invoked in two equivalent forms:

csound -U utilname  [flags]  filenames  . . . or

utilname [flags]  filenames  . . .

In the first, the utility is invoked as part of the Csound executable, while in the second it is called as a standalone program. Note  The second is smaller by about 200K, but the two forms are identical in function.  The first is convenient in not requiring the maintenance and use of several independent programs. None program does all.  When using this form, a -U flag detected in the command line will cause all subsequent flags and names to be interpreted as per the named utility;  i.e. Csound generation will not occur, and the program will terminate at the end of utility processing.

DIRECTORIES

Filenames are of two kinds, source soundfiles and resultant analysis files.  Each has a hierarchical naming convention, influenced by the directory from which the Utility is invoked.  Source soundfiles with a full pathname (begins with dot (.), slash (/), or for Macintosh includes a colon (:)), will be sought only in the directory named.  Soundfiles without a path will be sought first in the current directory, then in the directory named by the SSDIR environment variable (if defined), then in the directory named by SFDIR.  An unsuccessful search will return a "cannot open" error.

Resultant analysis files are written into the current directory, or to the named directory if a path is included.  It is tidy to keep analysis files separate from sound files, usually in a separate directory known to the SADIR variable.  Analysis is conveniently run from within the SADIR directory.  When an analysis file is later invoked by a Csound generator (adsyn, lpread, pvoc) it is sought first in the current directory, then in the directory defined by SADIR.

SOUNDFILE FORMATS

Csound can read and write audio files in a variety of formats.  Write formats are described by Csound command flags.  On reading, the format is determined from the soundfile header, and the data automatically converted to floating-point during internal processing.  When Csound is installed on a host with local soundfile conventions (SUN, NeXT, Macintosh) it may conditionally include local packaging code which creates soundfiles not portable to other hosts.  However, Csound on any host can always generate and read AIFF files, which is thus a portable format.  Sampled sound libraries are typically AIFF, and the variable SSDIR usually points to a directory of such sounds.  If defined, the SSDIR directory is in the search path during soundfile access.  Note that some AIFF sampled sounds have an audio looping feature for sustained performance;  the analysis programs will traverse any loop segment once only.

For soundfiles without headers, an SR value may be supplied by a command flag (or its default).  If both header and flag are present, the flag value will override.

When sound is accessed by the audio Analysis programs, only a single channel is read.  For stereo or quad files, the default is channel one;  alternate channels may be obtained on request.

AUTHOR:   Dan Ellis, dpwe@media-lab.media.mit.edu


HETRO.EXE - Hetrodyne filter analysis for adsyn
HETRO

Hetrodyne filter analysis for the Csound adsyn generator.

csound -U hetro  [flags]  infilename  outfilename or

hetro  [flags]  infilename  outfilename

Hetro takes an input soundfile, decomposes it into component sinusoids, and outputs a description of the components in the form of breakpoint amplitude and frequency tracks.  Analysis is conditioned by the control flags below.  A space is optional between flag and value.

NOTE

The max number of analysed harmonic partials used to be 50. This was changed in John Fitchs version 3.40. There will be a warning, but the processing continues. Note however that the adsyn ugen cannot process more than 50 partials as of yet. This may be be changed soon.

FLAGS

-s srate	sampling rate of the audio input file.  This will override the srate of the soundfile header, which otherwise applies.   If neither is present, the default is 10000.  Note that for adsyn synthesis the srate of the source file and the generating orchestra need not be the same.

-c channel	channel number sought.  The default is 1.

-b begin	beginning time (in seconds) of the audio segment to be analyzed.  The default is 0.0

-d duration	duration (in seconds) of the audio segment to be analyzed.  The default of 0.0 means to the end of the file.  Maximum length is 32.766 seconds.

-f begfreq	estimated starting frequency of the fundamental, necessary to initialize the filter analysis.  The default is 100 (cps).

-h partials	number of harmonic partials sought in the audio file.  Default is 10, maximum 50.

NOTE: This limitation was removed in John Fitchs version 3.40. There is no current maximum for analysis, nor (as of version 3.47) for resynthesis.

-M maxamp	maximum amplitude summed across all concurrent tracks.  The default is 32767.

-m minamp	amplitude threshold below which a single pair of amplitude/frequency tracks is considered dormant and will not contribute to output summation.  Typical values:  128 (48 db down from full scale), 64 (54 db down), 32 (60 db down), 0 (no thresholding).  The default threshold is 64 (54 db down).

-n brkpts	initial number of analysis breakpoints in each amplitude and frequency track, prior to thresholding (-m) and linear breakpoint consolidation.  The initial points are spread evenly over the duration.  The default is 256.

-l cutfreq	substitute a 3rd order Butterworth low-pass filter with cutoff frequency cutfreq (in cps), in place of the default averaging comb filter.  The default is 0 (don't use).

-- fname	log output to file 'fname'

EXAMPLE

hetro     -s44100  -b.5  -d2.5  -h16  -M24000 audiofile.test  adsynfile7

This will analyze 2.5 seconds of channel 1 of a file "audiofile.test", recorded at 44.1 KHz, beginning .5 seconds from the start, and place the result in a file "adsynfile7".  We request just the first 16 harmonics of the sound, with 256 initial breakpoint values per amplitude or frequency track, and a peak summation amplitude of 24000.  The fundamental is estimated to begin at 100 Hz.  Amplitude thresholding is at 54 db down.  The Butterworth LPF is not enabled.

FILE FORMAT

The output file contains time-sequenced amplitude and frequency values for each partial of an additive complex audio source.  The information is in the form of breakpoints (time, value, time, value, ....) using 16-bit integers in the range 0 - 32767.  Time is given in milliseconds, and frequency in Hertz (cps).  The breakpoint data is exclusively non-negative, and the values -1 and -2 uniquely signify the start of new amplitude and frequency tracks.  A track is terminated by the value 32767.  Before being written out, each track is data-reduced by amplitude thresholding and linear breakpoint consolidation.

A component partial is defined by two breakpoint sets:  an amplitude set, and a frequency set.  Within a composite file these sets may appear in any order (amplitude, frequency, amplitude ....;  or amplitude, amplitude..., then frequency, frequency,...).  During adsyn resynthesis the sets are automatically paired (amplitude, frequency) from the order in which they were found.  There should be an equal number of each.

A legal adsyn control file could have following format:

-1  time1  value1  ...   timeK  valueK   32767	; amplitude breakpoints for partial 1

-2  time1  value1  ...   timeL   valueL   32767	; frequency breakpoints for partial 1

-1  time1  value1  ...   timeM  valueM  32767	; amplitude breakpoints for partial 2

-2  time1  value1  ...   timeN   valueN  32767	; frequency breakpoints for partial 2

-2  time1  value1  ..........

-2  time1  value1  .......... 	; pairable tracks for partials 3 and 4

-1  time1  value1  ..........

-1  time2  value1  ..........


LPANAL.EXE
LPANAL

Linear predictive analysis for the Csound lp(...) generators

csound -U lpanal   [flags]   infilename   outfilename or

lpanal   [flags]   infilename   outfilename

LPANAL is an extensive modification of Paul Lansky's LPC analysis programs.

LPANAL performs both LPC and pitch-tracking analysis on a soundfile to produce a time-ordered sequence of frames of control information suitable for Csound resynthesis.  Analysis is conditioned by the control flags below.  A space is optional between the flag and its value.

FLAGS

-s srate	sampling rate of the audio input file.  This will override the srate of the soundfile header, which otherwise applies.   If neither is present, the default is 10000.

-c channel	channel number sought.  The default is 1.

-b begin	beginning time (in seconds) of the audio segment to be analyzed.  The default is 0.0

-d duration	duration (in seconds) of the audio segment to be analyzed.  The default of 0.0 means to the end of the file.

-p npoles	number of poles for analysis.  The default is 34, the maximum 50.

-a	request pole stabilisation.Makes LPANAL write a file with filter pole values rather than the original filter coefficient files NEW FLAG in Bath v3.44 See entry for LPC interpolation opcodes

-h hopsize	hop size (in samples) between frames of analysis.  This determines the number of frames per second (srate / hopsize) in the output control file.  The analysis framesize is hopsize * 2 samples.  The default is 200, the maximum 500.

-C string	text for the comments field of the lpfile header.  The default is the null string.

-P mincps	lowest frequency (in cps) of pitch tracking.  -P0 means no pitch tracking.

-Q maxcps	highest frequency (in cps) of pitch tracking.  The narrower the pitch range, the more accurate the pitch estimate.  The defaults are -P70, -Q200.

-v verbosity	level of terminal information during analysis.  0 = none,  1 = verbose, 2 = debug. The default is 0.

-g	graphical display of results

-- fname	log output to file 'fname'

LPC POLE STABILISATION

The -a flag [alternate storage] asks LPANAL to write a file with filter poles values rather than the usual filter coefficient files.

When lpread / lpreson are used with pole files, automatic stabilization is performed and the filter should not get wild anymore. Only one stabilization algorithm is implemented, more tune could be implemented later.

(This flag is set by default in the Windows GUI)

EXAMPLE

lpanal  -p26  -d2.5  -P100  -Q400  audiofile.test  lpfil22

will analyze the first 2.5 seconds of file "audiofile.test", producing srate/200 frames per second, each containing 26-pole filter coefficients and a pitch estimate between 100 and 400 Hertz.  Output will be placed in "lpfil22" in the current directory.

FILE FORMAT

Output is a file comprised of an identifiable header plus a set of frames of floating point analysis data.  Each frame contains four values of pitch and gain information, followed by npoles filter coefficients.  The file is readable by Csound's lpread ugen.


PVANAL.EXE
PVANAL

Fourier analysis for the Csound pvoc and pvread (et al) generators

csound -U pvanal   [flags]   infilename   outfilename or

pvanal   [flags]   infilename   outfilename

pvanal converts a soundfile into a series of short-time Fourier transform (STFT) frames at regular timepoints (a frequency-domain representation).  The output file can be used by pvoc to generate audio fragments based on the original sample, with timescales and pitches arbitrarily and dynamically modified. There are also a number of pvoc ugens which use the output files. These were written by Richard Karpen, and included in the Bath 3.44 release.  Analysis is conditioned by the flags below.  A space is optional between the flag and its argument.

FLAGS

-s srate	sampling rate of the audio input file.  This will override the srate of the soundfile header, which otherwise applies.   If neither is present, the default is 10000.

-c channel	channel number sought.  The default is 1.

-b begin	beginning time (in seconds) of the audio segment to be analyzed.  The default is 0.0

-d duration	duration (in seconds) of the audio segment to be analyzed.  The default of 0.0 means to the end of the file.

-n frmsiz	STFT frame size, the number of samples in each Fourier analysis frame.  Must be a power of two, in the range 16 to 16384.  For clean results, a frame must be larger than the longest pitch period of the sample.  However, very long frames result in temporal "smearing" or reverberation.  The bandwidth of each STFT bin is determined by sampling rate / frame size.  The default framesize is the smallest power of two that corresponds to more than 20 milliseconds of the source (e.g. 256 points at 10 kHz sampling, giving a 25.6 ms frame).

-w windfact	Window overlap factor.  This controls the number of Fourier transform frames per second.  Csound's pvoc will interpolate between frames, but too few frames will generate audible distortion;  too many frames will result in a huge analysis file.  A good compromise for windfact is 4, meaning that each input point occurs in 4 output windows, or conversely that the offset between successive STFT frames is framesize/4.  The default value is 4.  Do not use this flag with -h.

-h hopsize	STFT frame offset.  Converse of above, specifying the increment in samples between successive frames of analysis (see also lpcanal).  Do not use with -w.

-g	graphical display of results

-G latch	latch graphics to prevent too frequent resizing (default 200)

-V fname	send output to text file 'fname'

-v	use verbose mode

-- fname	log output to file 'fname'

EXAMPLE

pvanal  asound  pvfile

will analyze the soundfile "asound" using the default frmsiz and windfact to produce the file "pvfile" suitable for use with pvoc.

FILES

The output file has a special pvoc header containing details of the source audio file, the analysis frame rate and overlap.  Frames of analysis data are stored as float, with the magnitude and 'frequency' (in Hz) for the first N/2 + 1 Fourier bins of each frame in turn.  'Frequency' encodes the phase increment in such a way that for strong harmonics it gives a good indication of the true frequency.  For low amplitude or rapidly moving harmonics it is less meaningful.

DIAGNOSTICS

Prints total number of frames, and frames completed on every 20th.


CVANAL.EXE
CVANAL

Impulse Response Fourier Analysis for convolve operator

By Greg Sullivan

csound -U cvanal [flags] infilename outfilename

cvanal [flags] infilename outfilename

cvanal converts a soundfile into a single Fourier transform frame. The output file can be used by the convolve operator to perform Fast Convolution between an input signal and the original impulse response.  Analysis is conditioned by the flags below. A space is optional between the flag and its argument.

FLAGS

-s srate	sampling rate of the audio input file. This will over-ride the srate of the soundfile header, which otherwise applies. If neither is present, the default is 10000.

-c channel	channel number sought. If omitted, the default is to process all channels. If a value is given, only the selected channel will be processed.

-b begin	beginning time (in seconds) of the audio segment to be analysed. The default is 0.0

-d duration	duration (in seconds) of the audio segment to be analysed. The default of 0.0 means to the end of the file.

EXAMPLE

cvanal asound cvfile

will analyse the soundfile "asound" to produce the file "cvfile" for the use with CONVOLVE.

HINT: To use data that is not already contained in a soundfile, a soundfile converter that accepts text files may be used to create a standard audio file. E.g, the .DAT format for SOX.  This is useful for implementing FIR filters.

FILES

The output file has a special CONVOLVE header, containing details of the source audio file. The analysis data is stored as 'float', in rectangular (real/imaginary) form.

NOTE

The analysis file is NOT system independent! Ensure that the original impulse recording/data is retained. If/when required,  the analysis file can be recreated.

By Greg Sullivan, sullivan@aussie.enet.dec.com

(Based on algorithm given in 'Elements Of Computer Music', by F. Richard Moore.)


XTRCTOR.EXE

Program for extracting parts of a work.

xtrctor [-flags] soundfile

Legal flags are:

-o fnam	sound output filename

-N	Notify when done

-S integer 	Sample number at which to start file

-Z integer 	Sample number at which to end file

-Q integer 	Number of samples to read

-T fpnum  	Time in secs at which to start file

-E fpnum  	Time in secs at which to end file

-D fpnum  	Duration in secs of extract

-R	Rewrite header

-H	Heartbeat

-v	verbose mode for debugging

-- fnam	output to log file fnam

Flag defaults:

xtrctor -otest -S 0


SCSORT.EXE

Stand-alone sorting of sound files

Not tested on PC


SNDINFO.EXE

Get basic information about one or more soundfiles.

csound -U sndinfo  soundfilenames  . . . or

sndinfo   soundfilenames  . . .

Sndinfo will attempt to find each named file, open it for reading, read in the soundfile header, then print a report on the basic information it finds.  The order of search across soundfile directories is as described above.  If the file is of type AIFF, some further details are listed first.

EXAMPLE

csound -U sndinfo  test  Bosendorfer/"BOSEN mf A0 st"  foo  foo2

where the environment variables SFDIR = /u/bv/sound, and SSDIR = /so/bv/Samples, might produce the following:

util  SNDINFO:

/u/bv/sound/test:

    srate 22050, monaural, 16 bit shorts, 1.10 seconds

    headersiz 1024, datasiz 48500  (24250 sample frames)

/so/bv/Samples/Bosendorfer/BOSEN mf A0 st:  AIFF, 197586 stereo samples, base Frq 261.6 (midi 60), sustnLp: mode 1, 121642 to 197454, relesLp: mode 0

AIFF soundfile, looping with modes 1, 0

srate 44100, stereo, 16 bit shorts, 4.48 seconds

headersiz  402, datasiz 790344  (197586 sample frames)

/u/bv/sound/foo:

     no recognizable soundfile header

/u/bv/sound/foo2:

     couldn't find


SCALE.EXE

As well as doing the same as SNDINFO this utility reports on the maximum amplitude, and can generate a new soundfile with the amplitude scaled by a floating point value.  It can also change formats.

scale [-flags] soundfile

Legal flags are:

-o fnam 	sound output filename

-A	create an AIFF format output soundfile

-W	create a WAV format output soundfile

-h	no header on output soundfile

-c	8-bit signed_char sound samples

-a	alaw sound samples

-u	ulaw sound samples

-s	hort_int sound samples

-l	long_int sound samples

-f	float sound samples

-F fpnum	amount to scale amplitude

-F fname	envelope file for scaling

-R 	continually rewrite header while writing soundfile (WAV/AIFF)

-H	print a heartbeat character at each soundfile write

-N	notify (ring the bell) when score or miditrack is done

flag defaults: scale -s -otest -F 0.0

If scale is 0.0 then reports maximum possible scaling; otherwise scale and generate a new soundfile


MIXER.EXE

This utility can mix together a number of sound files (up to 20 at present) with different starting times and with scaling on each file.

mixer  [-flags] soundfile [-flags] soundfile ...

Legal flags are:

-o fnam	sound output filename

-A	create an AIFF format output soundfile

-W	create a WAV format output soundfile

-a	alaw sound samples

-u	ulaw sound samples

-s	short_int sound samples

-l	long_int sound samples

-c	8-bit signed_char sound samples

-8	8-bit unsigned_char sound samples

-f	float sound samples

-h	no header on output soundfile

-F fpnum	amount to scale amplitude of next sound file

-F fname	an envelope file for scaling

-R	continually rewrite header while writing soundfile (WAV/AIFF)

-H	print a heartbeat character at each soundfile write

-N	notify (ring the bell) when score or miditrack is done

-S int   	Sample at which to insert next sound file

-T fpnum	Time at which to insert next sound file

-1 -2 -3 -4	include named channel

-^ n m	include channel n and output as channel m

-v	verbose mode

Defaults are: mixer -s -otest -F1.0 -S0

MIXER can also be used for some echo effects.


MKGRAPH.EXE

A small utility to create envelope files for MIXER and SCALE.  Type ? when the program is running to get all the controls.

mkgraph [-v] [envfile] [-o outname]

Default is mkgraph -o newgraph.

If an envfile is given it is loaded and can be edited.  envfile and outname can be the same.

CONTROLS

Mouse:

Left button	Set new point

Right button	Modify node to left of cursor

Keyboard controls:

Escape	Write graph file and exit

Home	Redraw screen

Uparrow	Decrease amplitude range displayed

Downarrow	Increase amplitude range displayed

Rightarrow	Move time window right 5% of screen

PageUp	Display twice the time

PageDown	Display half the time

F1	Coarser grid

ALT+F1	Finer grid

E,e	Write envelope file

F,f	Write table file

G,g	Toggle display of grid

H,h	Help page

Q,q	Quit program

W,w	Write envelope file

?	Display help page


ENVEXT.EXE

Given a sound file it creates an envelope file with an approximation to the envelope of the sound file.

envext  [-w time] [-o file] soundfile

Legal flags are:

-o fnam	sound output filename

-w time	Size of window

Defaults are:

envext  -w 0.25 -o newenv


Opcodes:

VALUE CONVERTERS frac ampdb dbamp i [abs] [cos] [int][exp] [log log10] [sqrt] [sin] sininv cosinv taninv sinh cosh tanh taninv2

POWER FUNCTIONS pow

PITCH CONVERTERS octpch pchoct cpspch octcps cpsoct, cps2pch cpsxpch

ARITHMETIC OPERATIONS - + && || - + * / % ^

CONDITIONAL VALUES  ? : (tests: < > >= >= == !=)

ASSIGNMENT STATEMENTS = init tival divz

PROGRAM CONTROL igoto kgoto tigoto goto if...igoto if...kgoto if...tigoto if...goto timout, reinit rigoto rireturn

DURATION CONTROL STATEMENTS ihold turnoff turnon

TEMPO ESTIMATION & CONTROL tempest temp

SENSING & CONTROL xyin

SOUND INPUT & OUTPUT [in] ins inq soundin [out] outs...outs2 outq...outq4

SPATIALISATION pan, hrtf, space spsend spdist, locsig locsend

SIGNAL DISPLAY [print] display dispfft

K-RATE SIGNAL FILE IN/OUT readk/2/3/4 dumpk/2/3/4

GENERATE SCORE EVENTS schedule schedwhen

FUNCTION TABLE CONTROL ftgen ftlen ftlptim ftsr


Value converters

int(x)	(init- or control-rate args only)

frac(x)	(init- or control-rate args only)

dbamp(x)	(init- or control-rate args only)

i(x)	(control-rate args only)

abs(x)	(no rate restriction)

exp(x)	(no rate restriction)

log(x)	(no rate restriction)

log10(x)	(no rate restriction)

sqrt(x)	(no rate restriction)

sin(x)	(no rate restriction)

cos(x)	(no rate restriction)

ampdb(x)	(no rate restriction)

New in Csound 3.47-48:

sininv(x)	(no rate restriction)

sinh(x)	(no rate restriction)

cosinv(x)	(no rate restriction)

cosh(x)	(no rate restriction)

taninv(x)	(no rate restriction)

tanh(x)	(no rate restriction)

taninv2(x, y)	(no rate restriction)

where the argument within the parentheses may be an expression.

NOTE: The opcodes asin, acos, atan (introduced in 3.47) were renamed to sininv, cosinv, taninv respectively, in Csound 3.48, this to avoid namespace pollution (ie names beginning with a, k or i).

Value converters perform arithmetic translation from units of one kind to units of another. The result can then be a term in a further expression.

int(x)  returns the integer part of x.

frac(x)  returns the fractional part of x.

dbamp(x) returns the decibel equivalent of the raw amplitude x.

i(x)   returns an Init-type equivalent of the argument, thus permitting a k-time value to be accessed in at init-time or reinit-time, whenever valid.

abs(x)  returns the absolute value of x.

exp(x)  returns e  (= 2.7183) raised to the xth power.

log(x)  returns the natural log (base e) of x (x positive only).

log10(x)  returns the base 10 log of x (x positive only).

sqrt(x)  returns the square root of x (x non-negative).

sin(x)  returns the sine of x (x in radians).

cos(x)  returns the cosine of x (x in radians).

ampdb(x) returns the amplitude equivalent of the decibel value x. Thus 60 db gives 1000, 66 db gives 2000, 72 db gives 4000, 78 db gives 8000, 84 db gives 16000 and 90 db gives 32000.

New in Csound 3.47:

sininv(x) returns the arcsin of x

sinh(x) returns the hyperbolic sin of x

cosinv(x) returns the arccos of x

cosh(x) returns the hyperbolic cos of x

taninv(x) returns the arctan of x

tanh(x) returns the hyperbolic tan of x

taninv2(x, y) returns the arctan of y/x. If any of x or y is zero, taninv2 returns zero.

Note that for log and sqrt the argument value is restricted.


Power functions
Power function

ir	pow	iarg, ipow

kr	pow	karg, kpow, [inorm]

ar	pow	aarg, apow, [inorm]

Computes xarg  to the power of xpow  and scales the result by inorm. See also ^ operator.

NAME CHANGES

pow was split into three separate opcodes, ipow, kpow, apow, until the name purge in Csound 3.48/3.49.

INITIALISATION

inorm - The number to divide the result (default to 1).  This is especially useful if you are doing powers of a- or k- signals where samples out of range are extremely common!

EXAMPLES

1.	i2t2	pow	2,2	; Computes 2^2.

2.	kline	line	0, 1, 4

kexp	pow	kline, 2, 4

This feeds a linear function to pow at k-rate and scales that to the line's peak value. The output will be an exponential curve with the same range as the input line.

iamp	pow	10, 2

a1	oscil	iamp, 100, 1

a2	pow	a1, 2, iamp

out a2

This will output an audio-rate sine with its negative part folded over the amp axis.  The peak value will be iamp = 10^2 = 100.


Pitch converters

See also John Fitchs Tuning Opcodes

octpch(pch)	(init- or control-rate args only)

pchoct(oct)	(init- or control-rate args only)

cpspch(pch)	(init- or control-rate args only)

octcps(cps)	(init- or control-rate args only)

cpsoct(oct)	(no rate restriction)

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

Data concerning pitch and frequency can exist in any of the following forms:

name 	abbreviation

octave point pitch-class (8ve.pc)	  pch

octave point decimal    	  oct

cycles per second        	  cps

The first two forms consist of a whole number, representing octave registration, followed by a specially interpreted fractional part. For pch, the fraction is read as two decimal digits representing the 12 equal-tempered pitch classes from .00 for C to.11 for B. For oct, the fraction is interpreted as a true decimal fractional part of an octave. The two fractional forms are thus related by the factor 100/12. In both forms, the fraction is preceded by a whole number octave index such that 8.00 represents Middle C,9.00 the C above, etc. Thus A440 can be represented alternatively by 440 (cps),8.09 (pch), 8.75 (oct), or 7.21 (pch), etc. Microtonal divisions of the pch semitone can be encoded by using more than two decimal places.

The mnemonics of the pitch conversion units are derived from morphemes of the forms involved, the second morpheme describing the source and the first morpheme the object (result). Thus

cpspch(8.09)

will convert the pitch argument 8.09 to its cps (or Hertz) equivalent, giving the value of 440. Since the argument is constant over the duration of the note, this conversion will take place at i-time, before any samples for the current note are produced. By contrast, the conversion

cpsoct(8.75 + K1)

which gives the value of A440 transposed by the octave interval K1 will repeat the calculation every, K-period since that is the rate at which K1 varies.

NOTE

The conversion from pch or oct into cps is not a linear operation but involves an exponential process that could be time-consuming when executed repeatedly. Csound now uses a built-in table lookup to do this efficiently, even at audio rates.


Tuning opcodes

Tuning opcodes by John Fitch

icps	cps2pch	ipch, iequal

icps	cpsxpch	ipch, iequal, irepeat, ibase

Converts a pitch-class notation into cycles-per-second for equal divisions of the octave (for cps2pch) or for equal divisions of any interval. There is a restriction of no more than 100 equal divisions.

See also Pitch converters.

INITIALISATION

ipch - Input number of the form 8ve.pc, indicating an octave' and which note in the octave.

iequal - if positive, the number of equal intervals into which the octave' is divided. Must be less than or equal to 100. If negative is the number of a table of frequency multipliers

irepeat - Number indicating the interval which is the octave'. The integer 2 corresponds to octave divisions, 3 to a twelveth, 4 is two octaves, and so on. This need not be an integer, but must be positive.

ibase - The frequency which corresponds to pitch 0.0

NOTES

1. The following are essentially the same

ia = cpspch(8.02)

ib	cps2pch 8.02, 12

ic	cpsxpch 8.02, 12, 2, 1.02197503906

2. These are opcodes, not functions.

3. Negative values of ipch are allowed, but not negative irepeat, iequal or ibase.

EXAMPLES

inote	cps2pch	p5, 19	; convert oct.pch to cps in 19ET

inote	cpsxpch	p5, 12, 3, 261.62561	; Pierce scale centered on middle A

inote	cpsxpch	p5, 21, 4, 16.35160062496	; 10.5ET scale

The use of a table allows exotic scales by mapping frequencies in a table

For example the table

f2 0 16 -2 1 1.1 1.2 1.3 1.4 1.6 1.7 1.8 1.9

can be used with

ip	cps2pch p4, -2

to get a 10 note scale of unequal divisions


Arithmetic operators

- a

+ a

a && b	(logical AND; not audio-rate)

a || b	(logical OR;  not audio-rate)

a + b

a - b

a * b

a / b

a % b

a ^ b

where the arguments a and b may be further expressions.

NOTE: The power operator ^ was introduced in Csound version 3.493. Use with caution as it is not certain that precedence works as expected.

The modulus-like operator % was introduced in Csound 3.50. It returns the value a reduced by b, so that the result in absolute value is the absoute value of b, by repeated subtraction. This is the same as a modulus function in the integer case.

PERFORMANCE

Arithmetic operators perform operations of change-sign (negate), don't-change-sign, logical AND logical OR, add, subtract, multiply and divide. Note that a value or an expression may fall between two of these operators, either of which could take it as its left or right argument, as in

a + b * c.

In such cases three rules apply:

1)   * and / bind to their neighbors more strongly than + and -.

Thus the above expression is taken as

a + (b * c),

with * taking b and c and then + taking a and b * c.

2)   + and - bind more strongly than &&, which in turn is stronger than ||:

a && b - c || d

is taken as

(a && (b-c)) || d

3)   When both operators bind equally strongly, the operations are done left to right:

a - b - c is taken as (a - b) - c.

Parentheses may be used as above to force particular groupings.


Conditional values

(a > b  ? v1 : v2)

(a < b  ? v1 : v2)

(a > = b  ? v1 : v2)

(a < = b  ? v1 : v2)

(a = = b  ? v1 : v2)

(a ! = b  ? v1 : v2)

where a, b, v1 and v2 may be expressions, but a, b not audio-rate.

PERFORMANCE

In the above conditionals, a and b are first compared. If the indicated relation is true (a greater than b, a less than b, a greater than or equal to b, a less than or equal to b, a equal to b, a not equal to b), then the conditional expression has the value of v1; if the relation is false, the expression has the value of v2. (For convenience, a sole `=` will function as `==`.)

NOTE: If v1 or v2 are expressions, these will be evaluated before the conditional is determined.

In terms of binding strength, all conditional operators (i. e., the relational operators (>,<, etc.), and ?, and : ) are weaker than the arithmetic and logical operators (+, -, *, /, && and ||).

EXAMPLE

(k1 < p5/2 + p6 ? k1 : p7)

binds the terms p5 / 2 and p6. It will return the value k1 below this threshold, else the value p7.


Assignment statements

ir	 =	iarg

kr	 =	karg

ar	 =	xarg

kr	init  	iarg

ar	init  	iarg

ir	tival

ir	divz	ia, ib, isubst  (these not yet implemented)

kr	divz	ka, kb, ksubst

ar	divz	xa, xb, ksubst

PERFORMANCE

  =   (simple assignment) - Put the value of the expression iarg (karg, xarg) into the named result. This provides a means of saving an evaluated result for later use.

init - Put the value of the I-time expression iarg into a K- or A-variable, i.e., initialize the result. Note that init provides the only case of an Init-time statement being permitted to write into a Perftime (K- or A-rate) result cell; the statement has no effect at Perf-time.

tival - Put the value of the instrument's internal "tie-in" flag into the named I-variable. Assigns 1 if this note has been 'tied' onto a previously held note (see i statement); assigns 0 if no tie actually took place. (See also tigoto .)

divz - Whenever b is not zero, set the result to the value a / b; when b is zero, set it to the value of subst instead.

EXAMPLE

kcps   =  i2/3 + cpsoct(k2 + octpch(p5))


Jump statements

Program control statements

igoto	label

tigoto	label

kgoto	label

goto	label

if ia  R ib	igoto	label

if ka R kb	kgoto	label

if ia  R ib	goto	label

timout	istrt, idur, label

where label is in the same instrument block and is not an expression, and where R is one of the Relational operators (>, <, >=, <=, ==, !=) (also = for convenience).

PERFORMANCE

These statements are used to control the order in which statements in an instrument block are to be executed. I-time and P-time passes can be controlled separately as follows:

igoto - During the I-time pass only, unconditionally transfer control to the statement labeled by label.

tigoto - similar to igoto, but effective only during an I-time pass at which a new note is being 'tied' onto a previously held note (see i-statement); no-op when a tie has not taken place. Allows an instrument to skip initialization of units according to whether a proposed tie was in fact successful (see also tival, delay).

kgoto - During the P-time passes only, unconditionally transfer control to the statement labeled by label.

goto - (combination of igoto and kgoto) Transfer control to label on every pass.

if...igoto - conditional branch at I-time, depending on the truth value of the logical expression "ia R ib". The branch is taken only if the result is true.

if...kgoto - conditional branch during P-time, depending on the truth value of the logical expression "ka R kb". The branch is taken only if the result is true.

if...goto - combination of the above. Condition tested on every pass.

timout - conditional branch during P-time, depending on elapsed note time. istrt and idur specify time in seconds. The branch to label will become effective at time istrt, and will remain so for just idur seconds. Note that timout can be reinitialized for multiple activation within a single note (see example in Reinitialization statements).

EXAMPLE

if k3 > p5 + 10 kgoto next


Reinitialization statements
Reinitialisation statements

Permit an instrument to reinitialise itself during performance.

reinit 	label

rigoto	label

rireturn

PERFORMANCE

reinit - whenever this statement is encountered during a P-time pass, performance is temporarily suspended while a special Initialization pass, beginning at label and continuing to rireturn or endin, is executed. Performance will then be resumed from where it left off.

rigoto - similar to igoto, but effective only during a reinit pass (i.e., No-op at standard I-time). This statement is useful for bypassing units that are not to be reinitialized.

rireturn - terminates a reinit pass (i.e., No-op at standard I-time). This statement, or an endin, will cause normal performance to be resumed.

EXAMPLE

The following statements will generate an exponential control signal whose value moves from 440 to 880 exactly ten times over the duration p3.

reset:  	timout  0, p3 /10, contin	;after p3/10 seconds,

reinit    reset               	; reinit both timout

contin:	expon   440, p3/10,880	; and expon

riretum                            	; then resume perf


Duration control statements

turnon	insno[,itime]

ihold

turnoff

Permit the current note to modify its own duration.

PERFORMANCE

turnon activates an instrument with number insno for an indefinite time, after a delay of itime seconds. Note that turnon only can be used outside instr - endin statements, ie on the global level.

ihold - this I-time statement causes a finite-duration note to become a held' note. It thus has the same effect as a negative p3 (see Score i-statement), except that p3 here remains positive and the instrument reclassifies itself to being held indefinitely. The note can be turned off explicitly with turnoff, or its space taken over by another note of the same instrument number (i.e. it is tied into that note). Effective at I-time only; no-op during a reinit pass.

turnoff - this P-time statement enables an instrument to turn itself off. Whether of finite duration or 'held', the note currently being performed by this instrument is immediately removed from the active note list. No other notes are affected.

EXAMPLE

The following statements will cause a note to terminate when a control signal passes a certain threshold (here the Nyquist frequency).

k1	expon	440, p3/10,880 	; begin gliss and continue

if	k1 < sr/2	kgoto contin   	; until Nyquist detected

turnoff                       	; then quit

contin:

a1	oscil	a1, k1, 1


Tempo estimation & Control
Tempo estimation and control

ktemp	tempest	kin, iprd, imindur, imemdur, ihp, ithresh, ihtim, ixfdbak,  istartempo, ifn[, idisprd, itweek]

tempo	ktempo, istartempo

Estimate the tempo of beat patterns in a control signal. Apply tempo control to an uninterpreted score.

INITIALISATION

iprd - period between analyses (in seconds). Typically about .02 seconds.

imindur - minimum duration (in seconds) to serve as a unit of tempo. Typically about .2 seconds.

imemdur - duration (in seconds) of the kin short-term memory buffer which will be scanned for periodic patterns. Typically about 3 seconds.

ihp - half-power point (in cps) of a low-pass filter used to smooth input kin prior to other processing. This will tend to suppress activity that moves much faster. Typically 2 cps.

ithresh - loudness threshold by which the low-passed kin is center-clipped before being placed in the short-term buffer as tempo-relevant data. Typically at the noise floor of the incoming data.

ihtkim - half-time (in seconds) of an internal forward-masking filter that masks new kin data in the presence of recent, louder data. Typically about .005 seconds.

ixfdbak - proportion of this unit's anticipated value to be mixed with the incoming kin prior to all processing. Typically about .3.

istartempo - initial tempo (in beats per minute). Typically 60.

ifn - table number of a stored function (drawn left-to-right) by which the short-term memory data is attenuated over time.

idisprd (optional) - if non-zero, display the short-term past and future buffers every idisprd seconds (normally a multiple of iprd). The default value is 0 (no display).

itweek (optional) - fine-tune adjust this unit so that it is stable when analyzing events controlled by its own output. The default value is 1 (no change).

PERFORMANCE

tempest examines kin for amplitude periodicity, and estimates a current tempo. The input is first low-pass filtered, then center-clipped, and the residue placed in a short-term memory buffer (attenuated over time) where it is analyzed for periodicity using a form of autocorrelation. The period, expressed as a tempo in beats per minute, is output as ktemp. The period is also used internally to make predictions about future amplitude patterns, and these are placed in a buffer adjacent to that of the input. The two adjacent buffers can be periodically displayed, and the predicted values optionally mixed with the incoming signal to simulate expectation.

This unit is useful for sensing the metric implications of any k-signal (e.g- the RMS, the root-mean-square of an audio signal, or the second derivative of a conducting gesture), before sending to a tempo statement.

tempo allows the performance speed of Csound scored events to be controlled from within an orchestra. It operates only in the presence of the csound -t flag. When that flag is set, scored events will be performed from their uninterpreted p2 and p3 (beat) parameters, initially at the given command-line tempo. When a tempo statement is activated in any instrument (ktempo > 0.), the operating tempo will be adjusted to ktempo beats per minute. There may be any number of tempo statements in an orchestra, but coincident activation is best avoided.

EXAMPLE

ksum  	specsum	wsignal, 1  	; sum the amps of a spectrum

ktemp	tempest	ksum, .02, .1, 3, 2, 800, .005, 0, 60, 4, .1, .995	; and look for beats

kx,ky	xyin	.05, 30, 0, 120, 0, 75	; sample the cursor

tempo	kx, 75    	; and control the tempo of performance


Sensing and control
Sensing & Control

kx, ky	xyin	iprd, ixmin, ixmax, iymin, iymax[, ixinit, iyinit]

Sense the cursor position in an input window.

INITIALISATION

iprd - period of cursor sensing (in seconds). Typically .1 seconds. (But for eg controlling direct pitch cps, period of .02 secs seems necessary. - re)

ixmin, ixmax, iymin, iymax - edge values for the x-y coordinates of a cursor in the input window.

ixinit, iyinit (optional) - initial x-y coordinates reported; the default values are 0,0. If these values are not within the given min-max range, they will be coerced into that range.

PERFORMANCE

xyin samples the cursor x-y position in an input window every iprd seconds. Output values are repeated (not interpolated) at the K-rate, and remain fixed until a new change is registered in the window. There may be any number of input windows. This unit is useful for realtime performance control (See realtime support), but continuous motion should be avoided if iprd is unusually small.

NOTE: xyin was only implemented in Winsound version 3.48, and is not currently available in DOS version. Here is the release note for this implementation:

When xyin is called the position of the mouse within the output window is used to reply to the request.  This simple mechanism does mean that only one xyin can be used accurately at once.  The position of the mouse is reported in the output window.

The mouse position is read with ixmin to the left and iymin at the bottom of the window.

NOTE 2: For this opcode to function properly under Winsound, it seems you must have the Full option checked in the Graphics groupbox in the main dialog window.

EXAMPLE

kx,ky	xyin	.05, 30, 0, 120, 0, 75	; sample the cursor

tempo	kx, 75    	; and control the tempo of performance


Sound input & output

a1	in

a1, a2	ins

a1,..., a4	inq

a1	soundin	ifilcod[, iskptim][, iformat]

a1, a2	soundin	ifilcod[, iskptim][, iformat]

a1,..., a4	soundin	ifilcod[, iskptim][, iformat]

a1[,a2[,a3,a4]] diskin 	ifilcod, kpitch[,iskiptim][, iwraparound] [,iformat]

out    	asig

outs1	asig

outs2	asig

outs  	asig1, asig2

outq1	asig

outq2	asig

outq3	asig

outq4	asig

outq	asig1, asig2, asig3, asig4

Read/write audio data from/to an external device or stream.

(NOTE: As of Csound 3.492, if an outx opcode is used which is inconsistent with the selected nchnls value, Csound attempts to correct to the correct one, which is not necessarily correct.)

INITIALISATION

ifilcod - integer or character-string denoting the source soundfile name. An integer denotes the file soundin.filcod; a character-string (in double quotes, spaces permitted) gives the filename itself, optionally a full pathname. If not a full path, the named file is sought first in the current directory, then in that given by the environment variable SSDIR (if defined) then by SFDIR. See also GEN01.

iskptim (optional) - time in seconds of input sound to be skipped. The default value is 0.

iformat (optional) - specifies the audio data file format:

1 = 8-bit signed char

2 = 8-bit A-law bytes

3 = 8-bit U-law bytes

4 = 16-bit short integers

5 = 32bit long integers

6 = 32-bit floats

If iformat = 0 it is taken from the soundfile header, and if no header from the csound -o command flag. The default value is 0.

kpitch - can be any real number. a negative number signifies backwards playback.  The given number is a pitch ratio, where:

1= norm pitch,

2=oct higher,

3=12th higher,etc;

.5= oct lower,

.25=2oct lowr, etc;

-1= norm pitch backwards,-

2=oct higher backwrds,etc..

iwraparound - 1=on, 0=off (wraps around to end of file either direction)

PERFORMANCE

in, ins, inq - copy the current values from the standard audio input buffer. If the command-line flag -i is set, sound is read continuously from the audio input stream (e.g. stdin or a soundfile) into an internal buffer. Any number of these units can read freely from this buffer.

soundin is functionally an audio generator that derives its signal from a pre-existing file. The number of channels read in is set by the number of result cells, a1, a2, etc. A soundin unit opens this file whenever the host instrument is initialized, then closes it again each time the instrument is turned off. There can be any number of soundin units within a single instrument or orchestra; also, two or more of them can read simultaneously from the same external file.

diskin is identical to soundin, except that it can alter the pitch of the sound that is being read. (New in Csound 3.47)

out, outs, outq send audio samples to an accumulating output buffer (created at the beginning of performance) which serves to collect the output of all active instruments before the sound is written to disk. There can be any number of these output units in an instrument. The type (mono, stereo, or quad) must agree with nchnls, but units can be chosen to direct sound to any particular channel: outs1 sends to stereo channel 1, outq3 to quad channel 3, etc.


Panning
(Quad) Stereo panning

a1,…,a4   pan	asig, kx, ky, ifn[, imode][, ioffset]

Distribute an audio signal amongst four channels with localization control.

INITIALISATION

ifn   -  function table number of a stored pattern describing the amplitude growth in a speaker channel as sound moves towards it from an adjacent speaker. Requires extended guard-point.

imode (optional) - mode of the kx, ky position values. 0 signifies raw index mode, 1 means the inputs are normalized (0 - 1). The default value is 0.

ioffset (optional) - offset indicator for kx, ky. 0 infers the origin to be at channel 3 (left rear); 1 requests an axis shift to the quadraphonic center. The default value is 0.

PERFORMANCE

pan takes an input signal asig and distributes it amongst four outputs (essentially quad speakers) according to the controls kx and ky. For normalized input (mode=1) and no offset, the four output locations are in order: left-front at (0,1), right-front at (1,1), left-rear at the origin (0,0), and right-rear at (1,0). In the notation (kx, ky), the coordinates kx and ky, each ranging 0 - 1, thus control the 'rightness' and 'forwardness' of a sound location.

Movement between speakers is by amplitude variation, controlled by the stored function table ifn. As kx goes from 0 to 1, the strength of the right-hand signals will grow from the left-most table value to the right-most, while that of the left-hand signals will progress from the right-most table value to the left-most. For a simple linear pan, the table might contain the linear function 0 - 1. A more correct pan that maintains constant power would be obtained by storing the first quadrant of a sinusoid. Since pan will scale and truncate kx and ky in simple table lookup, a medium-large table (say 8193) should be used.

kx, ky values are not restricted to 0 - 1. A circular motion passing through all four speakers (enscribed) would have a diameter of root 2, and might be defined by a circle of radius R = root 1/2 with center at (.5,.5). kx, ky would then come from Rcos(angle), Rsin(angle), with an implicit origin at (.5,.5) (i.e. ioffset = 1). Unscaled raw values operate similarly. Sounds can thus be located anywhere in the polar or cartesian plane; points lying outside the speaker square are projected correctly onto the square's perimeter as for a listener at the center.

EXAMPLE

instr 1

k1	phasor	1/p3	; fraction of circle

k2	tablei	k1, 1, 1 	; sin of angle (sinusoid in f1)

k3 	tablei	k1, 1, 1, .25, 1	; cos of angle (sin offset 1/4 circle)

a1	oscili	10000,440, 1	; audio signal..

  a1,a2,a3,a4	pan	a1, k2/2, k3/2, 2, 1, 1	; sent in a circle (f2=1st quad sin)

outq	a1, a2, a3, a4

endin


Binaural 3-D sound
3-D Sound

Use of HRTF data

aleft, aright   hrtfer	asig, kAz, kElev, "HRTFcompact"

Output is binaural (headphone) 3D audio.

INITIALIZATION

kAz - azimuth value in degrees. Positive values represent position on the right, negative values are positions on the left.

kElev - elevation value in degrees. Positive values represent position above the horizontal plane, negative values are positions below the horizontal plane.

At present, the only file which can be used with hrtfer is HRTFcompact. It must be passed to the ugen as the last argument within qoutes as shown above. This file can be found on the Bath/Montreal sites, at

ftp://ftp.maths.bath.ac.uk/pub/dream/utilities/Analysis/

ftp://ftp.musique.umontreal.ca/pub/mirrors/dream/utilities/Analysis/

PERFORMANCE

This unit generator places a mono input signal in a virtual 3D space around the listner by convolving the input with the appropriate HRTF data specified by the opcode's azimuth and elevation values. hrtfer allows these values to be k-values, allowing for dynamic spatialization. hrtfer can only place the input at the reqeusted position because the HRTF is loaded in at i-time (remember that currently, csound has a limit of 20 files it can hold in memory, otherwise it causes a segmentation fault). The output will need to be scaled either by using balance or by multiplying the output by some scaling constant.

NOTE

The sampling rate of the orchestra must be 44.1kHz. This is because 44.1kHz is the sampling rate at which the HRTFs were measured. In order to be used at a different rate, the HRTFs need to be resampled at the desired rate.

EXAMPLE

kaz	linseg	 0, p3, -360 	; move the sound in circle around the listener,

kel 	linseg	 -40, p3, 45 	; changing elevation as it is turning

asrc	soundin "soundin.1"

aleft,aright 	hrtfer	asrc, kaz, kel, "HRTFcompact"

aleftscale	=	aleft * 200

arightscale 	=	aright * 200

outs	aleftscale, arightscale


Sound spatialisation

By Richard Karpen (New in Csound 3.48)

a1,..., a4	space	asig, ifn, ktime, kreverbsend [,kx, ky]

a1,..., a4	spsend

kr	spdist	ifn, ktime, [,kx, ky]

DESCRIPTION

space takes an input signal and distributes it among 4 channels using cartesian xy coordinates to calculate the balance of the outputs. The xy coordinates can be defined in a separate text file and accessed through a Function statement in the score using GEN28 (description of GEN28 given below), or they can be specified using the optional kx, ky arguments. The advantages to the former are:

1. 	A graphic user interface can be used to draw and edit the trajectory through the cartesian plane;

2. 	The file format is in the form time1 X1 Y1 time2 X2 Y2 time3 X3 Y3 allowing the user to define a time-tagged trajectory. space then allows the user to specify a time pointer (much as is used for pvoc, lpread and some other units) to have detailed control over the final speed of movement.

spsend depends upon the existence of a previously defined space. The output signals from spsend are derived from the values given for XY and reverb in the space and are ready to be sent to local or global reverb units (see example below).

spdist uses the same xy data as space, also either from a text file using GEN28 or from x and y arguments given to the unit directly. The purpose of this unit is to make available the values for distance that are calculated from the xy coordinates. In the case of space the xy values are used to determine a distance which is used to attenuate the signal and prepare it for use in spsend. But it is also useful to have these values for distance available to scale the frequency of the signal before it is sent to the space unit.

PERFORMANCE

The configuration of the XY coordinates in space places the signal in the following way: a1 is -1, 1; a2 is 1, 1; a3 is -1, -1; a4 is 1, -1. This assumes a loudspeaker set up as a1 is left front, a2 is right front, a3 is left back, a4 is right back:

a1	    front	a2

a3	    back	a4

Values greater than 1 will result in sounds being attenuated as if in the distance. space considers the speakers to be at a distance of 1; smaller values of XY can be used, but space will not amplify the signal in this case. It will, however balance the signal so that it can sound as if it were within the 4 speaker space.  x=0, y=1, will place the signal equally balanced between left and right front channels, x=y=0 will place the signal equally in all 4 channels, and so on. Although there must be 4 output signals from space, it can be used in a 2 channel orchestra. If the XY's are kept so that Y>=1, it should work well to do panning and fixed localization in a stereo field.

ifn - number of the stored function table created using GEN28. If ifn is 0 then space will take its values for the xy coordinates from kx and ky. This function generator reads a text file which contains sets of three values representing the xy coordinates and a time-tag for when the signal should be placed at that location. The file should contain ASCII numbers, in the format:

(time     X      Y)

   0        -1       1

   1         1       1

   2         4       4

   2.1     -4      -4

   3       10    -10

   5      -40       0

If that file were named "move" then the GEN28 call in the score would look like:

f1 0 0 "move"

GEN28 takes 0 as the size and automatically allocates memory. It creates values to 10 milliseconds of resolution. So in this case there will be 500 values created by interpolating X1 to X2 to X3 and so on, and Y1 to Y2 to Y3 and so on, over the appropriate number of values that are stored in the function table. In the above example, the sound will begin in the left front, over 1 second it will move to the right front, over another second it move further into the distance but still in the left front, then in just 1/10th of a second it moves to the left rear, a bit distant. Finally over the last .9 seconds the sound will move to the right rear, moderately distant, and it comes to rest between the two left channels (due west!), quite distant. Since the values in the table are accessed through the use of a time-ponter in the space unit, the actual timing can be made to follow the file's timing exactly or it can be made to go faster or slower through the same trajectory. If you have access to the GUI that allows one to draw and edit the files, there is no need to create the text files manually. But as long as the file is ASCII and in the format shown above, it doesn't matter how it is made!

ktime - index into the table containing the xy coordinates. If used like:

 ktime line 0, 5, 5

 a1, a2, a3, a4 space asig, 1, ktime, ...

with the file "move" described above, the speed of the signal's movement will be exactly as desribed in that file. However:

ktime line 0, 10, 5

the signal will move at half the speed specified. Or in the case of:

ktime line 5, 15, 0

the signal will move in the reverse direction as specified and 3 times slower! Finally:

ktime line 2, 10, 3

will cause the signal to move only from the place specified in line 3 of the text file to the place specified in line 5 of the text file, and it will take 10 seconds to do it.

kreverbsend - the percentage of the direct signal that will be factored along with the distance as derived from the XY coordinates to calculate signal amounts that can be sent to reverb units such as reverb, or reverb2.

kx, ky - when ifn is 0, space and spdist will use these values as the XY coordinates to localize the signal. They are optional and both default to 0.

EXAMPLE

instr 1

   ... (define asig as some audio signal)

ktime line 0, p3, p10

a1, a2, a3, a4 space asig,1, ktime, .1

ar1, ar2, ar3, ar4 spsend

ga1 = ga1+ar1

ga2 = ga2+ar2

ga3 = ga3+ar3

ga4 = ga4+ar4

outq a1, a2, a3, a4

endin

instr 99 ; reverb instrument

a1 reverb2 ga1, 2.5, .5

a2 reverb2 ga2, 2.5, .5

a3 reverb2 ga3, 2.5, .5

a4 reverb2 ga4, 2.5, .5

outq a1, a2, a3, a4

ga1=0

ga2=0

ga3=0

ga4=0

endin

In the above example, the signal, asig, is moved according to the data in Function #1 indexed by ktime. space sends the appropriate amount of the signal internally to spsend. The outputs of the spsend are added to global accumulators in a common Csound style and the global signals are used as inputs to the reverb units in a separate instrument.

space can useful for quad and stereo panning as well as fixed placed of sounds anywhere between two loudspeakers. Below is an example of the fixed placement of sounds in a stereo field using XY values from the score instead of a function table.

instr 1

... (asig an audio signal)

a1, a2, a3, a4   space asig, 0, 0, .1, p4, p5

ar1, ar2, ar3, ar4  spsend

ga1=ga1+ar1

ga2=ga2+ar2

outs a1, a2

endin

instr 99 ; reverb....

....

endin

A few notes: p4 and p5 are the X and Y values

;place the sound in the left speaker and near

i1 0 1 -1 1

;place the sound in the right speaker and far

i1 1 1 45 45

;place the sound equally between left and right and in the middle ground distance

i1 2 1 0 12

e

The next example shows a simple intuitive use of the distance values returned by spdist to simulate doppler shift.

ktime	line 0, p3, 10

kdist	spdist 1, ktime

kfreq = (ifreq * 340) / (340 + kdist)

asig	oscili iamp, kfreq, 1

a1, a2, a3, a4      space asig, 1, ktime, .1

ar1, ar2, ar3, ar4  spsend

The same function and time values are used for both spdist and space. This insures that the distance values used internally in the space unit will be the same as those returned by spdist to give the impression of a doppler shift!


Sound location

By Richard Karpen (New in Csound 3.48)

a1, a2	locsig	asig, kdegree, kdistance, kreverbsend

a1,... , a4	locsig	asig, kdegree, kdistance, kreverbsend

a1, a2	locsend

a1,..., a4	locsend

DESCRIPTION

locsig takes an input signal and distributes it among 2 or 4 channels using values in degrees to calculate the balance between adjacent channels. It also takes arguments for distance (used to attenuate signals that are to sound as if they are some distance further than the loudspeaker itself), and for the amount the signal that will be sent to reverberators. This unit is based upon the example in the Charles Dodge/Thomas Jerse book, "Computer Music," page 320.

locsend depends upon the existence of a previously defined locsig. The number of output signals must match the number in the previous locsig. The output signals from locsend are derived from the values given for distance and reverb in the locsig and are ready to be sent to local or global reverb units (see example below). The reverb amount and the balance between the 2 or 4 channels are calculated in the same way as described in the Dodge book (an essential text!).

PERFORMANCE

kdegree - value between 0 and 360 for placement of the signal in a 2 or 4 channel space configured as: a1=0, a2=90, a3=180, a4=270 (kdegree=45 would balanced the signal equally between a1 and a2). locsig maps kdegree to sin and cos functions to derive the signal balances (ie.: asig=1, kdegree=45, a1=a2=.707).

kdistance - value >= 1 used to attenuate the signal and to calculate reverb level to simulate distance cues.  As kdistance gets larger the sound should get softer and somewhat more reverberant (assuming the use of locsend in this case).

kreverbsend - the percentage of the direct signal that will be factored along with the distance and degree values to derive signal amounts that can be sent to a reverb unit such as reverb, or reverb2.

EXAMPLE

instr 1

   ... (define asig as some audio signal)

kdegree line 0, p3, 360

kdistance line 1, p3, 10

a1, a2, a3, a4     locsig asig, kdegree, kdistance, .1

ar1, ar2, ar3, ar4  locsend

ga1 = ga1+ar1

ga2 = ga2+ar2

ga3 = ga3+ar3

ga4 = ga4+ar4

outq a1, a2, a3, a4

endin

instr 99 ; reverb instrument

a1 nreverb ga1, 2.5, .5

a2 nreverb ga2, 2.5, .5

a3 nreverb ga3, 2.5, .5

a4 nreverb ga4, 2.5, .5

outq a1, a2, a3, a4

ga1=0

ga2=0

ga3=0

ga4=0

endin

In the above example, the signal, asig, is sent around a complete circle once during the duration of a note while at the same time it becomes more and more "distant" from the listeners' location. locsig sends the appropriate amount of the signal internally to locsend. The outputs of the locsend are added to global accumulators in a common Csound style and the global signals are used as inputs to the reverb units in a separate instrument.

locsig is useful for quad and stereo panning as well as fixed placed of sounds anywhere between two loudspeakers. Below is an example of the fixed placement of sounds in a stereo field.

instr 1

... (asig an audio signal)

a1, a2   locsig asig, p4, p5, .1

ar1, ar2 locsend

ga1=ga1+ar1

ga2=ga2+ar2

outs a1, a2

endin

instr 99 ; reverb....

....

endin

Score file - a few notes

;place the sound in the left speaker and near

i1 0 1 0 1

;place the sound in the right speaker and far

i1 1 1 90 25

;place the sound equally between left and right and in the middle ground distance

i1 2 1 45 12

e

The next example shows a simple intuitive use of the distance value to simulate doppler shift. The same value is used to scale the frequency as is used as the distance input to locsig.

kdistance  line 1, p3, 10

kfreq = (ifreq * 340) / (340 + kdistance)

asig   oscili iamp, kfreq, 1

kdegree  line 0, p3, 360

a1, a2, a3, a4 locsig asig, kdegree, kdistance, .1

ar1, ar2, ar3, ar4 locsend


Signal display

print	iarg[, iarg,...]

display	xsig, iprd[, iwtflg]

dispfft 	xsig, iprd, iwsiz[, iwtyp][, idbouti][, iwtflg]

These units will print orchestra Init-values, or produce graphic display of orchestra control signals and audio signals. Uses display windows if available in the system, else (or if -g flag is set) displays are approximated in ascii characters.

See also printk, printks

INITlALISATION

iprd - the period of display in seconds.

iwsiz - size of the input window in samples. A window of iwsiz points will produce a Fourier transform of iwsiz/2 points, spread linearly in frequency from 0 to sr/2. iwsiz must be a power of 2. The windows are permitted to overlap.

iwtyp (optional) - window type. 0 = rectangular, 1 = hanning. The default value is 0 (rectangular).

idbout (optional) - units of output for the Fourier coefficients. 0 = magnitude, 1 = decibels. The default is 0 (magnitude).

iwtflg (optional) - wait flag. If non-zero, each display is held until released by the user. The default value is 0 (no wait).

PERFORMANCE

print - print the current value of the I-time arguments (or expressions) iarg at every init-time pass through the instrument.

display - display the audio or control signal xsig every iprd seconds, as an amplitude vs. time graph.

dispfft - display the Fourier Transform of an audio or control signal (asig or ksig) every iprd seconds using the Fast Fourier Transform method.

EXAMPLE

k1	envlpx	l, .03, p3, .05, l, .5, .0l	; generate a note envelope

display	k1, p3	; and display entire shape


k-rate signal in/out
Input/output k-rate signals to file

k1	readk	ifilname, iformat, iprd [, interp]

k1,k2	readk2	ifilname, iformat, iprd [, interp]

k1,k2,k3	readk3	ifilname, iformat, iprd [, interp]

k1,…, k4	readk4	ifilname, iformat, iprd [, interp]

dumpk	ksig, ifilname, iformat, iprd

dumpk2	ksig1, ksig2, ifilname, iformat, iprd

dumpk3	ksig1, ksig2, ksig3, ifilname, iformat, iprd

dumpk4	ksig1, ksig2, ksig3, ksig4, ifilname, iformat, iprd

Periodically write orchestra control-signal values to a named external file in a specific format.

NAME CHANGES

The dumpk series were called kdumpN up until Csound 3.492.

The readk ugens were earlier documented as kread, but were never implemented until Csound 3.52 (by John ffitch).

INITIALISATION

ifilname - character string(in double quotes, spaces permitted) denoting the external file name. May either be a full path name with target directory specified or a simple filename to be created within the current directory

iformat - specifies the output data format:

1 = 8-bit signed char (high order 8 bits of a 16-bit integer),

4 = 16-bit short integers,

5 = 32-bit long integers,

6 = 32-bit floats (Csound internal signal format),

7 = ASCII long integers,

8 = ASCII floats (4 decimal places).

Note that A-law and U-law ouput are not available, and that all formats except the last two are binary. The output file contains no header information.

iprd - the period of ksig output i seconds, rounded to the nearest orchestra control period. A value of 0 implies one control period (the enforced minimum), which will create an output file sampled at the orchestra control rate.

interp (optional) - if non-zero, and iprd implies more than one control period, interpolate the k- signals between the periodic reads from the external file. The default value is 0 (repeat each signal between frames). Note: This argument is not yet implemented (Csound 3.52), so any input will be ignored.

PERFORMANCE

These units allow up to four generated control signal values to be saved in a named external file. The file contains no self-defining header information, but is a regularly sampled time series, suitable for later input or analysis.

There may be any number of kread units in an instrument or orchestra, and they may read from the same or different files.

There may be any number of dumpk units in an instrument or orchestra, but each must write to a different file.

EXAMPLE

knum	=   knum+1 	; at each k-period

ktemp	tempest	krms, .02, .1, 3, 2, 800, .005, 0, 60, 4, .1, .995

                             	 ;estimate the tempo

koct	specptrk	wsig, 6, .9, 0 	;and the pitch

dumpk3	knum, ktemp, cpsoct(koct), "what happened when", 8 0

 ;& save them


Create new score events

By John ffitch (New in Csound 3.491)

schedule	inst, iwhen, idur, ....

schedwhen	ktrigger, kinst, kwhen, kdur, ....

These opcodes incorporate ideas and code from G. Maldonado

PERFORMANCE

schedule adds a new score event.  The arguments are the same as in a score.  The i/kwhen time (p2) is measured from the time of the scheduling event.

If the duration is zero or negative the new event is of MIDI type, and inherits the release sub-event from the scheduling instruction.

In the case of schedwhen the event is only scheduled when the krate value ktrigger is first non-zero.

EXAMPLES

Double hit and 1sec separation.

instr 1

      schedule	2,  1, 0.5, p4, p5

      a1  shaker	p4, 60, 0.999, 0, 100, 0

      out	a1

endin

instr 2

      a1    marimba   p4, cpspch(p5), p6, p7, 2, 6.0, 0.05, 1, 0.1

      out       a1

endin

instr 3

      kr    table	kr, 1

      schedwhen	kr, 1, 0.25, 1, p4, p5

endin


Function table control

iafno	ftgen	ifno,itime,isize, igen, iarga[,...iargz]

ftlen(x) 	(init time args only)

ftlptim(x)	(init time args only)

ftsr(x)	(init-rate args only)

nsamp(x)	(init-rate args only)

Generate function tables in the orchestra file, and get information about a function table.

(NOTE: ftsr(x) and nsamp(x) were introduced in Csound version 3.49)

INITIALISATION

ifno	- either a requested or an automatically assigned table number above 100.  If ifno is zero the number is assigned automatically and the value placed in iafno,  Any other value is used as the table number.

itime	- ignored (and thus all ftables created by ftgen are created at time 0),

isize, igen, iarga… same functions as table generation in the score with the f statement.

For ftlen and ftlptim, the argument within the parentheses may be an expression.

PERFORMANCE

ftgen creates a function table from the orchestra file. It must be used outside instr - endin statements (eg in the orchestra header section). See GEN overview for available functions.

ftlen(x) returns the size (no. of points) of stored function table no. x. While most units referencing a stored table will automatically take its size into account (so tables can be of arbitrary length), this function reports the actual size if that is needed. Note that ftlen will always return a power-of-2 value, i.e. the function table guard point (see f statement) is not included.

ftlptim(x) returns the loop segment start-time (in seconds) of stored function table no. x. This reports the duration of the direct recorded attack and decay parts of a sound sample, prior to its looped segment.  Returns zero (and a warning message) if the sample does not contain loop points.

ftsr(x) (by Gabriel Maldonado) returns the sampling rate of a GEN01 or GEN22 generated table. The sampling rate is determined from the header of the original file. If no header is present in the original file, or the table was not created by either of these two GENs ftsr(x) returns 0.

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


Innehåll:

SIGNAL GENERATORS line expon linseg expseg linsegr expsegr phasor, table tablei table3 oscil1 osciln oscilx, oscil oscili oscil3 foscil foscili, poscil, poscil3 lposcil lposcil3, loscil loscil3 doscil, buzz gbuzz, fof fof2 fog, grain, granule (copyright note), pluck, rand randh randi rnd birnd, Notes on rand gens, linrand trirand exprand bexprnd cauchy pcauchy poisson gauss weibull betarand unirand (poscil, other functionality)


Linear signal generators

kr	line 	ia, idur1, ib

ar	line 	ia, idur1, ib

kr	expon	ia, idur1, ib

ar	expon	ia, idur1, ib

kr	linseg	ia, idur1, ib[, idur2, ic[...]]

ar	linseg	ia, idur1, ib[, idur2, icI...]]

kr	expseg	ia, idur1, ib[, idur2, ic[...]]

ar	expseg	ia, idur1, ib[, idur2, ic[...]]

For realtime MIDI control (new in Csound version 3.47):

kr	linsegr	ia, idur1, ib[,idur2, ic[..]]. irel, iz

ar	linsegr	ia, idur1, ib[,idur2, ic[..]]. irel, iz

kr	expsegr	ia, idur1, ib[,idur2, ic[..]]. irel, iz

ar	expsegr	ia, idur1, ib[,idur2, ic[..]]. irel, iz

Output values kr or ar trace a straight line (exponential curve) or a series of line segments (or exponential segments) between specified points.

INITIALISATION

ia - starting value. Zero is illegal for exponentials.

ib, ic, etc. - value after idur1 seconds, etc. For exponentials, 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.

irel - Release time after MIDI note-off.

iz - Final value at end of release time.

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.

linsegr and expsegr work like linseg/expseg, except that on a MIDI note off event the release section is used, extending the performance by irel seconds, during which the value of the opcode changes to iz.

EXAMPLE

k2   expseg    440, p3/2,880, p3/2,440

This statement creates a control signal which moves exponentially from 440 to 880 and back, over the duration p3.


Phase Generator

kr	phasor	kcps[, iphs]

ar	phasor	xcps[, iphs]

Produce a normalized moving phase value.

INITIALISATION

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

PERFORMANCE

An internal phase is successively accumulated in accordance with the cps frequency to produce a moving phase value, normalized to lie in the range 0. <= phs < 1.

When used as the index to a table unit, this phase (multiplied by the desired function table length) will cause it to behave like an oscillator.

Note that phasor is a special kind of integrator, accumulating phase increments that represent frequency settings.

EXAMPLE

k1	phasor	1	   ; cycle once per second

kpch	table	k1 * 12, 1	   ; through 12-note pch table

a1	oscil	p4, cpspch(kpch), 2	   ; with continuous sound


Table read generators
Table access

See also k-rate table manipulation

xr	table	xndx, ifn[, ixmode][, ixoff][, iwrap]

xr	tablei	xndx, ifn[, ixmode][, ixoff][, iwrap]

xr	table3	xndx, ifn[, ixmode][, ixoff][, iwrap]

kr	oscil1	idel, kamp, idur, ifn

kr	oscil1i	idel, kamp, idur, ifn

ar	osciln	kamp, ifrq, ifn, itimes

(ar	oscilx	kamp, ifrq, ifn, itimes)

Table values are accessed by direct indexing or by incremental sampling.

INITIALISATION

ifn - function table number. tablei, oscil1i require the extended guard point.

ixmode (optional) - xndx data mode. 0 = raw xndx, 1 = normalized (0 to 1). The default value is 0.

ixoff (optional) - amount by which xndx is to be offset. For a table with origin at center, use tablesize/2 (raw) or .5 (normalized). The default value is 0.

iwrap (optional) - wraparound xndx flag. 0 = nowrap (xndx < 0 treated as xndx =0; xndx > tablesize sticks at xndx =size), 1 = wraparound. The default value is 0.

idel - delay in seconds before oscil1 incremental sampling begins.

idur - duration in seconds to sample through the oscil1 table just once. A zero or negative value will cause all initialization to be skipped.

itimes - number of passes through sampled data (only osciln)

PERFORMANCE

table invokes table lookup on behalf of init, control or audio indices. These indices can be raw entry numbers (0,l,2...size -1) or scaled values (0 to 1-e). Indices are first modified by the offset value then checked for range before table lookup (see iwrap). If xndx is likely to be full scale, or if interpolation is being used, the table should have an extended guard point. table indexed by a periodic phasor (see phasor) will simulate an oscillator.

oscil1 accesses values by sampling once through the function table at a rate determined by idur. For the first idel seconds, the point of scan will reside at the first location of the table; it will then begin moving through the table at a constant rate, reaching the end in another idur seconds; from that time on (i.e. after idel + idur seconds) it will remain pointing at the last location. Each value obtained from sampling is then multiplied by an amplitude factor kamp before being written into the result.

osciln is like oscil1, but makes a total of itimes passes over the data, after which it is silent. New in Csound 3.47 (Author Barry Vercoe)

oscilx is an alias of osciln. It seems osciln is the primary, so stick with that one. (-re).

tablei and oscil1i are interpolating units in which the fractional part of xndx is used to interpolate between adjacent table entries. The smoothness gained by interpolation is at some small cost in execution time (see also oscili, etc.), but the interpolating and non-interpolating units are otherwise interchangeable. Note that when tablei uses a periodic index whose modulo n is less than the power of 2 table length, the interpolation process requires that there be an (n + 1)th table guard point (a value which is a repeat of the 1st table entry - see f statement in Score).

table3 is like tablei, except that it uses cubic interpolation to enhance audio quality. It was introduced in Csound 3.50.


Oscillators

kr	oscil  	kamp, kcps, ifn[, iphs]

kr	oscili	kamp, kcps, ifn[, iphs]

ar	oscil  	xamp, xcps, ifn[, iphs]

ar	oscili 	xamp, xcps, ifn[, iphs]

ar	oscil3 	xamp, xcps, ifn[, iphs]

ar	foscil  	xamp, kcps, xcar, xmod, kndx, ifn[, iphs]

ar	foscili	xamp, kcps, xcar, xmod, kndx, ifn[, iphs]

Table ifn is incrementally sampled modulo the table length and the value obtained is multiplied by xamp.

NOTES

The input arguments xcar and xmod to foscil and foscili were limited to k-rate values until Csound 3.50.

oscil3 is like oscili, except that it uses cubic interpolation for enhanced sound quality. It was also introduced in Csound 3.50.

INITIALISATION

ifn - 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

The oscil units output periodic control (or audio) signals consisting of the value of kamp (xamp) times the value returned from control rate (audio rate) sampling of a stored function table. The internal phase is simultaneously advanced in accordance with the cps input value. While the amplitude and frequency inputs to the k-rate oscils are scalar only, the corresponding inputs to the audio-rate oscils may each be either scalar or vector, thus permitting amplitude and frequency modulation at either sub-audio or audio frequencies.

foscil is a composite unit that effectively banks two oscils in the familiar Chowning FM setup, wherein the audio-rate output of one generator is used to modulate the frequency input of another (the "carrier"). Effective carrier frequency = kcps * xcar, and modulating frequency = kcps * xmod. For integral values of xcar and xmod, the perceived fundamental will be the minimum positive value of kcps * (xcar - n * kmod), n = 1,1,2,... The input kndx is the index of modulation (usually time-varying and ranging 0 to 4 or so) which determines the spread of acoustic energy over the partial positions given by n = 0,1,2,.., etc. ifn should point to a stored sine wave.

oscili and foscili differ from oscil and foscil respectively in that the standard procedure of using a truncated phase as a sampling index is here replaced by a process that interpolates between two successive lookups. Interpolating generators will produce a noticeably cleaner output signal, but they may take as much as twice as long to run. Adequate accuracy can also be gained without the time cost of interpolation by using large stored function tables of 2K, 4K or 8K points if the space is available.

EXAMPLE

k1	oscil	10, 5, 1	; 5 cps vibrato

a1	oscil	5000, 440 + k1, 1	; around A440 + -10 cps


High precision oscillators

By Gabriel Maldonado (New in Csound 3.52)

ar	poscil	kamp, kcps, 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]

INITALISATION

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 k-rate variation of the starting and ending point of a sample contained in a table.  This can be useful when reading samples loop of a wavetable which repeat speed can be varied during the performance.

The versions with a 3 use cubic interpolation.


Sample playback

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

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

ar1 [,ar2]	doscil	xamp, ifn

Read sampled sound (mono or stereo) from a table, with optional sustain and release looping. Useful for sampled effects such as percussion sounds. doscil is new as of Csound 3.47, loscil3 was introduced in Csound 3.50.

INITIALISATION

ifn - function table number, typically denoting an AIFF (or WAV) sampled sound segment with prescribed looping points. The source file may be mono or stereo.

ibas (optional) - base frequency in cps of the recorded sound. This optionally overrides the frequency given in the AIFF file, but is required if the file did not contain one. The default value is 0 (no override).

imod1, mod2 (optional) - play modes for the sustain and release loops. A value of 1 denotes normal looping, 2 denotes forward & backward looping, 0 denotes no looping. The default value (-1) will defer to the mode and the looping points given in the source file.

ibeg1, iend1, ibeg2, iend2 (optional, dependent on imod1, imod2) - begin and end points of the sustain and release loops. These are measured in sample frames from the beginning of the file, so will look the same whether the sound segment is monaural or stereo.

PERFORMANCE

loscil samples the ftable audio at a rate determined by kcps, then multiplies the result by xamp. The sampling increment for kcps is dependent on the table's base-note frequency ibas, and is automatically adjusted if the orchestra sr value differs from that at which the source was recorded. In this unit, the ftable is always sampled with interpolation.

loscil3 is like loscil, except that it uses cubic interpolation for enhanced sound quality. It was introduced in Csound 3.50.

If sampling reaches the sustain loop endpoint and looping is in effect, the point of sampling will be modified and loscil will continue reading from within that loop segment. Once the instrument has received a turnoff signal (from the score or from a MIDI noteoff event), the next sustain endpoint encountered will be ignored and sampling will continue towards the release loop end-point, or towards the last sample (henceforth to zeros).

loscil is the basic unit for building a sampling synthesizer. Given a sufficient set of recorded piano tones, for example, this unit can resample them to simulate the missing tones. Locating the sound source nearest a desired pitch can be done via table lookup. Once a sampling instrument has begun, its turnoff point may be unpredictable and require an external release envelope; this is often done by gating the sampled audio with linenr, which will extend the duration of a turned-off instrument by a specific period while it implements a decay.

doscil is a direct form of loscil, with no frequency control and no looping. It simply reads the table from beginning to end, then stops. This is useful for sampled effects such as percussion sounds, where the pitch needs no alteration and loop points are not provided.

EXAMPLE

inum	notnum

icps	cpsmidi

iamp	ampmidi	3000, 1

ifno 	table	inum, 2	;notnum to choose an audio sample

ibas	table	inum, 3

kamp	linenr	iamp, 0, .05, .01	;at noteoff, extend by 50 millisecs

asig	loscil	kamp, icps, ifno, cpsoct(ibas/12. + 3)


Buzzers and pulse generators
Buzzers

Variable Spectrum Oscillators (Sine - Pulse Train).

ar	buzz	xamp, xcps, knh, ifn[, iphs]

ar	gbuzz	xamp, xcps, knh, klh, kr, ifn[, iphs]

Output is a set of harmonically related cosine partials.

INITIALISATION

ifn - table number of a stored function containing (for buzz) a sine wave, or (for gbuzz) a cosine wave. In either case a large table of at least 8192 points is recommended.

To create a cosine ftable for gbuzz, use a line like the following:

f2  0  16384  9  1  1  90

Here GEN09 is used to create a sine wave with 90 degree phase shift.

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

PERFORMANCE

The buzz units generate an additive set of harmonically related cosine partials of fundamental frequency xcps, and whose amplitudes are scaled so their summation peak equals xamp. The selection and strength of partials is determined by the following control parameters:

knh  - total number of harmonics requested. Must be positive.

klh  - lowest harmonic present. Can be positive, zero or negative. In gbuzz the set of partials can begin at any partial number and proceeds upwards; if klh is negative, all partials below zero will reflect as positive partials without phase change (since cosine is an even function), and will add constructively to any positive partials in the set.

kr   -  specifies the multiplier in the series of amplitude coefficients. This is a power series: if the klh:th partial has a strength coefficient of A, the (klh + n)th partial will have a coefficient of A * (kr ** n), i.e. strength values trace an exponential curve. kr may be positive, zero or negative, and is not restricted to integers.

buzz and gbuzz are useful as complex sound sources in subtractive synthesis. buzz is a special case of the more general gbuzz in which klh = kr = 1; it thus produces a set of knh equal-strength harmonic partials, beginning with the fundamental. (This is a band-limited pulse train; if the partials extend to the Nyquist, i.e. knh = int (sr / 2 / fundamental freq.), the result is a real pulse train of amplitude xamp.) Although both knh and klh may be varied during performance, their internal values are necessarily integer and may cause "pops" due to discontinuities in the output; kr, however, can be varied during performance to good effect. Both buzz and gbuzz can be amplitude- and/or frequency-modulated by either control or audio signals.

NOTE

These two units have their analogs in GEN11, in which the same set of cosines can be stored in a function table for sampling by an oscillator. Although computationally more efficient, the stored pulse train has a fixed spectral content, not a time-varying one as above.


fof, fof2, fog
Voice Generator

Tutorial

ar	fof	xamp, xfund, xform, koct, kband, kris, kdur, kdec, iolaps, ifna, ifnb, itotdur[, iphs][, ifmode]

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

ar	fog	xamp, xdens, xtrans, aphs, koct, kband, kris, kdur, kdec, iolaps, ifna, ifnb, itotdur[, iphs][, itmode]

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.

fof2 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. (New in Csound v 3.45)

fog is similar to fof; like fof2 it permits granular synthesis. (New in Csound v 3.46)

INITIALISATION

iolaps - number of preallocated spaces needed to hold overlapping burst data. Overlaps are frequency dependent (fof: xfund, fog: xdens), and the space required depends on the maximum value of xfund * kdur.  Can be over-estimated at no computation cost. Uses less than 50 bytes of memory per iolap.

ifna, ifnb - table numbers of two stored functions. The first is a sine table for sineburst synthesis (size of at least 4096 recommended), or data used for granulation (in fof2/fog), usually from a soundfile (GEN01). The second is a rise shape, used forwards and backwards to shape the sineburst rise and decay; this may be linear (GEN07) or perhaps a sigmoid (GEN19).

itotdur - total time during which this fof will be active. Normally set to p3. No new sineburst is created if it cannot complete its kdur within the remaining itotdur.

iphs (optional) - initial phase of the fundamental, expressed as a fraction of a cycle (0 to 1). The default value is 0.

ifmode (optional) - formant frequency mode. If zero, each sineburst keeps the xform frequency it was launched with. If non-zero, each is influenced by xform continuously. The default value is 0. This is identical to the itmode argument for fog.

PERFORMANCE

xamp - peak amplitude of each sineburst, observed at the true end of its rise pattern. The rise may exceed this value given a large bandwidth (say, Q < 10) and/or when the bursts are overlapping.

xfund (or xdens for fog) - the fundamental frequency (in Hertz) of the impulses that create new sinebursts or grains.

xform - the formant frequency, i.e. freq of the sinusoid burst induced by each xfund impulse. This frequency can be fixed for each burst or can vary continuously (see ifmode).

xtrans - transposition factor for fog.  The rate at which data from the stored function table ifna is read within each grain.  This has the effect of transposing the original material.  A value of 1 produces the original pitch. Higher values transpose upwards, lower values downwards. Negative values result in the function table being read backwards.

aphs - (fog only) index (0 to 1) to ifna. This determines the movement of a pointer used as the starting point for reading data within each grain. (xtrans determines the rate at which data is read starting from this pointer.) Equivalent to kphs for fof2.

koct - octaviation index, normally zero. If greater than zero, lowers the effective xfund frequency by attenuating odd-numbered sinebursts. Whole numbers are full octaves, fractions transitional.

kband - the formant bandwidth (at -6dB), expressed in Hz. The bandwidth determines the rate of exponential decay throughout the sineburst, before the enveloping described below is applied.

kris, kdur, kdec - rise, overall duration, and decay times (in seconds) of the sinusoid burst. These values apply an enveloped duration to each burst, in similar fashion to a Csound linen generator but with rise and decay shapes derived from the ifnb input. kris inversely determines the skirtwidth (at -40 dB) of the induced formant region. kdur affects the density of sineburst overlaps, and thus the speed of computation. Typical values for vocal imitation are .003,.02,.007.

kphs - (fof2 only) Vary kphs between 0 and 1 to index the ifna wavetable.   This sets the starting point in ifna table for each individual grain.  If ifna is loaded with a sound file fof2 provides a fast method for time stretching. To set the 1:1 playback rate in kform, use the formula

    	ibas = sndsr / ftlen(ifna)

where sndsr is the original sample rate of the ifna file. Then kform = ibas will simply play back the sound.

When ifna is loaded with a sine table (as in normal fof synthesis), kphs may be randomised to provide noise bands. Bandwidth will be inversely dependent on the length of grains (as controlled by kdur argument).

kgliss - (fof2 only) sets the end pitch of each grain relative to the initial pitch, in octaves. Thus kgliss = 2 means that the grain ends two octaves above its initial pitch, while kgliss = -5/3 has the grain ending a perfect major sixth below.

EXAMPLE

fog example:

; p4 = transposition factor

; p5 = speed factor

; p6 = function table for grain data

i1	=  sr/ftlen(p6)	;scaling to reflect sample rate and table length

a1	phasor	i1*p5	;index for speed

a2	fog 	5000, 100, p4, a1, 0, 0, .01, .02, .01, 2, p6, 1, p3, 0, 1

fof2 example (See fof tutorial for more examples)

;Simple timestretching orchestra with grain glissandi towards end

sr    =  44100

kr    =   4410

ksmps  =  10

nchnls  =    1

instr 1

insnd = 10	; ifna, input sound file through gen 01

ibas  = 32000 / ftlen(insnd)	; 1:1 playback rate - use original sample rate of insnd file

kfund = 38	; around 35-45 seems ok, better if varying slightly

kform = ibas	; straight playback

kphs    line 0, p3, 1	; Now simply set the sound length in p3

kgliss  line 0, p3, .5 	; Grain glissandi

kdur  = 2.5 / kfund 	; (Can go up to 3.5 / kfund, but watch amp)

kris  = kdur / 2.1

kdec  = kris

iolaps = 20

a1    fof2    23000, kfund, kform, 0, 0, kris, kdur, kdec, iolaps, insnd, 7, p3, kphs, kgliss

out      a1

endin

;*********** score file **********

f7   0 8192    7  0  8192  1	 ;Straight line rise/decay

f10  0 131072  1  "Neopren.wav" 0 0 1	 ;ifna soundfile, try speech

i1 0 30	; p3 set to desired sound length

e

;********* end sco **********

CREDITS

Csound's fof generator is loosely based on Michael Clarke's C-coding of IRCAM's CHANT program (Xavier Rodet et al.). Each fof produces a single formant, and the output of four or more of these can be summed to produce a rich vocal imitation. fof synthesis is a special form of granular synthesis, and this implementation aids transformation between vocal imitation and granular textures. Computation speed depends on kdur, xfund, and the density of any overlaps.

The Csound fog generator is by Michael Clarke, extending his earlier work based on IRCAM's fof algorithm.

fof2 is a modification of fof by Rasmus Ekman.


grain (Grain textures)
Grain textures

ar	grain	xamp, xpitch, xdens, kampoff, kpitchoff, kgdur, igfn, ienvfn, imgdur [, igrnd]

Generates granular synthesis textures. This can also be done by fog/fof2, and with more control, but grain is faster than these opcodes.

INITIALISATION

igfn - The ftable number of the grain waveform. This can be just a sine wave or a sampled sound.

ienvfn - Ftable number of the amplitude envelope used for the grains (see also GEN20).

imgdur - Maximum grain duration in seconds. This the highest value to be assigned to kgdur.

igrn - (optional) if non-zero, turns off grain offset randomness. This means that all grains will start reading from the beginning of the igfn table. If zero (the default), grains will start reading from random igfn table positions.

PERFORMANCE

xamp - Total amplitude of the sound.

xpitch - Grain frequency in cps. Note that cycles per second here means times to play through ienvfn each second. To relate to the original frequency of the input sound, use the formula

sndsr / ftlen(igfn)

where sndsr is the original sample rate of the igfn sound.

xdens - Density of grains measured in grains per second. If this is constant then the output is synchronous granular synthesis, very similar to fof. If xdens has a random element (like added noise), then the result is more like asynchronous granular synthesis.

kampoff - Maximum amplitude deviation from xamp. This means that the maximum amplitude a grain can have is kamp + kampoff and the minimum is xamp. If kampoff is set to zero then there is no random amplitude for each grain.

kpitchoff - Maximum pitch deviation from xpitch in cps. Similar to kampoff.

kgdur - Grain duration in seconds. The maximum value for this should be declared in imgdur. If kgdur at any point becomes greater than imgdur, it will be truncated to imgdur.

EXAMPLE

A texture with gradually shortening grains, and widening amp and pitch spread

;;;;;;;;;;;;;;; graintest.orc

instr 1

ienvfn =  5 	; Hanning window

insnd  = 10 	; Sound file

ibasfrq = 32000 / ftlen(insnd) 	; Use original sample rate of insnd file

kamp   expseg 8000, p3/2, 8000, p3/2, 16000

kaoff  line 0, p3, 5000

kpitch line ibasfrq, p3, ibasfrq * .8

kpoff  line 0, p3, ibasfrq * .5

kdens  line 600, p3, 200

kgdur  line .4, p3, .1

maxgdur =  .5

ar  grain kamp, kpitch, kdens, kaoff, kpoff, kgdur, insnd, ienvfn, imaxgdur, 0.0

     out ar

endin

;;;;;;;;;;;;;;; graintest.sco

f5  0 512  20 2	; Hanning window

f10 0 65536 1  "Sound.wav" 0 0 1

i1 0 10

e


granule (Granular synthesis)
 Granular synthesis

By Allan Lee. Copyright notice

ar	granule	xamp, ivoice, iratio, imode, ithd, ifn, ipshift, igskip, igskip_os, ilength, kgap, igap_os, kgsize, igsize_os, iatt, idec [,iseed] [,ipitch1] [,ipitch2] [,ipitch3] [,ipitch4] [,ifnenv]

The granule unit generator is more complex than grain, but does add new possibilities. This is a shortened manual.

DESCRIPTION

granule is a Csound unit generator which employs a wavetable as input to produce granularly synthesized audio output. Wavetable data may be generated by any of the gen subroutines such as GEN01 which reads an audio data file into a wavetable. This enable a sampled sound to be used as the source for the grains. Up to 128 voices are implemented internally. granule has a built-in random number generator to handle all the random offset parameters. Thresholding is also implemented to scan the source function table at initialization stage. This facilitates features such as skipping silence passage between sentences.

The characteristics of the synthesis are controlled by 22 parameters. xamp is the amplitude of the output and it can be either audio rate or control rate variable. All parameters with prefix i must be valid at init time, parameters with prefix k can be either control-rate or init values.

(Programmers note: The sourcecode for this ugen is located in the unintuitively named grain4.h/c files The maximum number of voices can be increased by redefining the variable MAXVOICE in the grain4.h source code file.)

SUMMARY OF PARAMETERS

xamp	amplitude

ivoice	number of voices

iratio	ratio of the speed of the gskip pointer relative to audio sample rate. 0.5 will be half speed.

imode	+1 grain pointer move forward (same direction of the igskip pointer),

-1 backward (oppose direction of the igskip pointer) or 0 for random

ithd	threshold, if the sample signal is smaller than ithd, it will be skipped

ifn	function table number

ipshift	pitch shift control. If ipshift set to 0, pitch will be set randomly up and down an octave. If ipshift set to 1, 2, 3 or 4, up to four different pitches can be set amount all the voices set in ivoice, optional parameters ipitch1, ipitch2, ipitch3 and ipitch4 will be used.

igskip	initial skip from the beginning of the function table in sec.

igskip_os 	igskip pointer random offset in sec, 0 will be no offset.

ilength	length of the table to be used start from igskip in sec.

kgap	gap in sec.

igap_os 	gap random offset in % of the gap size, 0 will be no offset.

kgsize	grain size in sec.

igsize_os	grain size random offset in % of grain size.

iatt	attack in % of grain size.

idec	decade in % of grain size.

[iseed]	optional, seed for the random number generator, default is 0.5.

[ipitch1], [ipitch2], [ipitch3], [ipitch4] optional, pitch shift parameter if ipshift set to 1, 2, 3 or 4.

Range: 0.1 (down 10 octave) to 10 (up 10 octave). Default value is 1, original pitch.

[ifnenv]	Optional function table number to be used to generate the shape of the rise and decay of envelope.

EXAMPLE

Listing of orchestra file

sr	  =  44100

kr	  =    4410

ksmps =        10

nchnls =          2

instr 1

k1 linseg 0,0.5,1,(p3-p2-1),1,0.5,0

a1 granule p4*k1, p5, p6, p7,p8,p9,p10,p11,p12,p13,p14,p15, p16,p17,p18, p19, p20, p21, p22, p23, p24

a2 granule p4*k1,p5,p6,p7,p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18,p19, p20+0.17, p21, p22, p23, p24

outs a1,a2

endin

Listing of score file.

; f statement read sound file sine.aiff in the SFDIR directory into f-table 1

f 1 0 524288 1 "sine.aiff" 1 0

    i1 0 10 2000 64 0.5 0 0 1 4 0 0.005 10 0.01 50 0.02 50 30 30 0.39 1 1.42 0.29 2

e

The above example reads a sound file called sine.aiff into wavetable number 1 with 524,288 samples. It generates 10 seconds of stereo audio output using the wavetable. In the orchestra file, all parameters required to control the synthesis are passed from the score file. A linseg function generator is used to generate an envelope with 0.5 second of linear attack and decade. Stereo effect is generated by using different seeds for the two granule function calls. In the example, 0.17 is added to p20 before passing into the second granule call to ensure that all of the random offset events are different from the first one.

In the score file, the parameters are interpreted as:

p5 (ivoice) the number of voices is set to 64

p6 (iratio) is set to 0.5, it scans the wavetable at half the speed  of the audio output rate

p7 (imode) is set to 0, the grain pointer only move forward

p8 (ithd) is set to 0, skipping the thresholding process

p9 (ifn) is set to 1, function table number 1 is used

p10 (ipshift) is set to 4, four different pitches are going to be  generated

p11 (igskip) is set to 0 and p12 (igskip_os) is set to 0.005, no skipping into the wavetable and a 5 mSec random offset is used

p13 (ilength) is set to 10, 10 seconds of the wavetable is to be used

p14 (kgap) is set to 0.01 and p15 (igap_os) is set to 50, 10 mSec gap with 50% random offset is to be used

p16 (kgsize) is set to 0.02 and p17 (igsize_os) is set to 50, 20 mSec  grain with 50% random offset is used

p18 (iatt) and p19 (idec) are set to 30, 30% of linear attack and  decay is applied to the grain

p20 (iseed) seed for the random number generator is set to 0.39

p21 - p 24 are pitches set to 1 which is the original pitch, 1.42 which is a 5th up, 0.29 which is a 7th down and finally 2 which is an octave up.


GRANULE COPYRIGHT NOTICE

 ASC.Lee@ee.qub.ac.uk

 Copyright 1994, 1995 by the Allan S C Lee, Queen's

 University of Belfast. All rights reserved.

Permission to use, copy, or modify this software and documentation for educational and research purposes only and without fee is hereby granted, provided that this copyright and permission notice appear on all copies and supporting documentation. For any other uses of this software, in original or modified form, including but not limited to distribution in whole or in part, specific prior permission from Allan S C Lee must be obtained. Allan S C Lee and Queen's University of Belfast make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.


Karplus - Strong synthesis

ar	pluck	kamp, kcps, icps, ifn, imeth [, iparm1, iparm2]

Audio output is a naturally decaying plucked string or drum sound based on the Karplus-Strong algorithms.

INITIALISATION

icps - intended pitch value in cps, used to set up a buffer of 1 cycle of audio samples which will be smoothed over time by a chosen decay method. icps normally anticipates the value of kcps, but may be set artificially high or low to influence the size of the sample buffer.

ifn - table number of a stored function used to initialize the cyclic decay buffer. If ifn = 0, a random sequence will be used instead.

imeth - method of natural decay. There are six, some of which use parameters values that follow.

1  -  simple averaging.  A simple smoothing process, uninfluenced by parameter values.

2  -  stretched averaging.  As above, with smoothing time stretched by a factor of iparm1 ( >= 1 ).

3  -  simple drum.  The range from pitch to noise is controlled by a 'roughness factor' in iparm1 (0 to 1). Zero gives the plucked string effect, while 1 reverses the polarity of every sample (octave down, odd harmonics).
The setting .5 gives an optimum snare drum.

4  -  stretched drum.  Combines both roughness and stretch factors. iparm1 is roughness (0 to 1), and iparm2 the stretch factor ( >= 1 ).

5  -  weighted averaging.  As method 1, with iparm1 weighting the current sample (the status quo) and iparm2 weighting the previous adjacent one.
iparm1 + iparm2 must be <= 1.

6  -  1st order recursive filter, with coefs .5.  Unaffected by parameter values.

iparm1, iparm2 (optional) - parameter values for use by the smoothing algorithms (above). The default values are both 0.

PERFORMANCE

An internal audio buffer, filled at I-time according to ifn, is continually resampled with periodicity kcps and the resulting output is multiplied by kamp. Parallel with the sampling, the buffer is smoothed to simulate the effect of natural decay.

Plucked strings (1,2,5,6) are best realized by starting with a random noise source, which is rich in initial harmonics. Drum sounds (methods 3,4) work best with a flat source (wide pulse), which produces a deep noise attack and sharp decay.

The original Karplus-Strong algorithm used a fixed number of samples per cycle, which caused serious quantization of the pitches available and their intonation. This implementation resamples a buffer at the exact pitch given by kcps, which can be varied for vibrato and glissando effects. For low values of the orch sampling rate (e.g. sr = 10000), high frequencies will store only very few samples (sr / icps). Since this may cause noticeable noise in the resampling process, the internal buffer has a minimum size of 64 samples. This can be further enlarged by setting icps to some artificially lower pitch.


Uniform distribution random generators

kr	rand	xamp[, iseed, iuse31]

kr	randh	kamp, kcps[, iseed, iuse31]

kr	randi	kamp, kcps[, iseed, iuse31]

ar	rand	xamp[, iseed, iuse31]

ar	randh	xamp, xcps[, iseed, iuse31]

ar	randi	xamp, xcps[, iseed, iuse31]

Generate random signals.

There are also two random function generators for use directly in Csound orchestra statements (New in Csound 3.47):

rnd(x)

birnd(x)

The functionality of these two functions is slightly different from the rand family. See notes below. See also notes on Csound random systems.

Output is a controlled random number series between +xamp and -xamp, except for rnd, which produces random numbers between 0 and x.

INITIALISATION

iseed (optional) - seed value for the recursive psuedo-random formula. A value between 0 and +1 will produce an initial output of kamp * iseed A negative value will cause seed re-initialization to be skipped. The default seed value is .5.

iuse31 (optional, New in Csound 3.492) - use an enhanced 31-bit algorithm. If this argument is non-zero, rand/i/h will use an internal algorithm with much longer cycle than the old 16-bit version. This could be useful when generating large number of values, such as for a-rate noise.

NAME CHANGES

rnd and birnd were for a short while split into irnd/krnd and ibirnd/kbirnd.

PERFORMANCE

For rand, internal psuedo-random formula produces values which are uniformly distributed over the range kamp to -kamp. rand will thus generate uniform white noise with an RMS value of kamp / root 2.

randh and randi produce band-limited noise: the xcps parameters permit the user to specify that new random numbers are to be generated at a rate less than the sampling or control frequencies. randh will hold each new number for the period of the specified cycle; randi will produce straightline interpolation between each new number and the next.

TECHNOTE: Each instance of rand/i/h uses its own pseudo-random sequence of numbers. This means that two rand calls without initialiser will generate the same sequence:

krnd1	rand	5, 23252

krnd2	rand	5, 23252

krnd1 and krnd2 will step through the same sequence of numbers.

For rnd(x), birnd(x), the argument within the parentheses may be an expression.

The function rnd returns a random number in the unipolar range 0 to x, while birnd - returns values in the range -x to +x

NOTE: The k-/i-rate performance of a bi/rnd call is decided by the rate of the input x argument -- if x is i-rate, then the expression

krnd = rnd(10)

will generate the same value for krnd throughout the performance of the instrument instance.

TECHNOTE: All rnd and birnd instances in an orchestra share the same pseudo-random sequence. This means that if an instrument contains two bi/rnd calls, like

irnd1 = rnd(2)

irnd2 = birnd(2)

-- then they will get different values. Further, they will get new values each time the instrument is used in the score, and finally, if you insert any other rnd or birnd statement in the orchestra, the sequence of pseudo-random numbers that irnd1 and irnd2 step through will change.

The sequence of numbers that all bi/rnd calls in the orchestra steps through is the same at every orch run (modulus scaling); the sequence is not initialisable. (So these functions are perhaps not so useful for generating melodies and rythms.)

EXAMPLE

i1	=	octpch(p5)	; center pitch, to be modified

k1	randh     1,10	; 10 time/sec by random displacements up to 1 octave

a1	oscil       5000, cpsoct(i1+k1), 1


NOTES ON CSOUND RANDOM GENERATORS

There are three sets of ugens for generating pseudo-random numbers in Csound. They have been changed recently (version 3.44), and they all work slightly differently internally, so we will here try to list the differences. First a quick checklist, details follow.

Table of comparison:

Family	   rand/i/h	  bi/rnd	nonuniform

Source file	Ugens4.c/h	Aops.c/h	  Cmath.c/h

Cycle length	2^15 or 2^31	    ???	    sys dep

Num discr values	2^15 or 2^31	  2^23(?)	      2^15

Share sequence	       no	    yes	       yes

Seedable	      yes	    no	 yes (undoc.)

Rand distrib.	   uniform	 uniform	     variable

THE rand FAMILY

The ugens rand , randi and randh share the same internal pseudo-random number generator (PRNG), or rather generators (See Ugens4.c for code).

15-bit and 31-bit PRNG:s

The standard method of generating random numbers is implemented by a 15-bit generator, which means that it can produce up to 2^15 = 32768 values before the sequence repeats itself. This may be a too short cycle when generating a-rate noise, so a new generator was added recently; this will generate 2^31 (over 2  10^9) numbers before the sequence cycles.

Incidentally, the two random modes will also have different precision: The 15-bit version can only output 2^15 distinct numbers, while the 31-bit one can generate 2^31 distinct numbers. Eg, if you use the 15-bit method to generate pitches in the audible range (say over 8 octaves), there will be a maximum of 32768 / (8  12) = 341 different pitches per half tone (that's plenty for single notes, but perhaps not for a really dense spectrum(?)), while the 31-bit generator can output much more fine-grained different values. But since the generated (integer) values are scaled to floating-point precision, the 31-bit random number generator will be limited by the precision of 4-byte floating point numbers, and so generate at most 2^23 (almost 8.4 million) distinct values. (is this figure right?? -- not sure).

Not sharing the random number generator

Each instance of a rand/i/h generator will generate its own sequence of numbers. Eg,

krnd1 rand 5

krnd2 rand 5

Here, krnd1 and krnd2 will always get the same value. The ugen can be seeded, each seed will start at a different point in the sequence of pseudo-random numbers.

THE rnd AND birnd ORCHESTRA FUNCTIONS

The ugens rnd and birnd use yet another internal random number generator (it is not based on integer maths, but on a double-precision floating-point algorithm -- see the file Aops.c for code).

Sharing the random number generator

All rnd and birnd instances in an orchestra share the same pseudo-random sequence. This means that if an instrument contains two bi/rnd calls, like

irnd1 = rnd(2)

irnd2 = birnd(2)

-- then they will get different values. Further, they will get new values each time the instrument is used in the score, and finally, if you insert any other rnd or birnd statement in the orchestra, the sequence of pseudo-random numbers that irnd1 and irnd2 step through will change.

The sequence of numbers that all bi/rnd calls in the orchestra steps through is the same at every orch run (modulus scaling); the sequence is not initialisable. (So these functions are perhaps not so useful for generating melodies and rythms.)

THE NON-UNIFORM DISTRIBUTION FAMILY

This family of ugens (including linrand , birand, trirand, exprand, gauss, poisson et al) all  call the ANSI C function rand() internally (See Cmath.c for code). This is to say that they share the same PRNG, which means that they follow the same rules (but not the same sequence) as bi/rnd.

Using the C library function rnd()

Now moreover, the values generated internally for these ugens will NOT be the same on all Csound systems. Rather, they will vary according to implementation of the pseudo-random algorithm that is included with the compiler used to build the Csound executable. So, depending on the compiler, the internal sequence of numbers may be 15- 16- 31- or 32-bit, and thus has wildly different cycles: So the number of values that can be generated before the sequence begins to repeat ranges from 2^15 = 32768 through 2^32 = more than 4 billion.

But the ANSI C function rand() is defined as returning a 15-bit integer, so there will in no case be more than 32768 distinct values returned from the function (even though they can be scaled in Csound to floating-point resolution). (As noted above, this latter feature will for most purposes not be a limitation?)


Non-uniform distribution random generators

(Renamed in Csound version 3.49)

xr	linrand	krange

xr	trirand	krange

xr	exprand	krange

xr	bexprnd	krange

xr	cauchy	kalpha

xr	pcauchy	kalpha

xr	poisson	klambda

xr	gauss	krange

xr	weibull	ksigma, ktau

xr	betarand	krange, kalpha, kbeta

xr	unirand	krange

Generate random numbers with various distributions. All of these opcodes operate in i-, k- and a-rate.

See also notes on the various Csound random systems.

NAME CHANGES

In Csound versions previous to 3.484, these operators had to be named differently depending on the desired output rate. , ie a for a-rate, k for k-rate and i for i-rate. You therefore had to call them eg aunirand, kpcauchy, ipoisson etc in orchestra usage. Moreover, betarand was called ibeta, kbeta, abeta.

PERFORMANCE

linrand krange - Linear distribution random number generator.  krange is the range of the random numbers [0 - krange].  Outputs only positive numbers.

trirand krange  -  Same as above only ouputs both negative and  positive numbers.

exprand krange - Exponential distribution random number generator. krange is the range of the random numbers [0 - krange].  Outputs only positive numbers.

bexprnd krange - Same as above, only extends to negative numbers too with an exponential distribution.

cauchy kalpha - Cauchy distribution random number generator.  kalpha controls the spread from zero (big kalpha => big spread).  Outputs both positive and negative numbers.

pcauchy  kalpha  -  Same as above,  ouputs positive numbers only.

poisson klambda - Poisson distribution random number generator. klambda is the mean of the distribution.  Outputs only positive numbers.

gauss krange - Gaussian distribution random number generator.  krange is the range of the random numbers [-krange - 0 - krange].  Outputs both positive and negative numbers.

weibull ksigma, ktau - Weibull distribution random number generator. ksigma scales the spread of the distribution and ktau, if greater than one numbers near ksigma are favored, if smaller than one small values are favored and if t equals 1 the distribution is exponential. Outputs only positive numbers.

betarand krange, kalpha, kbeta - Beta distribution random number generator.  krange is the range of the random numbers [0 - krange].  If kalpha is smaller than one, smaller values favor values near 0.  If kbeta is smaller than one, smaller values favor values near krange. If both kalpha and kbeta equal one we have uniform distribution.  If both kalpha and kbeta are greater than one we have a sort of gaussian distribution.  Outputs only positive numbers.

unirand krange - Uniform distribution random number generator.  krange is the range of the random numbers (0 - krange). (NOTE: This opcode was introduced in Bath/Montreal version 3.45.)

EXAMPLES

a1	trirand	32000	; Audio noise with triangle distribution

k1	cauchy	10000	; Control noise with Cauchy dist

i1	betarand	30000, .5, .5	; i-time random value, beta dist.

For more detailed explanation of these distributions, see:

1. C. Dodge - T.A. Jerse 1985. Computer music.  Schirmer books.  pp.265 - 286

2. D. Lorrain. "A panoply of stochastic cannons".  In C. Roads, ed.  1989. Music machine .

Cambridge, Massachusetts: MIT press, pp. 351  - 379.


(Buzzers and) pulse generators

ar	poscil	kamp, kcps, kfrac[, iphs]

Output is a variable width pulse train. (poscil was introduced in Csound 3.47)

(QREF) Pulse generator and buzzers:

ar	poscil	kamp, kcps, kfrac[, iphs]

INITIALISATION

ifn - table number of a stored function containing (for buzz) a sine wave, or (for gbuzz) a cosine wave. In either case a large table of at least 8192 points is recommended.

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

PERFORMANCE

kfrac - fractional width of the pulse part of a cycle. poscil is a k-rate varying pulse-width audio oscillator, with on/off levels set to provide a zero-average DC offset. Although pulse-width oscillation is an unnatural signal (it does not occur in natural instruments), it is a popular source in synthesizers.


Innehåll: adsr xadsr madsr mxadsr, sndwarp-st wgpluck wgpluck2 repluck, wgbow wgbrass wgflute, gogobel marimba vibes, shaker, wguide1-2, fmtbell fmrhode fmwurlie fmmetal fmb3fmpercfl, fmvoice, moog, mandol, voice, lfo, vco, planet


Classic ADSR envelopes
Classic ADSR envelope generators

(New in Csound 3.49)

nr	adsr	iatt, idec, islev, irel[, idelay]

nr	xadsr	iatt, idec, islev, irel[, idelay]

nr	madsr	iatt, idec, islev, irel[, idelay]

nr	mxadsr	iatt, idec, islev, irel[, idelay]

DESCRIPTION

Calculates the classical ADSR envelope

INITALIZATION

iatt - duration of attack phase

idec - duration of decay

islev - level for sustain phase

irel - duration of release phase

idel - period of zero before the envelope starts

PERFORMANCE

The envelope is in the range 0 to 1 and may need to be scaled further.

The envelope may be described as

1

              -'-_

            _'    '-_

           .         '-_

          -             '-.

        _'                 '-.

       .                      '---------------------._

      -                                ^              '-._

    _'                                 |islev             '-._

   .                                   |                      '-._

 _-____________|______________|________v____________|_____________'-|______

 |             |              |                     |               |

 <---iatt----><---idec------>                      <---irel-------->

The length of the sustain is calculated from then length of the note.

This means adsr is not suitable for use with MIDI events.  The opcode madsr uses the linsegr mechanism and so can be used in MIDI applications.

xadsr and mxadsr are like adsr and madsr, respectively, but uses exponential envelopes.


sndwarp
Time stretching opcode

By Richard Karpen, 1992. Most recent revision, 1997 (New in Csound 3.44)

asig [,acmp] sndwarp  xamp, xtimewarp, xresample, ifn1, ibeg, iwsize, irandw, ioverlap, ifn2, itimemode

asig1, asig2 [, acmp1, acmp2] \

sndwarpst	xamp, xtimewarp, xresample, ifn1, ibeg, iwsize, irandw, ioverlap, ifn2, itimemode

DESCRIPTION

sndwarp reads sound samples from a table and applies time-stretching and/or pitch modification. Time and frequency modification are indepentant from one another. For example, a sound can be stretched in time while raising the pitch! The window size and overlap arguments are important to the result and should be experimented with. In general they should be as small as possible.

For example, start with iwsize=sr/10 and ioverlap=15. Try irandw=iwsize*.2. If you can get away with less overlaps, the program will be faster. But too few may cause an audible flutter in the amplitude. The algorithm reacts differently depending upon the input sound and there are no fixed rules for the best use in all circumstances. But with proper tuning, excellent results can be achieved.

OUTPUTS

asig - the single channel of output from the sndwarp unit generator while asig1 and asig2 are the stereo (left and right) outputs from sndwarpst.

sndwarp assumes that the function table holding the sampled signal is a mono one while sndwarpst assumes that it is stereo. This simply means that sndwarp will index the table by single-sample frame increments and sndwarpst will index the table by a two-sample frame increment. The user must be aware then that if a mono signal is used with sndwarst or a stereo one with sndwarp, time and pitch will be altered accordingly.

acmp in sndwarp and acmp1, acmp2 in sndwarpst, are single layer (no overlaps), unwindowed versions of the time and/or pitch altered signal. They are supplied in order to be able to balance the amplitude of the signal output, which typically contains many overlapping and windowed versions of the signal, with a clean version of the time-scaled and pitch-shifted signal. The sndwarp process can cause noticeable changes in amplitude, (up and down), due to a time differential between the overlaps when time-shifting is being done. When used with a balance unit, acmp, acmp1, acmp2 can greatly enhance the quality of sound. They are optional, but note that in sndwarpst they must both be present in the syntax (use both or neither). An example of how to use this is given below.

ARGUMENTS

ifn1 is the number of the table holding the sound samples which will be subjected to the sndwarp processing. GEN01 is the appropriate function generator to use to store the sound samples from a pre-existing soundfile.

xamp is the value by which to scale the amplitude (see note on the use of this when using acmp, acmp1, amcp2).

xtimewarp determines how the input signal will be stretched or shrunk in time. There are two ways to use this argument depending upon the value given for itimemode. When the value of itimemode is 0, xitimewarp will scale the time of the sound. For example, a value of 2 will stretch the sound by 2 times. When itimemode is any non-zero value then xtimewarp is used as a time pointer in a similar way in which the time pointer works in lpread and pvoc. An example below illustrates this. In both cases, the pitch will NOT be altered by this process. Pitch shifting is done independently using xresample.

xresample is the factor by which to change the pitch of the sound. For example, a value of 2 will produce a sound one octave higher than the original. The timing of the sound, however, will NOT be altered.

ibeg - the time in seconds to begin reading in the table (or soundfile). When itimemode is non- zero, the value of itimewarp is offset by ibeg.

iwsize - the window size in samples used in the time scaling algorithm.

irandw is the bandwidth of a random number generator. The random numbers will be added to iwsize.

ioverlap determines the density of overlapping windows.

ifn2 is a function used to shape the window. It is usually used to create a ramp of some kind from zero at the beginning and back down to zero at the end of each window. Try using a half a sine (ie: f1 0 16384 9 .5 1 0) which works quite well. Other shapes can also be used.

EXAMPLES

The below example shows a slowing down or stretching of the sound stored in the stored table (ifn1). Over the duration of the note, the stretching will grow from no change from the original to a sound which is ten times "slower" than the original. At the same time the overall pitch will move upward over the duration by an octave.

iwindfun=1

isampfun=2

ibeg=0

iwindsize=2000

iwindrand=400

ioverlap=10

awarp	line   1,  p3,  1

aresamp	line   1,  p3,  2

kenv	line   1,  p3, .1

asig	sndwarp	kenv, awarp, aresamp, isampfun, ibeg, iwindsize, \

iwindrand, ioverlap, iwindfun, 0

Now, here's an example using xtimewarp as a time pointer and using stereo.

itimemode=1

atime	line 0, p3, 10

asig1, asig2	sndwarpst  kenv, atime, aresamp, sampfun, ibeg, iwindsize, \

  iwindrand, ioverlap, iwindfun, itimemode

In the above, atime advances the time pointer used in the sndwarp from 0 to 10 over the duration of the note. If p3 is 20 then the sound will be two times slower than the original. Of course you can use a more complex function than just a single straight line to control the time factor.

Now the same as above but using the balance function with the optional outputs:

asig,acmp sndwarp	1,awarp,aresamp,isampfun,ibeg,iwindsize, \

iwindrand, ioverlap, iwindfun, itimemode

abal	balance asig, acmp

asig1,asig2,acmp1,acmp2 \

sndwarpst	1, atime, aresamp, sampfun, ibeg, iwindsize, \

iwindrand, ioverlap, iwindfun, itimemode

abal1 	balance	asig1, acmp1

abal2 	balance	asig2, acmp2

In the above two examples notice the use of the balance unit. The output of balance can then be scaled, enveloped, sent to an out or outs, and so on. Notice that the amplitude arguments to sndwarp and sndwarpst are "1" in these examples. By scaling the signal after the sndwarp process, abal, abal1, and abal2 should contain signals that have nearly the same amplitude as the original input signal to the sndwarp process. This makes it much easier to predict the levels and avoid samples out of range or sample values that are too small.

More advice: Only use the stereo version when you really need to be processing a stereo file. It is someone slower than the mono version and if you use the balance function it is slower again. There is nothing wrong with using a mono sndwarp in a stereo orchestra and sending the result to one or both channels of the stereo output!


Waveguide string physical models

By John Fitch and MKC (New in Csound 3.47)

ar	wgpluck	i, i, k, i, i, i, a

ar	wgpluck2	iplk, xamp, icps, kpick, krefl

ar	repluck	iplk, xamp, icps, kpick, krefl, axcite

See also the Karplus-Strong string model.

DESCRIPTION

wgpluck2 is an implementation of the physical model of the plucked string, with control over the pluck point, the pickup point and the bridge reflection filter.

repluck is the same operation, but with an additional audio signal used to excite the 'string'

ARGUMENTS

iplk - point of pluck expressed as a a fraction of the string length (0 to 1). A pluck point of zero means no initial pluck.

xamp - gain.

icps - pitch value in cps.

kpick - what proportion of the way along the string to sample the output.

krefl - reflection coefficient, controlling the reflection at the bridge. 1 means total reflection and 0 is totally dead.


Waveguide physical models

(New in Csound 3.47)

ar	wgbow	kamp, kfreq, kpres, kratio, kvibf, kvamp, ifn[, iminfreq]

ar	wgbrass	kamp, kfreq, kliptens, idetk, kvibf, kvamp, ifn[, iminfreq]

ar	wgclar	kamp, kfreq, kstiff, iatt, idetk, kngain, kvibf, kvamp, ifn[, iminfreq]

ar	wgflute	kamp, kfreq, kjet, iatt, idetk, kngain, kvibf, kvamp, ifn[, iminfreq]

Audio output is a tone similar to a bowed string, a brass instrument, a clarinet, or a flute, using physical models developed by Perry Cook, but re-coded for Csound.

INITIALISATION

iatt - time in seconds to reach full blowing pressure for wind instruments.  0.1 seems to correspond to reasonable playing (wgflute, wgclar). A longer time gives a definite initial wind sound.

idetk - time in seconds taken to stop blowing.  0.1 is a smooth ending

ifn - table of shape of vibrato, usually a sine table, created by a function generator.

iminfreq - lowest frequency at which the instrument will play.  If it is omitted it is taken to be the same as the initial kfreq. If negative, skip initialisation (NB: The last feature was introduced in Csound version 3.484).

PERFORMANCE

A note is played on a waveguide physical model of a conventional instrument, with the arguments as below.

kamp - Amplitude of note.

kfreq - Frequency of note played. Note: It seems this variable must be initialised for k-rate values to work. That is, you need to include a line like kfreq init 220 in your orchestra.

kpres - a parameter controlling the pressure of the wgbow bow on the string.  Values should be about 3.  The useful range is approximately 1 to 5.

kratio - the position of the wgbow bow along the string.  Usual playing is about 0.127236.  The suggested range is 0.025 to 0.23.

kliptens - lip tension of wgbrass model. Suggested range for the lip tension is about 0.4.

kstiff - a stiffness parameter for the wgclar reed.  Values should be negative, and about -0.3.  The useful range is approximately -0.44 to -0.18.

kjet - a parameter controlling the wgflute air jet.  Values should be positive, and about 0.3.  The useful range is approximately 0.08 to 0.56.

kngain - amplitude of the wgclar and wgflute noise components, about 0 to 0.5

kvibf - frequency of vibrato in Hertz. Suggested range is 0 to 12; about 6.1 for wgbrass.

kvamp - amplitude of the vibrato. Suggested range about 0.05 for wgbrass.

[NOTE:  wgbrass is rather poor, and at present uncontrolled. Needs revision, and possibly more parameters]

EXAMPLES

ar	wgbrass	31129.60, 440, 0.1, 6.137, 0.05, 1

ar	wgclar	31129.60, 440, -0.3, 0.1, 0.1, 0.2, 5.735, 0.1, 1

ar	wgflute	31129.60, 440, 0.32, 0.1, 0.1, 0.15, 5.925, 0.05, 1

A bowing with vibrato setting in after a short time.

kv	linseg	0, 0.5, 0, 1, 1, p3-0.5, 1

ar	wgbow	31129.60, 440, 3.0, 0.127236, 6.12723, kv*0.01, 1

out	ar

AUTHORS

By Perry Cook.

Recoded for Csound by John Fitch


Percussion physical models

(New in Csound 3.47)

ar	gogobel	kamp, kfreq, ihrd, ipos, imp, kvibf, kvamp, ivibfn

ar	marimba	kamp, kfreq, ihrd, ipos, imp, kvibf, kvamp, ivibfn, idec

ar	vibes	kamp, kfreq, ihrd, ipos, imp, kvibf, kvamp, ivibfn, idec

Audio output is a tone related to the striking of a wooden or metal block as found in a marimba or vibraphone; or a tone related to a cow bell or similar.  The method is a physical model developed from Perry Cook, but re-coded for Csound.

NAME CHANGES

Until Csound 3.52, gogobel was called agogobel.

INITIALISATION

ihrd -- the hardness of the stick used in the strike.  A range of 0 to 1 is used.  0.5 is a suitable value.

ipos -- where the block is hit, in the range 0 to 1.

imp - a table of the strike impulses.  The file "marmstk1.wav" is a suitable function for marimba and vibes, while "britestk.wav" is suitable for gogobel from measurements. The file can be loaded with a GEN01 table.

ivfn - shape of vibrato, usually a sine table, created by a function

idec - time before end of note when damping is introduced

PERFORMANCE

A note is played on a percussive instrument, with the arguments as below.

kamp - Amplitude of note.

kfreq - Frequency of note played.

kvibf - frequency of vibrato in Hertz. Suggested range is 0 to 12

kvamp - amplitude of the vibrato

EXAMPLES

ar	gogobel	31129.60, 440, p4, 0.561, 3, 6.0, 0.3, 1

ar	marimba	31129.60, 440, 0.5, 0.561, 2, 6.0, 0.05, 1, 0.1

ar	vibes	31129.60, 440, 0.5, 0.561, 2, 4.0, 0.2, 1, 0.1

AUTHORS

By Perry Cook.

Recoded for Csound by John Fitch


Shaker physical model

(New in Csound 3.47)

ar	shaker	kamp, kfreq, kbeans, kdamp, ktimes[, idecay]

Audio output is a tone related to the shaking of a maraca or similar gourd instrument.  The method is a physically inspired model developed from Perry Cook, but re-coded for Csound.

NOTE: Initially there was an extra argument, called knum in the docs, written before ktimes, but this was removed in version 3.49 as these have the same function.

NOTE 2: This change was not made properly, so Csound crashes if you try to use it. To complete the change, the struct member numshake must be removed from the Shaker struct in file Shaker.h in the distributed sources, then you'll have to recompile Csound for yourself. (-re; Csound 3.51-2)

INITIALISATION

idecay - If present indicates for how long at the end of the note the shaker is to be damped.  The default value is zero.

PERFORMANCE

A note is played on a shaker-like instrument, with the arguments as below.

kamp - Amplitude of note.

kfreq - Frequency of note played, that is the frequency of the gourd.

kbeans - The number of beans in the gourd.  A value of 8 seems suitable.

kdamp -- The damping value of the shaker.  Values of 0.98 to 1 seems suitable, with 0.99 a reasonable default.

ktimes -- Number of shakes of the gourd.  Values over 64 are considered infinite.

[RICK: Not sure all these are useful -- not clear in code]

EXAMPLE

ar	shaker	p4, 440, 8, 0.999, 100, 0

AUTHORS

By Perry Cook.

Recoded for Csound by John Fitch


Simple waveguide opcodes

By Gabriel Maldonado. (New in Csound 3.49)

ar	wguide1	asig, kfreq, kcutoff, kfeedback;

ar	wguide2	asig, kfreq1, kfreq2, kcutoff1, kcutoff2, kfeedback1, kfeedback2

NAME CHANGES

These opcodes were called physic1 and physic2 respectively in Maldonados CsoundRT 1.9 distribution.

PERFORMANCE

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

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

asig is the input of excitation noise, kfreq 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 from sr, allowing better performance - particulary when outputting real-time audio. See also the block diagram in the picture 'physic.bmp' (included with the Maldonado distribution).


4-operator FM instruments

(New in Csound 3.47)

ar	fmtbell	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmrhode	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmwurlie	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmmetal	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmb3	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

ar	fmpercfl	kamp, kfreq, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn

A family of FM sounds, all using 4 basic oscillators and various architectures, as used in the TX81Z synthesiser. See also FM voice synthesis.

INITIALISATION

All these opcodes take 5 tables for initialisation.  The first 4 are the basic inputs and the last is the low frequency oscillator (LFO) used for vibrato.  The last table should usually be a sine wave.

For the other opcodes the initial waves should be as in the table

ifn1	ifn2	ifn3	ifn4____

fmtbell 	sinewave	sinewave	sinewave	sinewave

fmrhode	sinewave	sinewave	sinewave	fwavblnk

fmwurlie	sinewave	sinewave	sinewave	fwavblnk

fmmetal	sinewave	twopeaks	twopeaks	sinewave

fmb3	sinewave	sinewave	sinewave	sinewave

fmpercfl	sinewave	sinewave	sinewave	sinewave

The sounds produced are then

fmtbell 	TubularBell

fmrhode	FenderRhodesElectricPiano

fmwurlie	WurlitzerElectricPiano

fmmetal	"HeavyMetal"

fmb3	HammondB3organ

fmpercfl	PercussiveFlute

PERFORMANCE

kamp -- Amplitude

kfreq -- frequency

kc1, kc2 -- Controls for the syntheser, as in the table

kc1	kc2	Algorithm___________________

fmtbell	Modindex1	Crossfase of two outputs	     5

fmrhode	Modindex1	Crossfase of two outputs	     5

fmwurlie	Modindex1	Crossfase of two outputs	     5

fmmetal	Totalmodindex	Crossfade of two modulators	     3

fmb3	Totalmodindex	Crossfade of two modulators	     4

fmpercfl	Totalmodindex	Crossfade of two modulators	     4

Here are some of the algorithms in the TX81Z:

3. 	    4--\

3-->2-- + -->1-->Out

4.   4->3--\

2-- + -->1-->Out

5. Two simple FM pairs summed together:

4->3--\

      + --> Out

2->1--/

6. Three carriers with a common modulator:

   /->1 -\

4-|-->2 - +-> Out

   \->3 -/

8. Simple additive synthesis:

1 --.

2 -\|

+-> Out

3 -/|

4 --.

kvdepth -- Vibrato depth

kvrate -- Vibrato rate

EXAMPLES

ar	fmtbell	31129.60, 440, 1,   1.2, 0.2, 6,   1,1,1,1, 1

ar	fmrhode	31129.60, 440, 1,   1.2, 0.2, 12,  1,1,1,4, 1

ar	fmwurlie	31129.60, 440, 1,   1.2, 0.2, 8,   1,1,1,4, 1

ar	fmmetal	31129.60, 110, 1,   1.2, 0.2, 5.5, 1,5,5,1, 1

ar	fmb3	31129.60, 440, 1,   1.2, 0.2, 8,   1,1,1,1, 1

ar	fmpercfl	31129.60, 440, 0.1, 0.1, 0.5, 12,  1,1,1,1, 1

AUTHORS

By Perry Cook.

Recoded for Csound by John Fitch


FM voice synthesis

By Perry Cook (New in Csound 3.47)

ar	fmvoice	kamp, kfreq, kvowel, ktilt, kvibamt, kvibrate, ifn1, ifn2, ifn3, ifn4, ivibfn

FM Singing Voice Synthesis. This instrument is based on FM Algorithm number 6 of the TX81Z commercial FM synthesizer :

6. Three carriers with a common modulator:

   /->1 -\

4-|-->2 - +-> Out

   \->3 -/

See 4-operator FM instruments for more similar instruments.

INITIALISATION

ifn1, ifn2, ifn3,ifn4 -- Tables, usually of sinewaves.

PERFORMANCE

kamp -- Amplitude control.

kfreq -- Base frequency of sound.

kvowel -- the vowel being sung, in the range 0-64; it is rounded to the nearest integer. Here are some of the intended resultant sounds (- re):

Numbers	    Vocal sounds

  0-4	eee	ihh	ehh	aaa

  5-8	ahh	aww	ohh	uhh

  9-12	uuu	ooo	rrr	lll

13-16	mmm	nnn	nng	ngg

17-20	fff	sss	thh	shh

21-24	xxx	hee	hoo	hah

25-28	bbb	ddd	jjj	ggg

29-32	vvv	zzz	thz	zhh

[Note: The sounds are actually undocumented, this was snipped from the code. Entries xxx-zhh are marked as Not really done yet in the code. - re]

ktilt -- the spectral tilt of the sound in the range 0 to 99

kvibamt -- Depth of vibrato

kvibrate -- Rate of vibrato

EXAMPLE

kr	line	0, p3, 64

ar	fmvoice	31129.60, 110, k1, 0, 0.005, 6, 1,1,1,1,1


Moog emulation

By Perry Cook (New in Csound 3.47)

ar	moog	kamp, kfreq, kfiltq, kfiltrate, kvibf, kvamp, iafn, iwfn, ivfn

An emulation of a mini-Moog syntheser.

INITIALISATION

iafn, iwfn, ivfn -- three table numbers containing the attack wave form (unlooped), the main looping wave form, and the vibrato waveform. The files mandpluk.aiff and impuls20.aiff are suitable for the first two, and a sine wave for the last.

PERFORMANCE

kamp - Amplitude of note.

kfreq - Frequency of note played. It can be varied in performance.

kfiltq - Q of the filter, in the range 0.8 to 0.9

kfiltrate - rate control for the filter in the range 0 to 0.0002

kvibf - frequency of vibrato in Hertz. Suggested range is 0 to 12

kvamp - amplitude of the vibrato

AUTHORS

By Perry Cook.

Recoded for Csound by John Fitch


Mandoline emulation

By Perry Cook (New in Csound 3.47)

ar	mandol	kamp, kfreq, kpluck, kdetune, kgain, ksize, ifn[, iminfreq]

An emulation of a mandolin.

INITIALISATION

ifn -- table number containing the pluck wave form.  The file mandpluk.aiff is suitable for this.

iminfreq -- Lowest frequency to be played on the note.  If it is omitted it is taken to be the same as the initial kfreq.

PERFORMANCE

kamp - Amplitude of note.

kfreq - Frequency of note played. It can be varied in performance.

kpluck - The pluck position, in range 0 to 1.  Suggested value is 0.4

kgain - the loop gain of the model, in the range 0.97 to 1

kdetune - The proportional detuning between the two strings. Suggested range 1 and 0.9

ksize - The size of the body of the mandolin.  Range 0 to 2


Voice emulation

By Perry Cook (New in Csound 3.47)

ar	voice	kamp, kfreq, kphoneme, kform, kvibf, kvamp, ifn, ivfn

An emulation of a human voice.

INITIALISATION

ifn, ivfn -- two table numbers containing the carrier wave form and the vibrato waveform. The files impuls20.aiff, ahh.aiff, eee.aiff or ooo.aiff are suitable for the first of these, and a sine wave for the second.

PERFORMANCE

kamp - Amplitude of note.

kfreq - Frequency of note played. It can be varied in performance.

kphoneme - an integer in the range 0 to 16, which select the formants for the sounds

"eee","ihh","ehh","aaa",

"ahh","aww","ohh","uhh",

"uuu","ooo","rrr","lll",

"mmm","nnn","nng","ngg".

At present the phonemes

"fff","sss","thh","shh",

"xxx","hee","hoo","hah",

"bbb","ddd","jjj","ggg",

"vvv","zzz","thz","zhh"

are not available

kform - Gain on the phoneme.  values 0.0 to 1.2 recommended.

kvibf - frequency of vibrato in Hertz. Suggested range is 0 to 12

kvamp - amplitude of the vibrato


Low frequency oscillator

(New in Csound 3.49)

kr	lfo	kamp, kcps[, itype]

ar	lfo	kamp, kcps[, itype]

DESCRIPTION

A LFO of various shapes. See also oscil.

INITALISATION

itype -- determine the form of the oscillator:

  	0  sine (default)

  	1  triangles

2  square (bipolar)

3  square (unipolar)

4  saw-tooth

5  saw-tooth(down)

The sine wave is implemented as a 4096 table and read with linear interpolation.  The others are calculated.

PERFORMANCE

ar, kr - output signal

kamp - amplitude

kcps - frequency of oscilator

EXAMPLE

instr 1

      kp    lfo	10, 5, 4

      ar    oscil	p4, p5+kp, 1

      out	ar

endin


Voltage Controlled Oscillator

By Hans Mikelson (New in Csound 3.50)

ar	vco	kamp, kfqc, iwave, kpw, isine, imaxd

Implementation of a band limited analog modeled oscillator based on integration of band limited impulses.

INITIALISATION

iwave - the waveform. 1 = sawtooth, 2 = Square/PWM, 3 = triangle/Saw ramp

PERFORMANCE

vco can be used to simulate a variety of analog wave forms.

kamp - amplitude.

kfqc - the frequency of the wave.

kpw determines the pulse width when iwave is set to 2, and determines Saw/ramp character when iwave is set to 3. The value of kpw should be between 0 and 1. A value of .5 will generate a square wave or a triangle wave depending on iwave.

isine should be the number of a stored sine wave table.

imaxd is the maximum delay time. A time of 1/ifqc may be required for the PWM and triangle waveforms. To bend the pitch down this value must be as large as 1/(minimum frequency).

EXAMPLE

instr 10

    idur = p3	; Duration

    iamp = p4	; Amplitude

    ifqc = cpspch(p5)  	; Frequency

    iwave = p6	; Selected wave form 1=Saw, 2=Square/PWM, 3=Tri/Saw-Ramp-Mod

    isine = 1

    imaxd = 1/ifqc*2	; Allows pitch bend down of two octaves

    kpw1 oscil .25, ifqc/200, 1

    kpw = kpw1 + .5

    asig vco iamp, ifqc, iwave, kpw, 1, imaxd

           outs asig, asig 	; Ouput and amplification

endin

; Score

f1 0 65536 10 1      ; Sine wave

;      Sta Dur  Amp     Pitch   Wave

i10    0    2   20000    5.00      1

i10    +    .      .            .           2

i10    .     .       .           .           3

i10    .     2   20000    7.00      1

i10    .     .       .           .           2

i10    .     .       .           .           3

i10    .     2   20000    9.00      1

i10    .     .       .           .           2

i10    .     .       .           .           3

i10    .     2   20000  11.00      1

i10    .     .       .           .           2

i10    .     .       .           .           3


Binary star system simulation

By Hans Mikelson (New in Csound 3.50)

ax,ay,az	planet	kmass1, kmass2, ksep, ix, iy, iz, ivx, ivy, ivz, idelta, ifriction

Signal generator which loosely simulates a planet orbiting in a binary star system.

INITIALISATION

ix, iy, iz - the initial x, y and z coordinates of the planet.

ivx, ivy, ivz - the initial velocity vector components for the planet.

idelta - the step size used to approximate the differential equation.

ifriction - a value for friction which can used to keep the system from blowing up.

PERFORMANCE

kmass1 - the mass of the first star.

kmass2 - the mass of the second star.

ksep - determines the distance between the two stars.

planet simulates a planet orbiting in a binary star system. The outputs are the x, y and z coordinates of the orbiting planet. It is possible for the planet to achieve escape velocity by a close encounter with a star. This makes this system somewhat unstable.

EXAMPLE

      instr 1

idur      =     p3

iamp    =     p4

km1     =     p5

km2     =     p6

ksep    =     p7

ix         =     p8

iy         =     p9

iz         =     p10

ivx       =     p11

ivy       =     p12

ivz       =     p13

ih         =     p14

ifric      =     p15

kamp   linseg     0, .002, iamp, idur-.004, iamp, .002, 0

ax, ay, az planet km1, km2, ksep, ix, iy, iz, ivx, ivy, ivz, ih, ifric

           outs   ax*kamp, ay*kamp

      endin

; Score

;   Sta  Dur  Amp   M1  M2  Sep   X    Y   Z  VX  VY  VZ  h   Frict

i1   0     1    5000   .5    .35  2.2    0   .1   0   .5   .6   -.1   .5  -0.1

i1   +     .       .        .5    0      0      0   .1   0   .5   .6   -.1   .5   0.1

i1   .      .       .        .4    .3     2      0   .1   0   .5   .6   -.1   .5   0.0

i1   .      .       .        .3    .3     2      0   .1   0   .5   .6   -.1   .5   0.1

i1   .      .       .        .25  .3     2      0   .1   0   .5   .6   -.1   .5   1.0

i1   .      .       .        .2    .5     2      0   .1   0   .5   .6   -.1   .1   1.0


ïïInnehåll:

ENVELOPES linen linenr envlpx follow

GAIN MODS/LIMITERS rms gain balance, dam, ilimit limit wrap mirror, ntrpol, dcblock

FILTERS port tone atone reson areson, tonex atonex resonex, butterhp butterlp butterbp butterbr, filter2 zfilter2, lowres lowresx vlowres, biquad moogvcf rezzy, nlfilt+tips, pareq

SAMPLE INTEGRATORS downsamp upsamp interp integ diff samphold

DELAYS delayr delayw delay delay deltap deltapi deltapi deltap3 vdelay vdelay3 multitap

REVERBS comb alpass reverb reverb2 nreverb, streson

MISC RECENT OPS harmon, flanger, distort1


Envelope generators

kr	linen	kamp, irise, idur, idec

ar	linen	xamp, irise, idur, idec

kr	linenr	kamp, irise, idec, iatdec

ar	linenr	xamp, irise, idec, iatdec

kr	envlpx	kamp, irise, idur, idec, ifn, iatss, iatdec[,ixmod]

ar	envlpx	xamp, irise, idur, idec, ifn, iatss, iatdec[,ixmod]

linen - apply a straight line rise and decay pattern to an input amp signal.  linenr - apply a straight line rise, then an exponential decay while the note is extended in time (only works with notes triggered by MIDI input). envlpx - apply an envelope consisting of 3 segments:

1) stored function rise shape,

2) modified exponential "pseudo steady state",

3) exponential decay

((envlpxr should probably go here to, but its documentation has not been provided - re))

INITIALISATION

irise - rise time in seconds. A zero or negative value signifies no rise modification.

idur - overall duration in seconds. A zero or negative value will cause initialization to be skipped.

idec - decay time in seconds. Zero means no decay. An idec > idur will cause a truncated decay.

ifn - function table number of stored rise shape with extended guard point.

iatss - attenuation factor, by which the last value of the envlpx rise is modified during the note's pseudo "steady state." A factor > l causes an exponential growth, and < l an exponential decay. A 1 will maintain a true steady state at the last rise value. Note that this attenuation is not by fixed rate (as in a piano), but is sensitive to a note's duration. However, if iatss is negative (or if "steady state" < 4 k-periods) a fixed attenuation rate of abs(iatss) per second will be used. 0 is illegal.

iatdec - attenuation factor by which the closing "steady state" value is reduced exponentially over the decay period. This value must be positive and is normally of the order of .01. A large or excessively small value is apt to produce a cutoff which is audible. A zero or neg value is illegal.

ixkmod (optional, between +- .9 or so) - exponential curve modifier, influencing the "steepness" of the exponential trajectory during the "steady state." Values less than zero will cause an accelerated growth or decay towards the target (e.g. subito piano). Values greater than zero will cause a retarded growth or decay. The default value is zero (unmodified exponential).

PERFORMANCE

Rise modifications are applied for the first irise seconds, and decay from time idur - idec. If these periods are separated in time there will be a "steady state" during which amp will be unmodified (linen) or modified by the first exponential pattern (envlpx). If linen rise and decay periods overlap then both modifications will be in effect for that time; in envlpx that will cause a truncated decay. If the overall duration idur is exceeded in performance, the final decay will continue on in the same direction, going negative for linen but tending asymptotically to zero in envlpx.

linenr is unique within Csound in containing a note-off sensor and release time extender. When it senses either a score event termination or a MIDI noteoff, it will immediately extend the performance time of the current instrument by idec seconds, then execute an exponential decay towards the factor iatdec. For two or more units in an instrument, extension is by the greatest idec.

Note that linenr only works with events started by MIDI input.


 Envelope follower

ar	follow	asig, idt

Envelope follower unit generator.

INITIALISATION

idt - This is the period, in seconds, that the average amplitude of asig is reported.  If the frequency of asig is low then idt must be large (more than half the period of asig ).

PERFORMANCE

asig  - This is the signal from which to extract the envelope.

EXAMPLE

k1	line	0, p3, 30000	; Make k1 a simple envelope

a1	oscil	k1, 1000, 1	; Make a simple signal using k1

ak1	follow	a1, .02	; ak1 is now like k1

a2	oscil	ak1, 1000, 1	; Make a simple signal using ak1

out	a2	; Both a1 and a2 are the same

To avoid zipper noise, by discontinuities produced from complex envelope tracking, a lowpass filter could be used, to smooth the estimated envelope.


Gain units

kr	rms	asig[, ihp, istor]

ar	gain	asig, krms[, ihp, istor]

ar	balance	asig, acomp[, ihp, istor]

The rms (root mean square) power of asig can be interrogated, set, or adjusted to match that of a comparator signal.

INlTlALISATlON

ihp (optional) - half-power point (in cps) of a special internal low-pass filter. The default value is 10.

istor (optional) - initial disposition of internal data space (see reson). The default value is 0.

PERFORMANCE

rms output values kr will trace the rms value of the audio input asig. This unit is not a signal modifier, but functions rather as a signal power-gauge.

gain provides an amplitude modification of asig so that the output ar has rms power equal to krms. rms and gain used together (and given matching ihp values) will provide the same effect as balance.

balance outputs a version of asig, amplitude-modified so that its rms power is equal to that of a comparator signal acomp. Thus a signal that has suffered loss of power (eg., in passing through a filter bank) can be restored by matching it with, for instance, its own source. It should be noted that gain and balance provide amplitude modification only - output signals are not altered in any other respect.

EXAMPLE

asrc	buzz	10000,440, sr/440, 1	; band-limited pulse train

a1	reson 	asrc, 1000,100	; sent through

a2	reson	a1,3000,500 	; 2 filters

afin	balance	a2, asrc	; then balanced with source


Dynamic amplitude modifier

By Marc Resibosis (New in Csound 3.47)

ar	dam	ain, kthresh, icomp1, icomp2, irtme, iftme

DESCRIPTION

This opcode dynamically modifies a gain value applied to the input sound ain by comparing its power level to a given threshold level. The signal will be compressed/expanded with different factors depending on whether it is over or under the threshold.

INITIALIZATION

icomp1	- Compression ratio for upper zone.

icomp2	- Compression ratio for lower zone.

irtime	- Gain raise time. Time over which the gain factor is allowed to raise by one unit.

iftime	- Gain fall time. Time over which the gain factor is allowed to decrease by one unit.

PERFORMANCE

aout	- Output sound stream

ain	- Input sound stream

kthreshold	- Sound level acting as a threshold. Can be changed at k-rate (e.g. for ducking).

Note on the compression factors:

A compression ratio of 1 (one) leaves the sound unchanged. Setting the ratio to a value smaller than one will compress the signal (reduce its volume) while setting the ratio to a value greater than one will expand the signal (increase its volume).

AUTHOR:

Marc Resibois

Belgium

1997


Limiter signal modifier
Limiter signal modifiers

By Robin Whittle and Gabriel Maldonado. (New in Csound 3.46 and 3.49)

ir	limit	isig, ilow, ihigh

kr	limit	ksig, klow, khigh

ar	limit	asig, klow, khigh

xr	wrap	xsig, xlow, xhigh

xr	mirror	xsig, xlow, xhigh

NAME CHANGES

Until Csound 3.52, the i-rate version of limit was called ilimit.

The names iwrap and imirror were used for i-rate versions of wrap and mirror in Maldonados CsoundRT 1.9 but do not exist in Bath Csound.

PERFORMANCE

xdest - output signal

xsig - input ignal

xlow - low threshold

xhigh - high threshold

limit and ilimit (by Robin Whittle, in Csound 3.46) set lower and upper limits on the xsig value they process. If xhigh is lower than xlow, then the output will be the average of  the two - it will not be affected by xsig.

mirror (by Gabriel Maldonado, in Csound 3.49) “reflects the signal if it exceeds the low or high thresholds.

wrap (by Gabriel Maldonado, in Csound 3.49) wraps around the signal if it exceeds the low or high thresholds.

These opcodes are useful in several situations, such as for table indexing and for clipping and modeling i-, k- or a-rate signals. wrap is also useful for wrapping-around tables data when maximum index is not a power of 2 (see table and tablei).


Interpolate values of two signals

(New in Csound 3.49)

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 ntrpol 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.


Direct current (dc) blocking

Due to P. Cook, coded by John ffitch (New in Csound 3.481)

ar	dcblock	asig [, igain]

Performs dc blocking.

PERFORMANCE

The formula used is

Y[n] = X[n] - X[n-1] + (igain * Y[n-1])

igain - gives control over the internal parameter g in the formula (default value 0.99). The preferred form is not to change ig.


Filters (port, tone, reson)
Filters

kr	port	ksig, ihtim[, isig]

ar	tone	asig, khp[, istor]

ar	atone	asig, khp[, istor]

ar	reson	asig, kcf, kbw[, iscl, istor]

ar	areson	asig, kcf, kbw[, iscl, istor]

A control or audio signal is modified by a low- or band-pass recursive filter with variable frequency response. See also the new filter bank opcodes (which were added in Csound 3.49)

INITIALISATION

isig - initial (i.e. previous) value for internal feedback. 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.

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.

PERFORMANCE

port applies portamento to a step-valued control signal. At each new step value, ksig is low-pass filtered to move towards that value at a rate determined by ihtim. ihtim is the "half-time" of the function (in seconds), during which the curve will traverse half the distance towards the new value, then half as much again, etc., theoretically never reaching its asymptote.

tone implements a first-order recursive low-pass filter in which the variable khp (in cps) determines the response curve's half -power point. Half power is defined as peak power / root 2.

reson is a second-order filter in which kcf controls the center frequency, or cps position of the peak response, and kbw controls its bandwidth (the cps difference between the upper and lower half -power points).

atone, areson are filters whose transfer functions are the complements of tone and reson. atone is thus a form of high-pass filter and areson a notch filter whose transfer functions represent the "filtered out" aspects of their complements. Note, however, that power scaling is not normalized in atone, areson, but remains the true complement of the corresponding unit. Thus an audio signal, filtered by parallel matching reson and areson units, would under addition simply reconstruct the original spectrum. This property is particularly useful for controlled mixing of different sources (e.g., see lpreson).

Complex response curves such as those with multiple peaks can be obtained by using a bank of suitable filters in series. (The resultant response is the product of the component responses.) In such cases, the combined attenuation may result in a serious loss of signal power, but this can be regained by the use of balance.


Filter banks

By Gabriel Maldonado. (New in Csound 3.49)

ar	tonex	asig, khp[, inumlayer, istor]

ar	atonex	asig, khp[, inumalayer, istor]

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

INITALISATION

inumlayer - number of elements of filter stack. Default value is 4. Maximum value is 10

isig - same as tone, atone and reson

istor - same as tone, atone and reson

iscl - same as reson

PERFORMANCE

ar - output signal

asig - input signal

khp - same as tone, atone

kcf - same as reson

kbw - same as reson

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


Butterworth second-order filters

ar	butterhp	asig, kfreq [, iskip]

ar	butterlp	asig, kfreq [, iskip]

ar	butterbp	asig, kfreq, kband [, iskip]

ar	butterbr	asig, kfreq, kband [, iskip]

Implementations of second-order hipass, lopass, bandpass and bandreject Butterworth filters.

Coloured arguments were introduced in the Bath/Montreal version 3.46.

PERFORMANCE

These new filters are butterworth second-order IIR filters.  They are slightly slower than the original filters in Csound, but they offer an almost flat passband and very good precision and stopband attenuation.

asig  - Input signal to be filtered.

kfreq  - Cuttoff or center frequency for each of the filters.

kband  - Bandwidth of the bandpass and bandreject filters.

iskip  - Skip initialisation if present and non zero (compare istor argument of other filter opcodes).

EXAMPLE

asig	rand	10000	; White noise signal

alpf  	butterlp	asig, 1000	; cutting frequencies above1K

ahpf	butterhp	asig, 500	; passing frequencies above 500Hz

abpf	butterbp	asig, 2000, 100	; passing only 1950 to 2050 Hz

abrf	butterbr	asig, 4500, 200	; cutting only 4400 to 4600 Hz


General filter design units

By Michael A. Casey (New in Csound 3.47)

ar	filter2	asig, iM, iN, ib0 ,ib1,..., ibM, ia1, ia2,..., iaN

kr	filter2	ksig, iM, iN, ib0, ib1,...,ibM,ia1,ia2,..., iaN

ar	zfilter2	asig, kdamp, kfreq, M, iN, ib0, ib1,..., ibM,ia1, ia2,..., iaN

General purpose custom filter with time-varying pole control.

NAME CHANGES

The k-rate version of filter2 was called kfilter2 until Csound 3.492.

INITIALISATION

At initialisation the number of zeros and poles of the filter are specified along with the corresponding zero and pole coefficients. The coefficients must be obtained by an external filter-design application such as Matlab and specified directly or loaded into a table via GEN01. With zfilter2, the roots of the characteristic polynomials are solved at initialization so that the pole-control operations can be implemented efficiently.

PERFORMANCE

The filter coefficients implement the following difference equation:

(1)*y(n) = b0*x[n] + b1*x[n-1] + ... + bM*x[n-M] - a1*y[n-1] - ... - aN*y[n-N]

the system function for which is represented by:

                             -1            -M

         B(Z)       b0 + b1*Z  + ... + bM*Z

H(Z) =   ----  =  ------------------------------

                             -1            -N

         A(Z)        1 + a1*Z  + ... + aN*Z

The filter2 and kfilter2 opcodes perform filtering using a transposed form-II digital filter lattice with no time-varying control.

zfilter2 uses the additional operations of radial pole-shearing and angular pole-warping in the Z plane.

Pole shearing increases the magnitude of poles along radial lines in the Z-plane. This has the affect of altering filter ring times. The k-rate variable kdamp is the damping parameter. Positive values (0.01 to 0.99) increase the ring-time of the filter (hi-Q), negative values (-0.01 to -0.99) decrease the ring-time of the filter, (lo-Q).

Pole warping changes the frequency of poles by moving them along angular paths in the Z plane. This operation leaves the shape of the magnitude response unchanged but alters the frequencies by a constant factor (preserving 0 and p). The k-rate variable kfreq determines the frequency warp factor. Positive values (0.01 to 0.99) increase frequencies toward p and negative values (-0.01 to -0.99) decrease frequencies toward 0.

Since filter2 implements generalized recursive filters, it can be used to specify a large range of general DSP algorithms. For example, a digital waveguide can be implemented for musical instrument modeling using a pair of delayr and delayw opcodes in conjunction with the filter2 opcode.

EXAMPLES

A first-order linear-phase lowpass linear-phase FIR filter operating on a k-rate signal:

kr	filter2	ksig, 2, 0, 0.5, 0.5	; k-rate FIR filter

A controllable second-order IIR filter operating on an a-rate signal:

ar	zfilter2	asig, kdamp, kfreq, 1, 2, 1, ia1, ia2        ; controllable a-rate IIR filter

AUTHOR

Michael A. Casey

M.I.T., Cambridge, Mass.

1997


Resonant lowpass filters

By Gabriel Maldonado. (New in Csound 3.49)

ar	lowres	asig, kcutoff, kresonance [,istor]

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

ar	vlowres	asig, kcutoff, kresonance, iord, ksep;

DESCRIPTION

lowres is a resonant lowpass filter.

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

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

NAME CHANGES

These opcodes were called lpres, lpresx, and vplres respectively in Maldonados CsoundRT 1.9 distribution.

INITIALIZATION

inumlayer - number of elements of lowresx stack. Default value is 4.  There is no maximum.

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.

iord - total nuber of filter (1 to 10)

PERFORMANCE

ar - output signal

asig  - input signal

kcutoff - filter cutoff frequency point

kresonance - resonance amount

ksep - frequency cutoff separation for each filter

lowres is a resonant lowpass filter derived from an orchestra by Hans Mikelson.  This implementation is of course much faster than implementing it in the Csound orch language, and it allows kr lower than sr.  kcutoff is not in cps and kresonance is not in dB, so experiment to find the best results.

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

vlowres (variable resonant lowpass filter) allows a variable response curve in resonant filters.  It can be thought of 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.


Sweepable Filters

By Hans Mikelson (New in Csound 3.49)

ar	biquad	asig, kb0, kb1, kb2, ka0, ka1, ka2 [, iskip]

ar	moogvcf	asig, xfco, xres [, iscale]

ar	rezzy	asig, xfco, xres [, imode]

Implementation of a sweepable general purpose filter and two sweepable resonant low-pass filters.

NOTES

The xfco and xres arguments of moogvcf and rezzy were at first limited to k-rate, but can as of Csound 3.50 be a-rate as well.

The optional arguments iskip, iscale and imode were also added in Csound 3.50.

PERFORMANCE

biquad is a general purpose biquadratic digital filter of the form:

a0*y(n) + a1*y[n-1] + a2*y[n-2] = b0*x[n] + b1*x[n-1] + b2*x[n-2]

This filter has the following frequency response:

                       -1      -2

       B(Z)   b0 + b1*Z  + b2*Z

H(Z) = ---- = ------------------

                       -1      -2

       A(Z)   a0 + a1*Z  + a2*Z

This type of filter is often encountered in digital signal processing literature. It allows six user defined k-rate coefficients.

If the optional i-time argument iskip is non-zero, initialisation of biquad is skipped, to allow smooth transitions in carried notes. This argument was added in Csound 3.50.

rezzy is a resonant low-pass filter created empirically by Hans Mikelson.

imode - if 0, do low-pass filtering, if non-zero, perform high-pass filtering. Default value is 0

xfco is the filter cut-off frequency in Hz

xres is the amount of resonance. Values of 1 to 100 are typical. Resonance should be 1 (one) or greater.

moogvcf is a digital emulation of the Moog diode ladder filter configuration. This emulation is based loosely on the paper "Analyzing the Moog VCF with Considerations for Digital Implementation" by Stilson and Smith (CCRMA). This version was originally coded in Csound orc language by Josep Comajuncosas. Some modifications and conversion to C were done by Hans Mikelson.

Note: This filter requires that the input signal be normalized to one.

iscale - an optional scaling factor. Input asig is divided by this value, then output is multiplied with the same. This is intended to facilitate normalization, if asig in the rest of orchestra code is not in the range +/-1.0. Default value is 1.0.

xfco - the filter cut-off frequency in Hz.

xres - the amount of resonance with self-oscillation occurring when xres is approximately one.

EXAMPLES

biquad example

kfcon   =      2*3.14159265*kfco/sr

kalpha  =      1-2*krez*cos(kfcon)*cos(kfcon)+krez*krez*cos(2*kfcon)

kbeta   =      krez*krez*sin(2*kfcon)-2*krez*cos(kfcon)*sin(kfcon)

kgama   =      1+cos(kfcon)

km1     =      kalpha*kgama+kbeta*sin(kfcon)

km2     =      kalpha*kgama-kbeta*sin(kfcon)

kden    =      sqrt(km1*km1+km2*km2)

kb0     =      1.5*(kalpha*kalpha+kbeta*kbeta)/kden

kb1     =      kb0

kb2     =      0

ka0     =      1

ka1     =     -2*krez*cos(kfcon)

ka2     =      krez*krez

ayn     biquad axn, kb0, kb1, kb2, ka0, ka1, ka2

        outs   ayn*iamp/2, ayn*iamp/2

Orchestra

;   Sta  Dur  Amp    Pitch Fco   Rez

i14 8.0  1.0  20000  6.00  1000  .8

i14 +    1.0  20000  6.03  2000  .95

rezzy example

kfco	expseg 100+.01*ifco, .2*idur, ifco+100, .5*idur, ifco*.1+100, .3*idur, .001*ifco+100

apulse1 buzz   1,ifqc, sr/2/ifqc, 1 ; Avoid aliasing

asaw	integ  apulse1

axn     =      asaw-.5

ayn	rezzy  axn, kfco, krez

        outs   ayn*iamp, ayn*iamp

Orchestra

;    Sta  Dur  Amp    Pitch  Fco   Rez

i10  0.0  1.0  20000  6.00   1000  2

i10  +    1.0  20000  6.03   2000  10

moogvcf example

apulse1 buzz    1,ifqc, sr/2/ifqc, 1 ; Avoid aliasing

asaw    integ   apulse1

ax      =       asaw-.5

ayn     moogvcf ax, kfco, krez

        outs    ayn*iamp, ayn*iamp

Orchestra

;     Sta  Dur  Amp    Pitch  Fco   Rez

i11   4.0  1.0  20000  6.00   1000  .4

i11   +    1.0  20000  6.03   2000  .7


String resonator

By Victor Lazzarini (New in Csound 3.494)

ar	streson	asig, kfr, ifdbgain

An audio signal is modified by an string resonator with variable fundamental frequency.

INITIALISATION

ifdbgain - feedback gain, between 0 and 1, of the internal delay line. A value close to 1 creates a slower decay and a more pronounced resonance. Small values may leave the input signal unaffected. Depending on the filter frequency, typical values are > .9.

PERFORMANCE

streson passes the input asig through a network composed of comb, low-pass and all-pass filters, similar to the one used in some versions of the Karplus-Strong algorythm, creating a string resonator effect. The fundamental frequency of the "string" is controled by the k-rate variable kfr. This opcode can be used to simulate sympathetic resonances to an input signal.

streson is an adaptation of the StringFlt object of the SndObj Sound Object Library developed by the author.

Victor Lazzarini

Music Department

National University of Ireland, Maynooth

Maynooth Co.Kildare

Ireland


Non-linear filter

By Richard Dobson and John Fitch

ar	nlfilt	ain, ka, kb, kd, kC, kL

Implements the filter Y{n} = a Y{n-1} + b Y{n-2} + d Y{n-L}^2 + X{n} - C

(Note: Values shown inside curled brackets {, } in the formula are sample indexes).

See also some hints for nlfilt opcode.

ARGUMENTS

ain	- input audio rate signal; corresponds to X{n} in the formula.

ka, kb, kd	- multipliers of one sample, two sample and variable length (L) sample delays, respectively.

kC	- value to be subtracted from filter output.

kL	- length of third delay line. Note that kL is an integer sample offset. It may be changed at k-rate, but this will likely result in discontinuities in the output.

EXAMPLES

i) Non-linear effect:

With a = b = 0 and a delay (L) of 20 samples. The other parameters range over:

d = 0.8, 0.9, 0.7

C = 0.4, 0.5, 0.6

This affects the lower register most but there are audible effects over the whole range. We suggest that it may be useful for colouring drums, and for adding arbitrary highlights to notes

ii) Low Pass with non-linear:

a = 0.4

b = 0.2

d = 0.7

C = 0.11

L = 20, ... 200

There are instability problems with this variant but the effect is more pronounced of the lower register, but is otherwise much like the pure comb. Short values of L can add attack to a sound.

iii) High Pass with non-linear:

The range of parameters are

a = 0.35

b = -0.3

d = 0.95

C = 0,2, ... 0.4

L = 200

iv) High Pass with non-linear:

The range of parameters are

a = 0.7

b = -0.2, ... 0.5

d = 0.9

C = 0.12, ... 0.24

L = 500, 10

The high pass version is less likely to oscillate. It adds scintillation to medium-high registers. With a large delay L it is a little like a reverberation, while with small values there appear to be formant-like regions. There are arbitrary colour changes and resonances as the pitch changes. Works well with individual notes.

Warning: The "useful" ranges of parameters are not yet mapped.


Some tips for nlfilt opcode
Some hints for nlfilt opcode

Compiled from articles by Richard Dobson and John Fitch

nlfilt implements the filter Y{n} = a Y{n-1} + b Y{n-2} + d Y{n-L}^2 + X{n} - C.

The algorithm has been described in Experiments with Non-Linear Filters; Discovering Excitable Regions (Dobson and Fitch ICMC'96); available from

http://www.bath.ac.uk/~masjpf/MusPapers.html

INTRODUCTION: EXCITABLE REGIONS

The goal in designing nlfilt was to create a purely arithmetical instrument with excitable regions. This can be explained by analogy with a string on a violin. Up to a point, increasing its tension will increase its fundamental rate of vibration; beyond that point it will break. Similarly, below a minimum tension it will not vibrate at all. The violin thus has four excitable regions.

The problem with conventional synthesis techniques (from our point of view) is that they do not in general exhibit such bounded excitable regions. We in our researches are relatively unconcerned to use mathematical artifices to overcome all analogous limitations in a given filter; thus you will need to explore the opcode to find useful sets of parameter values.

The sound source of nlfilt is provided by a non-linear oscillator algorithm (see Experiments with Chaotic Oscillators, by Dobson and Fitch, 1995, available from the www address given above), adapted from the simple recurrence relation of the Mandelbrot set [Mandelbrot, 1992]: X{n+1} = X{n}^2 - C. This can be shown to be stable for values of 0 < C < 2. To this we have provided for addition of up to three delay elements, leading to a recurrence relation which combines a conventional linear filter with a non-linear delay.

With careful selection of coefficient values, a wide range of decaying and sustained sounds, often of richly time-varying spectral character, can be realized. Above all, these oscillators exhibit Excitable Regions, outside which they will either converge rapidly, or exceed the bounds of their numerical representation (in effect, they will break). Within these regions, they can be forced into unexpected modes of oscillation, in much the same way that a wind instrument will generate multiphonics or squeak, if played incorrectly or unconventionally.

THE NON-LINEAR PART

For stability, d and C should be opposite in sign, but may be of similar magnitude, |C| usually less than |d|); ie the ranges 0 < C << 1, 0 < d < 1 are recommended.

The constant term C has the unavoidable side-effect of imposing a DC component, with starting transient, on the output. Although the filter exhibits useful behaviour without it, we have found that the most striking effects are dependent on its inclusion, despite the concomitant need for a DC removal filter on the output.

Although the filter is by its nature sensitive to the input, we have so far had no problems with stability so long as the input is constrained within the range -0.5 < ain < 0.5. This is however a maximum; chaotic behaviour develops rapidly as the input rises above -12dB.

The filter exhibits distinctly comb-like behaviour as the delay L is increased. However, unlike the response of a linear comb filter, in which the peaks are regular in spacing, width and amplitude, this filter exhibits marked irregularities in all those aspects. Some responses look remarkably like formant regions, indicating that this filter has a distinctive set of personalities, and is therefore able to provide a range of resonant bodies' for our arithmetical instrument.

We consider the single most significant property of this filter to be the fact that, whereas an input sine wave will excite but one resonant peak of a linear comb filter, it will excite several in this case; the filter's Excitable Regions will be multiply activated in a moderately unpredictable way according to the characteristics of the input. Accordingly, we call this and its derivatives an ER filter.

THE LINEAR PART

On its own the linear part forms a simple resonator (band-pass), which can be configured also as a low or high-pass filter.

The combination of the linear and non-linear elements can be interpreted in two equally useful ways. Firstly, d and C can be taken together as a kind of modulation or fractal' index (whose range must clearly reduced according to the gain of the linear filter), which, as it increases from zero, adds a comb-like irregularity to the linear band-pass response -- the ER filter can be fractalized' dynamically. For stability the range of the index must be reduced according to the gain of the linear filter; putting it another way, we want to leave room for non-linear behaviour to be introduced by keeping the linear gain within conservative levels.

The delay L can be set at 3 for the closest match between chaotic and linear responses, or it can be set to any reasonable distance as for a comb filter.


(verkar inte riktigt detta avsnitt)

CHAOTIC OSCILLATORS AND nlfilt

The opcode nlfilt may also be used as an implementation of the chaotic oscillator described in the article Experiments with Chaotic Oscillators referred to above. To implement this instrument, ain must be a constant value (normally 0). In this context, nlfilt might be called a fractal waveform generator.

Generally, C should be in the range 0 < C <= 1. This will generate a simple exponentially decaying sequence, which is however forced into extended and possibly sustained oscillation by the negative C. The constant C causes a DC offset, which can however simply be removed. C + d should not exceed a threshold valueof around 0.95 (unless you use a limiter like limit to the output signal).

For example, with L = 16, the resulting output has the form of a square wave with slightly sloping sides.

The coefficient d will have a rounding effect of the positive linear term; this is clear even at d = 0.25. With judicious values for C the waveform can be made to reduce to something approaching a sine wave -- a behaviour bearing obvious similarities to that of the Karplus-Strong algorithm (see pluck).

The effect of a negative d is more significant. Whereas a large negative C tends to produce crude linear-segment oscillations (to say nothing of the large DC offset) through successive iterations, a large d can in fact endow impressive rounding to the waveform (i.e. by extending its period), or add fractal complexity to it, and C can (indeed must) be kept small. In some cases, large values of d (i.e. close to -1 (minus one)) introduce ringing to an extent that the underlying square wave shape can be completed swamped by more rapid oscillations in forms suggestive of grains or wavelets. It almost goes without saying that the grain shapes differ according to the length of the delay L: the difference between odd and even lengths is especially striking.

Although it is rarely safe to generalise in a subject such as this, it has been observed that relatively prime ratios between L and the offset most often lead to the most elaborate waveform evolutions, whereas simple ratios can lead to very rapid convergence for all but the most extreme parameter values.

The period of the waveform is not necessarily of length L (although this is true of the more elaborate formulae described later); the period can be be three to four times L, even for L=2. For many of these waveforms, C functions as a sort of modulation index -- indeed the spectrum can look remarkably like that of an FM-generated signal. However, as C is increased, a chaotic threshold is reached, inducing strange attack patterns. A high C induces a long attack phase.


Parametric Equalizer Filters

By Hans Mikelson (New in Csound 3.50)

ar	pareq	asig, kc, iv, iq, imode

Implementation of Zoelzer's Parametric Equalizer Filters.

INITIALISATION

iv - volume boost or cut

iq - the quality factor (sqrt(.5) = 0.7071... is no resonance)

imode - 0=Peaking EQ, 1=Low Shelf, 2=High Shelf

PERFORMANCE

kc - the centre of shelf value

asig - the incoming signal

EXAMPLE

instr 15

    ifc     =     p4	; Center / Shelf

    iq      =     p5	; Quality factor sqrt(.5) is no resonance

    iv      =     ampdb(p6) 	; Volume Boost/Cut

    imode   =     p7 	; Mode 0=Peaking EQ, 1=Low Shelf, 2=High Shelf

    kfc     linseg  ifc*2, p3, ifc/2

    asig    rand  5000 	; Random number source for testing

    aout    pareq asig, kfc, iv, iq, imode	; Parmetric equalization

        outs  aout, aout	; Output the results

endin

; Score:

;     Sta  Dur  Fcenter   Q     Boost/Cut(dB)  Mode

i15   0     1     10000    .2            12                1

i15   +     .        5000    .2            12                1

i15    .     .        1000    .707       -12                2

i15    .     .        5000    .1           -12                0


Sample level operators

kr	downsamp	asig[, iwlen]

ar	upsamp	ksig

ar	interp	ksig[, istor]

kr	integ	ksig[, istor]

ar	integ	asig[, istor]

kr	diff   	ksig[, istor]

ar	diff   	asig[, istor]

kr	samphold	xsig, kgate[, ival, ivstor]

ar	samphold	asig, xgate[, ival, ivstor]

Modify a signal by up- or down-sampling, integration, and differentiation.

INITIALISATION

iwlen (optional) - window length in samples over which the audio signal is averaged to determine a downsampled value. Maximum length is ksmps; 0 and 1 imply no window averaging.  The default value is 0.

istor (optional) - initial disposition of internal save space (see reson). The default value is 0.

ival, ivstor (optional) - controls initial disposition of internal save space. If ivstor is zero the internal "hold" value is set to ival ; else it retains its previous value. Defaults are 0,0 (i.e. init to zero).

PERFORMANCE

downsamp converts an audio signal to a control signal by downsampling. It produces one kval for each audio control period. The optional window invokes a simple averaging process to suppress foldover.

upsamp, interp convert a control signal to an audio signal. The first does it by simple repetition of the kval, the second by linear interpolation between successive kvals. upsamp is a slightly more efficient form of the assignment, asig = ksig'.

integ, diff perform integration and differentiation on an input control signal or audio signal. Each is the converse of the other, and applying both will reconstruct the original signal. Since these units are special cases of low-pass and high-pass filters, they produce a scaled (and phase shifted) output that is frequency-dependent. Thus diff of a sine produces a cosine, with amplitude 2 * sin(pi * cps / sr) that of the original (for each component partial); integ will inversely affect the magnitudes of its component inputs. With this understanding, these units can provide useful signal modification.

samphold performs a sample-and-hold operation on its input according to the value of xgate. If xgate > 0, the input samples are passed to the output; If xgate <= 0, the last output value is repeated. The controlling gate can be a constant, a control signal, or an audio signal.

EXAMPLE

asrc	buzz 	10000,440,20, 1	; band-limited pulse train

adif	diff	asrc	; emphasize the highs

anew	balance	adif, asrc	;       but retain the power

agate	reson	asrc,0,440 	; use a lowpass of the original

asamp	samphold	anew, agate 	;       to gate the new audiosig

aout	tone	asamp,100	; smooth out the rough edges


Delay paths

ar 	delayr	idlt[, istor]

delayw	asig

ar	delay 	asig, idlt[, istor]

ar	delay1	asig[, istor]

A signal can be read from or written into a delay path, or it can be automatically delayed by some time interval.

INITIALISATION

idlt - requested delay time in seconds. This can be as large as available memory will permit. The space required for n seconds of delay is 4n * sr bytes. It is allocated at the time the instrument is first initialized, and returned to the pool at the end of a score section.

istor (optional) - initial disposition of delay-loop data space (see reson). The default value is 0.

PERFORMANCE

delayr reads from an automatically established digital delay line, in which the signal retrieved has been resident for idlt seconds. This unit must be paired with and precede an accompanying delayw unit. Any other Csound statements can intervene.

delayw writes asig into the delay area established by the preceding delayr unit. Viewed as a pair, these two units permit the formation of modified feedback loops, etc. However, there is a lower bound on the value of idlt, which must be at least 1 control period (or 1/kr).

delay is a composite of the above two units, both reading from and writing into its own storage area. It can thus accomplish signal time-shift, although modified feedback is not possible. There is no minimum delay period.

delay1 is a special form of delay that serves to delay the audio signal asig by just one sample. It is thus functionally equivalent to "delay asig, 1/sr" but is more efficient in both time and space. This unit is particularly useful in the fabrication of generalized non-recursive filters.

EXAMPLE

tigoto	contin	; except on a tie,

a2	delay	a1, .05, 0	; begin 50 msec clean delay of sig

contin:


Delay taps

ar	deltap	kdlt

ar	deltapi	xdlt

ar	deltap3	xdlt

ar	deltapn	xnumsamps

Tap a delay line at variable offset times.

PERFORMANCE

These units can tap into a delayr/delayw pair, extracting delayed audio from the idlt seconds of stored sound. There can be any number of deltap and/or deltapi units between a read/write pair. Each receives an audio tap with no change of original amplitude.

deltap extracts sound by reading the stored samples directly; deltapi extracts sound by interpolated readout. By interpolating between adjacent stored samples deltapi represents a particular delay time with more accuracy, but it will take about twice as long to run. deltap3 is like deltapi, but uses cubic interpolation for enhanced sound quality (experimental, new in Csound 3.50).

deltapn taps the delay by xnumsamps number of samples, rather than measuring the delay time in seconds. By Hans Mikelson, new in Csound 3.50.

The arguments kdlt, xdlt specify the tapped delay time in seconds. Each can range from 1 Control Period to the full delay time of the read/write pair; however, since there is no internal check for adherence to this range, the user is wholly responsible. Each argument can be a constant, a variable, or a time-varying signal; the xdlt argument in deltapi implies that an audio-varying delay is permitted there.

These units can provide multiple delay taps for arbitrary delay path and feedback networks. They can deliver either constant-time or time-varying taps, and are useful for building chorus effects, harmonizers, and doppler shifts. Constant-time delay taps (and some slowly changing ones) do not need interpolated readout; they are well served by deltap. Medium-paced or fast varying dlt's, however, will need the extra services of deltapi.

NOTE

K-rate delay times are not internally interpolated, but rather lay down stepped time-shifts of audio samples; this will be found quite adequate for slowly changing tap times. For medium to fastpaced changes, however, one should provide a higher resolution audio-rate timeshift as input.

EXAMPLE

asource	buzz	1, 440, 20, 1

atime	linseg	1, p3/2,.01, p3/2,1	; trace a distance in secs

ampfac	 =	1/atime/atime	;     and calc an amp factor

adump	delayr    1	; set maximum distance

amove	deltapi	atime	; move sound source past

delayw	asource	;     the listener

out	amove * ampfac


Variable time delay

ar	vdelay	asig, adel, imaxdel [, iskip]

ar	vdelay3	asig, adel, imaxdel [, iskip]

This is an interpolating variable time delay, it is not very different from the existing implementation (deltapi), it is only easier to use.

The argument iskip was introduced in Bath/Montreal version 3.46.

vdelay3 is experimental, and uses cubic interpolation for enhanced sound quality. It was introduced in Csound 3.50.

INITIALISATION

imaxdel - Maximum value of delay in milliseconds.  If adel gains a value greater than imaxdel it is folded around imaxdel.  This should not happen.

iskip  - Skip initialisation if present and non zero (compare istor argument of other filter opcodes).

PERFORMANCE

With this unit generator it is possible to do Doppler effects or chorusing and flanging.

asig  - Input signal.

adel - Current value of delay in milliseconds.  Note that linear functions have no pitch change effects.  Fast changing values of adel will cause discontinuities in the waveform resulting noise.

EXAMPLE

f1 0 8192 10 1	; Sine table (in score file)

ims	= 	100   	; Maximum delay time in msec

a1	oscil	10000, 1737, 1	; Make a signal

a2	oscil	ims/2, 1/p3, 1	; Make an LFO with sine in table 1

a2	 =	a2 + ims/2	; Offset the LFO so that it is positive

a3	vdelay	a1, a2, ims	; Use the LFO to control delay time

 	out	a3

Two important points here.  First, the delay time must be always positive.  And second, even though the delay time can be controlled in k-rate, it is not advised to do so, since sudden time changes will create clicks.


Multitap delay

Multitap delay line implementation.

ar	multitap	asig, itime1, igain1, itime2, igain2 . . .

INITIALIZATION

The arguments itime and igain set the position and gain of each tap. The delay line is fed by asig.

EXAMPLE

a1	oscil	1000, 100, 1

a2	multitap	a1, 1.2, .5, 1.4, .2

 	out	a2

This results in two delays, one with length of 1.2 and gain of .5, and one with length of 1.4 and gain of .2.


Reverberation units

ar	comb 	asig, krvt, ilpt[, istor]

ar	alpass	asig, krvt, ilpt[, istor]

ar	reverb	asig, krvt[, istor]

ar	reverb2	asig, krvt, khdif [, iskip]

ar	nreverb	asig, krvt, khdif [, iskip]

An input signal is reverberated for krvt seconds with "colored" (comb), flat (alpass), or "natural room" (reverb, reverb2, nreverb) frequency response.

INITIALISATION

ilpt  -  loop time in seconds, which determines the "echo density" of the reverberation. This in turn characterizes the "color" of the comb filter whose frequency response curve will contain ilpt * sr/2 peaks spaced evenly between 0 and sr/2 (the Nyquist frequency). Loop time can be as large as available memory will permit. The space required for an n second loop is 4n * sr bytes. comb and alpass delay space is allocated and returned as in delay.

istor (optional) - initial disposition of delay-loop data space (cf. reson). The default value is 0.

iskip  - Skip initialisation if present and non zero (compare istor argument of other filter opcodes).

PERFORMANCE

These filters reiterate input with an echo density determined by loop time ilpt. The attenuation rate is independent and is determined by krvt, the reverberation time (defined as the time in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude). Output from a comb filter will appear only after ilpt seconds; alpass output will begin to appear immediately.

A standard reverb unit is composed of four comb filters in parallel followed by two alpass units in series. Looptimes are set for optimal "natural room response." Core storage requirements for this unit are proportional only to the sampling rate, each unit requiring approximately 3K words for every 10KC. The comb, alpass, delay, tone and other Csound units provide the means for experimenting with alternate reverberator designs

Since output from the standard reverb will begin to appear only after 1/20 second or so of delay, and often with less than three-fourths of the original power, it is normal to output both the source and the reverberated signal. Also, since the reverberated sound will persist long after the cessation of source events, it is normal to put reverb in a separate instrument to which sound is passed via a global variable, and to leave that instrument running throughout the performance.

reverb2 consists of 6 parallel comb-lowpass filters being fed into a series of 5 allpass filters.

It turned out that reverb2 was tuned to a particular sample rate. It has been replaced by nreverb, and the two names now refer to the same opcode.

The input signal asig to reverb2/nreverb is reverberated for krvt seconds.  The parameter khdif controls the high frequency diffusion amount.  The values of khdif should be from 0 to 1.  If khdif is set to 0 the all the frequencies decay with the same speed.  If khdif is 1, high frequencies decay faster that lower ones.

EXAMPLES

ga1	init 0   	; init an audio receiver/mixer

instr 1         	; instr (there may be many copies)

a1	oscili	8000, cpspch(p5), 1 	; generate a source signal

out	a1	; output the direct sound

ga1	 =	ga1 + a1	; and add to audio receiver

endin

instr  99      	; (highest instr number executed last)

a3	reverb	ga1, 1.5	 ; reverberate whatever is in ga1

out	a1	; and output the result

ga1	 =	0	; empty the receiver for the next pass

endin

Here is also a reverb2 example:

a1	oscil	10000, 100, 1

a2	reverb2	a1, 2.5, .3

 	out	a1 + a2 * .2

This results in a 2.5 sec reverb with faster high frequency attenuation.


Harmonizer opcode

By Barry Vercoe (New in Csound 3.47)

ar	harmon	asig, kestfrq, kmaxvar, kgenfrq1, kgenfrq2, imode, iminfrq, iprd

Analyse an audio input and generate harmonising voices in synchrony.

ARGUMENTS

imode - how to treat the 2 generated frequency inputs kgenfreq1, kgenfreq2.

=0: as ratios; =1: as cps

iminfrq - the lowest expects frequency (in cps) of the audio input. This parameter determines how much of the input is saved for the running analysis, and sets a lower bound on the internal pitch tracker.

iprd - the period of analysis (in seconds). Since the internal pitch analysis can be time-consuming, the input is typically analysed only each 20 to 50 milliseconds.

kestfrq - an estimate of the input frequency

kmaxvar - a ratio to limit the search.

PERFORMANCE

This unit is a harmonizer, able to provide up to two additional voices with the same amplitude and spectrum as the input. The input analysis is assisted by two things: an input estimated frequency kestfrq (in cps), and a fractional maximum variance kmaxvar about that estimate which serves to limit the size of the search. Once the real input frequency is determined, the most recent pulse shape is used to generate the other voices at their requested frequencies.

The three frequency inputs can be derived in various ways from a score file or MIDI source. The first is the expected pitch, with a variance parameter allowing for inflections or inaccuracies; if the expected pitch is zero the harmonizer will be silent. The second and third pitches control the output frequencies; if either is zero the harmonizer will output only the non-zero request; if both are zero the harmonizer will be silent. When the requested frequency is higher than the input, the process requires additional computation due to overlapped output pulses. This is currently limited for efficiency reasons, with the result that only one voice can be higher than the input at any one time.

This unit is useful for supplying a background chorus effect on demand, or for correcting the pitch of a faulty input vocal. There is essentially no delay between input and output. Output includes only the generated parts, and does not include the input.

EXAMPLE

asig1	in   	       	; get the live input

kcps1	cpsmidib     	; and its target pitch

; add maj 3rd

asig2	harmon	asig1, kcps1, .3, kcps1, kcps1 * 1.25, 1, 110, .04

out 	asig2         	; output just the corrected and added voices


Flanger

By Gabriel Maldonado. (New in Csound 3.484)

ar	flanger	asig, adel, kfeedback, imaxd

A user controlled flanger

INITALISATION

imaxd - maximum delay (needed for inital memory allocation)

PERFORMANCE

ar - output signal

asig - input signal

adel - delay in seconds

kfeedback - feedback amount

This unit is useful for generating chourses and flangers. The delay must be varied at k-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 wguide1, the only difference is flanger does not have the lowpass filter.)


Distortion

By Hans Mikelson. (New in Csound 3.50)

aout	distort1	asig [, kpregain, kpostgain, kshape1, kshape2]

Implementation of modified hyperbolic tangent distortion.

Note: Name chosen to avoid clash with the distort opcode in Extended Csound.

NOTE2: Until Csound 3.52, all arguments were required (non-optional).

PERFORMANCE

asig is the input signal.

kpregain determines the amount of gain applied to the signal before waveshaping. A value of 1 (default)  gives slight distortion.

kpostgain determines the amount of gain applied to the signal after waveshaping. Default value: one.

kshape1 determines the shape of the positive part of the curve. A value of zero (default) gives a flat clip, small positive values give sloped shaping.

kshape2 determines the shape of the negative part of the curve. Default value: zero.

distort1 can be used to generate wave shaping distortion based on a modification of the tanh function.

exp(asig * (pregain + shape1)) - exp(asig*(pregain+shape2))

aout =  ---------------------------------------------------------------------------------------------

exp(asig*pregain)                    + exp(-asig*pregain)

EXAMPLE

gadist  init    0

        instr   1

iamp    =       p4

ifqc     =       cpspch(p5)

asig   pluck   iamp, ifqc, ifqc, 0, 1

gadist  =       gadist + asig

        endin

        instr   50

kpre       init    p4

kpost     init    p5

kshap1  init    p6

kshap2  init    p7

aout    distort1 gadist, kpre, kpost, kshap1, kshap2

        outs    aout, aout

gadist  =       0

        endin

; Score:

;   Sta  Dur  Amp    Pitch

i1  0.0  3.0  10000  6.00

i1  0.5  2.5  10000  7.00

i1  1.0  2.0  10000  7.07

i1  1.5  1.5  10000  8.00

;   Sta  Dur  PreGain PostGain Shape1 Shape2

i50 0    3    2       1        0      0


Innehåll: adsyn pvoc, pvoc, pvadd, pvread pvbufread pvcross tableseg tablexseg vpvoc, cross2, lpread lpreson lpfreson, lpslot lpinterpol, convolve

SPECTRAL DATA TYPES (octdown noctdft), spectrum, specaddm specdiff specscal spechist specfilt, specptrk specsum specdisp.


Phase vocoder
Oscillator bank resynthesis

See also more phase vocoder opcodes, and pvadd.

ar	adsyn	kamod, kfmod, ksmod, ifilcod

ar	pvoc	ktimpnt, kfmod, ifilcod [, ispecwp]

Output is an additive set of individually controlled sinusoids, using either an oscillator bank or phase vocoder resynthesis. The data for these ugens are generated by the Csound utilities HETRO and PVANAL, respectively.

INITIALISATION

ifilcod - integer or character-string denoting a control-file derived from analysis of an audio signal. An integer denotes the suffix of a file adsyn.m or pvoc.m; a character-string (in double quotes) gives a filename, optionally a full pathname. If not fullpath, the file is sought first in the current directory, then in the one given by the environment variable SADIR (if defined).

adsyn control files contain breakpoint amplitude- and frequency-envelope values organized for oscillator resynthesis, while pvoc control files contain similar data organized for FFT resynthesis. Memory usage depends on the size of the files involved, which are read and held entirely in memory during computation but are shared by multiple calls (see also lpread).

ispecwp (optional) - if non-zero, attempts to preserve the spectral envelope while its frequency content is varied by kfmod. The default value is zero. (New optional argument in Csound version 3.46)

PERFORMANCE

adsyn synthesizes complex time-varying timbres through the method of additive synthesis. Any number of sinusoids, each individually controlled in frequency and amplitude, can be summed by high-speed arithmetic to produce a high-fidelity result.

Component sinusoids are described by a control file describing amplitude and frequency tracks in millisecond breakpoint fashion. Tracks are defined by sequences of 16-bit binary integers:

-1, time, amp, time, amp,...

-2, time, freq, time, freq,...

such as from hetrodyne filter analysis of an audio file. (For details see HETRO.) The instantaneous amplitude and frequency values are used by an internal fixed-point oscillator that adds each active partial into an accumulated output signal. There is no restriction on the number of contributing partials (max was 50 until Csound v 3.47), there is no restriction on their behavior over time. Any sound that can be described in terms of the behavior of sinusoids can be synthesized by adsyn alone.

Sound described by an adsyn control file can also be modified during re-synthesis. The signals kamod, kfmod, ksmod will modify the amplitude, frequency, and speed of contributing partials. These are multiplying factors, with kfmod modifying the cps frequency and ksmod modifying the speed with which the millisecond bread-point line-segments are traversed. Thus .7, 1.5, and 2 will give rise to a softer sound, a perfect fifth higher, but only half as long. The values 1,1,1 will leave the sound unmodified. Each of these inputs can be a control signal.

pvoc implements signal reconstruction using an FFT-based phase vocoder. The control data stems from a precomputed analysis file with a known frame rate. The passage of time through this file is specified by ktimpnt, which represents the time in seconds. ktimpnt must always be positive, but can move forwards or backwards in time, be stationary or discontinuous, as a pointer into the analysis file. kfmod is a control-rate transposition factor: a value of 1 incurs no transposition, 1.5 transposes up a perfect fifth, and .5 down an octave.

This implementation of pvoc was written by Dan Ellis. It is based in part on the system of Mark Dolson, but the pre-analysis concept is new.


Additive synthesis on phase vocoder files

By Richard Karpen, 1998 (New in Csound 3.48)

ar	pvadd	ktimpnt, kfmod, ifile, ifn, ibins [, ibinoffset, ibinincr]

DESCRIPTION

pvadd reads from a phase vocoder analysis file generated by the Csound utility PVANAL and uses the data to perform additive synthesis using an internal array of interpolating oscillators. The user supplies the wave table (usually one period of a sine wave), and can choose which analysis bins will be used in the re-synthesis. See also pvoc and other phase vocoder opcodes.

PERFORMANCE

ktimpnt, kfmod, and ifile are used in the same way as in pvoc.

ifn  - the table number of a stored function containing a sine wave.

ibins  - the number of bins that will be used in the resynthesis (each bin counts as one oscillator in the re-synthesis).

ibinoffset is the first bin used (it is optional and defaults to 0).

ibinincr sets an increment by which pvadd counts up from ibinoffset for ibins components in the re-synthesis (see below for a further explanation).

EXAMPLES

ktime	line	0, p3, p3

asig	pvadd	ktime, 1, "oboe.pvoc", 1, 100, 2

In the above, ibins is 100 and ibinoffset is 2. Using these settings the resynthesis will contain 100 components beginning with bin #2 (bins are counted starting with 0). That is, resynthesis will be done using bins 2-101 inclusive. It is usually a good idea to begin with bin 1 or 2 since the 0th and often 1st bin have data that is neither necessary nor even helpful for creating good clean resynthesis.

ktime	line	0, p3, p3

asig	pvadd 	ktime, 1, "oboe.pvoc", 1, 100, 2, 2

The above is the same as the previous example with the addition of the value 2 used for the optional ibinincr argument. This result will still result in 100 components in the resynthesis, but pvadd will count through the bins by 2 instead of by 1. It will use bins 2, 4, 6, 8, 10, and so on. For ibins=10, ibinoffset=10, and ibinincr=10, pvadd would use bins 10, 20, 30, 40, up to and including 100.

USEFUL HINTS:

By using several pvadd units together, one can gradually fade in different parts of the resynthesis, creating various "filtering" effects. The author uses pvadd to synthesis one bin at a time to have control over each separate component of the re-synthesis.

If any combination of ibins, ibinoffset, and ibinincr, creates a situation where pvadd is asked to used a bin number greater than the number of bins in the analysis, it will just use all of the available bins and give no complain.  So to use every bin just make ibins a big number (ie. 2000).

Expect to have to scale up the amplitudes by factors of 10-100 by the way.


Extended Phase vocoder manipulation
More phase vocoder opcodes

By Richard Karpen (New in Csound 3.44)

kfrq,kamp	pvread	ktimpnt, ifile, ibin

pvbufread	ktimpnt, ifile

ar	pvinterp	ktimpnt, kfmod, ifile, kfreqscale1, kfreqscale2, kampscale1, kampscale2, kfreqinterp, kampinterp

ar	pvcross	ktimpnt, kfmod, ifile, kamp1, kamp2, [ispecwp]

tableseg	ifn1, idur1, ifn2[, idur2, ifn3[...]]

tablexseg	ifn1, idur1, ifn2[, idur2, ifn3[...]]

ar	vpvoc	ktimpnt, kfmod, ifile, [ispecwp]

Ugens using phase vocoder analysis files generated by the Csound utility PVANAL, and an oscillator opcode, by Richard Karpen. See also pvoc and pvadd.

NAME CHANGES

ar	voscili	kamp, kcps [, iphs]

This opcode was removed in Csound 3.49, since it did not work well and the functionality exists elsewhere.

ARGUMENTS

ifile - the pvoc number (n in pvoc.n) or the name in quotes of the analysis file made using PVANAL. See pvoc documentation in Csound manual.

kfreq and kamp - the outputs of the pvread unit. These values, retrieved from a phase vocoder analysis file, represent the values of frequency and amplitude from a single analysis channel specified in the ibin argument. Interpolation between analysis frames is performed at k-rate resolution and dependent of course upon the rate and direction of ktimpnt.

ktimpnt, kfmod, and ispecwp used in pvread and vpvoc are exactly the same as for pvoc (see description of pvinterp for its special use of kfmod).

ibin - the number of the analysis channel from which to return frequency in cps and magnitude.

kfreqscale1, kfreqscale2, kampscale1, kampscale2 are used in pvinterp to scale the frequencies and amplitudes stored in each frame of the phase vocoder analysis file. kfreqscale1 and kampscale1 scale the frequencies and amplitudes of the data from the file read by the previously called pvbufread (this data is passed internally to the pvinterp unit). kfreqscale2 and kampscale2 scale the frequencies and amplitudes of the file named by ifile in the pvinterp argument list and read within the pvinterp unit. By using these arguments it is possible to adjust these values before applying the interpolation. For example, if file1 is much louder than file2, it might be desirable to scale down the amplitudes of file1 or scale up those of file2 before interpolating. Likewise one can adjust the frequencies of each to bring them more in accord with one another (or just the opposite of course!) before the interpolation is performed.

kfreqinterp and kampinterp, used in pvinterp, determine the interpolation distance between the values of one phase vocoder file and the values of a second file. When the value of kfreqinterp is 0, the frequency values will be entirely those from the first file (read by the pvbufread), post scaling by the kfreqscale1 argument. When the value of kfreqinterp is 1 the frequency values will be those of the second file (read by the pvinterp unit itself), post scaling by kfreqscale2. When kfreqinterp is between 0 and 1 the frequency values will be calculated, on a bin, by bin basis, as the percentage between each pair of frequencies (in other words, kfreqinterp=.5 will cause the frequencies values to be half way between the values in the set of data from the first file and the set of data from the second file). kampinterp works in the same way upon the amplitudes of the two files. Since these are k-rate arguments, the percentages can change over time making it possible to create many kinds of transitions between sounds.

ifn1, ifn2, ifn3, etc... in tableseg and tablexseg are stored functions, created from an f-card in the numeric notelist. ifn1, ifn2, and so on. They MUST be of the same size.

idur1, idur2, etc...in tableseg and tablexseg are the durations during which interpolation from one table to the next will take place.

PERFORMANCE

pvread reads from a phase vocoder analysis file and returns the frequency and amplitude from a single analysis channel or bin. The returned values can be used anywhere else in the csound instrument. For example, one can use them as arguments to an oscillator to synthesize a single component from an analyzed signal or a bank of pvreads can be used to resynthesize the analyzed sound using additive synthesis by passing the frequency and magnitude values to a bank of oscillators. See also pvadd.

pvbufread reads from a phase vocoder analysis file and makes the retrieved data available to any following pvinterp and pvcross units that appear in an instrument before a subsequent pvbufread (just as lpread and lpreson work together). The data is passed internally and the unit has no output of its own. pvinterp and pvcross allow the interprocessing of two phase vocoder analysis files prior to the resynthesis which these units do also. Both of these units receive data from one of the files from a previously called pvbufread unit. The other file is read by the pvinterp and/or pvcross units. Since each of these units has its own time-pointer the analysis files can be read at different speeds and directions from one another. pvinterp does not allow for the use of the ispecwp process as with the pvoc and vpvoc units.

pvinterp interpolates between the amplitudes and frequencies, on a bin by bin basis, of two phase vocoder analysis files (one from a previously called pvbufread unit and the other from within its own argument list), allowing for user defined transitions between analyzed sounds. It also allows for general scaling of the amplitudes and frequencies of each file separately before the interpolated values are calculated and sent to the resynthesis routines. The kfmod argument in pvinterp performs its frequency scaling on the frequency values after their derivation from the separate scaling and subsequent interpolation is performed so that this acts as an overall scaling value of the new frequency components.

pvcross applies the amplitudes from one phase vocoder analysis file to the data from a second file and then performs the resynthesis. The data is passed, as described above, from a previously called pvbufread unit. The two k-rate amplitude arguments are used to scale the amplitudes of each files separately before they are added together and used in the resynthesis (see below for further explanation). The frequencies of the first file are not used at all in this process. This unit simply allows for cross-synthesis through the application of the amplitudes of the spectra of one signal to the frequencies of a second signal. Unlike pvinterp, pvcross does allow for the use of the ispecwp as in pvoc and vpvoc.

tableseg and tablexseg are like linseg and expseg but interpolate between values in a stored function tables. The result is a new function table passed internally to any following vpvoc which occurs before a subsequent tableseg or tablexseg (much like lpread/lpreson pairs work). The uses of these are described below under vpvoc.

vpvoc is identical to pvoc except that it takes the result of a previous tableseg or tablexseg and uses the resulting function table (passed internally to the vpvoc), as an envelope over the magnitudes of the analysis data channels. The result is spectral enveloping. The function size used in the tableseg should be framesize/2, where framesize is the number of bins in the phase vocoder analysis file that is being used by the vpvoc. Each location in the table will be used to scale a single analysis bin. By using different functions for ifn1, ifn2, etc.. in the tableseg, the spectral envelope becomes a dynamically changing one.

SIMPLE EXAMPLES

The example below shows the use pvread to synthesize a single component from a phase vocoder analysis file. It should be noted that the kfreq and kamp outputs can be used for any kind of synthesis, filtering, processing, and so on.

ktime	line	0, p3, 3

kfreq, kamp	pvread	ktime, "pvoc.file", 7	; read data from 7th analysis bin.

asig	oscili	kamp, kfreq, 1	; function 1 is a stored sine

The below shows an example using pvbufread with pvinterp to interpolate between the sound of an oboe and the sound of a clarinet. The value of kinterp returned by a linseg is used to determine the timing of the transitions between the two sounds. The interpolation of frequencies and amplitudes are controlled by the same factor in this example, but for other effects it might be interesting to not have them sychnronized in this way. In this example the sound will begin as a clarinet, transform into the oboe and then return again to the clarinet sound. The value of kfreqscale2 is 1.065 because the oboe in this case is a semitone higher in pitch than the clarinet and this brings them approximately to the same pitch. The value of kampscale2 is .75 because the analyzed clarinet was somewhat louder than the analyzed oboe. The setting of these two parameters make the transition quite smooth in this case, but such adjustments are by no means necessary or even advocated.

ktime1	line 	0, p3, 3.5 	; used as index into the "oboe.pvoc" data file

ktime2	line 	0, p3, 4.5 	; used as index into the "clar.pvoc" data file

kinterp	linseg 	1, p3*.15, 1, p3*.35, 0, p3*.25, 0, p3*.15, 1, p3*.1, 1

pvbufread ktime1, "oboe.pvoc"

apv 	pvinterp 	ktime2,1,"clar.pvoc",1,1.065,1,.75,1-kinterp,1-kinterp

Below is an example using pvbufread with pvcross. In this example the amplitudes used in the resynthesis gradually change from those of the oboe to those of the clarinet. The frequencies, of course, remain those of the clarinet throughout the process since pvcross does not use the frequency data from the file read by pvbufread.

ktime1	line 	0, p3, 3.5	; used as index in the "oboe.pvoc" data file

ktime2	line 	0, p3, 4.5	; used as index in the "clar.pvoc" data file

kcross 	expon 	.001, p3, 1

pvbufread ktime1, "oboe.pvoc"

apv 	pvcross 	ktime2, 1, "clar.pvoc", 1-kcross, kcross

 In following example using vpvoc shows the use of functions such as

f 1 0 256 5 .001 128 1 128 .001

f 2 0 256 5 1 128 .001 128 1

f 3 0 256 7 1 256 1

to scale the amplitudes of the separate analysis bins.

ktime	line 	0, p3,3 	; time pointer, in seconds, into data file

ktablexseg   1, p3*.5, 2, p3*.5, 3

apv	vpvoc 	ktime,1, "pvoc.file"

The result would be a time-varying "spectral envelope" applied to the phase vocoder analysis data. Since this amplifies or attenuates the amount of signal at the frequencies that are paired with the amplitudes which are scaled by these functions, it has the effect of applying very accurate filters to the signal. In this example the first table would have the effect of a band- pass filter , gradually be band-rejected over half the note's duration, and then go towards no modification of the magnitudes over the second half.


Morphing cross-synthesizer

By PS (New in Csound 3.47)

ar	cross2	ain1, ain2, isize, ioverlap, iwin, kbias

Cross synthesis between two audio signals using FFT's.

INITIALIZATION

isize  -  This is the size of the FFT to be performed.  The larger the size the better the frequency responce but a sloppy time response.

ioverlap  -  This is the overlap factor of the FFT's, must be a power of two.  The best settings are 2 and 4.  A big overlap takes a long time to compile.

iwin   -  This is the ftable that contains the window to be used in the analysis.

PERFORMANCE

ain1  -  The stimulus sound.  Must have high frequencies for best results.

ain2  -  The modulating sound.  Must have a moving frequency response (like speech) for best results.

kbias -  The amount of cross synthesis.  1 is the normal, 0 is no cross synthesis.

EXAMPLE

a1	oscil	10000, 1, 1

a2	rand	10000

a3	cross2	a2, a1, 2048, 4, 2, 1

out	a3

If ftable 1 (one) is a speech sound, this will result in speaking white noise. ftable 2 must be a window function (GEN20).


LPC - Dynamic spectrum modifiers
Dynamic spectrum modifiers

Linear predictive resynthesis

See also LPC interpolation

krmsr, krmso, kerr, kcps \

lpread	ktimpnt, ifilcod[, inpoles][,ifrmrate]

ar	lpreson	asig

ar	lpfreson	asig, kfrqratio

These units, used as a read/reson pair, use a control file of time-varying filter coefficients to dynamically modify the spectrum of an audio signal. The LPC sound analysis file is generated by the Csound utility LPANAL.

INITIALISATION

ifilcod - integer or character-string denoting a control-file (reflection coefficients and four parameter values) derived from n-pole linear predictive spectral analysis of a source audio signal. An integer denotes the suffix of a file lp.m; a character-string (in double quotes) gives a filename, optionally a full pathname. If not fullpath, the file is sought first in the current directory, then in that of the environment variable SADIR (if defined). Memory usage depends on the size of the file, which is held entirely in memory during computation but shared by multiple calls (see also adsyn, pvoc).

inpoles, ifrmrate (optional) - number of poles, and frame rate per second in the lpc analysis. These arguments are required only when the control file does not have a header; they are ignored when a header is detected. The default value for both is zero.

PERFORMANCE

lpread accesses a control file of time-ordered information frames, each containing n-pole filter coefficients derived from linear predictive analysis of a source signal at fixed time intervals (e.g. 1/100 of a second), plus four parameter values:

krmsr - root-mean-square (RMS) of the residual of analysis.

krmso - rms of the original signal.

kerr - the normalized error signal.

kcps - pitch in cps.

lpread gets its values from the control file according to the input value ktimpnt (in seconds). If ktimpnt proceeds at the analysis rate, time-normal synthesis will result; proceeding at a faster, slower, or variable rate will result in time-warped synthesis.

At each k-period, lpread interpolates between adjacent frames to more accurately determine the parameter values (presented as output) and the filter coefficient settings (passed internally to a subsequent lpreson).

The error signal kerr (between 0 and 1) derived during predictive analysis reflects the deterministic/random nature of the analyzed source. This will emerge low for pitched (periodic) material and higher for noisy material. The transition from voiced to unvoiced speech, for example, produces an error signal value of around 0.001 (recommended transition area: 0.0001 - 0.01). During synthesis, the error signal value can be used to determine the nature of the lpreson driving function: for example, by arbitrating between pitched and non-pitched input, or even by determining a mix of the two. In normal speech resynthesis, the pitched input to lpreson is a wideband periodic signal or pulse train derived from a unit such as buzz, and the nonpitched source is usually derived from rand. However, any audio signal can be used as the driving function, the only assumption of the analysis being that it has a flat response.

lpfreson is a formant shifted lpreson, in which kfrqratio is the (cps) ratio of shifted to original formant positions. This permits synthesis in which the source object changes its apparent acoustic size. lpfreson with kfrqratio = 1 is equivalent to lpreson.

Generally, lpreson provides a means whereby the time-varying content and spectral shaping of a composite audio signal can be controlled by the dynamic spectral content of another. There can be any number of lpread/lpreson (or lpfreson) pairs in an instrument or in an orchestra; they can read from the same or different control files independently.


LPC - Pole stabilisation & Interpolation
LPC interpolation

lpslot	islot

lpinterpol	islot1,islot2,kmix

Two opcodes to perform interpolation between pole files of two analyses. These are generated by the Csound utility LPANAL See also LPC resynthesis.

ARGUMENTS

islot - number of slot to be selected [0<islot<20]

islot1 - slot where the first analysis was stored

islot2 - slot where the second analysis was stored

kmix - mix value between the two analysis. Should be between 0 and 1. 0 means analysis 1 only. 1 means analysis 2 only. Any value inbetween will produce interpolation between the filters.

lpslot selects the slot to be use by further lp opcodes (lpread/lpreson). This is the way to load and reference several analyses at the same time.

lpinterpol computes a new set of poles from the interpolation between two analysis. The poles will be stored in the current lpslot and used by the next lpreson opcode.

EXAMPLE

Here is a typical orc using the opcodes:

sr = 44100

kr =  4410

nchnls = 1

instr 1

ipower	init	50000	; Define sound generator

ifreq 	init	440

asrc  	buzz	ipower, ifreq, 10, 1

ktime	line 	0, p3, p3	; Define time line

 	lpslot 	0	; Read square data poles

krmsr,krmso,kerr,kcps  \

lpread  ktime,"square.pol"

 	lpslot 	1	; Read triangle data poles

krmsr,krmso,kerr,kcps  \

lpread  ktime,"triangle.pol"

kmix	line 	0, p3, 1	; Compute result of mixing

 	lpinterp	0, 1, kmix	;     and balance power

ares	lpreson	asrc

aout	balance	ares,asrc

out 	aout

endin


Convolution

Fast Convolution unit generator by Greg Sullivan

ar1[,...[,ar4]]]   convolve	ain,ifilcod,channel

Output is the convolution of signal ain and the impulse response contained in ifilcod, which is created by the Csound utlity CVANAL.Note that it is considerably more efficient to use one instance of the operator when processing a mono input to create stereo, or quad, outputs.

INITIALISATION

ifilcod - integer or character-string denoting an impulse response data file. An integer denotes the suffix of a file convolve.m; a character string (in double quotes) gives a filename, optionally a full pathname.  If not a fullpath, the file is sought first in the the current directory, then in the one given by the environment variable SADIR (if defined). The data file contains the Fourier transform of an impulse response, created by CVANAL. Memory usage depends on the size of the data file, which is read and held entirely in memory during computation, but which is shared by multiple calls.

channel - integer denoting the channel of the impulse response to be used for the convolution. 0 (the default) means to use all channels. For multi-channel output, the number of channels in the impulse response must match the number of output signals.

PERFORMANCE

convolve implements Fast Convolution. The output of this operator is delayed with respect to the input. The following formulas should be used to calculate the delay:

For (1/kr) <= IRdur:

Delay = ceil(IRdur * kr) / kr

For (1/kr) > IRdur:

Delay = IRdur * ceil(1/(kr*IRdur))

Where:

kr  = Csound control rate

IRdur = duration, in seconds, of impulse response

ceil(n) = smallest integer not smaller than n

One should be careful to also take into account the initial delay, if any, of the impulse response. For example, if an impulse response is created from a recording, the soundfile may not have the initial delay included. Thus, one should either ensure that the soundfile has the correct amount of zero padding at the start, or, preferably, compensate for this delay in the orchestra. (the latter method is more efficient). To compensate for the delay in the  orchestra, subtract the initial delay from the result calculated using the above formula(s), when calculating the required delay to introduce into the 'dry' audio path.

For typical applications, such as reverb, the delay will be in  the order of 0.5 to 1.5 seconds, or even longer. This renders the current implementation unsuitable for real time applications. It could conceivably be used for real time filtering however, if  the number of taps is is small enough.

EXAMPLE

1 - Create frequency domain impulse response file:

  c:\> csound -Ucvanal l1_44.wav l1_44.cv

   (one may also use the standalone CVANAL, available either as a DOS command-line program, or through the Winsound dialogs).

2 - Determine duration of impulse response. For high accuracy, determine the number of sample frames in the impulse response soundfile, and then compute the duration with:

  duration = (sample frames)/(sample rate of soundfile)

  This is due to the fact that the SNDINFO utility only reports the duration to the nearest 10ms. If you have a  utility that reports the duration to the required accuracy, then you can simply use the reported value directly.

  c:\> sndinfo l1_44.wav

  length = 60822 samples, sample rate = 44100

  Duration = 60822/44100 = 1.379s.

3 - Determine initial delay, if any, of impulse response.  If the impulse response has not had the initial    delay removed, then you can skip this step. If it has been removed, then the only way you will know the initial delay is if the information has been provided separately.  For this example, let's assume that the initial delay is 60ms. (0.06s)

4 - Determine the required delay to apply to the dry signal, to align it with the convolved signal:

If kr = 441:

1/kr = 0.0023, which is <= IRdur (1.379s), so:

Delay1	= ceil(IRdur * kr) / kr

      	= ceil(608.14) / 441

= 609/441

= 1.38s

  Accounting for the initial delay:

delay2	= 0.06s

Total delay = delay1 - delay2

 	= 1.38 - 0.06

 	= 1.32s

5 - Create .orc file, e.g:

; Simple demonstration of convolve operator, to apply reverb.

sr = 44100

kr = 441

ksmps = 100

nchnls = 2

instr   1

imix = 0.22 	; Wet/dry mix. Vary as desired.

; NB: 'Small' reverbs often require a much higher

; percentage of wet signal to sound interesting. 'Large'

; reverbs seem to require less. Experiment! The wet/dry mix is

; very important - a small change can make a large difference.

ivol = 0.9  	; Overall volume level of reverb. May need to adjust

; when wet/dry mix is changed, to avoid clipping.

idel = 1.32	; Required delay to align dry audio with output of convolve.

; This can be automatically calculated within the orc file,

; if desired.

adry	soundin   "anechoic.wav" 	; input (dry) audio

    awet1,awet2	convolve  adry,"l1_44.cv"	; stereo convolved (wet) audio

adrydel	delay    (1-imix)*adry,idel	; Delay dry signal, to align it with

; convolved signal. Apply level adjustment here too.

outs    ivol*(adrydel+imix*awet1),ivol*(adrydel+imix*awet2)

; Mix wet & dry signals, and output

endin

By Greg Sullivan, sullivan@aussie.enet.dec.com

(Based on algorithm given in 'Elements Of Computer Music', by F. Richard Moore.)


Spectral data types Overview
OPERATIONS USING SPECTRAL DATA-TYPES

These units generate and process non-standard signal data types, such as down-sampled time-domain control signals and audio signals, and their frequency-domain (spectral) representations. The new data types (d-, w-) are self-defining, and the contents are not processable by any other Csound units. These unit generators are experimental, and subject to change between releases; they will also be joined by others later.

wsig	spectrum	xsig, iprd, iocts, ifrqs, iq[,ihann, idbout, idsprd, idsinrs]

wsig	specaddm	wsig1, wsig2[, imul2]

wsig	specdiff	wsigin

wsig	specscal	wsigin, ifscale, ifthresh

wsig	spechist	wsigin

wsig	specfilt	wsigin, ifhtim

koct	specptrk	wsig, inptls, irolloff, iodd[, interp, ifprd, iwtflg]

ksum	specsum	wsig[, interp]

specdisp	wsig, iprd[, iwtflg]


Convert signal to spectral dataype

dsig	octdown	xsig, iocts, isamps[, idisprd]

wsig	noctdft	dsig, iprd, ifrqs, iq[, ihann, idbout, idsines]

INITIALISATION

idisprd (optional) - if non-zero, display the output every idisprd seconds. The default value is 0 (no display).

ihann, idbout, idsines (optional) - if non-zero, then respectively: apply a hanning window to the input; convert the output magnitudes to dB; display the windowed sinusoids used in DFT filtering. The default values are 0,0,0 (rectangular window, magnitude output, no sinusoid display).

PERFORMANCE

octdown - put signal asig or ksig through iocts successive applications of octave decimation and downsampling, and preserve isamps down-sampled values in each octave. Optionally display the composite buffer every idisprd seconds.

noctdft - generate a constant-Q, exponentially-spaced DFT across all octaves of the multiply-downsampled input dsig. Every iprd seconds, each octave of dsig is optionally windowed (ihann non-zero), filtered (using ifrqs parallel filters per octave, exponentially spaced, and with frequency/bandwidth Q of iq), and the output magnitudes optionally converted to dB (idbout non-zero). This unit produces a self-defining spectral datablock wsig, whose characteristics are readable by any units that receive it as input, and for which it becomes the template for output. The information used in producing this wsig (iprd, iocts, ifrqs) is passed via the data block to all derivative wksigs, and is thus available to subsequent spectral operators if needed.

EXAMPLE

asig	in   	; get external audio

dsamp	octdown  asig, 6, 180, 0 	; downsample in 6 octaves

wsig1	noctdft    dsamp, .02, 12, 33, 0, 1, 1	; and calc 72-point dft (dB)


Generate spectral data of type wsig

(New in Csound 3.49)

wsig	spectrum	xsig, iprd, iocts, ifrqs, iq[,ihann, idbout, idsprd, idsinrs]

Generate a constant-Q, exponentially-spaced DFT across all octaves of a multiply-downsampled control or audio input signal.

INITIALIZATION

ihann (optional) - apply a hamming or hanning window to the input. The default is 0 (hamming window)

idbout (optional) - coded conversion of the DFT output: 0 = magnitude, 1 = dB, 2 = mag squared, 3 = root magnitude.  The default value is 0 (magnitude).

idisprd (optional) - if non-zero, display the composite downsampling buffer every idisprd seconds.  The default value is 0 (no display).

idsines (optional) - if non-zero, display the hamming or hanning windowed sinusoids used in DFT filtering.  The default value is 0 (no sinusoid display).

NAME CHANGES

This function used to be performable by octdown and nocdft, but these were removed around Csound 3.46 or so.

PERFORMANCE

This unit first puts the a- or k-rate signal xsig through iocts of successive octave decimation and downsampling, and preserves a buffer of down-sampled values in each octave (optionally displayed as a composite buffer every idisprd seconds).  Then at every iprd seconds, the preserved samples are passed through a filter bank (ifrqs parallel filters per octave, exponentially spaced, with frequency/bandwidth Q of iq), and the output magnitudes optionally converted (idbout ) to produce a band-limited spectrum that can be read by other units.

The stages in this process are computationally intensive, and computation time varies directly with iocts, ifrqs, iq, and inversely with iprd.  Settings of ifrqs = 12, iq = 10, idbout = 3, and iprd = .02 will normally be adequate, but experimentation is encouraged. ifrqs currently has a maximum of 120 divisions per octave.  For audio input, the frequency bins are tuned to coincide with A440.

This unit produces a self-defining spectral datablock wsig, whose characteristics used (iprd, iocts, ifrqs, idbout) are passed via the data block itself to all derivative wsigs.  There can be any number of spectrum units in an instrument or orchestra, but all wsig names must be unique.

EXAMPLE

asig  in	; get external audio

wsig  spectrum  asig,.02,6,12,33,0,1,1	; downsample in 6 octs & calc a 72 pt

;   dft (Q 33, dB out) every 20 msecs


Spectrum local operators

wsig	specaddm	wsig1, wsig2[, imul2]

wsig	specdiff	wsigin

wsig	specscal	wsigin, ifscale, ifthresh

wsig	spechist	wsigin

wsig	specfilt	wsigin, ifhtim

INITIALISATION

imul2 (optional) - if non-zero, scale the wsig2 magnitudes before adding. The default value is 0.

PERFORMANCE

specaddm - do a weighted add of two input spectra. For each channel of the two input spectra, the two magnitudes are combined and written to the output according to: magout = mag1in + mag2in * imul2. The operation is performed whenever the input wsig1 is sensed to be new. This unit will (at Initialisation) verify the consistency of the two spectra (equal size, equal period, equal mag types).

specdiff - find the positive difference values between consecutive spectral frames. At each new frame of wsigin, each magnitude value is compared with its predecessor, and the positive changes written to the output spectrum. This unit is useful as an energy onset detector.

specscal - scale an input spectral datablock with spectral envelopes. Function tables ifthresh and ifscale are initially sampled across the (logarithmic) frequency space of the input spectrum; then each time a new input spectrum is sensed the sampled values are used to scale each of its magnitude channels as follows: if ifthresh is non-zero, each magnitude is reduced by its corresponding table-value (to not less than zero); then each magnitude is rescaled by the corresponding ifscale value, and the resulting spectrum written to wsig.

spechist - accumulate the values of successive spectral frames. At each new frame of wsigin, the accumulations-to-date in each magnitude track are written to the output spectrum. This unit thus provides a running histogram of spectral distribution.

specfilt - filter each channel of an input spectrum. At each new frame of wsigin, each magnitude value is injected into a 1st-order lowpass recursive filter, whose half-time constant has been initially set by sampling the ftable ifhtim across the (logarithmic) frequency space of the input spectrum. This unit effectively applies a persistence factor to the data occurring in each spectral channel, and is useful for simulating the energy integration that occurs during auditory perception. It may also be used as a time-attenuated running histogram of the spectral distribution.

EXAMPLE

wsig2  	specdiff	wsig1	; sense onsets

wsig3  	specfilt	wsig2, 2	; absorb slowly

specdisp	wsig2, .1 	; & display both spectra

specdisp	wsig3, .1


Spectrum global operators

koct	specptrk	wsig, inptls, irolloff, iodd[, interp, ifprd, iwtflg]

ksum	specsum	wsig[, interp]

specdisp	wsig, iprd[, iwtflg]

INITIALISATION

interp (optional) - if non-zero, interpolate the output signal (koct or ksum). The default value is 0 (repeat the signal value between changes).

ifprd (optional) - if non-zero, display the internally computed fundamental spectrum. The default value is 0 (no display).

iwtflg (optional) - wait flag. If non-zero, hold each display until released by the user. The default value is 0 (no wait).

PERFORMANCE

specptrk - estimate the pitch of the most prominent complex tone in the spectrum. At note initialization this unit creates a set of inptls harmonically related partials (odd if iodd non-zero) with amplitude rolloff to the fraction irolloff per octave. Then at each new frame of wsig, the spectrum is cross-correlated with this set, and the result at each point added to an internal copy of the spectrum (optionally displayed). A pitch is then estimated, and the result is released in decimal octave form. Between frames, the output is either repeated or interpolated at the K-rate.

specsum - sum the magnitudes across all channels of the spectrum. At each new frame of wsig, the magnitudes are summed and released as a scalar ksum signal. Between frames, the output is either repeated or interpolated at the k-rate. This unit produces a k-signal summation of the magnitudes present in the spectral data, and is thereby a running measure of its moment-to-moment overall strength.

specdisp - display the magnitude values of spectrum wsig every iprd seconds (rounded to some integral number of wsig's originating iprd).

EXAMPLE

ksum	specsum   wsig,  1	; sum the spec bins, and ksmooth

     if	ksum < 2000     kgoto  zero	; if sufficient amplitude

koct	specptrk   wsig	;    pitch-track the signal

kgoto   contin

zero:	koct =  0  	; else output zero

contin:

. . .


Gen Routines Overview
GEN Routines

The GEN subroutines are function-drawing procedures called by f statements to construct stored wavetables.  They are available throughout orchestra performance, and can be invoked at any point in the score as given by p2.  p1 assigns a table number, and p3 the table size (see f statement).  p4 specifies the GEN routine to be called; each GEN routine will assign special meaning to the pfield values that follow.

New: As of Csound version 3.47, there is also a function table generator opcode, ftgen, to generate function tables in Csound orchestra files.

GEN01 - Soundfile input

GEN02 - List of literal values

GEN03 - Polynomial function

GEN04 - Normalizing function

GEN05, GEN07 - Exponential/line segments

GEN06 - Cubic polynomial segments

GEN08 - Cubic spline curve (smoothest possible path through given points)

GEN09, GEN10, GEN19 - Sums of weighted sinusoids

GEN11 - Additive set of cosine partials

GEN12 - Bessel function

GEN13, GEN14 - Chebyshev functions

GEN15 - Phase quadrature (of dual Chebyshev function tables)

GEN17 - Step function

GEN20 - Generate windows

GEN21 - Random distributions

GEN23 - Read values from an ASCII text file

GEN25, GEN27 - Exponential/line segments using breakpoint style arguments.

GEN28 - Read text file with information for space and spdist


GEN01- Soundfile input
GEN 01

Transfer data from a soundfile into a function table.

f  #  time  size  1  filcod  skiptime  format  channel

#, time  - the usual GEN parameters. See f statement.

size - number of points in the table.  Ordinarily a power of 2 or a power-of-2 plus 1 (see f statement); the maximum table size is 16777216 (2**24) points. If the source soundfile is of type AIFF, allocation of table memory can be deferred by setting this parameter to 0; the size allocated is then the number of points in the file (probably not a power-of-2), and the table is not usable by normal oscillators, but it is usable by eg a loscil unit.  An AIFF source can also be mono or stereo.

filcod - integer or character-string denoting the source soundfile name.  An integer denotes the file soundin.filcod ; a character-string (in double quotes, spaces permitted) gives the filename itself, optionally a full pathname.  If not a full path, the file is sought first in the current directory, then in that given by the environment variable SSDIR (if defined) then by SFDIR.  See also soundin.

skiptime - begin reading at skiptime seconds into the file.

format  - specifies the audio data-file format:

1 - 8-bit signed character

2 - 8-bit A-law bytes

3 - 8-bit U-law bytes

4 - 16-bit short integers

5 - 32-bit long integers

6 - 32-bit floats

If format = 0 the sample format is taken from the soundfile header, or by default from the csound -o command flag.

channel - read only a specific channel (1,2,3 or 4) from the file.  A zero means read all channels.

Reading stops at end-of-file or when the table is full.  Table locations not filled will contain zeros.

NOTE

If p4 is positive, the table will be post-normalized (rescaled to a maximum absolute value of 1 after generation).  A negative p4 will cause rescaling to be skipped.

EXAMPLES

 f  1  0  8192  1  23  0  4   2

 f  2  0  0  -1  "trumpet  A#5"  0  4   0

The tables are filled from 2 files, "soundin.23" and "trumpet A#5", expected in SSDIR or SFDIR.  The first table is pre-allocated;  the second is allocated dynamically, and its rescaling is inhibited. From the first, only channel 2 is read, from the second, all channels are included.


GEN02 - List of literal values
GEN02

List of literal values

f  #  time  size  2  v1  v2  v3  .  .  .

#, time, size - the usual GEN parameters. See f statement.

v1, v2, v3, ... - values to be copied directly into the table space.  The number of values is limited by the compile-time variable PMAX, which controls the maximum pfields (currently 150).  The values copied may include the table guard point;  any table locations not filled will contain zeros.

This subroutine transfers data from immediate pfields into a function table.

NOTE

If p4 is positive, the table will be post-normalized (rescaled to a maximum absolute value of 1 after generation).  A negative p4 will cause rescaling to be skipped.

EXAMPLE

     f   1  0  16  -2  0  1  2  3  4  5  6  7  8  9  10  11  0

This calls upon GEN02 to place 12 values plus an explicit wrap-around guard value into a table of size next-highest power of 2.  Rescaling is inhibited.


GEN03 - Polynomial function
GEN03

Polynomial function

This subroutine generates a stored function table by evaluating a polynomial in x over a fixed interval and with specified coefficients.

f  #  time  size  3  xval1  xval2  c0  c1  c2  .  .  .  cn

#, time, size - the usual GEN parameters. See f statement.

xval1, xval2 - left and right values of the x interval over which the polynomial is defined (xval1 < xval2).  These will produce the 1st stored value and the (power-of-2 plus l)th stored value respectively in the generated function table.

c0, c1, c2,  ...  cn  - coefficients of the nth-order polynomial  c0 + c1x + c2x2 + .  .  .  + cnxn

Coefficients may be positive or negative real numbers; a zero denotes a missing term in the polynomial.  The coefficient list begins in p7, providing a current upper limit of 144 terms. The defined segment [fn(xval1),fn(xval2)] is evenly distributed.  Thus a 512-point table over the interval [-1,1] will have its origin at location 257 (at the start of the 2nd half).  Provided the extended guard point is requested, both fn(-1) and fn(1) will exist in the table.

GEN03 is useful in conjunction with table or tablei for audio waveshaping (sound modification by non-linear distortion).  Coefficients to produce a particular formant from a sinusoidal lookup index of known amplitude can be determined at preprocessing time using algorithms such as Chebyshev formulae.  See also GEN13.

EXAMPLE

     f   1  0   1025  3  -1  1  5  4  3  2  2  1

This calls GEN03 to fill a table with a 4th order polynomial function over the x-interval -1 to 1.  The origin will be at the offset position 512.  The function is post-normalized.


GEN04 - Normalizing function
GEN04

Generates a normalizing function by examining the contents of an existing table.

f  #  time  size  4  source#  sourcemode

#, time, size - the usual GEN parameters. See f statement.

source #  -  table number of stored function to be examined.

sourcemode - a coded value, specifying how the source table is to be scanned to obtain the normalizing function.  Zero indicates that the source is to be scanned from left to right.  Non-zero indicates that the source has a bipolar structure; scanning will begin at the mid-point and progress outwards, looking at pairs of points equidistant from the center.

NOTE

The normalizing function derives from the progressive absolute maxima of the source table being scanned.  The new table is created left-to-right, with stored values equal to 1/(absolute maximum so far scanned).  Stored values will thus begin with 1/(first value scanned), then get progressively smaller as new maxima are encountered.  For a source table which is normalized (values <= 1), the derived values will range from 1/(first value scanned) down to 1.  If the first value scanned is zero, that inverse will be set to 1.

The normalizing function from GEN04 is not itself normalized.

GEN04 is useful for scaling a table-derived signal so that it has a consistent peak amplitude.  A particular application occurs in waveshaping when the carrier (or indexing) signal is less than full amplitude.

EXAMPLE

f   2   0   512   4    1   1

This creates a normalizing function for use in connection with the GEN03 table 1 example.  Midpoint bipolar offset is specified.


GEN05, GEN07 - Exponential / Line segments
GEN05, GEN07

These subroutines are used to construct functions from segments of exponential curves (GEN05) or straight lines (GEN07).  You can do the same with GEN25, GEN27, but using breakpoint style arguments

f  #    time    size   5   a   n1   b   n2   c  .  .  .

f  #    time    size   7   a   n1   b   n2   c  .  .  .

#, time, size - the usual GEN parameters. See f statement.

a, b, c, etc.  - ordinate values, in odd-numbered pfields p5, p7, p9, .  .  .  For GEN05 these must be nonzero and must be alike in sign.  No such restrictions exist for GEN07.

n1, n2, etc.  - length of segment (no.  of storage locations), in even-numbered pfields.  Cannot be negative, but a zero is meaningful for specifying discontinuous waveforms (e.g. in the example below).  The sum n1 + n2 + ....  will normally equal size for fully specified functions.  If the sum is smaller, the function locations not included will be set to zero; if the sum is greater, only the first size locations will be stored.

NOTE

If p4 is positive, functions are post-normalized (rescaled to a maximum absolute value of 1 after generation).  A negative p4 will cause rescaling to be skipped.

Discrete-point linear interpolation implies an increase or decrease along a segment by equal differences between adjacent locations; exponential interpolation implies that the progression is by equal ratio.  In both forms the interpolation from a to b is such as to assume that the value b will be attained in the n + 1th location.  For discontinuous functions, and for the segment encompassing the end location, this value will not actually be reached, although it may eventually appear as a result of final scaling.

EXAMPLE

f   1   0   256   7   0   128   1   0   -1   128   0

This describes a single-cycle sawtooth whose discontinuity is mid-way in the stored function.


GEN06 - Cubic polynomial segments
GEN06

This subroutine will generate a function comprised of segments of cubic polynomials, spanning specified points just three at a time.

f  #   time   size   6   a   n1   b   n2   c   n3   d .  .

.

#, time, size - the usual GEN parameters. See f statement.

a, c, e, ...  - local maxima or minima of successive segments, depending on the relation of these points to adjacent inflexions.  May be either positive or negative.

b, d, f, ...  - ordinate values of points of inflexion at the ends of successive curved segments.  May be positive or negative.

n1, n2, n3...  - number of stored values between specified points.  Cannot be negative, but a zero is meaningful for specifying discontinuities.  The sum n1 + n2 + ...  will normally equal size for fully specified functions.  (for details, see GEN05).

NOTE

GEN06 constructs a stored function from segments of cubic polynomial functions.  Segments link ordinate values in groups of 3: point of inflexion, maximum/minimum, point of inflexion.  The first complete segment encompasses b,c,d and has length n2 + n3, the next encompasses d,e,f and has length n4 + n5, etc.  The first segment (a,b with length n1) is partial with only one inflexion; the last segment may be partial too.  Although the inflexion points b,d,f ...  each figure in two segments (to the left and right), the slope of the two segments remains independent at that common point (i.e.  the 1st derivative will likely be discontinuous).  When a,c,e...  are alternately maximum and minimum, the inflexion joins will be relatively smooth; for successive maxima or successive minima the inflexions will be comb-like.

EXAMPLE

f    1    0    65    6   0   16   .5    16   1   16   0   16  -1

This creates a curve running 0 to 1 to -1, with a minimum, maximum and minimum at these values respectively.  Inflexions are at  .5 and 0, and are relatively smooth.


GEN08 - Cubic spline curve (smoothest possible path)
GEN08

This subroutine will generate a piecewise cubic spline curve, the smoothest possible path through all specified points.

f #   time   size    8    a    n1    b    n2    c    n3   d  .  .  .

#, time, size - the usual GEN parameters. See f statement.

a, b, c ... - ordinate values of the function.

n1, n2, n3  ... - length of each segment measured in stored values.  May not be zero, but may be fractional.  A particular segment may or may not actually store any values; stored values will be generated at integral points from the beginning of the function.  The sum n1 + n2 + ... will normally equal size for fully specified functions.

NOTE

GEN08 constructs a stored table from segments of cubic polynomial functions.  Each segment runs between two specified points but depends as well on their neighbors on each side.  Neighboring segments will agree in both value and slope at their common point.  (The common slope is that of a parabola through that point and its two neighbors).  The slope at the two ends of the function is constrained to be zero (flat).

HINT:  to make a discontinuity in slope or value in the function as stored, arrange a series of points in the interval between two stored values; likewise for a non-zero boundary slope.

EXAMPLES

f    1    0    65    8    0    16    0    16    1    16    0   16    0

This example creates a curve with a smooth hump in the middle, going briefly negative outside the hump then flat at its ends.

f    2    0    65    8    0    16    0   .1    0    15.9   1    15.9    0    .1    0    16    0

This example is similar, but does not go negative.


GEN09, GEN10, GEN19 - Sums of weighted sinusoids
GEN09, GEN10, GEN19

These subroutines generate composite waveforms made up of weighted sums of simple sinusoids.  The specification of each contributing partial requires 3 pfields using GEN09, 1 using GEN10, and 4 using GEN19.

f   #    time    size    9      pna     stra    phsa    pnb   strb    phsb  .  .  .

f   #    time    size  10      str1     str2    str3     str4  .  .  .  .

f   #    time    size  19      pna     stra    phsa    dcoa   pnb    strb    phsb   dcob  .  .  .

#, time, size - the usual GEN parameters. See f statement.

pna, pnb, etc.  - partial no.  (relative to a fundamental that would occupy size locations per cycle) of sinusoid a, sinusoid b, etc.  Must be positive, but need not be a whole number, i.e., non-harmonic partials are permitted.  Partials may be in any order.

stra, strb, etc.  - strength of partials pna, pnb, etc.  These are relative strengths, since the composite waveform may be rescaled later.  Negative values are permitted and imply a 180 degree phase shift.

phsa, phsb, etc.  - initial phase of partials pna, pnb, etc., expressed in degrees.

dcoa, dcob,  etc.  - DC offset of partials pna, pnb, etc.  This is applied after strength scaling, i.e. a value of 2 will lift a 2-strength sinusoid from range [-2,2] to range [0,4]  (before later rescaling).

str1, str2, str3, etc.  - relative strengths of the fixed harmonic partial numbers 1,2,3, etc., beginning in p5.  Partials not required should be given a strength of zero.

NOTE

These subroutines generate stored functions as sums of sinusoids of different frequencies.  The two major restrictions on GEN10 - that the partials be harmonic and in phase - do not apply to GEN09 or GEN19.

In each case the composite wave, once drawn, is then rescaled to unity if p4 was positive.  A negative p4 will cause rescaling to be skipped.

EXAMPLES

f    1    0    1024      9    1    3      0    3    1    0   9   .3333    180

f    2    0    1024    19    .5   1  270    1

f 1 combines partials l, 3 and 9 in the relative strengths in which they are found in a square wave, except that partial 9 is upside down.   f 2 creates a rising sigmoid [0 - 2].   Both will be rescaled.


GEN11 - Additive set of cosine partials
GEN11

This subroutine generates an additive set of cosine partials, in the manner of Csound generators buzz and gbuzz.

f    #    time    size    11    nh    lh    r

#, time, size - the usual GEN parameters. See f statement.

nh 	- number of harmonics requested.  Must be positive.

lh (optional) - lowest harmonic partial present.  Can be positive, zero or negative.  The set of partials can begin at any partial number and proceeds upwards; if lh is negative, all partials below zero will reflect in zero to produce positive partials without phase change (since cosine is an even function), and will add constructively to any positive partials in the set.  The default value is 1.

r (optional) - multiplier in an amplitude coefficient series.  This is a power series: if the lhth partial has a strength coefficient of A the (lh + n)th partial will have a coefficient of A * r**n, i.e.  strength values trace an exponential curve.  r may be positive, zero or negative, and is not restricted to integers.  The default value is 1.

NOTE

This subroutine is a non-time-varying version of the csound buzz and gbuzz generators, and is similarly useful as a complex sound source in subtractive synthesis.  With lh and r present it parallels gbuzz; with both absent or equal to 1 it reduces to the simpler buzz (i.e. nh equal-strength harmonic partials beginning with the fundamental).

Sampling the stored waveform with an oscillator is more efficient than using dynamic buzz units.  However, the spectral content is invariant, and care is necessary lest the higher partials exceed the Nyquist during sampling to produce foldover.

EXAMPLES

f  1    0    2049   11    4

f  2    0    2049   11    4    1    1

f  3    0    2049  -11    7    3   .5

The first two tables will contain identical band-limited pulse waves of four equal-strength harmonic partials beginning with the fundamental.  The third table will sum seven consecutive harmonics, beginning with the third, and at progressively weaker strengths (1, .5, .25, .125 .  .  .).  It will not be post-normalized.


GEN12 - Bessel function
GEN12

This generates the log of a modified Bessel function of the second kind, order 0, suitable for use in amplitude-modulated FM.

f    #    time    size    -12    xint

#, time, size - the usual GEN parameters. See f statement.

xint - specifies the x interval [0 to +int] over which the function is defined.

NOTE

This subroutine draws the natural log of a modified Bessel function of the second kind, order 0 (commonly written as I subscript 0), over the x-interval requested.  The call should have rescaling inhibited.

The function is useful as an amplitude scaling factor in cycle-synchronous amplitude-modulated FM.  (See Palamin & Palamin, J. Audio Eng. Soc., 36/9, Sept. 1988, pp.671-684.) The algorithm is interesting because it permits the normally symmetric FM spectrum to be made asymmetric around a frequency other than the carrier, and is thereby useful for formant positioning.  By using a table lookup index of I(r - 1/r), where I is the FM modulation index and r is an exponential parameter affecting partial strengths, the Palamin algorithm becomes relatively efficient, requiring only oscil's, table lookups, and a single exp call.

EXAMPLE

     f    1    0    2049    -12    20

This draws an unscaled ln(I0(x)) from 0 to 20.


GEN13, GEN14 - Chebyshev functions
GEN13, GEN14

These subroutines use Chebyshev coefficients to generate stored polynomial functions which, under waveshaping, can be used to split a sinusoid into harmonic partials having a predefinable spectrum.

f    #    time    size    13    xint    xamp    h0    h1   h2  .  .  .  hn

f    #    time    size    14    xint    xamp    h0    h1   h2  .  .  .  hn

#, time, size - the usual GEN parameters. See f statement.

xint - provides the left and right values [-xint,  +xint] of the x interval over which the polynomial is to be drawn.  These subroutines both call GEN03 to draw their functions; the p5 value here is therefor expanded to a negative-positive p5,p6 pair before GEN03 is actually called.  The normal value is 1.

xamp - amplitude scaling factor of the sinusoid input that is expected to produce the following spectrum.

h0, h1, h2, ....  hn - relative strength of partials 0 (DC), 1 (fundamental), 2 ...  that will result when a sinusoid of amplitude xamp * int(size/2)/xint is waveshaped using this function table.  These values thus describe a frequency spectrum associated with a particular factor xamp of the input signal.

NOTE

GEN13 is the function generator normally employed in standard waveshaping.  It stores a polynomial whose coefficients derive from the Chebyshev polynomials of the first kind, so that a driving sinusoid of strength xamp will exhibit the specified spectrum at output.  Note that the evolution of this spectrum is generally not linear with varying xamp.  However, it is bandlimited (the only partials to appear will be those specified at generation time); and the partials will tend to occur and to develop in ascending order (the lower partials dominating at low xamp, and the spectral richness increasing for higher values of xamp).  A negative hn value implies a 180 degree phase shift of that partial; the requested full-amplitude spectrum will not be affected by this shift, although the evolution of several of its component partials may be.  The pattern +,+,-,-,+,+,...  for h0,h1,h2...  will minimize the normalization problem for low xamp values (see above), but does not necessarily provide the smoothest pattern of evolution.

GEN14 stores a polynomial whose coefficients derive from Chebyshevs of the second kind.

EXAMPLE

f    1    0   1025    13    1   1    0    5    0    3    0   1

This creates a function which, under waveshaping, will split a sinusoid into 3 odd-harmonic partials of relative strength 5:3:1.


GEN15 - Phase quadrature (Chebyshev)
GEN15

This subroutine creates two tables of stored polynomial functions, suitable for use in phase quadrature operations.

f    #    time    size    15    xint    xamp    h0    phs0   h1    phs1    h2    phs2  .  .  .

#, time, size - the usual GEN parameters. See f statement.

xint - provides the left and right values [-xint,  +xint] of the x interval over which the polynomial is to be drawn.  This subroutine will eventually call GEN03 to draw both functions; this p5 value is therefor expanded to a negative-positive p5, p6 pair before GEN03 is actually called.  The normal value is 1.

xamp - amplitude scaling factor of the sinusoid input that is expected to produce the following spectrum.

h0, h1, h2, ... hn - relative strength of partials 0 (DC), 1 (fundamental), 2 ...  that will result when a sinusoid of amplitude xamp * int(size/2)/xint is waveshaped using this function table.  These values thus describe a frequency spectrum associated with a particular factor xamp of the input signal.

phs0, phs1, ...  - phase in degrees of desired harmonics h0, h1, ...  when the two functions of GEN15 are used with phase quadrature.

NOTE

GEN15 creates two tables of equal size, labelled f # and f # + 1.  Table # will contain a Chebyshev function of the first kind, drawn using GEN03 with partial strengths h0cos(phs0), h1cos(phs1), ...  Table #+1 will contain a Chebyshev function of the 2nd kind by calling GEN14 with partials h1 sin(phs1), h2sin(phs2),...  (note the harmonic displacement).  The two tables can be used in conjunction in a waveshaping network that exploits phase quadrature.


GEN17 - Step function
GEN17

This subroutine creates a step function from given x-y pairs.

f  #   time  size  17    x1  a  x2  b  x3  c  .  .  .

#, time, size - the usual GEN parameters. See f statement.

x1, x2, x3, etc. - x-ordinate values, in ascending order, 0 first.

a, b, c, etc. - y-values at those x-ordinates, held until the next x-ordinate.

This subroutine creates a step function of x-y pairs whose y-values are held to the right.  The right-most y-value is then held to the end of the table.  The function is useful for mapping one set of data values onto another, such as MIDI note numbers onto sampled sound ftable numbers  (see loscil).

EXAMPLE

f  1  0  128  -17   0  1   12  2   24  3   36  4   48  5  60  6   72  7   84  8

This describes a step function with 8 successively increasing levels, each 12 locations wide except the last which extends its value to the end of the table.  Rescaling is inhibited.  Indexing into this table with a MIDI note-number would retrieve a different value every octave up to the eighth, above which the value returned would remain the same.


GEN20 - Generate windows
GEN20

Window functions

This subroutine generates functions of different windows. These windows are usually used for spectrum analysis or for grain envelopes.

f  #   time   size   20   window  max  opt

#, time, size - the usual GEN parameters. See f statement.

window  - Type of window to generate:

1 - Hamming

2 - Hanning

3 - Bartlett ( triangle)

4 - Blackman ( 3 - term)

5 - Blackman - Harris ( 4 - term)

6 - Gaussian

7 - Kaiser

8 - Rectangle

9 - Sinc

max - For negative p4 this will be the absolute value at window peak point.  If p4 is positive or p4 is negative and p6 is missing the table will be post-rescaled to a maximum value of 1.

opt - Optional argument required by the Kaiser window.

EXAMPLES

f  1   0   1024   20   5

This creates a function which contains a 4 - term Blackman - Harris  window with maximum value of 1.

f  1   0   1024   -20   2   456

This creates a function that contains a Hanning window with a maximum  value of 456.

   f   1   0   1024   -20   1

This creates a function that contains a Hamming window with a maximum  value of 1.

   f   1   0   1024   20   7   1   2

This creates a function that contains a Kaiser window with a maximum  value of 1.  The extra argument specifies how open' the window is, for  example a value of 0 results in a rectangular window and a value of 10 in  a Hamming like window.


GEN21 - Random distributions
GEN21

This generates tables of different random distributions. (see also Non-uniform random unit generators).

f  #   time   size   21   type    lvl  arg1  arg2

#, time, size - the usual GEN parameters. See f statement.

type defines the  distribution to be used:

1   - Uniform

2   - Linear

3   - Triangular

4   - Exponential

5   - Biexponential

6   - Gaussian

7   - Cauchy

8   - Positive Cauchy

9   - Beta

10  - Weibull

11  - Poison

Of all these cases only 9 (Beta) and 10 (Weibull) need extra arguments.  Beta needs two arguments and Weibull one.

EXAMPLES

f 1   0  1024   21    1	; Uniform (white noise)

f 1   0  1024   21    6	; Gaussian

f 1   0  1024   21    9   1   1   2	; Beta (note that level precedes arguments)

f 1   0  1024   21  10   1   2   	; Weibull


GEN23 - Read values from an ASCII text file
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 character 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).


GEN25, GEN27 Line segments (breakpoint fashion)
GEN25, GEN27

These subroutines are used to construct functions from segments of exponential curves (GEN25) or straight lines (GEN27) in breakpoint fashion. See also GEN05 and GEN07.

f #  time  size  25  x1 y1 x2 y2 x3 y3 . . .

f #  time  size  27  x1 y1 x2 y2 x3 y3 . . .

#, time, size - the usual GEN parameters. See f statement.

x1, x2, x3, etc. - locations in table at which to attain the following y value. Must be in increasing order.  If the last value is less than size, then the rest will be set to zero.  Should not be negative but can be zero.

y1, y2, y3,  etc. - Breakpoint values attained at the location specified by the preceding x value.  For GEN25 these must be non-zero and must be alike in sign.  No such restrictions exist for GEN27.

NOTE: If p4 is positive, functions are post-normalized (rescaled to a maximum absolute value of 1 after generation).  A negative p4 will cause rescaling to be skipped.

EXAMPLES

f 1 0 257 27 0 0 100 1 200 -1 256 0

Describes a function which begins at 0, rises to 1 at the 100th table location, falls to -1, by the 200th location, and returns to 0 by the end of the table.  The interpolation is linear.

f 1 0 257 25 0 0.001 100 1 200 .001 256 0.001

Similar to above, but creates exponential curve. No values <= 0 are allowed in GEN25


GEN28 - Read text file with information for space and spdist
GEN28

This function generator reads a text file and generates spatialisation data for the opcodes space and spdist.

f #  time  size  28  filename

The size argument should be zero: GEN28 automatically allocates memory.

This function generator reads a text file which contains sets of three values representing the xy coordinates and a time-tag for when the signal should be placed at that location. The file should contain ASCII numbers, in the format:

(time    X      Y)

  0        -1       1

  1         1       1

  2         4       4

  2.1     -4      -4

  3       10    -10

  5      -40       0

(The text (time X Y) should of course not be in the file.) If that file were named "move" then the GEN28 call in the score would look like:

f1  0  0  28  "move"

GEN28 takes 0 as the size and automatically allocates memory. It creates values to 10 milliseconds of resolution. So in the above example there will be 500 values created by interpolating X1 to X2 to X3 and so on, and Y1 to Y2 to Y3 and so on, over the appropriate number of values that are stored in the function table. In the above example, the sound will begin in the left front, over 1 second it will move to the right front, over another second it move further into the distance but still in the left front, then in just 1/10th of a second it moves to the left rear, a bit distant. Finally over the last .9 seconds the sound will move to the right rear, moderately distant, and it comes to rest between the two left channels (due west!), quite distant. Since the values in the table are accessed through the use of a time-ponter in the space unit, the actual timing can be made to follow the file's timing exactly or it can be made to go faster or slower through the same trajectory.

If you have access to the GUI that allows one to draw and edit the files, there is no need to create the text files manually. But as long as the file is ASCII and in the format shown above, it doesn't matter how it is made!


ïContents:

Main overview.

TABLE READ/WRITE: Table manipulation overview; tablekt tableikt, tableng, itablew tablew tablewk tablewkt itablegpw tablegpw, itablecopy tablecopy, itablemix tablemix, tablera tablewa,

THE ZAK SYSTEM: ZAK overview;  zakinit, zir zkr zar ziw zkw zaw ziwm zkwm zawm zkcl zacl, zkmod zamod,

TIME-READING UGENS: timek times instimek imstimes

 K-RATE PRINTING: printk printk2 printks

K-RATE SIGNAL FILTERS: portk tonek resonk aresonk

31-bit noise programmers note.


Robin Whittles new ugens - overview
Robin Whittle's new ugens

DOCUMENTATION

Table manipulation overview

The "zak" system

Filters for k-rate signals

Time reading ugens

Two ugens for k-rate printing

31-bit random number generators

OVERVIEW OF THE NEW UNIT GENERATORS

(Most of these opcodes were included in the Bath/Montreal release 3.46, as indicated in the documentation.)

1)	For writing directly into function tables at i- k- or a rates - with i- or k-rate control of the table  number.

2)	Ugens for manipulating data in tables: tablegpw, tableng, tablemix and tablecopy.

3)	Ugens for reading and writing to table locations sequentially  from a-rate variables.  One of the uses of this is to read a  rate data into a table (or several a rates into several  tables), and use any k-rate code to process the data, before  converting it back to a rate.  This means that when you really  want to, you can use all of Csounds ugens and operations on a  rate code.  It is somewhat slow, but faster than running with  ksmps = 1 and using upsamp and downsamp.

4)	Global patching of i-, k- and a-rate signals based on numbers  generated at i- or k- rate.  This is really a fudge until the  language supports arrays.  This is called the "zak" system.  However it is extremely useful.  There is a numbered set of  "zk" k-rate patch points and another set of "za" a-rate patch  points.  A variety of ugens read, write and mix to these -  with k-rate control over which patch point is used.  This  enables the code in each instrument to decide where to get and  send a and k-rate signals when working with other instruments.

5)	Simple ugens to read the time elapsed since the start of the  piece or the initialisation of the instrument.

6)	Two ugens for printing k-rate variables as numbers on the  screen.  The second of these allows four variables to be  printed in the midst of a text string - by printf().  It also  allows any byte to be printed and makes it easy to insert  escape codes into the text for cursor control.

7)	kport - a low pass filter for k-rate variables like port, but now with a k-rate frequency control.

8)	Filters for k-rate variables: ktone, katone, kreson & kareson

9)	limit ugen for setting k- (or i-) rate upper and lower limits on i- k- or a-rate variables.

10)	A 31 bit random number generator replaces the previous 15 bit one.  A seed ugen is provided to set it.  These are really programmers notes.

This global random number generator is used for all of the new  set of noise (random number) ugens introduced early in 1995  by Paris Smarargdis - the linrand family. (These modifications have not yet been incorporated into any Bath/Montreal release)

11)	To complete the family, there is now an unirand ugen for uniform distribution of random numbers between 0 and the value given to the ugen. (Included in Bath/Montreal release 3.45, though not in its 31-bit version)

This documents the features of my 1995 additions to Csound. There are no example files in this release.

Your comments, bug reports and carefully considered suggestions about new unit generators are welcome!

- Robin Whittle 11 September 1995

Copyright notice


Function table manipulation - overview
 Table manipulation - Overview

By Robin Whittle (New in Csound 3.46)

K-rate Table Read

Table read ugens tablekt, tableikt

What the table read ugens should do

Table terminology

Get Table Info

Determine table length tableng

Copy a function table tablecopy

Modify Function Tables

Table write overview

Write into a function table tablew, tablewk, tablewkt, tablegpw

Mix two tables tablemix

Table read/write sequential locations tablera, tablewa

WHAT THE TABLE READ UGENS SHOULD DO

Consider an example table with 5 entries:

Location        0       1       2       3       4

Value           10      11      12      13      10

The main body of the table is locations 0 to 3.  Location 4 is the guard point.  Not all tables have one, but if you are doing interpolated reading with total indexes above 3, then you will be reading both locations 3 and 4, and taking a fraction of each for your output.

"Total index" here means the index generated from the ndx and xoff parameters in the table or tablei command line, after being scaled by the "Normalisation factor".

The "Normalisation factor" is internal to the ugen.  Usually it is 1 - so for this table, the range of the ndx and xoff would be 0 to 3 or 4.

If parameter ixmode is set to 1, then the normalisation factor is set to the table length so that an input ranges of 0 to 1 can be used for both ndx and xoff.

"Table length" is a tricky thing.  In this discussion, I will use it as meaning the power of two number which is the table size, not including the guardpoint.  There is something of a mystery about how this guardpoint survives, because the code which allocates memory seems to do it on the basis of the table length, whereas tables can be specified to have a guardpoint - one more than this length.

The FUNC data structure which describes the table gives no indication of whether the table has a guard point.  The table length there is always a power of 2. So in our example, the length is 4, but there are 5 entries including the guard point.  Sorry about this terminology.

The guardpoint seems intended to allow interpolated reading to produce a smooth waveform.  In this case, its value is set to the same as that of location 0.  However it could be set to any other value if the aim was not to produce a smooth waveform with an interpolated oscillator or cyclic table read.

If location 4 contained 14, then an interpolated read would produce a sawtooth with a sharp edge at the end of the waveform - falling to 10 at index 0.

So the basic function of ndx, ixmode and ixoff are now clear, as is the function of interpolated read.

What does ixwrap do?

Without ixwrap, or if it is set to 0, the ugen is in what I call "Limit mode".  Its behavior differs depending on whether it is interpolated or not - but the concept is the same.

TABLE TERMINOLOGY

"Total index" is the sum of xndx and ixoff, after being scaled according to ixmode.

"Final index" is the total index, after it has been limited to something within the length of the table, either as a result of "limit" or "wrap" mode.

The final index determines where the table is read from and so determines the final result.

In Limit mode, final indexes below 0 are limited to 0 and so the value of location 0 is read for all 0 and negative total indexes.  This is the same for table and tablei.

In non-interpolated table read, total indexes higher than 3 are limited to a final index of 3, and the value at location 3 is read out.

In interpolated table read, if the total index is above 4.0, it is limited to a final index of 4.0 and the value of the guardpoint is read out. This means that a set of 5 interpolated segments bridges the 0 to 4 total index range.

Wrap mode - when ixwrap = 1 - is when the total index is truncated modulo the table length to give continuous scanning of the table no matter what the total index is.  So in interpolate mode, a steadily increasing total index would produce a final index rising as a sawtooth from 0 to 3.9999 repeatedly. With interpolation this would produce a saw tooth wave rising from 10 to 13 in 3 segments, and then down to 10 in the fourth.  Without interpolation, the output would have been a sequence of four square steps - 10, 11, 12 and 13 repeated.

THE TABLE WRITE UGENS

The table write ugens works on existing function tables, changing their contents.  There could be all sorts of uses for this.  Assuming that users (.orc  and .sco programmers) know what they are doing, then there should be  no more trouble than the use of global variables.

As when using global variables, the user must consider how the code is run.

In each k-cycle, instruments are executed, in order of instrument  number, and within instruments, in order of the instances of the  instrument.  I presume the instance order depends on their starting  time.

As execution proceeds, each ugen is run once at k-time.  For k- type  ugens, they do their job once.  For a-rate ugens, they process one or  more arrays of a-rate variables.  For instance a table read at a-rate,  with ksmps = 7, uses a 7 long array of indexes to read into a table,  retrieving 7 different values and writing them to a 7 long array for  the output.

So

ablah	table	azot, 5

will read from table 5, a set of values pointed to by an array of indexes pointed to by azot, and write them to an array pointed to by ablah.

We may conceive of an idea of writing successive a-rate values to a  single table location, and subsequently reading them from that  location.  This would not work with ksmps = 7 - only the last written value would remain by the time execution passed to the next ugen.

So table write is a means of patching i- or k-rate signals to  particular locations in function tables, where they can be read by  table read ugens.  However this does not work for a-rate signals,  unless you conspire to use a range of the table, and organise your  indexes very carefully.

Patching of i-, k- and a-rate signals under .orc program control is best  achieved with arrays - which do not yet exist.  See the zak system for  a next best solution with ugens.

Purpose and Applications

The main purpose of a table write ugen is to refashion function  tables on the fly under program control.  tablemix, tablecopy, tablera  and tablewa can also be used for such purposes.

Applications are diverse.  One is to generate a waveshaping table with .orc code.   A loop could be created and an instrument could spend  some time with k-rate operations looping to address each table  location - rewriting the table, before letting performance proceed.   This would probably be too slow to work with real-time music  production.

Another application is to continuously sculpt tables while they are  being used.  Each k- or a- cycle, one or a few locations are changed a  little.

With these applications in mind, please read further about tablew and itablew.


Table read ugens with k-rate table selection
 K-rate table read ugens

By Robin Whittle (New in Csound 3.47)

See also Table manipulation overview

kr	tablekt	kndx, kfn [, ixmode] [,ixoff] [,iwrap]

ar	tableikt	andx, kfn [, ixmode] [,ixoff] [,iwrap]

K-rate control over table numbers.

DESCRIPTION

The standard Csound ugens table and tablei, when producing a k- or a-rate result, can only use an init-time variable to select the table number. tablekt and tableikt accept k-rate control as well as i-time. In all other respects they are similar to the original ugens. See also Table read/write sequential locations.

ARGUMENTS

indx, kndx, - Index into table, either a positive number range

andx  - matching the table length (ixmode = 0) or a 0 to 1 range (ixmode != 0)

ifn, kfn  - Table number. Must be >= 1. Floats are rounded down to an integer.  If a table number does not point to a valid table, or the table has not yet been loaded (GEN01) then an error will result and the instrument will be de-activated.

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.

ixoff  (optional; default = 0)

   ==0 - Total index is controlled directly by  xndx.  ie. the indexing starts from the start of the table.

   !=0 - Start indexing from somewhere else in the table. Value must be positive and less than the table length (ixmode = 0) or less than 1 (ixmode !=0)

iwra  (optional; default = 0)

   ==0 - Limit mode: when total index is below 0, then final index is 0.Total index above table length results in a final  index of the table length - high out of range total indexes stick at the upper limit of the table.See discussion below for exact detailed differences between interpolated and non interpolated modes.

    !=0 - Wrap mode: total index is wrapped  modulo the table length so that all total indexes map into the table. For instance in a table of length 8, xndx = 5 and ixoff = 6 gives a total index of 11, which wraps to a final  index of 3. See discussion below for finer points in interpolated mode.


Determine table length

By Robin Whittle (New in Csound 3.46)

See also Table manipulation overview

ir	tableng	ifn

kr	tableng	kfn

NAME CHANGES

Until Csound 3.52, the i-rate version of tableng was called itableng.

ARGUMENTS

ifn - i-time number of function table

kfn - k-rate number of function table

PERFORMANCE

tableng returns the length of the specified table. This will be a power of two number in most circumstances - it will not show whether a table has a guardpoint or not - it seems this information is not available in the table's data structure. If the table is not found, then 0 will be returned.

Likely to be useful for setting up code for table manipulation operations, such as tablemix and tablecopy.


 Write into a function table

By Robin Whittle (New in Csound 3.46)

See also Table manipulation overview

tableiw	isig, indx, ifn [,ixmode] [,ixoff] [,iwgmode]

tablew	ksig, kndx, ifn [,ixmode] [,ixoff] [,iwgmode]

tablew	asig, andx, ifn [,ixmode] [,ixoff] [,iwgmode]

tablewk	ksig, kndx, kfn [,ixmode] [,ixoff] [,iwgmode]

tablewkt	asig, andx, kfn [,ixmode] [,ixoff] [,iwgmode]

tableigpw	ifn

tablegpw	kfn

Unit generators that write into a function table during instrument performance time.

NAME CHANGES

Until Csound 3.52, tableiw and tableigpw were called itablew, itablegpw.

ARGUMENTS

isig, ksig, asig  - The value to be written into the table.

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

ifn, kfn - Table number. Must be >= 1. Floats are rounded down to an integer.  If a table number does not point to a valid table, or the table has not yet been loaded (gen01) then an error will result and the instrument will be de-activated.

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.

ixoff (optional; default 0)

==0 - Total index is controlled directly by xndx.  ie. the indexing starts from the start of the table.

!=0 - Start indexing from somewhere else in the table. Value must be positive andless than the table length (ixmode = 0) or less than 1 (ixmode !=0

iwgmode  (optional; default 0) - guardpoint writing mode. Can take one of the values 0 (limit mode), 1 (wrap mode) or 2 (guardpoint mode). For details, see below.

PERFORMANCE

tablew is for writing into function tables at k- or at arates, with the table number being specified at init time. tablew has no output value.  The last three parameters are optional and have default values of 0.

tablewkt is the same, but uses a k-rate variable for selecting the table number. The valid combinations of variable types are shown by the first letter of the variable names.

tableiw is just the same as k-rate tablew, except it only happens once at the initialisation of the ugen.  (I must investigate what happens if an i-time ugen is executed first, via an if goto, some time after the instrument is initialised.) Use tableiw when all inputs are init time variables or constants and you only want to run it at the initialisation of the instrument.

tableigpw and tablegpw  are for writing the table's guard point, with the value which is in location 0.  Does nothing if table does not exist. They are likely to be useful after manipulating a table with tablemix or tablecopy.

The Csound orchestra loader decides whether this is k- or a-rate operation, and fires up the appropriate subroutine in the unit generator code.

There is no output variable.

GUARD POINT WRITING MODES

0 = Limit mode

Limit the total index (ndx + ixoff) to between 0 and the guard point.

For a table of length 5, this means that locations 0 to 3 and location 4 (the guard point) can be written.  A negative total index writes to location 0.  Total indexes > 4 write to location 4.

1 = Wrap mode

Wrap total index value into locations 0 to E, where E is one less than either the table length or the factor of 2 number which is one less than the table length. For example, wrap into a 0 to 3 range - so that total index 6 writes to location 2.

2 = Guardpoint mode

The guardpoint is written at the same time as location 0 is written - with the same value.

This facilitates writing to tables which are intended to be read with interpolation for producing smooth cyclic waveforms. In addition, before it is used, the total index is incremented by half the range between one location and the next, before being rounded down to the integer address of a table location.

Normally (igwmode = 0 or 1) for a table of length 5 - which has locations 0 to 3 as the main table and location 4 as the guard point, a total index in the range of 0 to 0.999 will write to location 0.  ("0.999" means just less than 1.0.)  1.0 to 1.999 will write to location 1 etc.

A similar pattern holds for all total indexes 0 to 4.999 (igwmode = 0) or to 3.999 (igwmode = 1). igwmode = 0 enables locations 0 to 4 to be written - with the guardpoint (4) being written with a potentially different value from location 0.

With a table of length 5 and the iwgmode = 2, then when the total index is in the range 0 to 0.499, it will write to locations 0 and 4.  Range 0.5 to 1.499 will write to location 1 etc. 3.5 to 4.0 will also write to locations 0 and 4.

This way, the writing operation most closely approximates the results of interpolated reading. Guard point mode should only be used with tables that have a guardpoint.

Guardpoint mode is accomplished by adding 0.5 to the total index, rounding to the next lowest integer, wrapping it modulo the factor of two which is one less than the table length, writing the the table (locations 0 to 3 in our example) and then writing to the guard point if index == 0.

CAUTION WITH K-RATE TABLE NUMBERS

The following notes also apply to the tablekt and tableikt ugens which can now have their table number changed at k-rate.

At k-rate or a-rate, if a table number of < 1 is given, or the table number points to a non-existent table, or to one which has a length of 0 (it is to be loaded from a file later) then an error will result and the instrument will be deactivated.


Copy a function table

By Robin Whittle (New in Csound 3.46)

See also Table manipulation overview

tableicopy	idft, isft

tablecopy	kdft, ksft

Copy data from one function table to another.

NAME CHANGES

Until Csound 3.52, tableicopy was called itablecopy.

ARGUMENTS

kdft - Number of destination function table.

ksft - Number of source function table.

PERFORMANCE

Simple, fast table copy ugens.  Takes the table length from the  destination table, and reads from the start of the source table. For speed reasons, these do not check the source length - just copies regardless - in "wrap" mode.  This may read through the source  table several times.  A source table with length 1 will cause all values in the destination table to be written to its value.

Table copy cannot read or write the guardpoint.  To read it use table read, with ndx = the table length.  Likewise use table write to write it. To write the guardpoint to the value in location 0, use tablegpw. This is primarily to change function tables quickly in a real-time situation.


Mix two tables

By Robin Whittle (New in Csound 3.46)

See also Table manipulation overview

tablemix	kdft, kdoff, klen, ks1ft, ks1off, ks1g, ks2ft, ks2off, ks2g

tableimix	idft, idoff, ilen, is1ft, is1off, is1g, is2ft, is2off, is2g

This ugen mixes from two tables, with separate gains into the destination table.  Writing is done for klen locations, usually stepping forward through the table - if klen was positive. If it is negative, then the writing and reading order is backwards - towards lower indexes in the tables.  This bidirectional option makes it easy to shift the contents of a table by reading from it and writing back to it.

NAME CHANGES

Until Csound 3.52, tableimix was called itablemix.

ARGUMENTS

kdft - Destination function table.

kdoff - Offset to start writing from. Can be negative.

klen - Number of write operations to perform. Negative means work backwards.

ks1ft ks2ft - Source function tables. These can be the same as the destination table, if care is exercised about direction of copying data.

ks1off ks2off - Offsets to start reading from in source tables.

ks1g ks2g - Gains to apply when reading from the source tables.  The results are added and the sum is written to the destination table.

PERFORMANCE

If klen is 0, no writing occurs. Note that the internal integer value of klen is derived from the ANSI C floor( ) function - which returns the next most negative integer.  Hence a fractional negative klen value of -2.3 would create an internal length of 3, and cause  the copying to start from the offset locations and proceed for two locations to the left.

The total index for table reading and writing is calculated from the starting offset for each table, plus the index value, which starts at 0 and then increments (or decrements) by 1 as mixing proceeds. These total indexes can potentially be very large, since there is no restriction on the offset or the klen. However each total index for each table is ANDed with a length mask (such as 0000 0111 for a table of length 8) to form a final index which is actually used for  reading or writing.  So no reading or writing can occur outside the tables.

This is the same as "wrap" mode in table read and write. This process does not read or write the guardpoint.

If a table has been rewritten with one of these, then if it has a guardpoint which is supposed to contain the same value as the location 0, then call tablegpw afterwards.

The indexes and offsets are all in table steps - they are not normalised to 0 - 1.  So for a table of length 256, klen would be set to 256 if all the table was to be read or written.

The tables do not need to be the same length - wrapping occurs  individually for each table.


Table read/write sequential locations

By Robin Whittle (New in Csound 3.46)

See also Table manipulation overview

ar	tablera	kfn, kstart, koff

kstart	tablewa	kfn, asig, koff

These ugens read and write tables in sequential locations to and from an a-rate variable.  Some thought is required before using them.  They have at least two major, and quite different, applications which are discussed below.

ARGUMENTS

ar - a-rate distination for reading ksmps values from a table.

kfn - i- or k- rate number of the table to read or write.

kstart - Where in table to read or write.

asig - a-rate signal to read from when writing to the table.

koff - k- rate offset into table. Range unlimited - see explanation at end of this section.

In one application, these are intended to be used in pairs, or with several tablera ugens before a tablewa - all sharing the same kstart variable.These read from and write to sequential locations in a table at audio rates, with ksmps floats being written and read each cycle.

PERFORMANCE

tablera starts reading from location kstart.

tablewa starts writing to location kstart, and then writes to kstart with the number of the location one more than the one it last wrote. (Note that for tablewa, kstart is both an input and output variable.) If the writing index reaches the end of the table, then the no further writing occurs and zero is written to kstart.

For instance, if the table's length was 16 (locations 0 to 15), and ksmps was 5. Then the following steps would occur with repetitive runs of the tablewa ugen, assuming that kstart started at 0:

Run no. Initial Final   locations written

        kstart  kstart

  1       0       5       0  1  2  3  4

  2       5      10       5  6  7  8  9

  3      10      15      10 11 12 13 14

  4      15       0      15

This is to facilitate processing table data using standard a-rate orchestra code between the tablera and tablewa ugens:

;------------------------------------------------------

;

kstart = 0                       	;

; Read 5 values from table into an

; a-rate variable.

lab1:  atemp   tablera ktabsource, kstart, 0

; Process the values using a-rate code.

atemp = log(atemp)	;

; Write it back to the table

kstart  tablewa ktabdest, atemp, 0

; Loop until all table locations have

; been processed.

if ktemp > 0 goto lab1            	;

;

;------------------------------------------------------

This example shows a processing loop, which runs every k-cycle, eading each location in the table ktabsource, and writing the log f those values into the same locations of table ktabdest.

This enables whole tables, parts of tables (with offsets and different control loops) and data from several tables at once to be manipulated with a-rate code and written back to another (or the same) table.

This is a bit of a fudge, but it is faster than doing it with k-rate table read and write code.

ANOTHER APPLICATION

;------------------------------------------------------

;

kzero = 0                       	;

kloop = 0                       	;

;

kzero	tablewa 23, asignal, 0	; ksmps a-rate samples written into

; locations 0 to (ksmps -1) of table 23.

;

lab1: ktemp table kloop, 23     	; Start a loop which runs ksmps times,

; in which each cycle processes one of

  [ Some code to manipulate ]	; table 23's values with k-rate orchestra

  [ the value of ktemp.     ]	; code.

;

;

tablew ktemp, kloop, 23	; Write the processed value to the table.

;

kloop = kloop + 1                          	; Increment the kloop, which is both the

; pointer into the table and the loop

if kloop < ksmps goto lab1	; counter.  Keep looping until all values

; in the table have been processed.

;

asignal	tablera 23, 0, 0                  	; Copy the table contents back to an a-rate

; variable.

;------------------------------------------------------

koff - This is an offset which is added to the sum of kstart and the internal index variable  which steps through the table.  The result is then ANDed with the lengthmask (000 0111 for a table of length 8 - or  9 with guardpoint) and that final index is used to read or write to the table.  koff can be any value.  It is converted into a long using the ANSI floor() function so that -4.3 becomes -5.  This is what we would want when using wide ranging offsets.

Ideally this would be an optional variable, defaulting to 0, however with the existing Csount orchestra read code, such default parameters must be init time only.  We want k-rate here, so we cannot have a  default.

NOTES ON TABLERA AND TABLEWA

These are a fudge, but they allows all Csounds k-rate operators to be used (with caution) on a-rate variables - something that would only be possible otherwise by ksmps = 1, downsamp and upsamp.

Several cautions:

1 - 	The k-rate code in the processing loop is really running at a rate, so time dependant functions like port would not work normally.

2 - 	This system will produce undesirable results unless the ksmps fits within the table length.  For instance a table of length 16 will  accomodate 1 to 16 samples, so this example will work with ksmps = 1 to 16.

Both these ugens generate an error and deactivate the instrument if a table with length < ksmps is selected. Likewise an error occurs if kstart is below 0 or greater than the highest entry in the table -  if kstart >= table length.

3 - 	kstart is intended to contain integer values between 0 and (table  length - 1).  Fractional values above this should not affect operation but do not achieve anything useful.

4 -	These ugens do not do interpolation and the kstart and koff parameters always have a range of 0 to (table length - 1) - not 0 to 1 as is available in other table read/write ugens.  koff can be outside this range but it is wrapped around by the final AND operation.

5 - 	These ugens are permanently in wrap mode.  When koff is 0, no wrapping needs to occur, since the kstart++ index will always be within the table's normal range.  koff != 0 can lead to wrapping.

6 - 	The offset does not affect the number of read/write cycles performed, or the value written to kstart by tablewa.

7 - 	These ugens cannot read or write the guardpoint.  Use tablegpw to  write the guardpoint after manipulations have been done with tablewa.


The zak system
 The ZAK system - Overview

By Robin Whittle (New in Csound 3.46)

"zak" means a- or k-rate patching, (i-time too), with a z as the first letter of the ugen names.

This is a fudge to do the work until arrays are implemented.  I want to use such facilities and will use ZAK for the time being.

The ZAK system uses one area of memory as a global i- or k-rate patching area, zk, and another for audio rate patching, za. These are establised by a ugen which must be called once only: zakinit.

At least one location is always allocated for both zk and za spaces. There is nothing wrong with having za and zk ranges thousands or tens of thousands, but most pieces probably only need a few dozen to patch their signals around.

The zak space uses indices from zero up to and including the number used to init the space. This means that whatever your array indexing habits, it will work. See zakinit for further details.

SYNTAX OF UNIT GENERATORS

Allocating zak space

Zak  read/write operations

Zak signal modulation

SUMMARY OF ZAK UGENS

Types of input variables used:

Runs at time

ir	zir 	indx	     i

kr	zkr	kndx	     k

ziw  	isig, indx                    	     i

zkw	ksig, kndx          	     k

ziwm	isig, indx, imix	     i

zkwm	ksig, kndx, kmix	     k

zkcl	kfirst, klast	     k

ar	zar  	kndx                   	k but does arrays

ar	zarg	kndx, kgain        	k but does arrays

zaw	asig, kndx                	k but does arrays

zawm	asig, kndx, kmix      	k but does arrays

zacl	kfirst, klast                	k but does arrays

Where:

isig	}

indx	} Known at init time

imix	}

ksig	}

kndx	}

kmix	} k-rate variables

kfirst	}

klast	}

kgain	}

asig	} a-rate variable - an array of floats.

Known bugs in ZAK system:

When using the mix function of zkwm or zawm, care must be taken that  the variables mixed to are zeroed at the end (or start) of each k-cycle.  The same applies to any variables to which signals are mixed.   If you keep adding signals to them, their values can drift to  astronomical figures - which is probably not what you want.

My intention is to have certain ranges of za and zk variables used for  mixing - I use zkcl and zacl in the last instrument to clear those  ranges.


ZAK space allocation

By Robin Whittle (New in Csound 3.46)

See also The ZAK System Overview

zakinit	isizea, isizek

Allocate memory for za and zk spaces.

ARGUMENTS

isizek - the number of locations we want to reserve for floats in the zk space.  These can be written and read at i- and k- rates.

isizea - the number of audio rate "locations" for a-rate patching. Each "location" is actually an array which is ksmps long.

PERFORMANCE

The za space is separate from the zk space.

At least one location is always allocated for both zk and za spaces. There is nothing wrong with having za and zk ranges thousands or tens of thousands, but most pieces probably only need a few dozen to patch their signals around.

The zak spaces use indices from zero up to and including the number used to init the space. This means that whether you like to index arrays from 0 through (isizek - 1) or from 1 through isizek, you can.

EXAMPLE

zakinit 10 30

This reserves memory for locations 0 to 10 of a-rate za space, and for locations 0 to 30 of a-rate zk space. With ksmps = 8, this would use 31 floats for zk and 88 floats for za space.


Reading and writing ZAK space

By Robin Whittle (New in Csound 3.46)

See also The ZAK System Overview

ir	zir	indx

kr	zkr	kndx

ar	zar	kndx

ar	zarg	kndx, kgain

ziw	isig, indx

zkw	ksig, kndx

zaw	asig, kndx

ziwm	isig, indx, imix

zkwm	ksig, kindx, kimix

zawm	asig, kindx, amix

zkcl	kfirst, klast

zacl	kfirst, klast

Read/write zak patching locations, addressed by index.

ARGUMENTS

indx, kndx - points to which za variable to read.

xsig 	- a signal to write or mix into the addressed zak space.

xmix	- the amount of xsig mixed into zak space.

kfirst, klast - the first and last locations of zak space to be zeroed by zkcl/zacl.

PERFORMANCE

These opcodes are fast and always check that the index (indx or kndx) is within the range of zk space.  If it is out of range, an error is reported and 0 is returned, or no writing takes place.

zir and zkr are two short, simple, fast opcodes which read a location in zk space, either at i- time or at the k-rate. zar does the same for za space.

zarg is similar to zar, but multiplies the a-rate signal by a k-rate value kgain. Both for this ugen and for zar, the ugen figures out where the array is and auto-indexes through it to get each of the ksmps number of samples.

ziw and zkw similarly write to a location in zk space at i- time or at k-rate. zaw writes to a kndx location in za space.

ziwm, zkwm and zawm are like ziw, zkw, zaw above, except that they mix the signal xsig to the current value of the variable.  If no imix is specified,  they mix, but if imix is used, then 0 will cause writing (like ziw, zkw, zaw) while any other value will cause direct mixing.

zkcl and zacl will clear to zero one or more variables in the zk (zkcl) or the za (zkcl) space. Useful for those variables which are accumulators for mixing things during the processing for each cycle, but which must be cleared to zero before the next set of calculations.

EXAMPLES

The kndx argument can be used so that parameter 8 of the instrument's command line controls where in zk space the output is written:

zkw	kzoom, p8

This will always write it to zk location 7:

zkw	kzoom, 7

This following will write kzoom to locations 40 to 55 on a one second scan cycle.

kxxx	phasor 1

kdest	= 40 + kxxx * 16

zkw    kzoom, kdest


ZAK signal modulation

By Robin Whittle (New in Csound 3.46)

See also The ZAK System Overview

kr	zkmod	ksig, kzkmod

ar	zamod	asig, kzamod

ARGUMENTS

ksig - the input signal, to be modulated and sent to the output of the zkmod unit generator.

kzkmod - controls which zk variable is used for modulation, and which type of modulation is used. A positive value indicates addition of the signals, while a negative value indicates that the signals should be multiplied.

PERFORMANCE

zkmod is a unit generator intended to facilitate the modulation of one signal by another, where the modulating signal comes from a zk variable.  Either additive or mulitiplicative modulation is provided.

zamod - Modulation of one audio rate signal by a second one - which comes from a za variable.  The location of the modulating variable is controlled by the k-rate variable kzamod.  This is the audio rate version of zkmod.

A positive value means additive modulation, a negative value means multiplicative modulation.  A value of 0 means no change to ksig - it is transferred directly to the output. For instance kzkmod = 23 will read from zk variable 23, and add the value it finds there to ksig.  If kzkmod = -402, then ksig is multiplied by the value read from zk location 402.

kzkmod can be an init time constant, or a k-rate value.


 Time reading ugens

By Robin Whittle (New in Csound 3.46)

ir	timek

kr	timek

ir	times

kr	times

kr	instimek

kr	instimes

NAME CHANGES

Until Csound 3.52, the i-rate versions of timek and times were called itimek, itimes.

DESCRIPTION

timek returns an integer number stating the number of k-rate cycles since the start of the performance of the orchestra.

times returns a float with the number of seconds since the start of orchestra performance.

instimek and instimes are similar to timek and times, except they return the time counting from the start of this instance of the instrument.


k-rate signal display
Print k-rate values to screen

By Robin Whittle and Gabriel Maldonado (New in Csound 3.46-48)

printk 	itime, kval [, ispace]

printk2	kval [,ispace]

printks	"txtstring", itime, kval1, kval2, kval3, kval4

Orchestra debugging tools. See also print.

ARGUMENTS

itime - How much time in seconds is to elapse between printings.

kval - The number to be printed.

ispace (optional: default = 1) - How many spaces to insert before kval is printed.  (Max 120.)

txtstring - Text to be printed first - can be up to 130 characters at least. Must be in double quotes.

kvalx - The k-rate values to be printed. Use 0 for unused value places.

PERFORMANCE

printk prints one k-rate value on every k-cycle, every second or at intervals specified.  First the instrument number is printed, then   the absolute time in seconds, then a specified number of spaces, then  the value.  The variable number of spaces enables different values to be spaced out across the screen - so they are easier to view. This is for debugging orchestra code.

The first print is on the first k-cycle of the instance of the instrument.

printk2 (by GM, in Csound 3.48) is derived from Robin Whittle's printk. This ugen 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 varying k-signals! This could hang the computer, as the rate of printing is too fast.

printks prints numbers and text, with up to four printable numbers - which can be i- or k-rate values.

An init error is generated if the first parameter is not a string of length > 0 enclosed in double quotes.

To print the four parameters, special codes in txtstring act as placeholders for the numbers, and at the same time tell how to format the printed text. The codes are the standard printf %f etc. codes, as used in ANSI C. See below for examples on the printf formating codes.

New lines and tabs in printks

To print special characters in the output text, like tabs and new lines, the C programming language uses special escape sequences: A backslash, followed by a single character code. In C, tabs are written like \t; new line: \n; and backslash: \\.

Now these \n style character codes are not interpreted by printf, but are converted by the C compiler into string literals, as found in the C program. To overcome this problem, printks translates some of these codes:

\n or \N	Newline

\t or \T	Tab

   ^	Escape character

  ^^	^

   ~	Escape and '['

These are the leading codes for MSDOS ANSI.SYS screen control characters.

NOTE: On the Bath PC versions, the newline and tab characters must be preceded by two backslashes, not one! (not sure about other systems) - eg, \\t, \\n. (-re)

printf() style %f formatting

One of the less enjoyable parts of C programming is trying to figure out what magic incantations to offer to printf(). This is less of a problem here, since all parameters in Csound are floats.

Thus we only have to consider two formating commands:

1 - How many decimal points of precision do we want at most?  (0 means no decimal point.)

2 - How many digits (or spaces) do we want printed in total - including those after the decimal point?

%f	Just prints with full precision - 1234.123456

%6.2f	Prints 1234.12

%5.0f	Prints  1234

There is more to the printf() codes than this - see an ANSI C library reference.  Instead of 'f', you can use 'e' to get scientific notation. Using any other format specifiers than f, e, g, E and G will cause unpredictable results, since the parameters are always floating point numbers.

EXAMPLES

printks "Volume = %6.2f  Freq = %8.3f\n", 0.1, kvol, kfreq, 0, 0

This would print:

Volume = 1234.56 Freq = 12345.678

Additional output mode

A special mode of operation allows this ugen to convert the first input parameter into a 0 to 255 character, and  to use it as the first character to be printed. This enables a Csound program to send arbitrary characters to the console - albeit with a little awkwardness.

The ANSI C function printf() does not have a  format specifier to read a float and turn it into a byte  for direct output. We could add extra code to do this if we really wanted to put arbitrary characters out with ease. To acheive this, make the first character of the string a # and then, if desired continue with normal text and format specifiers.  Three more format specifers may be used - they access kval2, kval3 and kval4.

Example:

printks "#x\\y = %6.2\n", 0.1, kxy, 0, 0, 0

This would print a tab character followed by:

x\y = 1234.56

Comments on printk and printks

Both these printing ugens can be made to run on every k-cycle - or at  least every k-cycle they are run in the instrument.  Conditional goto  statements can be used to run them only at certain times or when  something goes wrong.  To make them run on every k-cycle like this,  set itime to 0.

When itime is not 0, then (if the orchestra code runs the ugen on  every k-cycle) then the ugen will decide when to print.  It will  always print on the first k-cycle it is called.  This means that if  you set one of these to print only every 10 seconds, and conditional  code in the instrument causes it to be run for the very first time at  3 seconds, then it will print at 3 seconds.

Subsequent runs of the ugen at between 3 and 9.999 seconds would not  cause it to print.  This could be very useful - set the time to longer  than the piece and conditional code in the instrument can be used to  report a bug just once, on its first occurrence.  You almost certainly  do not want a print operation happening every k-cycle - it slows the  program down too much.

Staying with the 10 second cycle example, if such a printk or printks  ugen was called every k-cycle, then it would print at 0 seconds  (actually the first k-cycle after 0), at 10.0 seconds, at 20.0 seconds  etc.

The time cycles start from the time the ugen is initialized -  typically the initialisation of the instrument.

Damien Miller pointed out an interesting application of these ugens -  get the output of the program and sort the lines with a line sorter.   The result would be the printed lines sorted first by instrument  number, and then by time - for printk. However printks can be made to  produce almost anything.  The instrument is available as p1 and the  time can easily be found and made available as a printks parameter.

One option I have considered but not implemented is for these printed lines to be written to a file as well as to the screen.  Let me know if you like this idea, or have any other ideas about debugging.

(NOTE: When running Csound from the command line, you can always redirect Csound text output to a file, by using the DOS command  > filename  at the end of the Csound command line. This can be useful, though you will also get all other Csound text output in this file.)

AUTHOR

printk and printks are by Robin Whittle.

Some changes to printks documentation by r.e, 98-11-29


 Filters for k-rate signals

By Robin Whittle (New in Csound 3.46, renamed in 3.49)

kr	portk	ksig, khtime [,isig]

kr	tonek	ksig, khp [,istor]

kr	atonek	ksig, khp [,istor]

kr	resonk	ksig, kcf, kbw [, iscl] [,istor]

kr	aresonk	ksig, kcf, kbw [, iscl] [,istor]

NAME CHANGES

Before Csound version 3.49 these opcodes were called kport, ktone, katone, kreson and kareson, respectively.

ARGUMENTS

ksig  - k-rate output.

khtime - k-rate time for output ot reach halfway to input.

isig - i-time, initialisation for internal state.

khp - k-rate frequency at which half power is reached.

istor (optional; default = 0: clear) - i-time, initialise internal state.

kcf - k-rate centre frequency.

kbw - k-rate bandwidth - between lower and upper half power points.

iscl  (optional; default = 1: gain at centre ) - i-time,

   0 = no gain change (default in a-rate reson, areson but leads to huge signals.)

   1 = gain at centre = 1 (default in kreson, kareson)

   2 = overall RMS gain = 1 (What exactly does this mean?)

istor  (optional; default = 0: clear) - i-time, initialise internal state.

PERFORMANCE

kport is like port, except the half time can be controlled at k-rate.

ktone, katone, kreson and kareson are like tone, atone, reson and areson except:

1 -  They work with k-rate signals instead of a-rate.

2 -  For kreson and kareson, the default for iscl is 1.


31-bit Uniform random generators, programmers notes
 31-bit uniform random generators

Unit generators by Robin Whittle    8 September 1995

(These changes are NOT yet incorporated in any Bath/Montreal release)

NOTES FOR CSOUND USERS AND C PROGRAMMERS.

Mods to the linrand series of noise generators added by Paris Smarargdis early in 1995.

* A new common 31 bit random source for these generators.

* Setting the seed of this generator.

* A new uniform distribution generator to make the family complete.  (Uniform means even distribution between 0 and 1.)

INTRODUCTION

I am interested in a Csound piece having quite a few random elements, and there being:

1)	An even distribution of random values.

2)	A long pattern of pseudo-randomness - ie. not a short repeat pattern.

3)	The ability to start all random functions from a single seed.

So ideally, all random functions would return a huge range of values, in a very long repeating pattern, and a single seed would start the process.  This enables me to create a piece say ten times, based on ten seeds that I choose.  Then I can listen to them and depending on which one I like the most, know that I can regenerate that version predictably from the same .ORC and .SCO file and the same seed.

So all random numbers would arise from a single common function, working from a single variable which is updated every call.  This variable is initialised by the seed I put in. Ideally, we would be dealing with floating point numbers, or at least 32 bit long integers.  The repeat time is typically a direct function of the length of the internal state number.

What we have at present (until my mods) in Csound is rather different from that.

STANDARD (UNIFORM DISTRIBUTION) RAND UGENS

These are rand, rand and randi in ugens4.c.  They all share a common approach to generating a pseudo-random number. Each instance maintains its own state, so if you have two rand ugens in the one instrument, or in separate instruments (or separate instances of instruments) then if you start with the same seed, each ugen will always produce the same sequence of numbers, at whatever rate it runs.

The default is for a seed of 0.5.  The 16 bit state is multiplied by a constant (15625) then 1 is added.  The result overflows, and the remainder is a 16 bit number, which is treated as a signed short integer (+32767 to - 32768).  This is converted to a float and divided by 32768 to give a +/- 1 pseudo-random number.

I presume the constant has been chosen wisely to give a repeat cycle as long as possible.  Since it is a 16 bit internal state, it must repeat at least every 65536 cycles.This system has no common state which I seek for controlling all pseudo-randomness in a peice from a single seed.  I suspect that the sophisication of the random generator is modest.  Certainly it has a short repeat cycle.

ZLINRAND FAMILY OF NOISE GENERATORS

These were added by Paris Smaragdis early in 1995 (See Non-uniform random generators).  The doco I use comes from John Fitch's README.CSO 14 April 95 (the original file name on his Bath ftp server was README.csound).

Looking at the code in CMATH.C, it can be seen that they all operate from the standard ANSI C library function int rand(), which returns a 16 bit pseudo random number and maintains a 16 bit state.

This goes a long way towards what I want.  Given a particular seed, rand() will produce a predictable sequence of numbers.  I presume its algorithm is a more sophisticated than that used in ugens4.c.

In the doco, there is nothing mentioned about setting the seed, but Paris has provided a ugen for it.

seed	iblah

This ugen runs only once, at the init time of the instrument it is in.  It sets the C library's rand() internal state to the contents of iblah.  It also prints iblah on the console, with three decimal places of precision.

Looking at the ANSI C doco and running tests, I have determined the following:

1)	The result and internal state of rand() is based on a 16 bit integer.

2)	The seed ugen feeds its parameter directly to the ANSI srand() function.

3)	This is expecting an integer, not a float. So there is no difference between iblah being 12.7 and 12.  This means that the printing of 3 decimal places of precision is misleading - these make no difference.

4)	The seed ugen requires an integer between 0 and 65535.  Anything outside that just wraps around.  So giving it 0 or 65536 gives the same subsequent set of pseudo-random results.

DJGPP (DOS GCC ANSI Compiler) contains an "improved" set of pseudo-random generators random() and srandom(), but they too are based on 16 bit values.  These are not, to my knowledge standard ANSI C functions.

I will use Paris' set of random noise generators in preference to the standard Csound ones - they share a common seed, allow the seed to be set, and use the ANSI library random number generator.

I wish I knew more about some of the distributions provided in this set of ugens.

The above comments apply to the original CMATH.C and CMATH.H - now called CMATH.COL and CMATH.HOL in my CSRW_SRC.ZIP.

MY MODIFICATIONS

Here is what I have done in my modified CSMATH.C and CSMATH.H.These mods do not affect the standard Csound random generators - only Paris' linrand family - and then only in the quality of the random numbers they generate.

THE GLOBAL RANDOM NUMBER GENERATOR

I have removed Paris' use of the compiler's rand() function.  In its place I have installed a 31 bit function - the source code of which I obtained from a library function of a BSD Unix release which I found via a WWW search.  This is but one line from their rand() function - a simple self contained function which was only used when some much more elaborate code is not used.

It seems that pseudo random generators come in three flavours:

1)	El-cheapo 15 or 16 bit things - quite sus for audio rate noise.

2)	Relatively rare, but still simple 31 bit generators like this one.  (This is the only one I could find.)

3)	Much more complex, highly sophisticated generators suitable for use in the most demanding scientific calculations.

The new generator is the multiply by foo and add bar kind - where both foo and bar have somehow been chosen to give a very long repeat cycle.

The original Csound random number generators rand, randh and randi are not affected by this - they have their own self contained generator for each instance.

To set the seed for the new global generator use the seed ugen:

seed	iblah

Where the seed is any number.  Values with three decimal places between 0 and 2147483.647 should give unique starting points.

Here is the new code for the common random number generator and its seed setting function.

#define GRAND_MAX  0x7FFFFFFFL

/* grand()

A 31 bit global random number generator.

This is intended to give a  long cycle - longer than the 32767 cycles

available from ANSI rand() - which showup as cyclic fluctuations in noise

when we use them at audio rates.

We need a global variable forthe state - a 32 bit long integer.

Initialize it with an auspicious number derived from 32 tosses of a coin.

Also define the maximum value forthe random number generator - seed start of file.

The generator produces a 31 bit positive integer.

*/

long    grandstat = 0x16BA2118L;

/* Random number generator. */

long    grand(void) {

        grandstat = (grandstat * 1103515245 + 12345) & GRAND_MAX;

        return  grandstat;

}

void seedrand(PRAND *p) {

/* New random seed setting function.

Paris wrote it to use the samePRAND data structure as the other

functions. It has only one input parameter, and no output parameterss

o the input is in the first variable in PRAND.

Take this to be a floating pointnumber with three decimal points.

Display this and multiply it by1000 to make these parts of the number

map into the final 32 bitseed. This is quite arbitrary, but it enables people

to use numbers between 0.000 and 2147483.647 to get unique starting points.

Hash the seed with another auspicious number before using it.

This number comes from the xor of 32 tosses of two coins -and rounded to

an odd number sobits 0 to 30 of the originalvalue affect their respective bits

of the final 31 bit seed.

Unique starting points can behad from any number with three

decimal places of precision from0.0 to 2147483.647.

*/

        printf("Seeding with %.3f\n", *p->out);

        grandstat = ( (unsigned int)*p->out * 1000) * 0xA7DD150D + 1234567;

        grandstat = grandstat & GRAND_MAX;

}


ïºInnehåll:

MIDI CONVERTERS ampmidi aftouch chpress pchbend midictrl midictrl

Maldonados opcodes (also non-MIDI ones); MIDI controller input, Initialise MIDI input, MIDI output single note/note stream/channel messages/system real-time messages, Extend MIDI event, (Limit MIDI signal. Barry Vercoe MIDI opcodes: )

midiin, midiout, midion2, nrpn

midi slider banks


MIDI Converters

By Barry Vercoe, Mike Berry and Gabriel Maldonado

ival	notnum

ival	veloc

icps	cpsmidi

icps	cpsmidib

kcps	cpsmidib	[irange]

ioct	octmidi

ioct	octmidib

koct	octmidib	[irange]

ipch	pchmidi

ipch	pchmidib

kpch	pchmidib	[irange]

iamp	ampmidi	iscal[, ifn]

kaft	aftouch	[iscal, initial]

kchpr	chpress	iscal

kbend	pchbend	iscal

ival	midictrl	inum [, initial]

kval	midictrl	inum [, initial]

icps	cpstmid	ifn

(kval	midictrlsc	inum [,iscal] [, ioffset] [, initial] -- N/A, see note below)

Get a value from the MIDI event that activated this instrument, or from a continuous MIDI controller, and convert it to a locally useful format.

NOTES

midictrlsc (by Mike Berry) was documented in Csound 3.46, but the actual opcode seems to be missing from the exe.

Also, some optional arguments were changed in Csound version 3.46. Unfortunately the provided documentation of arguments is not correct; must try to find the right word on this. ( -re)

cpstmid (by Gabriel Madonado) was added in Csound 3.492.

INITIALISATION

iscal - I-time scaling factor.

ifn (optional for ampmidi) - function table number of a normalized translation table, by which the incoming value is first interpreted. The default value is 0, denoting no translation.

ifn - (compulsory for cpsmid) function table containing the parameters (numgrades, interval, basefreq, basekeymidi) and the tuning ratios. (init rate argument only)

inum - MIDI controller number.

initial - the initial value of the controller.

irange - the pitch bend range in semitones.

PERFORMANCE

notnum, veloc - get the MIDI byte value (0 - 127) denoting the note number or velocity of the current event.

cpsmidi, octmidi, pchmidi - get the note number of the current MIDI event, expressed in cps, oct, or pch units for local processing.

cpsmidib, octmidib, pchmidib - get the note number of the current MIDI event, modify it by the current pitch-bend value, and express the result in cps, oct, or pch units. Available as an I-time value or as a continuous ksig value.

ampmidi - get the velocity of the current MIDI event, optionally pass it through a normalized translation table, and return an amplitude value in the range 0 - iscal.

aftouch, chpress, pchbend - get the current after-touch, channel pressure, or pitch-bend value for this channel, rescaled to the range 0 - iscal. Note that this access to pitch-bend data is independent of the MIDI pitch, enabling the value here to be used for any arbitrary purpose. The initial value of aftouch defaults to 127.

midictrl - get the current value (0 - 127) of a specified MIDI controller.

midictrlsc - get a scaled and offset value of a controller.

cpstmid is similar to cpsmidi above, but allows fully customized micro-tuning scales.  It requires five or more parameters for the tuning ratios. For convenience, these should be stored in a function table ifn, which is sent as the only argument to the opcode.  This function table ifn should be generated by the GEN02. The first four values stored in the 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.

EXAMPLES for cpstmid:

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 .......

;	            interval         basekeymidi

f1 0 64 -2   12    2        261        60        1  1.059463094359  1.122462048309  1.189207115003 ..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...


MIDI input
MIDI controller input

By Gabriel Maldonado and Barry Vercoe (New in Csound 3.47)

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]

ival	chanctrl	ichan, ictlno [,ilow,ihigh]

kval	chanctrl	ichan, ictlno [,ilow,ihigh]

bend	pchbend	[ilow, ihigh]

Allow input of MIDI controller signals. See also Initialisation of MIDI controllers .

All these ugens were introduced in Csound version 3.47. They are by Gabriel Maldonado except chanctrl, and pchbend, which are by Barry Vercoe.

NAME CHANGES

In the name purge of Csound 3.52, the following changes were made:

imidic7/14/21 => midic7/14/21 and ictrl7/14/21 => ctrl7/14/21.

The effect is that midic... and ctrl... were taught to differentiate i-rate arguments.

INITIALISATION

idest - output signal

ichan - MIDI channel (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)

imi - 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- or 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 does the same as midic7 with 14-bit precision. midic21 does the same as midic7 with 21-bit precision.

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

chanctrl gets the current value of a controller and optionally maps it onto specified range.

pchbend gets the current pitchbend value from a MIDI channel, and maps it to the specified range

Warning! Dont use midicXX opcodes within a score-activated i-statement or Csound will crash. Instruments containing midicXX opcodes can be only activated by a MIDI note-on message. Use 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 ugens can be included in sco-oriented instruments without Csound crashes.

2) They need the additional parameter ichan containing the MIDI channel of the controller. MIDI channel is the same for all the controller used in a single ctrl14 or ctrl21 opcode.


Initialise MIDI input controller

By Gabriel Maldonado and Barry Vercoe (New in Csound 3.47)

initc7	ichan, ictlno, ivalue

initc14	ichan, ictlno1, ictlno2, ivalue

initc21	ichan, ictlno1, ictlno2, ictlno3, ivalue

ctrlinit	ichnkm, ictlno1, ival1[, ictlno2, ival2[, ictlno3, ival3[,..ival32]]

initc7/14/21 initializes MIDI controller ictlno with ivalue. (By Gabriel Maldonado)

ctrlinit sets initial values for a set of MIDI controllers. (By Barry Vercoe).

See also MIDI controller input.

INITIALISATION

ichan - midi channel

ictlno - controller number (initc7)

ictlno1 - MSB controller number

ictlno2 - in initc14 LSB controller number; in initc21 Middle 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. The 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)


Single MIDI Note output

By Gabriel Maldonado (New in Csound 3.47)

noteon	ichn, inum, ivel

noteoff	ichn, inum, ivel

ondur	ichn, inum, ivel, idur

ondur2	ichn, inum, ivel, idur

Send note-on and note-off messages to the MIDI OUT port. See also MIDI note stream output

NAME CHANGES

In the name purge of Csound 3.52, the following changes were made:

noteoff was formerly known as ion; ioff became noteoff; ondur and ondur2 were known as iondur/iondur2.

INITIALISATION

ichn - MIDI channel number (0-15)

inum - note number (0-127)

ivel - velocity  (0-127)

PERFORMANCE

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

These noteon and noteoff are useful only when introducing a timout statement to play a non zero duration MIDI note.

For most purposes it is better to use ondur and ondur2.

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

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

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

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


MIDI Note output streams

By Gabriel Maldonado (New in Csound 3.47)

moscil	kchn, knum, kvel, kdur, kpause

midion	kchn, knum, kvel

Send stream of note-on and note-off  messages to the MIDI OUT port. See also single MIDI note output.

NAME CHANGES

midion was called kon until Csound 3.492.

PERFORMANCE

kchn - MIDI channel number (0-15)

knum - note number (0-127)

kvel - velocity  (0-127)

kdur - note duration in seconds

kpause - pause duration after each note-off 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 algorithmically generated melodic lines. When current instrument is deactivated, the note played by current instance of moscil is forcibly truncated.

kon (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.


Output MIDI Channel messages

By Gabriel Maldonado (New in Csound 3.47)

outic	ichn, inum, ivalue, imin, imax

outkc	kchn, knum, kvalue, kmin, kmax

outic14	ichn, imsb, ilsb, ivalue, imin, imax

outkc14	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

Send a single Channel message to the MIDI OUT port.

NAME CHANGES

In the name purge of Csound 3.52, the following changes were made:

The whole set of outi.../outk... opcodes were renamed from iout.../kout...

INITIALISATION AND PERFORMANCE

ichn, kchn - MIDI channel number (0-15)

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)

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

outi14 and outk14 (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.

outipb and outkpb (i and k-rate pitch bend output) send pitch bend messages.

outiat and outkat (i and k-rate aftertouch output) send aftertouch messages.

outiat and outkat (i and k-rate aftertouch output) send aftertouch messages.

outipc and outkpc (i and k-rate program change output) send program change messages.

outipat and outkpat (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.

NOTE

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.


Output MIDI system realtime messages

By Gabriel Maldonado (New in Csound 3.47)

mclock	ifreq

mrtmsg	imsgtype

Send System Realtime messages to the MIDI OUT port.

INITIALISATION

ifreq - clock message frequency rate in Hz

imsgtype - type of real-time message:

 1 - send a START message (0xFA);

 2 - send a CONTINUE message (0xFB);

 0 - send a STOP message (0xFC);

-1 - send a SYSTEM RESET message (0xFF);

-2 - send 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 message in Hz.

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


Extend MIDI events

By Gabriel Maldonado (New in Csound 3.47)

xtratim	 iextradur

kflag	release

Extend the duration of realtime generated events and handle their extra life. See also MIDI note generation and note stream generation

INITIALISATION

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

Allow complex ADSR envelope with MIDI events.

instr	1

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


Generic MIDI in- and output
MIDI input

By Gabriel Maldonado. (New in Csound 3.492)

kstatus, kchan, kdata1, kdata2 \

midiin

midiout	kstatus, kchan, kdata1, kdata2

Send a generic midi message to the midi out port, or get 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. This opcode works at k-rate.

kstatus is normally zero(i.e. when no messages are pending), it is is set to the type of the relative messages only when new midi data are present in the midi in buffer.

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 non- zero.

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


Triggered MIDI ouput

By Gabriel Maldonado. (New in Csound 3.492)

midion2	kchn, knum, kvel, ktrig

Send note on and off messages to the MIDI out port when triggered by a value other than zero.

NAME CHANGES

This opcode was called kon2 in Maldonado's proprietary Csound distribution.

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 only when ktrig is different than zero. This opcode is meant to work toghether with the output of the trigger opcode.


Non-Registered Param Number MIDI message

By Gabriel Maldonado. (New in Csound 3.492)

nrpn	kchan, kparmnum, kparmvalue

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 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)


Input MIDI control slider banks

By Gabriel Maldonado. (New in Csound 3.50)

In the following opcode prototypes, N can be any of the values 8, 16, 32, 64.

k1,...,kN	sliderN	ichan, ictlnum1, imin1, imax1, init1, ifn1, .... , ictlnumN, iminN, imaxN, initN, ifnN

k1,...,kN	sliderNf	ichan, ictlnum1, imin1, imax1, init1, ifn1, icutoff1, .... , ictlnumN, iminN, imaxN, initN, ifnN, icutoffN

i1,...,iN	sliderN	ichan, ictlnum1, imin1, imax1, ifn1, .... , ictlnumN, iminN, imaxN, ifnN

In the following opcode prototypes, N can be either of the values 16 or 32.

k1,...,kN	sNb14 	ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, initvalue1, ifn1, ...., ictlno_msbN, ictlno_lsbN, iminN, imaxN, initvalueN, ifnN

i1,...,iN	sNb14	ichan, ictlno_msb1, ictlno_lsb1, imin1, imax1, ifn1, ...., ictlno_msbN, ictlno_lsbN, iminN, imaxN, ifnN

Note that the number of in/out arguments must correspond to the value of N.

NAME CHANGES

In the name purge of Csound 3.52, the following changes were made:

islider8/16/32/64 was renamed to slider...; isNb14 was renamed sNb14

In effect, sliderN and sNb14 were taught to recognize i-rate output arguments

INITIALISATION

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

sliderN, and sliderNf are banks of MIDI controller (useful 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 translation is allowed, useful for enabling exponential response curves.

When no function table translation is requested, 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 do 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-cycles, since the filter slightly delays the output.

As the input arguments are many, you can split the line using '\' (backslash) character (new in version 3.47 (but not working yet - re)) to improve the readability. Using these opcodes is a lot more efficient than using the separate ones (ctrl7 and ktone) when several controllers are required.

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

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


Innehåll: trigger, Overview of RTCsound 1.9, RTCsound command line flags, Bath/Maldonado versions of Perry Cook physical model opcodes, Opcodes not in Bath version: mseq, ftlen2(x), loscil2, fof3, GEN22, posc lposc lposcint, mdelay, aexpseg, powoftwo


Thresholding

By Gabriel Maldonado. (New in Csound 3.49)

kout	trigger	ksig, kthreshold, kmode

Informs when a k-rate signal crosses a threshold

NAME CHANGES

This opcode was called trig in Maldonados CsoundRT 1.9 distribution.

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 ktrig:

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

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

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


Maldonado CsoundRT version overview
Maldonado Csound version

Overview of CsoundRT version 1.9

NOTE: This distribution and all the information that you can reach directly under this entry may be deprecated, as there is a new Csound version at Maldonados site. Please go there to get updated information. Most of the opcodes have been incorporated with the official Bath version, often under different names. (- re)

There are some ugens and features written by Gabriel Maldonado, which used to be provided only through his separately distributed Csound version. This has changed, youll see the status of each opcode under its separate entry.

There are also a number of name differences between Maldonados version re the Perry Cook physical model opcodes. List follows.

NOTE: These ugens are not fully integrated with the documentation for the Bath/Montreal release (eg not found in the Quickref) for the moment, until I know what their status will be. (- re)

Special command line flags

GM provides some additional flags with his version. Read all about them here.

See his examples of using the command line flags (also a good read if you run the Bath/Montreal distribution).

MIDI related

Limit MIDI output signals - wrap, mirror

MIDI in/output - midiin, midiout, kon2, mseq

MIDI delay - mdelay

Send a Non-Registered Param Number MIDI message - nrpn

Input MIDI control slider banks

Optimised 16-bit soundfile usage

Import a 16-bit soundfile into a ftable - GEN22

Sample player for 16-bit files - loscil2

Time-warp and granulate a 16-bit sound fof3

Info about soundfile function tables

Get length of an ftable (also works with GEN22) ftlen2(x)

Get actual number of samples imported by GEN01 or GEN22 - nsamp(x)

Get sample rate of a sound imported by GEN22 - ftsr(x)

Other

Audio rate expseg - aexpseg

Sampled sound oscillators - posc, lposc, lposcint

Threshold sensor - trig

Fast power of two function - powoftwo(x)

Physical model building blocks - physic1, physic2

Resonant lowpass filter - lpres, lpresx

Filter stacks - tonex, atonex, resonx

Resonant filter bank - vlpres

Flanger opcode - flanger

Perry Cook physical model opcodes; Maldonado vs Bath

Both Maldonado and, later, ffitch have independently incorporated a set of physical model opcodes, originally written by Perry Cook. The names overlap and clash in some cases. Here is the documentation.


CsoundRT additional flags

By Gabriel Maldonado. (NOT in Bath version)

Here are the all the flags which are available in Maldonados separately distributed Csound version. The standard (well, Bath/Montreal) distribution of course also has a whole lot of flags.

He also provides several examples of how to trim your Csound session for realtime/MIDI output.

Some relevant flags from Bath distribution

-Msbmidi   - allows realtime midi input

-odevaudio - allows realtime hardware soundboard wave output

-z0 or -z1   - list currently implemented UGs

-b num  - buffer length (still required for optimizing realtime operations)

(-B num  - hardware buffer length is now obsolete)

-P num  - sustain MIDI pedal (controller 64 or 0x40) treshold

Command-Line Flags Introduced With Release 1.0:

-K num  - MIDI device id number (optional, use only if MIDI devices are more than one)

-q num  - WAVE OUT device id number (optional, use only if you have more than one WAVE OUT device)

-p num - number of WAVE OUT buffers (optional; default=4, maximum=40)

-j num  - console virtual text rows number

-J num  - console virtual text columns number

Command-Line Flags Introduced With Release 1.5:

-O   (uppercase letter) - suppress all output messages for better realtime performance.

This switch is better that '-m0' because '-m0' still leaves some message output to the console. Use both switches together for the best realtime performance.

Warning! Use '-O' only when your orc/sco files are fully tested!

-e - allow arbitrary output sample rate (for cards that support this feature)

-y - don't wait for keypress to exit.

-E - graphic display for WCSHELL by Riccardo Bianchini.

Command-Line Flags Introduced With Release 1.7:

-Q  num - enable MIDI OUT operations and optionally chooses device id num (if num argument is present)

-Y  - disable WAVE OUT (for better MIDI OUT timing performances)

-*  - yield control to system until DAC  buffer is half-empty - for better multitasking.

Command-Line Flags Introduced With Release 1.72:

-/  filename  Allows the command line to be read from a text file.

IMPORTANT

Now (relase 1.7) flags '-odevaudio', '-M' (MIDI device name) and '-B' are redundant when using '-q', '-K' and '-b' flags.

Now (relase 1.8) when using '-o <FILENAME>' together with '-q' flag, realtime WAVE OUT and FILE out are enabled in parallel.

tip:

There is also a "magic" flag that suppresses initial message box.

I tell it only to persons who explicitly ask me via email.


Command line flag examples

By Gabriel Maldonado.

These examples make use of the special flags in Maldonados distribution, but some of the comments below are also informative for users of Bath Csound.

EXAMPLES

The following command-line invokes realtime midi performance of Csound with pedal treshold of 99, 12 wave out buffers of 882 bytes each, and prompts the user to input the MIDI IN and WAVE OUT device numbers (these values are good with my Pentium133 with a sr=44100 and kr=441):

csound -P99 -p12 -b882 -Msbmidi -odevaudio  miditest.orc  miditest.sco

Same as above but with all displays suppressed ("-O" and "-m0" flags. Use this feature only when your orc and sco are fully tested!):

csound -O -m0 -P99 -p12 -b882 -Msbmidi -odevaudio  miditest.orc  miditest.sco

Same as above but with display enabled, a 1000 rows virtual console, midi device number 4 (flag '-K') and wave out device number 0 (flag '-q'). Notice the lack of '-Msbmidi' and '-odevaudio', now redundant:

csound -j1000 -K4 -q0 -P99 -p12 -b882  miditest.orc   miditest.sco

Same as above but with '-*' flag to enhance Windows multitasking. This reduces polyphony when using short buffer length:

csound -* -j1000 -K4 -q0 -P99 -p12 -b882  miditest.orc   miditest.sco

Allow arbitrary sample rate (e.g.other than 1025/22050/44100) with '-e' flag (Note the reduced -p and -b values when using "rounded" sr and kr values; these values are good with my Pentium133 with sr=40000 and kr=400):

csound -e -O -m0 -P99 -p4 -b100 -odevaudio -Msbmidi  miditest.orc  miditest.sco

Allow MIDI OUT operations with device num.5 (flag '-Q') in parallel with WAVE OUT:

csound -e -P99 -j2000 -Q5 -q -p4 -K4 -b100  midiout.orc  midiout.sco

Allow MIDI OUT operations with device num.5 (flag '-Q') and suppresses WAVE OUT for better MIDI OUT timing (flag '-Y'):

csound -e -Y -P99 -j2000 -Q5 -q -K4  midiout.orc  midiout.sco

Call csound by command line contained in file 'cl.txt':

csound -/cl.txt

Enable realtime WAVE IN operation (flag '-i' without arguments) in parallel with WAVE OUT (flag '-q') and asks to the user the number of Multimedia-Windows devices:

csound -p12 -b882 -q -i

NOTE THAT…

- Finding the optimal values for "-b" and "-p" flags requires some experimentation: Longer buffers means more latency delay but also more safety from dropouts and sound interruptions (flag "-B" is now obsolete, don't use it).

  You now can drastically reduce buffer length and delay by using '-e' flag and 'rounded' sr and kr. Note that sometimes a smaller buffer length can handle sound flow better than a larger. Only experiments can lead you toward optimal '-b' values.

- Optimum "-b" and "-p" flag values need to be changed with different audio and k rates. These changes are not linear and not intuitive. So experiment!

- it is suggested to set "-b" value to integer multiples or submultiples of kr. This is useful sometimes, sometimes not. Experiment to find optimal values.

- "-b" and "-p" flags value can now be reduced considerably by using "rounded" sr and kr values (for example sr=32000 and kr=320; sr=40000 and kr=400 and so on) together with "-e" flag (till now this feature was tested only with a SB16 ASP and with an AWE32 card. I don't know if other cards support it). Reducing "-b" and "-p" flag values means reducing latency delay and so a more interactive realtime playing.

- "-Q" flag allows parallel MIDI OUT and DAC performance. Unfortunately the realtime timing implemented in Csound is completely managed by DAC buffer sample flow. So MIDI OUT operations can present some time irregularities. These irregularities can be fully eliminated when suppressing DAC operations themselves ('-Y' flag).

- "-Y" flag suppresses DAC operations. This enhances timing of midi out operations when used in conjunction with "-Q" flag. It is recommended to use "-Y" with low krates (max. kr=1000). As in Win95 maximum timer resolution is 1/1000 of second, unpredictable results can occurr when using it at krates greater than 1000.

  Also it is very important to set only kr values in which the following division:

1000/kr

produces integer results (for example:  kr =  10;  20; 50; 100; 125; 200; 250  etc.) because Win95 timer only handles integer periods in milliseconds. If you use a kr value that produces a non integer result in the above formula Csound seems to run normally but times will be not reliable.

  With my computer I work very well with a value of kr=200.  Maybe with slower computers a lower value works better. Experiment!

  I recommend to use kr=200 or less because with values greater than    200 increases the overhead affecting the entire system and do not    give a notable precision improvement. A time resoultion of 1/200 of    sec is enough precision for almost all MIDI application.   You must respect sr/kr/ksmps ratio even if sr value is meaningless when using "-Y" flag, or an error message will stop the performance.

- '-*' flag compells Csound to yield control to system until audio output buffer content passes a certain threshold. Below this threshold Csound continues processing, while over this threshold Csound yields control to Windows. This gives a big enhanchement in multitasking processes. Enabling this option reduces polyphony a bit when using short buffer space. So the user should increase the number ('-p' flag) and the length ('-b' flag) of buffers when setting '-*' flag. Experiment to find best values. Do not use this flag when time response to gestural actions is critical.

- For best realtime performance, it is (obviously) useful to:

1) reduce the number of concurrent applications running

2) not move resize, or closing windows during all realtime session.

- '-O' flag suppresses all text output during the performance   time. Using only '-m0' flag, some text messages are still sent    to the console. I suggest to use '-m0' and '-O' flag together   for maximum performance speed.

- xtratim and release opcodes (as well as linenr) don't operate well when using -t flag.

- When using ctrlXX and midicXX opcodes you must be sure the MIDI IN flag (-K and/or -Msbmidi) is activated, or Csound will crash! - When using realtime AUDIO input you must set the -i flag without argument, or followed by a number which represent the wave-in port number recognized by Win95. (ex. -i0) - When using parallel WAVE and FILE out, you must set -o flag followed by file name. The use of -q flag enables automatically WAVE OUT operations


Perry Cook opcodes
Perry Cook physical model opcodes

(NOT in Bath version)

All these opcodes use the same arguments. Here is the prototype:

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

NOTE: These opcodes are not included in the same form in the standard Bath/Montreal Csound distribution. See the references in the list.

Here are all the names. There are unfortunately some confusing name clashes with the official Bath/Montreal Csound version, as you can see.

Maldonado	Bath/jffitch

marimjpff	marimba

marimba 	---

vibraphone 	vibes

agogobell 	agogobell

plucked 	wgpluck

mandolin 	mandol

clarinet    	wgclar

flute 	wgflute

brass 	wgbrass

bowed    	wgbow

rhodes    	---

wurlitzer 	---

tubularbell 	---

heavymetal 	---

percussiveflute 	---

hammond 	---

fmvoices 	fmvoice

minimoog 	moog

voiceformant	---

Audio output is a physical model of the named instrument based on waveguide synthesis, frequency modulation synthesis, or modal synthesis.

INITIALISATION

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.


Output MIDI Sequence

By Gabriel Maldonado. (NOT in Bath version)

mseq	kpitchoff, ktimeratio, ktabevents, ktabdurs, [itimeoff], [iloop]

Send a timed MIDI sequence to the MIDI OUT port. (NOT YET IMPLEMENTED)

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

INITIALISATION

itimeoff - time offset from the beginning when sequence starts in seconds (optional; default = 0)

iloop - loop flag (default = 0 meaning no loop playing)

PERFORMANCE

kpitchoff - overall pitch offset in semitones (0 = no transposition, 1 = a semitone up,  -12 = an octave down)

ktimeratio - time stretch ratio (1 = no stretch, 2 = twice faster, 0.5 = twice slower, -1 = backward playing)

ktabevents - number of a function table containing midi event opcodes

ktabdurs - number of a function table containing relative times beetween each MIDI event pair stored in ktabevents table

mseq (MIDI sequencer) is a powerful sequencer of table stored midi events.

Base pitch can be transposed by a k-rate variant offset, as well as time ratio. A negative ktimeratio allows backward playing. MIDI events and durations are handled separately, allowing table substitution at k-rate. A sequence stored in ktabevents table can be polyphonic and multi-timbral, containing different MIDI channels events at the same time.

Any number of mseq opcodes can appear in the same Csound instrument allowing a 'sequence polyphony'.


ftlen2(x)

By Gabriel Maldonado. (NOT in Bath version)

DESCRIPTION

This function is the same as ftlen(x)  but operates also with deferred-allocation function size with GEN01 and GEN22.

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.


loscil2

By Gabriel Maldonado. (NOT in Bath version)

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

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

DESCRIPTION

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

INITIALISATION

See loscil for details.

PERFORMANCE

See loscil for details.

NOTE

This opcode is almost identical to loscil, the only difference is that loscil2 uses 16-bit integer function table (see GEN22) for storing samples, increasing realtime performance and reducing sample-memory consumption in half. No sound quality or signal to noise ratio degradation will result from using loscil2.

WARNING! You MUST ONLY use GEN22 for this opcode to operate correctly!


fof3

By Gabriel Maldonado. (NOT in Bath version)

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

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

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.

INITIALISATION

See fof, fof2 and fog

NOTE

fof3 is identical to fof2, except that 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 information.


GEN22 - Import 16-bit soundfile data for direct usage
GEN22

By Gabriel Maldonado. (NOT in Bath version)

NOTE: This function generator is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

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 GEN01.

This gen-function is almost identical to GEN01. The only difference is that 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 opcode. 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 function tables is loscil2 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 might surpass the range limit of output. Do not attempt to use GEN22 with any other opcodes (for now).


Oscillators for sampled sounds

By Gabriel Maldonado. (NOT in Bath version)

ar	posc	kamp, kcps, ift [,iphs]

kr	posc	kamp, kcps, ift [,iphs]

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

kr	lposc	kamp, kfreqratio, kloop, kend, ift [,iphs]

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

NOTE: These opcodes are not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

INITALISATION

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)

posc (precise oscillator) is the same as oscili but allows hugely more precise frequency control (especially when using long tables and low frequency values). It is a bit slower than oscili.

lposc (loop oscillator) allows to vary in k rate the starting and ending phase of a table. This can be useful when reading samples loop of a wavetable which repeat speed can be varied during the performance.

lposcint is the same as lposc, but uses integer stored sample tables (GEN22) to reduce ram memory needs.


MIDI delay

By Gabriel Maldonado. (NOT in Bath version)

mdelay  kstatus,  kchan,  kdata1,  kdata2, kdelay

A midi delay

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

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 instances 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.


A-rate exponential segment generator

By Gabriel Maldonado. (NOT in Bath version)

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

An exponential segment generator operating at a-rate.

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.

DESCRIPTION

This unit is almost identical to expseg, but much more precise when defining segments with very short duration (i.e. in percussive attack phase) at audio-rate. Note that the old expseg opcode does not operate correctly at audio rate when segments are shorter than a k-period.

INITIALISATION

ia - initial value. Zero is illegal.

ib, ic, etc. - value after idur1 seconds, etc.  This 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.


Power of two function

By Gabriel Maldonado. (NOT in Bath version)

powoftwo(x)

This function returns 2 ^ x. Fast, because integer arithmetic and table reading is implemented (it is a variant of cpsoct(x) function). Useful when working with tuning ratios. Works at i and k-rate.

NOTE: This opcode is not included (yet?) in the standard Bath/Montreal Csound distribution. See addresses.