API

Introduction

Csound is a sound and music computing system. It was originally written by Barry Vercoe at the Massachusetts Institute of Technology in 1984 as the first C language version of this type of software. Since then Csound has received numerous contributions from researchers, programmers, and musicians from around the world.

Outline of the API

The Csound Application Programming Interfaces

The Csound Application Programming Interface (API) reference is written in C. ctcsound is a Python module which wraps the C functions of the Csound API in a Python class called ctcsound.Csound. The methods of this class call the corresponding C function of the API.

Purposes

The purposes of the Csound API are as follows:

  • Declare a stable public application programming interface (API).
  • Hide the internal implementation details of Csound from users of the API, so that development of Csound can proceed without affecting code that uses the API.

Examples Using the Csound (host) API

The Csound command-line program is itself built using the Csound API. A similar Python application is as follows:

import sys
import ctcsound

cs = ctcsound.Csound()
result = cs.compile_(sys.argv)
if result == 0:
    while cs.performKsmps() == 0:
        pass
cs.cleanup()
del cs
sys.exit(result)

Csound code can also be supplied directly using strings, either as a multi-section CSD (with the same format as CSD files) or directly as a string. It can be compiled any number of times before or during performance.

Using a CSD text

System options can be passed via the CSD text before the engine is started. These are ignored in subsequent compilations:

import sys
import ctcsound

csd_text = '''
  <CsoundSynthesizer>
  <CsOptions>
    -odac
  </CsOptions>
  <CsInstruments>
  instr 1
    out(linen(oscili(p4,p5),0.1,p3,0.1))
  endin
  </CsInstruments>
  <CsScore>
  i1 0 5 1000 440
  </CsScore>
  </CsoundSynthesizer>'''

cs = ctcsound.Csound()
result = cs.compileCsdText(csd_text)
result = cs.start()
while True:
    result = cs.performKsmps()
    if result != 0:
        break
result = cs.cleanup()
cs.reset()
del cs
sys.exit(result)

Using Csound code directly.

Options can be passed via Csound.setOption() before the engine starts:

import sys
import ctcsound

orc_text = '''
  instr 1
    out(linen(oscili(p4,p5),0.1,p3,0.1))
  endin'''

sco_text = "i1 0 5 1000 440"

cs = ctcsound.Csound()
result = cs.setOption("-d")
result = cs.setOption("-odac")
result = cs.compileOrc(orc_text)
result = cs.readScore(sco_text)
result = cs.start()
while True:
    result = cs.performKsmps()
    if result != 0:
        break
result = cs.cleanup()
cs.reset()
del cs
sys.exit(result)

csound.h declares the public Csound application programming interface (API). It was authored by John P. ffitch, Michael Gogins, Matt Ingalls, John D. Ramsdell, Istvan Varga, Victor Lazzarini, Andres Cabrera and Steven Yi.

ctcsound.py is a Python wrapper module to the Csound API, written by François Pinot usind ctypes. It needs numpy and can be run from Python 2.x and Python3.x as well.

Python hosts using the Csound API must import ctcsound, to get access to the API functions through the methods of a ctcsound.Csound object.

Hosts must first create an instance of Csound: cs = ctcsound.Csound(). When hosts are finished using Csound, they must destroy the instance of csound: del cs. The other Csound API functions are called as methods of the cs object that was created. For example:

sr = cs.sr()

ctcsound.py is distributed with Csound since version 6.07.

Csound Class

ctcsound.csoundInitialize(flags)

Initializes Csound library with specific flags.

This function is called internally by csoundCreate(), so there is generally no need to use it explicitly unless you need to avoid default initialization that sets signal handlers and atexit() callbacks. Return value is zero on success, positive if initialization was done already, and negative on error.

class ctcsound.Csound(hostData=None, pointer_=None)
A4()

Returns the A4 frequency reference.

APIVersion()

Returns the API version number times 100 (1.00 = 100).

CPUTime(timerStruct)

Returns the elapsed CPU time (in seconds).

The time is measured since the specified timer structure was initialised.

UDPConsole(addr, port, mirror)

Turns on the transmission of console messages to UDP on addr:port.

If mirror is one, the messages will continue to be sent to the usual destination (see setMessageCallback()) as well as to UDP. Returns CSOUND_SUCCESS or CSOUND_ERROR if the UDP transmission could not be set up.

UDPServerClose()

Closes the UDP server.

Returns CSOUND_SUCCESS if the running server was successfully closed, CSOUND_ERROR otherwise.

UDPServerStart(port)

Starts the UDP server on a supplied port number.

Returns CSOUND_SUCCESS if server has been started successfully, otherwise, CSOUND_ERROR.

UDPServerStatus()

Returns the port number on which the server is running.

If the server is not running, CSOUND_ERROR is returned.

addSpinSample(frame, channel, sample)

Adds the indicated sample into the audio input working buffer (spin).

This only ever makes sense before calling performKsmps(). The frame and channel must be in bounds relative to ksmps() and nchnlsInput().

NB: the spin buffer needs to be cleared at every k-cycle by calling clearSpin().

