CsoundUnity 4.0.0-alpha.3
Loading...
Searching...
No Matches
Csound.Unity.CsoundWorker Class Reference

A Csound instance on a thread of its own, started with -n -d so it touches no audio device. Used for work that must not run on the audio thread: rendering a csd to a file, and scanning a csd for the channels its orchestra allocates. More...

Inheritance diagram for Csound.Unity.CsoundWorker:
Csound.Unity.CsoundUnityBridge

Public Member Functions

 CsoundWorker ()
 Creates and starts an offline worker. Call from Unity's main thread.
override bool Reset ()
 Refuses reset because the worker owns a performance thread outside the audio handshake.
override bool Destroy ()
 Joins the performance thread, then frees the instance.
int CreateTable (int tableNumber, MYFLT[] samples)
 Creates a table with the supplied samples. Can be called during performance.
int CreateTableInstrument (int tableNumber, int tableLength)
 Creates an empty table, to be filled with samples later. Please note that trying to read the samples from an empty table will produce a crash. Can be called during performance.
bool SaveAudioFile (string destination, float[] samples, int bitsPerSample=16)
 Writes samples to an audio file, by loading them into a function table and running an instrument that calls ftaudio. The extension of destination picks the format.
int ScheduleInstrument (int instrNumber, float start, float duration, params string[] pfields)
 Schedules one instrument instance on this worker's instance.
void PerformanceThread ()
 The worker's loop: calls csoundPerformKsmps until the score ends, an error comes back, or the worker is destroyed. This is the body of the dedicated thread.
Public Member Functions inherited from Csound.Unity.CsoundUnityBridge
CsoundArrayChannelStatus InitializeArrayChannel (string name, CsoundArrayChannelType type, params int[] sizes)
 Initialize an array channel, or validate an existing channel without resizing it. May allocate and briefly suspend Unity audio; never call from a performance callback. A subclass driving its own performance thread must stop that thread before initialization.
CsoundArrayChannelStatus GetArrayChannelInfo (string name, int[] sizes, out CsoundArrayChannelInfo info)
 Read array metadata and axis sizes into a reusable buffer; no channel is created.
CsoundArrayChannelStatus GetArrayChannel (string name, MYFLT[] destination, out int length)
 Copy a complete numeric array to a flat buffer; length reports required capacity on BufferTooSmall.
CsoundArrayChannelStatus GetArrayChannel (string name, MYFLT[] destination, int[] sizes, out CsoundArrayChannelInfo info)
 Read numeric values, axis sizes and matching metadata atomically; no partial copy occurs.
CsoundArrayChannelStatus SetArrayChannel (string name, MYFLT[] source)
 Write exactly the current number of numeric elements without creating or resizing the channel.
CsoundArrayChannelStatus GetAudioArrayChannel (string name, MYFLT[] destination, out int length)
 Read a[] blocks in element order, ksmps samples per element; length reports required samples.
CsoundArrayChannelStatus GetAudioArrayChannel (string name, MYFLT[] destination, int[] sizes, out CsoundArrayChannelInfo info)
 Read all audio blocks and their matching shape; no buffer changes on BufferTooSmall.
CsoundArrayChannelStatus SetAudioArrayChannel (string name, MYFLT[] source)
 Replace all a[] blocks; source must contain exactly ElementCount × ksmps samples.
 CsoundUnityBridge ()
 Default parameterless constructor. Creates an uninitialised bridge instance.
 CsoundUnityBridge (string csdFile, List< EnvironmentSettings > environmentSettings, float audioRate, float controlRate, int ksmps=0)
 The CsoundUnityBridge constructor sets up the Csound Global Environment Variables set by the user. Then it creates an instance of Csound and compiles the full csdFile passed as a string. Then it starts Csound.
void EnqueueMidiMessage (byte[] data)
 Enqueues a raw MIDI message to be delivered to Csound on the next ksmps cycle. Can be called from any thread.
int LoadPlugins (string dir)
 Loads all Csound plugins found in the specified directory. Not available on iOS; use the conditional compilation guard before calling.