appendOpcode(opname, dsblksiz, flags, thread, outypes, intypes, iopfunc, kopfunc, aopfunc)

Appends an opcode implemented by external software.

This opcode is added to Csound’s internal opcode list. The opcode list is extended by one slot, and the parameters are copied into the new slot.

Returns zero on success.

audioChannel(name, samples)

Copies the audio channel identified by name into ndarray samples.

samples should contain enough memory for ksmps() MYFLTs.

audioDevList(isOutput)

Returns a list of available input or output audio devices.

Each item in the list is a dictionnary representing a device. The dictionnary keys are device_name, device_id, rt_module (value type string), max_nchnls (value type int), and isOutput (value type boolean).

Must be called after an orchestra has been compiled to get meaningful information.

channelDatasize(name)

Returns the size of data stored in a channel.

For string channels this might change if the channel space gets reallocated. Since string variables use dynamic memory allocation in Csound6, this function can be called to get the space required for stringChannel().

channelLock(name)

Recovers a pointer to a lock for the specified channel called name.

The returned lock can be locked/unlocked with the spinLock() and spinUnLock() functions. Returns the address of the lock or NULL if the channel does not exist.

channelPtr(name, type_)

Returns a pointer to the specified channel and an error message.

If the channel is a control or an audio channel, the pointer is translated to an ndarray of MYFLT. If the channel is a string channel, the pointer is casted to c_char_p. The error message is either an empty string or a string describing the error that occured.

The channel is created first if it does not exist yet. type_ must be the bitwise OR of exactly one of the following values,

CSOUND_CONTROL_CHANNEL
control data (one MYFLT value)
CSOUND_AUDIO_CHANNEL
audio data (ksmps() MYFLT values)
CSOUND_STRING_CHANNEL
string data (MYFLT values with enough space to store getChannelDatasize() characters, including the NULL character at the end of the string)

and at least one of these:

CSOUND_INPUT_CHANNEL

CSOUND_OUTPUT_CHANNEL

If the channel already exists, it must match the data type (control, audio, or string), however, the input/output bits are OR’d with the new value. Note that audio and string channels can only be created after calling compile_(), because the storage size is not known until then.

Return value is zero on success, or a negative error code,

CSOUND_MEMORY
there is not enough memory for allocating the channel
CSOUND_ERROR
the specified name or type is invalid

or, if a channel with the same name but incompatible type already exists, the type of the existing channel. In the case of any non-zero return value, *p is set to NULL. Note: to find out the type of a channel without actually creating or changing it, set type_ to zero, so that the return value will be either the type of the channel, or CSOUND_ERROR if it does not exist.

Operations on the pointer are not thread-safe by default. The host is required to take care of threadsafety by retrieving the channel lock with channelLock() and using spinLock() and spinUnLock() to protect access to the pointer.

See Top/threadsafe.c in the Csound library sources for examples. Optionally, use the channel get/set functions provided below, which are threadsafe by default.

cleanup()

Prints information and closes audio and MIDI devices.

The information is about the end of a performance.
Note: after calling cleanup(), the operation of the perform function is undefined.
clearSpin()

Clears the input buffer (spin).

closeLibrary(library)

Platform-independent function to unload a shared library.

compileArgs(*args)

Compiles args.

Reads arguments, parses and compiles an orchestra, reads, processes and loads a score.

compileCsd(csd_filename)

Compiles a Csound input file (.csd file).

The input file includes command-line arguments, but does not perform the file. Returns a non-zero error code on failure. In this (host-driven) mode, the sequence of calls should be as follows:

cs.compileCsd(args)
while cs.performBuffer() == 0:
    pass
cs.cleanup()
cs.reset()

NB: this function can be called during performance to replace or add new instruments and events. On a first call and if called before start(), this function behaves similarly to compile_().

compileCsdText(csd_text)

Compiles a Csound input file contained in a string of text.

The string of text includes command-line arguments, orchestra, score, etc., but it is not performed. Returns a non-zero error code on failure. In this (host-driven) mode, the sequence of calls should be as follows:

cs.compileCsdText(csd_text)
while cs.performBuffer() == 0:
    pass
cs.cleanup()
cs.reset()

NB: a temporary file is created, the csd_text is written to the temporary file, and compileCsd() is called with the name of the temporary file, which is deleted after compilation. Behavior may vary by platform.

compileOrc(orc)

Parses, and compiles the given orchestra from an ASCII string.

Also evaluating any global space code (i-time only). This can be called during performance to compile a new orchestra:

orc = 'instr 1 \n a1 rand 0dbfs/4 \n out a1 \n'
cs.compileOrc(orc)
compileOrcAsync(orc)

Async version of compileOrc().

The code is parsed and compiled, then placed on a queue for asynchronous merge into the running engine, and evaluation. The function returns following parsing and compilation.

compileTree(tree)

Compiles the given TREE node into structs for Csound to use.

This can be called during performance to compile a new TREE.

compileTreeAsync(tree)

Asynchronous version of compileTree().

compile_(*args)

Compiles Csound input files (such as an orchestra and score).

As directed by the supplied command-line arguments, but does not perform them. Returns a non-zero error code on failure. This function cannot be called during performance, and before a repeated call, reset() needs to be called. In this (host-driven) mode, the sequence of calls should be as follows:

cs.compile_(args)
while cs.performBuffer() == 0:
    pass
cs.cleanup()
cs.reset()

Calls start() internally.

controlChannel(name)

Retrieves the value of control channel identified by name.

A second value is returned, which is the error (or success) code finding or accessing the channel.

controlChannelHints(name)

Returns special parameters (if any) of a control channel.

Those parameters have been previously set with setControlChannelHints() or the chnparams opcode.

The return values are a ControlChannelHints structure and CSOUND_SUCCESS if the channel exists and is a control channel, otherwise, None and an error code are returned.

createBarrier(max_)

Creates a Thread Barrier.

Max value parameter should be equal to the number of child threads using the barrier plus one for the master thread.

createCircularBuffer(numelem, elemsize)

Creates a circular buffer with numelem number of elements.

The element’s size is set from elemsize. It should be used like:

rb = cs.createCircularBuffer(1024, cs.sizeOfMYFLT())
createGlobalVariable(name, nbytes)

Allocates nbytes bytes of memory.

This memory can be accessed later by calling :py:meth`queryGlobalVariable()` with the specified name; the space is cleared to zero.

Returns CSOUND_SUCCESS on success, CSOUND_ERROR in case of invalid parameters (zero nbytes, invalid or already used name), or CSOUND_MEMORY if there is not enough memory.

createMessageBuffer(toStdOut)

Creates a buffer for storing messages printed by Csound.

Should be called after creating a Csound instance and the buffer can be freed by calling destroyMessageBuffer() before deleting the Csound instance. You will generally want to call cleanup() to make sure the last messages are flushed to the message buffer before destroying Csound.

If toStdOut is True, the messages are also printed to stdout and stderr (depending on the type of the message), in addition to being stored in the buffer.

Using the message buffer ties up the internal message callback, so setMessageCallback() should not be called after creating the message buffer.

createMutex(isRecursive)

Creates and returns a mutex object, or None if not successful.

Mutexes can be faster than the more general purpose monitor objects returned by createThreadLock() on some platforms, and can also be recursive, but the result of unlocking a mutex that is owned by another thread or is not locked is undefined.

If isRecursive’ id True, the mutex can be re-locked multiple times by the same thread, requiring an equal number of unlock calls; otherwise, attempting to re-lock the mutex results in undefined behavior.

Note: the handles returned by createThreadLock() and createMutex() are not compatible.

createThread(function, userdata)

Creates and starts a new thread of execution.

Returns an opaque pointer that represents the thread on success, or None for failure. The userdata pointer is passed to the thread routine.

createThreadLock()

Creates and returns a monitor object, or None if not successful.

The object is initially in signaled (notified) state.

csound()

Returns the opaque pointer to the running Csound instance.

currentThreadId()

Returns the ID of the currently executing thread, or None for failure.

NOTE: The return value can be used as a pointer to a thread object, but it should not be compared as a pointer. The pointed to values should be compared, and the user must free the pointer after use.

currentTimeSamples()

Returns the current performance time in samples.

debug()

Returns whether Csound is set to print debug messages.

Those messages are sent through the DebugMsg() internal API function.

deleteChannelList(lst)

Releases a channel list previously returned by listChannels().

deleteTree(tree)

Frees the resources associated with the TREE tree.

This function should be called whenever the TREE was created with parseOrc() and memory can be deallocated.

destroyBarrier(barrier)

Destroys a Thread Barrier.

destroyCircularBuffer(circularBuffer)

Frees circular buffer.

destroyGlobalVariable(name)

Frees memory allocated for name and remove name from the database.

Return value is CSOUND_SUCCESS on success, or CSOUND_ERROR if the name is not defined.

destroyMessageBuffer()

Releases all memory used by the message buffer.

destroyMutex(mutex)

Destroys the indicated mutex object.

Destroying a mutex that is currently owned by a thread results in undefined behavior.

destroyThreadLock(lock)

Destroys the indicated monitor object.

disposeOpcodeList(lst)

Releases an opcode list.

env(name, withCsoundInstance=True)

Gets the value of environment variable name.

The searching order is: local environment of Csound (if withCsoundInstance is True), variables set with setGlobalEnv(), and system environment variables. If withCsoundInstance is True, should be called after compile_().

Return value is None if the variable is not set.

evalCode(code)

Parses and compiles an orchestra given on an string.

Evaluating any global space code (i-time only). On SUCCESS it returns a value passed to the ‘return’ opcode in global space:

code = 'i1 = 2 + 2 \n return i1 \n'
retval = cs.evalCode(code)
firstMessage()

Returns the first message from the buffer.

firstMessageAttr()

Returns the attribute parameter of the first message in the buffer.

flushCircularBuffer(circularBuffer)

Empties circular buffer of any remaining data.

This function should only be used if there is no reader actively getting data from the buffer.

circular_buffer
pointer to an existing circular buffer
get0dBFS()