int GetVersion ()
 Returns the Csound library version as an integer (e.g. 6180 for version 6.18.0). On WebGL, available after initialization completes.
bool CompiledWithoutError ()
 Returns true if the CSD compiled without errors; equivalent to reading CompiledOk.
int CompileOrc (string orchStr)
 Compiles the given Csound orchestra string at runtime, adding new instruments and UDOs to the running instance.
int Start ()
 Starts a compiled orchestra after reset and enables audio callbacks. Call CompileOrc first. A running instance is left running without starting it twice.
int PerformKsmps ()
 Advances Csound by one ksmps block, filling the spout buffer, and caches the spout/spin pointers on the first successful call.
MYFLT Get0dbfs ()
 Returns the 0 dBFS value (full-scale amplitude) for this Csound instance, as set by the 0dbfs header statement.
long GetCurrentTimeSamples ()
 Returns the current performance position in samples from the start of the performance.
void SendScoreEvent (string scoreEvent)
 Sends a score event string to Csound (e.g. "i 1 0 1 0.5 440") for immediate processing.
void RewindScore ()
 Rewinds the score to the beginning, allowing the performance to repeat from time zero.
void CsoundSetScoreOffsetSeconds (MYFLT value)
 Sets the score time offset in seconds, causing performance to start from the given point in the score.
void SetChannel (string channel, MYFLT value)
 Sets the value of a named Csound control channel.
void SetStringChannel (string channel, string value)
 Sets the value of a named Csound string channel.
void SetAudioChannel (string name, MYFLT[] audio)
 Writes a ksmps-length audio buffer into the named Csound audio channel. Only the first ksmps samples are used; excess samples are ignored. A shorter array is padded with silence; an empty array clears the channel.
MYFLT[] GetAudioChannel (string name)
 Reads the named Csound audio channel into a newly allocated array of length ksmps. Use the zero-allocation overload on hot audio-thread paths to avoid GC pressure.
void GetAudioChannel (string name, MYFLT[] dest)
 Zero-allocation overload: reads the named audio channel directly into dest without any managed or native heap allocation. Use this on hot audio-thread paths to avoid GC pressure.
string GetStringChannel (string name)
 Reads the current value of the named Csound string channel.
int TableLength (int table)
 Returns the length of a function table (not including the guard point), or -1 if the table does not exist.
MYFLT GetTable (int table, int index)
 Returns the value of a slot in a function table. The table number and index are assumed to be valid.
void SetTable (int table, int index, MYFLT value)
 Sets the value of a slot in a function table. The table number and index are assumed to be valid.
void TableCopyOut (int table, out MYFLT[] dest)
 Copies the contents of a function table into a supplied array. The table number is assumed to be valid, and the destination will be resized to fit all table contents.
void TableCopyIn (int table, MYFLT[] source)
 Copies the contents of an array into a given function table. The table number is assumed to be valid, and the table must have sufficient space to receive all array contents.
int GetTable (out MYFLT[] tableValues, int numTable)
 Stores values of function table numTable in tableValues , and returns the table length (not including the guard point). If the table does not exist, tableValues is set to null and -1 is returned.
int GetTableArgs (out MYFLT[] args, int index)
 Stores the arguments used to generate function table index in args , and returns the number of arguments used. If the table does not exist, args is set to null and -1 is returned.
MYFLT GetSr ()
 Returns the audio sample rate (sr) of the current Csound instance.
MYFLT GetKr ()
 Returns the control rate (kr) of the current Csound instance.
uint GetKsmps ()
 Returns the number of samples per control period (ksmps). Returns the cached value when available (set after csoundStart) to avoid a P/Invoke on the hot path.
MYFLT GetSpoutSample (int frame, int channel)
 Get a sample from Csound's audio output buffer. Hot path — uses cached spout pointer and channel count; zero allocation. The pointer is fetched lazily because csoundGetSpout may return NULL before the first csoundPerformKsmps.
void AddSpinSample (int frame, int channel, MYFLT sample)
 Add a value to a sample in Csound's audio input buffer. Hot path — uses cached spin pointer and channel count; zero allocation.