Returns the 0dBFS level of the spin/spout buffers.

getLibrarySymbol(library, symbolName)

Platform-independent function to get a symbol address in a shared library.

hostData()

Returns host data.

initTimerStruct(timerStruct)

Initializes a timer structure.

inputBuffer()

Returns the Csound audio input buffer as an ndarray.

Enables external software to write audio into Csound before calling performBuffer().

inputBufferSize()

Returns the number of samples in Csound’s input buffer.

inputMessage(message)

Inputs a NULL-terminated string (as if from a console).

Used for line events.

inputMessageAsync(message)

Asynchronous version of inputMessage().

inputName()

Returns the audio input name (-i)

isNamedGEN(num)

Checks if a given GEN number num is a named GEN.

If so, it returns the string length. Otherwise it returns 0.

isScorePending()

Tells whether Csound score events are performed or not.

Independently of real-time MIDI events (see setScorePending()).

joinThread(thread)

Waits until the indicated thread’s routine has finished.

Returns the value returned by the thread routine.

keyPress(c)

Sets the ASCII code of the most recent key pressed.

This value is used by the sensekey opcode if a callback for returning keyboard events is not set (see registerKeyboardCallback()).

killInstance(instr, instrName, mode, allowRelease)

Kills off one or more running instances of an instrument.

The instances are identified by instr (number) or instrName (name). If instrName is None, the instrument number is used.

mode is a sum of the following values:
0, 1, 2: kill all instances (0), oldest only (1), or newest (2)
4: only turnoff notes with exactly matching (fractional) instr number
8: only turnoff notes with indefinite duration (p3 < 0 or MIDI).

If allowRelease is True, the killed instances are allowed to release.

kr()

Returns the number of control samples per second.

ksmps()

Returns the number of audio sample frames per control sample.

listChannels()

Returns a pointer and an error message.

The pointer points to a list of ControlChannelInfo objects for allocated channels. A ControlChannelInfo object contains the channel characteristics. The error message indicates if there is not enough memory for allocating the list or it is an empty string if there is no error. In the case of no channels or an error, the pointer is None.

Notes: the caller is responsible for freeing the list returned by the C API with deleteChannelList(). The name pointers may become invalid after calling reset().

listUtilities()

Returns a list of registered utility names.

The return value may be None in case of an error.

lockMutex(mutex)

Acquires the indicated mutex object.

If it is already in use by another thread, the function waits until the mutex is released by the other thread.

lockMutexNoWait(mutex)

Acquire the indicated mutex object.

Returns zero, unless it is already in use by another thread, in which case a non-zero value is returned immediately, rather than waiting until the mutex becomes available.

Note: this function may be unimplemented on Windows.

message(fmt, *args)

Displays an informational message.

This is a workaround because ctypes does not support variadic functions. The arguments are formatted in a string, using the python way, either old style or new style, and then this formatted string is passed to the Csound display message system.

messageCnt()

Returns the number of pending messages in the buffer.

messageLevel()

Returns the Csound message level (from 0 to 231).

messageS(attr, fmt, *args)

Prints message with special attributes.

(See msg_attr for the list of available attributes). With attr=0, messageS() is identical to message(). This is a workaround because ctypes does not support variadic functions. The arguments are formatted in a string, using the python way, either old style or new style, and then this formatted string is passed to the csound display message system.

midiDevList(isOutput)

Returns a list of available input or output midi devices.

Each item in the list is a dictionnary representing a device. The dictionnary keys are device_name, interface_name, device_id, midi_module (value type string), isOutput (value type boolean).

Must be called after an orchestra has been compiled to get meaningful information.

module(number)

Retrieves a module name and type given a number.

Type is “audio” or “midi”. Modules are added to list as csound loads them. Return CSOUND_SUCCESS on success and CSOUND_ERROR if module number was not found:

n = 0
while True:
    name, type_, err = cs.module(n)
    if err == ctcsound.CSOUND_ERROR:
        break
    print("Module %d:%s (%s)\n" % (n, name, type_))
    n = n + 1
namedGEN(num, nameLen)

Gets the GEN name from a GEN number, if this is a named GEN.

The final parameter is the max len of the string.

namedGens()

Finds the list of named gens.

nchnls()

Returns the number of audio output channels.

Set through the nchnls header variable in the csd file.

nchnlsInput()

Returns the number of audio input channels.

Set through the nchnls_i header variable in the csd file. If this variable is not set, the value is taken from nchnls.

newOpcodeList()

Gets an alphabetically sorted list of all opcodes.

Should be called after externals are loaded by compile_(). Returns a pointer to the list of OpcodeListEntry structures and the number of opcodes, or a negative error code on failure. Make sure to call disposeOpcodeList() when done with the list.

notifyThreadLock(lock)

Notifies the indicated monitor object.

openLibrary(libraryPath)

Platform-independent function to load a shared library.

outputBuffer()

Returns the Csound audio output buffer as an ndarray.

Enables external software to read audio from Csound after calling performBuffer().

outputBufferSize()

Returns the number of samples in Csound’s output buffer.