void SetSpinSample (int frame, int channel, MYFLT sample)
 Set a sample in Csound's audio input buffer. Hot path — uses cached spin pointer and channel count; zero allocation.
void ClearSpin ()
 Clears the input buffer (spin).
MYFLT[] GetSpin ()
 Returns the Csound audio input working buffer (spin) as a MYFLT array. Enables external software to write audio into Csound before calling csoundPerformKsmps.
MYFLT[] GetSpout ()
 Returns the Csound audio output working buffer (spout) as a MYFLT array. Enables external software to read audio from Csound after calling csoundPerformKsmps.
MYFLT GetChannel (string channel)
 Returns the current value of the named Csound control channel. On WebGL returns the last-known cached value (0 until the first async read completes) and automatically schedules a non-blocking refresh via the callback-based overload.
uint GetNchnlsInput ()
 Get number of input channels.
uint GetNchnls ()
 Get number of output channels.
int GetCsoundMessageCount ()
 Returns the number of pending messages in Csound's message buffer.
string GetCsoundMessage ()
 Retrieves and removes the first pending message from Csound's message buffer.
IDictionary< string, ChannelInfo > GetChannelList ()
 Provides a dictionary of all currently defined channels resulting from compilation of an orchestra containing channel definitions. Entries, keyed by name, are polymorphically assigned to their correct data type: control, audio, string, pvc. Used internally to initialize channel contents.
string GetEnv (string key)
 Gets a string value from csound's environment values. Meaningful values include the contents of Windows' OS environment values such as SFDIR or SADIR for path name defaults.
int SetGlobalEnv (string name, string value)
 Set the global value of environment variable 'name' to 'value', or delete variable if 'value' is NULL. It is not safe to call this function while any Csound instances are active. See https://csound.com/docs/manual/CommandEnvironment.html for a list of the variables that can be used.
CsoundPvsChannelStatus InitializePvsChannel (string name, int fftSize, int overlap, int windowSize, int windowType=1, CsoundPvsFormat format=CsoundPvsFormat.AmplitudeFrequency)
 Create or verify a fixed-layout, non-sliding PVS channel. Setup only; may briefly suspend Unity audio.
CsoundPvsChannelStatus GetPvsChannelInfo (string name, out CsoundPvsChannelInfo info)
 Read PVS layout and frame counter without creating a channel.
CsoundPvsChannelStatus GetPvsChannel (string name, float[] destination, out CsoundPvsChannelInfo info)
 Read one complete N+2 float frame and matching metadata; unused trailing entries are unchanged.
CsoundPvsChannelStatus SetPvsChannel (string name, float[] source)
 Write exactly N+2 floats and advance the destination frame counter once on success.
CsoundPvsChannelStatus SetPvsChannel (string name, float[] source, CsoundPvsChannelInfo frame)
 Write a snapshot to a channel with the same layout, preserving the supplied frame counter.
CsoundArrayChannelStatus GetStringArrayChannel (string name, string[] destination, out int length)
 Read S[] values into a reusable container; changed strings allocate and unused trailing entries remain unchanged.
CsoundArrayChannelStatus GetStringArrayChannel (string name, string[] destination, int[] sizes, out CsoundArrayChannelInfo info)
 Read string data and matching axis sizes atomically; UTF-8 decoding happens outside the native lock.
CsoundArrayChannelStatus SetStringArrayChannel (string name, string[] source)
 Replace every S[] element; null becomes empty, embedded null characters are rejected. Not for audio callbacks.
void TableCopyOutAsync (int table, out MYFLT[] dest)
 Queues a table read. The returned array is filled during a later performance cycle.
CsoundTableCopySubmission TableCopyOutAsync (int table, out MYFLT[] dest, out CsoundTableCopyRequest request)
 Queues a table read and returns a request to poll. The destination is valid on success.
void TableCopyInAsync (int table, MYFLT[] source)
 Queues a copy of the source samples into the table, preserving any remaining entries.
CsoundTableCopySubmission TableCopyInAsync (int table, MYFLT[] source, out CsoundTableCopyRequest request)
 Queues a table write and returns a request to poll, or null if it could not be queued.