outputFormat()

Gets output type and format.

outputName()

Returns the audio output name (-o)

params(params)

Gets the current set of parameters from a CSOUND instance.

These parameters are in a CsoundParams structure. See setParams():

p = CsoundParams()
cs.params(p)
parseOrc(orc)

Parses the given orchestra from an ASCII string into a TREE.

This can be called during performance to parse new code.

peekCircularBuffer(circularBuffer, out, items)

Reads from circular buffer without removing them from the buffer.

circular_buffer
pointer to an existing circular buffer
out
preallocated ndarray with at least items number of elements, where buffer contents will be read into
items
number of samples to be read

Returns the actual number of items read (0 <= n <= items).

perform()

Senses input events and performs audio output.

This is done until the end of score is reached (positive return value), an error occurs (negative return value), or performance is stopped by calling stop() from another thread (zero return value).

Note that compile_(), or compileOrc(), readScore(), start() must be called first.

In the case of zero return value, perform() can be called again to continue the stopped performance. Otherwise, reset() should be called to clean up after the finished or failed performance.

performBuffer()

Performs Csound, sensing real-time and score events.

Processing one buffer’s worth (-b frames) of interleaved audio.

Note that compile_() must be called first, then call outputBuffer() and inputBuffer(()) to get ndarrays pointing to Csound’s I/O buffers.

Returns False during performance, and true when performance is finished.

performKsmps()

Senses input events, and performs audio output.

This is done for one control sample worth (ksmps).

Note that compile_(), or compileOrc(), readScore(), start() must be called first.

Returns False during performance, and True when performance is finished. If called until it returns True, it will perform an entire score.

Enables external software to control the execution of Csound, and to synchronize performance with audio input and output.

popFirstMessage()

Removes the first message from the buffer.

pvsChannel(fout, name)

Receives a PvsdatExt fout from the pvsout opcode (f-rate) at channel name.

Returns zero on success, CSOUND_ERROR if the index is invalid or if fsig framesizes are incompatible.
CSOUND_MEMORY if there is not enough memory to extend the bus.
queryGlobalVariable(name)

Gets pointer to space allocated with the name name.

Return None if the specified name is not defined.

queryGlobalVariableNoCheck(name)

This function is the similar to :py:meth`queryGlobalVariable()`.

Except the variable is assumed to exist and no error checking is done. Faster, but may crash or return an invalid pointer if name is not defined.

rand31(seed)

Simple linear congruential random number generator:

seed = seed * 742938285 % 2147483647

The initial value of seed must be in the range 1 to 2147483646. Returns the next number from the pseudo-random sequence, in the range 1 to 2147483646.

randMT(state)

Returns next random number from MT19937 generator.

The PRNG must be initialized first by calling :py:meth`csoundSeedRandMT()`.

randomSeedFromTime()

Returns a 32-bit unsigned integer to be used as seed from current time.

readCircularBuffer(circularBuffer, out, items)

Reads from circular buffer.

circular_buffer
pointer to an existing circular buffer
out
preallocated ndarray with at least items number of elements, where buffer contents will be read into
items
number of samples to be read

Returns the actual number of items read (0 <= n <= items).

readScore(sco)

Reads, preprocesses, and loads a score from an ASCII string.

It can be called repeatedly, with the new score events being added to the currently scheduled ones.

readScoreAsync(sco)

Asynchronous version of readScore().

realTime(timerStruct)

Returns the elapsed real time (in seconds).

The time is measured since the specified timer structure was initialised.

registerKeyboardCallback(function, userData, type_)

Registers general purpose callback functions for keyboard events.

These callbacks are called on every control period by the sensekey opcode.

The callback is preserved on reset(), and multiple callbacks may be set and will be called in reverse order of registration. If the same function is set again, it is only moved in the list of callbacks so that it will be called first, and the user data and type mask parameters are updated. type_ can be the bitwise OR of callback types for which the function should be called, or zero for all types.

Returns zero on success, CSOUND_ERROR if the specified function pointer or type mask is invalid, and CSOUND_MEMORY if there is not enough memory.

The callback function takes the following arguments:

userData
the “user data” pointer, as specified when setting the callback
p
data pointer, depending on the callback type
type_

callback type, can be one of the following (more may be added in future versions of Csound):

CSOUND_CALLBACK_KBD_EVENT

CSOUND_CALLBACK_KBD_TEXT

called by the sensekey opcode to fetch key codes. The data pointer is a pointer to a single value of type int, for returning the key code, which can be in the range 1 to 65535, or 0 if there is no keyboard event.

For CSOUND_CALLBACK_KBD_EVENT, both key press and release events should be returned (with 65536 (0x10000) added to the key code in the latter case) as unshifted ASCII codes. CSOUND_CALLBACK_KBD_TEXT expects key press events only as the actual text that is typed.

The return value should be zero on success, negative on error, and positive if the callback was ignored (for example because the type is not known).

registerSenseEventCallback(function, userData)

Registers a function to be called by sensevents().

This function will be called once in every control period. Any number of functions may be registered, and will be called in the order of registration.

The callback function takes two arguments: the Csound instance pointer, and the userData pointer as passed to this function.

This facility can be used to ensure a function is called synchronously before every csound control buffer processing. It is important to make sure no blocking operations are performed in the callback. The callbacks are cleared on cleanup().

Returns zero on success.

removeKeyboardCallback(function)

Removes a callback previously set with registerKeyboardCallback().

reset()

Resets all internal memory and state.

In preparation for a new performance. Enable external software to run successive Csound performances without reloading Csound. Implies cleanup(), unless already called.

rewindScore()

Rewinds a compiled Csound score.

It is rewinded to the time specified with setScoreOffsetSeconds().

rtPlaydUserData()

Returns pointer to user data pointer for real time audio output.

rtRecordUserData()

Returns pointer to user data pointer for real time audio input.

runCommand(args, noWait)

Runs an external command with the arguments specified in list args.

args[0] is the name of the program to execute (if not a full path file name, it is searched in the directories defined by the PATH environment variable).

If noWait is False, the function waits until the external program finishes, otherwise it returns immediately. In the first case, a non-negative return value is the exit status of the command (0 to 255), otherwise it is the PID of the newly created process. On error, a negative value is returned.

runUtility(name, args)

Runs utility with the specified name and command line arguments.

Should be called after loading utility plugins. Use :py:meth`reset()` to clean up after calling this function. Returns zero if the utility was run successfully.

scoreEvent(type_, pFields)

Sends a new score event.

type_ is the score event type (‘a’, ‘i’, ‘q’, ‘f’, or ‘e’).
pFields is a tuple, a list, or an ndarray of MYFLTs with all the pfields for this event, starting with the p1 value specified in pFields[0].
scoreEventAbsolute(type_, pFields, timeOffset)

Like scoreEvent(), this function inserts a score event.

The event is inserted at absolute time with respect to the start of performance, or from an offset set with timeOffset.

scoreEventAbsoluteAsync(type_, pFields, timeOffset)

Asynchronous version of scoreEventAbsolute().

scoreEventAsync(type_, pFields)

Asynchronous version of scoreEvent().

scoreOffsetSeconds()

Returns the score time beginning midway through a Csound score.

At this time score events will actually immediately be performed (see setScoreOffsetSeconds()).

scoreTime()

Returns the current score time.

The return value is the time in seconds since the beginning of performance.

seedRandMT(initKey)

Initializes Mersenne Twister (MT19937) random number generator.

initKey can be a single int, a list of int, or an ndarray of int. Those int values are converted to unsigned 32 bit values and used for seeding.

Returns a CsoundRandMTState stuct to be used by :py:meth`csoundRandMT()`.

setAudioChannel(name, samples)

Sets the audio channel name with data from the ndarray samples.

samples should contain at least ksmps() MYFLTs.

setAudioDevListCallback(function)

Sets a callback for obtaining a list of audio devices.

This should be set by rtaudio modules and should not be set by hosts. (See audioDevList()).

setControlChannel(name, val)

Sets the value of control channel identified by name.

setControlChannelHints(name, hints)

Sets parameters hints for a control channel.

These hints have no internal function but can be used by front ends to construct GUIs or to constrain values. See the ControlChannelHints structure for details. Returns zero on success, or a non-zero error code on failure:

CSOUND_ERROR
the channel does not exist, is not a control channel, or the specified parameters are invalid
CSOUND_MEMORY
could not allocate memory
setCscoreCallback(function)

Sets an external callback for Cscore processing.

Pass None to reset to the internal cscore() function (which does nothing). This callback is retained after a reset() call.

setDebug(debug)

Sets whether Csound prints debug messages.

The debug argument must have value True or False. Those messages come from the DebugMsg() internal API function.

setDrawGraphCallback(function)

Called by external software to set Csound’s DrawGraph function.

setExitGraphCallback(function)

Called by external software to set Csound’s ExitGraph function.

setExternalMidiErrorStringCallback(function)

Sets a callback for converting MIDI error codes to strings.

setExternalMidiInCloseCallback(function)

Sets a callback for closing real time MIDI input.

setExternalMidiInOpenCallback(function)

Sets a callback for opening real-time MIDI input.

setExternalMidiOutCloseCallback(function)

Sets a callback for closing real time MIDI input.

setExternalMidiOutOpenCallback(function)

Sets a callback for opening real-time MIDI input.

setExternalMidiReadCallback(function)

Sets a callback for reading from real time MIDI input.

setExternalMidiWriteCallback(function)

Sets a callback for reading from real time MIDI input.

setFileOpenCallback(function)

Sets a callback for receiving notices whenever Csound opens a file.

The callback is made after the file is successfully opened. The following information is passed to the callback:

bytes
pathname of the file; either full or relative to current dir
int
a file type code from the enumeration CSOUND_FILETYPES
int
1 if Csound is writing the file, 0 if reading
int
1 if a temporary file that Csound will delete; 0 if not

Pass NULL to disable the callback. This callback is retained after a reset() call.

setGlobalEnv(name, value)

Sets the global value of environment variable name to value.