Static Public Member Functions

static CsoundWorker Create ()
 Creates a worker with an empty csd, ready to compile orchestra code into.
static void ScanCsdForChannels (string csdString, Action< IDictionary< string, CsoundUnityBridge.ChannelInfo > > onComplete, List< EnvironmentSettings > environmentSettings=null)
 Scans a CSD string in a temporary, isolated Csound instance (−n −d, no audio I/O). After compiling the CSD and running one PerformKsmps, all channels allocated by the orchestra are queried and returned via onComplete .
Static Public Member Functions inherited from Csound.Unity.CsoundUnityBridge
static string GetMessageText (IntPtr message)
 Converts a native char pointer returned by Csound into a managed string.

Protected Member Functions

virtual void Dispose ()
 Stops the performance loop and waits for the thread to exit, then frees the callback handles. Does nothing on a second call.
void ReleaseProtectedPointer (IntPtr pgcData)
 Frees a GCHandle that was pinned for a native callback.
Protected Member Functions inherited from Csound.Unity.CsoundUnityBridge
 CsoundUnityBridge (float sampleRate, int ksmps)
 Records the host settings for a derived bridge that creates its own instance.

Protected Attributes

bool m_disposed = false
 True once Dispose has run, so it does not run twice.

Package Functions

GCHandle SetMessageCallback (MessageStrCallbackProxy callback)
GCHandle FreezeCallbackInHeap (Delegate callback)
Package Functions inherited from Csound.Unity.CsoundUnityBridge
bool TryEnterAudio ()
 Claims this bridge for the duration of one audio callback. Returns false when the instance is being destroyed, reset or awaiting start, and the caller must produce silence without touching the bridge at all.
void ExitAudio ()
 Releases the claim taken by TryEnterAudio. Clears the claim id only if it is this thread's, so a second caller cannot erase the id of a thread that is still inside.
int StartWithSetup (Action prepareAudio)

Properties

bool IsInitialized [get, set]
 True once the instance has been created and its csd compiled.
Properties inherited from Csound.Unity.CsoundUnityBridge
bool CompiledOk [get]
 Returns true while this instance holds a successfully compiled orchestra.
float OutputGain [get]
 Gain the audio paths that read spout directly should apply to their output: 0 while muted or paused, 1 otherwise. Exists so the two of them — IAudioGenerator and RootOutput — cannot drift apart on what "silent" means.

Additional Inherited Members

Public Types inherited from Csound.Unity.CsoundUnityBridge
enum  ChannelBehavior { None = 0 , Integer = 1 , Linear = 2 , Exponential = 3 }
 Defines the interpolation behavior of a Csound control channel. More...
enum  ChannelType {
  None = 0 , Control = 1 , Audio = 2 , String = 3 ,
  Pvs = 4 , Var = 5 , Array = 6
}
 Identifies the data type carried by a Csound software-bus channel. More...
enum  ChannelDirection { Input = 1 , Output = 2 }
 Flags indicating whether a Csound channel is readable (input), writable (output), or both. More...
Public Attributes inherited from Csound.Unity.CsoundUnityBridge
IntPtr csound
 The raw Csound instance handle used for all native P/Invoke calls.
volatile bool Muted
 Mirrors the owning CsoundUnity.mute flag so that the audio paths which read spout without going through ProcessBlock — IAudioGenerator and RootOutput — can honour it. ProcessBlock checks mute directly and does not use this.
volatile bool Paused
 Mirrors the owning CsoundUnity.pauseProcessing flag, for the same reason as Muted. When set, those paths skip PerformKsmps entirely and output silence.
volatile int StartupFadeFrames
 Length of the startup fade in output frames, 0 when off. Pushed by CsoundUnity from its fadeInSeconds; lives here for the same reason OutputGain does, so the paths that read spout directly — IAudioGenerator and RootOutput — cannot end up fading differently from each other or from OnAudioFilterRead.