The variable is deleted if value is None. It is not safe to call this function while any Csound instances are active.

Returns zero on success.

setHostData(data)

Sets host data.

setHostImplementedAudioIO(state, bufSize)

Sets user handling of sound I/O.

Calling this function with a True state value between creation of the Csound object and the start of performance will disable all default handling of sound I/O by the Csound library, allowing the host application to use the spin/spout/input/output buffers directly.

For applications using spin/spout, bufSize should be set to 0. If bufSize is greater than zero, the buffer size (-b) will be set to the integer multiple of ksmps() that is nearest to the value specified.

setHostImplementedMIDIIO(state)

Called with state True if the host is implementing via callbacks.

setInput(name)

Sets input source.

setInputChannelCallback(function)

Sets the function to call whenever the invalue opcode is used.

setIsGraphable(isGraphable)

Tells Csound whether external graphic table display is supported.

Return the previously set value (initially False).

setKillGraphCallback(function)

Called by external software to set Csound’s KillGraph function.

setLanguage(lang_code)

Sets language to lang_code.

lang_code can be for example CSLANGUAGE_ENGLISH_UK or CSLANGUAGE_FRENCH or many others, (see n_getstr.h for the list of languages). This affects all Csound instances running in the address space of the current process. The special language code CSLANGUAGE_DEFAULT can be used to disable translation of messages and free all memory allocated by a previous call to setLanguage(). setLanguage() loads all files for the selected language from the directory specified by the CSSTRNGS environment variable.

setMIDIFileInput(name)

Sets MIDI file input name.

setMIDIFileOutput(name)

Sets MIDI file output name.

setMIDIInput(name)

Sets MIDI input device name/number.

setMIDIModule(module)

Sets the current MIDI IO module.

setMIDIOutput(name)

Sets MIDI output device name/number.

setMakeGraphCallback(function)

Called by external software to set Csound’s MakeGraph function.

setMessageLevel(messageLevel)

Sets the Csound message level (from 0 to 231).

setMidiDevListCallback(function)

Sets a callback for obtaining a list of MIDI devices.

This should be set by IO plugins and should not be set by hosts. (See midiDevList()).

setOption(option)

Sets a single csound option (flag).

Returns CSOUND_SUCCESS on success.
NB: blank spaces are not allowed.
setOutput(name, type_, format)

Sets output destination, type and format.

type_ can be one of “wav”, “aiff”, “au”, “raw”, “paf”, “svx”, “nist”, “voc”, “ircam”, “w64”, “mat4”, “mat5”, “pvf”, “xi”, “htk”, “sds”, “avr”, “wavex”, “sd2”, “flac”, “caf”, “wve”, “ogg”, “mpc2k”, “rf64”, or NULL (use default or realtime IO).
format can be one of “alaw”, “schar”, “uchar”, “float”, “double”, “long”, “short”, “ulaw”, “24bit”, “vorbis”, or NULL (use default or realtime IO).

For RT audio, use device_id from CS_AUDIODEVICE for a given audio device.

setOutputChannelCallback(function)

Sets the function to call whenever the outvalue opcode is used.

setParams(params)

Configures Csound with a given set of parameters.

These parameters are defined in the CsoundParams structure. They are the part of the OPARMS struct that are configurable through command line flags. The CsoundParams structure can be obtained using params(). These options should only be changed before performance has started.

setPlayOpenCallback(function)

Sets a callback for opening real-time audio playback.

setPvsChannel(fin, name)

Sends a PvsdatExt fin to the pvsin opcode (f-rate) for channel name.

Returns zero on success, CSOUND_ERROR if the index is invalid or fsig framesizes are incompatible.
CSOUND_MEMORY if there is not enough memory to extend the bus.
setRTAudioModule(module)

Sets the current RT audio module.

setRecordOpenCallback(function)

Sets a callback for opening real-time audio recording.

setRtCloseCallback(function)

Sets a callback for closing real-time audio playback and recording.

setRtPlayCallback(function)

Sets a callback for performing real-time audio playback.

setRtRecordCallback(function)

Sets a callback for performing real-time audio recording.

setScoreOffsetSeconds(time)

Csound score events prior to the specified time are not performed.

Performance begins immediately at the specified time (real-time events will continue to be performed as they are received). Can be used by external software, such as a VST host, to begin score performance midway through a Csound score, for example to repeat a loop in a sequencer, or to synchronize other events with the Csound score.

setScorePending(pending)

Sets whether Csound score events are performed or not.

Real-time events will continue to be performed. Can be used by external software, such as a VST host, to turn off performance of score events (while continuing to perform real-time events), for example to mute a Csound score while working on other tracks of a piece, or to play the Csound instruments live.

setSpinSample(frame, channel, sample)

Sets the audio input working buffer (spin) to the indicated sample.

This only ever makes sense before calling performKsmps(). The frame and channel must be in bounds relative to ksmps() and nchnlsInput().

setStringChannel(name, string)

Sets the string channel identified by name with string.

setYieldCallback(function)

Called by external software to set a yield function.

This callback is used for checking system events, yielding cpu time for coopertative multitasking, etc.

This function is optional. It is often used as a way to ‘turn off’ Csound, allowing it to exit gracefully. In addition, some operations like utility analysis routines are not reentrant and you should use this function to do any kind of updating during the operation.

Returns an ‘OK to continue’ boolean.

sizeOfMYFLT()

Returns the size of MYFLT in bytes.

sleep(milliseconds)

Waits for at least the specified number of milliseconds.

It yields the CPU to other threads.

spin()

Returns the Csound audio input working buffer (spin) as an ndarray.

Enables external software to write audio into Csound before calling performKsmps().

spinLock(spinlock)

Locks the spinlock.

spinLockInit(spinlock)

Inits the spinlock.

If the spinlock is not locked, locks it and returns; if is is locked, waits until it is unlocked, then locks it and returns. Uses atomic compare and swap operations that are safe across processors and safe for out of order operations, and which are more efficient than operating system locks.

Use spinlocks to protect access to shared data, especially in functions that do little more than read or write such data, for example:

lock = ctypes.c_int32(0)
cs.spinLockInit(lock)
def write(cs, frames, signal):
    cs.spinLock(lock)
    for frame in range(frames) :
        global_buffer[frame] += signal[frame];
    cs.spinUnlock(lock)
spinTryLock(spinlock)

Tries the spinlock.

returns CSOUND_SUCCESS if lock could be acquired, CSOUND_ERROR, otherwise.

spinUnlock(spinlock)

Unlocks the spinlock.

spout()

Returns the address of the Csound audio output working buffer (spout).

Enables external software to read audio from Csound after calling performKsmps().

spoutSample(frame, channel)

Returns one sample from the Csound audio output working buf (spout).

Only ever makes sense after calling performKsmps(). The frame and channel must be in bounds relative to ksmps() and nchnls().

sr()

Returns the number of audio sample frames per second.

start()

Prepares Csound for performance.

Normally called after compiling a csd file or an orc file, in which case score preprocessing is performed and performance terminates when the score terminates.

However, if called before compiling a csd file or an orc file, score preprocessing is not performed and “i” statements are dispatched as real-time events, the <CsOptions> tag is ignored, and performance continues indefinitely or until ended using the API.

NB: this is called internally by compile_(), therefore it is only required if performance is started without a call to that function.

stop()

Stops a perform() running in another thread.

Note that it is not guaranteed that perform() has already stopped when this function returns.

stopUDPConsole()

Stops transmitting console messages via UDP.

stringChannel(name, string)

Copies the string channel identified by name into string.

string should contain enough memory for the string (see channelDatasize() below).

table(tableNum)

Returns a pointer to function table tableNum as an ndarray.

The ndarray does not include the guard point. If the table does not exist, None is returned.

tableArgs(tableNum)

Returns a pointer to the args used to generate a function table.

The pointer is returned as an ndarray. If the table does not exist, None is returned.

NB: the argument list starts with the GEN number and is followed by its parameters. eg. f 1 0 1024 10 1 0.5 yields the list {10.0, 1.0, 0.5}

tableCopyIn(table, src)

Copies the contents of an ndarray src into a given function table.

The table number is assumed to be valid, and the table needs to have sufficient space to receive all the array contents.

tableCopyInAsync(table, src)

Asynchronous version of tableCopyIn().

tableCopyOut(table, dest)

Copies the contents of a function table into a supplied ndarray dest.

The table number is assumed to be valid, and the destination needs to have sufficient space to receive all the function table contents.

tableCopyOutAsync(table, dest)

Asynchronous version of tableCopyOut().

tableGet(table, index)

Returns the value of a slot in a function table.

The table number and index are assumed to be valid.

tableLength(table)

Returns the length of a function table.

(Not including the guard point). If the table does not exist, returns -1.

tableSet(table, index, value)

Sets the value of a slot in a function table.

The table number and index are assumed to be valid.

unlockMutex(mutex)

Releases the indicated mutex object.

The mutex should be owned by the current thread, otherwise the operation of this function is undefined. A recursive mutex needs to be unlocked as many times as it was locked previously.

utilityDescription(name)

Gets utility description.

Returns None if the utility was not found, or it has no description, or an error occured.

version()

Returns the version number times 1000 (5.00.0 = 5000).

waitBarrier(barrier)

Waits on the thread barrier.

waitThreadLock(lock, milliseconds)

Waits on the indicated monitor object for the indicated period.

The function returns either when the monitor object is notified, or when the period has elapsed, whichever is sooner; in the first case, zero is returned.

If milliseconds is zero and the object is not notified, the function will return immediately with a non-zero status.

waitThreadLockNoTimeout(lock)

Waits on the indicated monitor object until it is notified.

This function is similar to waitThreadLock() with an infinite wait time, but may be more efficient.

writeCircularBuffer(circularBuffer, in_, items)

Writes to circular buffer.

circular_buffer
pointer to an existing circular buffer
in_
ndarray with at least items number of elements to be written into circular buffer
items
number of samples to write

Returns the actual number of items written (0 <= n <= items).