volatile float LoudThreshold = float.PositiveInfinity
 Sample value at which an audio path silences a sample and reports a runaway. Pushed by CsoundUnity from its loudWarningThreshold, and PositiveInfinity when that check is off, which still catches a sample that is not a number. Here for the same reason StartupFadeFrames is: so the paths that read spout directly guard the output the way OnAudioFilterRead does.
volatile float SpatialBlend
 How far the AudioSource is spatialized, 0 to 1, pushed by CsoundUnity every frame. The IAudioGenerator path needs it because Unity sums a generator's channels for a spatialized source, so a mono bed written into every channel has to be divided by what that costs.
volatile float LoudPeak
 The largest sample an audio path had to silence in its last block, 0 when nothing tripped and infinity when what tripped it was not a number. Written on the audio thread and cleared by its reader, so the warning is printed on the thread that is allowed to print.
Static Public Attributes inherited from Csound.Unity.CsoundUnityBridge
static int WebGLVariation = 3
 Which @csound/browser variation to create: 0 single threaded, 1 worker with a SharedArrayBuffer, 2 worker with a MessagePort. Anything higher clamps to the last. Read only in a WebGL player, and declared outside the guard so that code setting it compiles on every platform.
const int DestroyedSentinel = int.MinValue
 Returned by PerformKsmps when the instance has already been destroyed. Distinct from 0 (running) and from every positive value (score ended), so that a caller testing > 0 cannot mistake a freed instance for a finished score.
Static Protected Member Functions inherited from Csound.Unity.CsoundUnityBridge
static string UserOpcodeDir (List< EnvironmentSettings > environmentSettings)
 The plugin opcode folder the user asked for in the environment settings, or null when there is none for this platform. Csound takes the folder from the argument of csoundCreate, which wins over OPCODE7DIR64, so a setting that is only exported as an environment variable would be ignored.
static IntPtr CreateCsound (float sampleRate, int ksmps=0, string opcodeDir=null)
 Creates a Csound instance with the setup every path in the package needs: a message buffer, Csound's own audio I/O disabled, and the host's rates. The caller compiles the csd and calls csoundStart.
Static Package Functions inherited from Csound.Unity.CsoundUnityBridge
static IDictionary< string, ChannelInfo > GetChannelList (IntPtr csoundHandle)
 Lists the channels allocated on a raw Csound handle. CsoundWorker.ScanCsdForChannels calls it for the temporary instance it manages, and GetChannelList() for this one.
static string CharPtr2String (IntPtr pString)
 Converts the char* for an ascii "c" string represented by the provided IntPtr into a managed string. Usually used for values returning a const char * from a csound routine. Using this method avoids pInvoke's default automatic attempted deletion of the returned char[] when string is expressly given as a marshalling type.

Detailed Description

A Csound instance on a thread of its own, started with -n -d so it touches no audio device. Used for work that must not run on the audio thread: rendering a csd to a file, and scanning a csd for the channels its orchestra allocates.

Constructor & Destructor Documentation

◆ CsoundWorker()

Csound.Unity.CsoundWorker.CsoundWorker ( )
inline

Creates and starts an offline worker. Call from Unity's main thread.

Member Function Documentation

◆ Create()

CsoundWorker Csound.Unity.CsoundWorker.Create ( )
inlinestatic

Creates a worker with an empty csd, ready to compile orchestra code into.

Returns
The new worker.

◆ CreateTable()

int Csound.Unity.CsoundWorker.CreateTable ( int tableNumber,
MYFLT[] samples )
inline

Creates a table with the supplied samples. Can be called during performance.

Parameters
tableNumberThe table number
samples
Returns

◆ CreateTableInstrument()

int Csound.Unity.CsoundWorker.CreateTableInstrument ( int tableNumber,
int tableLength )
inline

Creates an empty table, to be filled with samples later. Please note that trying to read the samples from an empty table will produce a crash. Can be called during performance.

Parameters
tableNumberThe number of the newly created table
tableLengthThe length of the table in samples
Returns
0 If the table could be created

◆ Destroy()

override bool Csound.Unity.CsoundWorker.Destroy ( )
inlinevirtual

Joins the performance thread, then frees the instance.

The order is the point: csoundDestroy takes an internal Csound lock that csoundPerformKsmps holds, so freeing while the thread is still inside it deadlocks. Dispose does not return until the thread has exited.

Returns
Whatever the base teardown returns: true when the instance was freed.

Reimplemented from Csound.Unity.CsoundUnityBridge.

◆ Dispose()

virtual void Csound.Unity.CsoundWorker.Dispose ( )
inlineprotectedvirtual

Stops the performance loop and waits for the thread to exit, then frees the callback handles. Does nothing on a second call.

◆ FreezeCallbackInHeap()

GCHandle Csound.Unity.CsoundWorker.FreezeCallbackInHeap ( Delegate callback)
inlinepackage

◆ PerformanceThread()

void Csound.Unity.CsoundWorker.PerformanceThread ( )
inline

The worker's loop: calls csoundPerformKsmps until the score ends, an error comes back, or the worker is destroyed. This is the body of the dedicated thread.

◆ ReleaseProtectedPointer()

void Csound.Unity.CsoundWorker.ReleaseProtectedPointer ( IntPtr pgcData)
inlineprotected

Frees a GCHandle that was pinned for a native callback.

Parameters
pgcDataThe handle as an IntPtr. Null and zero are ignored.

◆ Reset()

override bool Csound.Unity.CsoundWorker.Reset ( )
inlinevirtual

Refuses reset because the worker owns a performance thread outside the audio handshake.

Call Destroy and create a new worker for another orchestra.

Returns
Always false. The worker is neither reset nor stopped.

Reimplemented from Csound.Unity.CsoundUnityBridge.

◆ SaveAudioFile()

bool Csound.Unity.CsoundWorker.SaveAudioFile ( string destination,
float[] samples,
int bitsPerSample = 16 )
inline

Writes samples to an audio file, by loading them into a function table and running an instrument that calls ftaudio. The extension of destination picks the format.

Parameters
destinationFull path of the file to write, extension included.
samplesThe samples to write, in Unity's ±1 range.
bitsPerSampleBit depth of the written file.
Returns
True when Csound accepted the instrument that writes the file.

◆ ScanCsdForChannels()

void Csound.Unity.CsoundWorker.ScanCsdForChannels ( string csdString,
Action< IDictionary< string, CsoundUnityBridge.ChannelInfo > > onComplete,
List< EnvironmentSettings > environmentSettings = null )
inlinestatic

Scans a CSD string in a temporary, isolated Csound instance (−n −d, no audio I/O). After compiling the CSD and running one PerformKsmps, all channels allocated by the orchestra are queried and returned via onComplete .

The callback is invoked on the background scan thread. To update Unity or Editor state, marshal back to the main thread (e.g. via EditorApplication.update).

Parameters
csdStringFull CSD content as a string.
onCompleteInvoked with a dictionary mapping channel name → CsoundUnityBridge.ChannelInfo.
environmentSettingsThe instance's environment settings, read for a user-set opcode directory. Without one the scan loads no plugin opcodes, so a CSD that needs them fails to compile here while it would run at playback.

◆ ScheduleInstrument()

int Csound.Unity.CsoundWorker.ScheduleInstrument ( int instrNumber,
float start,
float duration,
params string[] pfields )
inline

Schedules one instrument instance on this worker's instance.

Parameters
instrNumberThe instrument number.
startStart time in seconds, from now.
durationDuration in seconds. A negative value holds the note on.
pfieldsExtra p-fields, from p4 on.
Returns
0 when Csound accepted the event.

◆ SetMessageCallback()

GCHandle Csound.Unity.CsoundWorker.SetMessageCallback ( MessageStrCallbackProxy callback)
inlinepackage

Member Data Documentation

◆ m_disposed

bool Csound.Unity.CsoundWorker.m_disposed = false
protected

True once Dispose has run, so it does not run twice.

Property Documentation

◆ IsInitialized

bool Csound.Unity.CsoundWorker.IsInitialized
getset

True once the instance has been created and its csd compiled.


The documentation for this class was generated from the following file: