Debian Codegraph @

interfaces/ctcsound.py

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 #
2 # ctcsound.py:
3 #
4 # Copyright (C) 2016 Francois Pinot
5 #
6 # This file is part of Csound.
7 #
8 # This code is free software; you can redistribute it
9 # and/or modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # Csound is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with Csound; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21 # 02110-1301 USA
22 #
23
24 import ctypes as ct
25 import ctypes.util
26 import numpy as np
27 import sys
28
29 # This is a workaround to yield the PEP 3118 problem which appeared with
30 # numpy 1.15.0
31 if np.__version__ < '1.15':
32 arrFromPointer = lambda p : np.ctypeslib.as_array(p)
33 elif np.__version__ < '1.16':
34 sys.exit("ctcsound won't work with numpy 1.15.x. Please revert numpy" +
35 " to an older version or update numpy to a version >= 1.16")
36 else:
37 arrFromPointer = lambda p : p.contents
38
39 if sys.platform.startswith('linux'):
40 libcsound = ct.CDLL("libcsound64.so")
41 elif sys.platform.startswith('win'):
42 if sys.version_info.major <=3 and sys.version_info.minor < 8:
43 libcsound = ct.cdll.csound64
44 else:
45 libcsound = ct.CDLL(ctypes.util.find_library("csound64"))
46 elif sys.platform.startswith('darwin'):
47 libcsound = ct.CDLL(ctypes.util.find_library("CsoundLib64"))
48 else:
49 sys.exit("Don't know your system! Exiting...")
50
51 MYFLT = ct.c_double
52
53 class CsoundParams(ct.Structure):
54 _fields_ = [("debug_mode", ct.c_int), # debug mode, 0 or 1
55 ("buffer_frames", ct.c_int), # number of frames in in/out buffers
56 ("hardware_buffer_frames", ct.c_int), # ibid. hardware
57 ("displays", ct.c_int), # graph displays, 0 or 1
58 ("ascii_graphs", ct.c_int), # use ASCII graphs, 0 or 1
59 ("postscript_graphs", ct.c_int), # use postscript graphs, 0 or 1
60 ("message_level", ct.c_int), # message printout control
61 ("tempo", ct.c_int), # tempo ("sets Beatmode)
62 ("ring_bell", ct.c_int), # bell, 0 or 1
63 ("use_cscore", ct.c_int), # use cscore for processing
64 ("terminate_on_midi", ct.c_int), # terminate performance at the end
65 # of midifile, 0 or 1
66 ("heartbeat", ct.c_int), # print heart beat, 0 or 1
67 ("defer_gen01_load", ct.c_int), # defer GEN01 load, 0 or 1
68 ("midi_key", ct.c_int), # pfield to map midi key no
69 ("midi_key_cps", ct.c_int), # pfield to map midi key no as cps
70 ("midi_key_oct", ct.c_int), # pfield to map midi key no as oct
71 ("midi_key_pch", ct.c_int), # pfield to map midi key no as pch
72 ("midi_velocity", ct.c_int), # pfield to map midi velocity
73 ("midi_velocity_amp", ct.c_int), # pfield to map midi velocity as amplitude
74 ("no_default_paths", ct.c_int), # disable relative paths from files, 0 or 1
75 ("number_of_threads", ct.c_int), # number of threads for multicore performance
76 ("syntax_check_only", ct.c_int), # do not compile, only check syntax
77 ("csd_line_counts", ct.c_int), # csd line error reporting
78 ("compute_weights", ct.c_int), # deprecated, kept for backwards comp.
79 ("realtime_mode", ct.c_int), # use realtime priority mode, 0 or 1
80 ("sample_accurate", ct.c_int), # use sample-level score event accuracy
81 ("sample_rate_override", MYFLT), # overriding sample rate
82 ("control_rate_override", MYFLT), # overriding control rate
83 ("nchnls_override", ct.c_int), # overriding number of out channels
84 ("nchnls_i_override", ct.c_int), # overriding number of in channels
85 ("e0dbfs_override", MYFLT), # overriding 0dbfs
86 ("daemon", ct.c_int), # daemon mode
87 ("ksmps_override", ct.c_int), # ksmps override
88 ("FFT_library", ct.c_int)] # fft_lib
89
90 string128 = ct.c_char * 128
91
92 class CsoundAudioDevice(ct.Structure):
93 _fields_ = [("device_name", string128),
94 ("device_id", string128),
95 ("rt_module", string128),
96 ("max_nchnls", ct.c_int),
97 ("isOutput", ct.c_int)]
98
99 class CsoundMidiDevice(ct.Structure):
100 _fields_ = [("device_name", string128),
101 ("interface_name", string128),
102 ("device_id", string128),
103 ("midi_module", string128),
104 ("isOutput", ct.c_int)]
105
106 class CsoundRtAudioParams(ct.Structure):
107 _fields_ = [("devName", ct.c_char_p), # device name (NULL/empty: default)
108 ("devNum", ct.c_int), # device number (0-1023), 1024: default
109 ("bufSamp_SW", ct.c_uint), # buffer fragment size (-b) in sample frames
110 ("bufSamp_HW", ct.c_int), # total buffer size (-B) in sample frames
111 ("nChannels", ct.c_int), # number of channels
112 ("sampleFormat", ct.c_int), # sample format (AE_SHORT etc.)
113 ("sampleRate", ct.c_float)] # sample rate in Hz
114
115 class RtClock(ct.Structure):
116 _fields_ = [("starttime_real", ct.c_int64),
117 ("starttime_CPU", ct.c_int64)]
118
119 class OpcodeListEntry(ct.Structure):
120 _fields_ = [("opname", ct.c_char_p),
121 ("outypes", ct.c_char_p),
122 ("intypes", ct.c_char_p),
123 ("flags", ct.c_int)]
124
125 class CsoundRandMTState(ct.Structure):
126 _fields_ = [("mti", ct.c_int),
127 ("mt", ct.c_uint32*624)]
128
129 # PVSDATEXT is a variation on PVSDAT used in the pvs bus interface
130 class PvsdatExt(ct.Structure):
131 _fields_ = [("N", ct.c_int32),
132 ("sliding", ct.c_int), # Flag to indicate sliding case
133 ("NB", ct.c_int32),
134 ("overlap", ct.c_int32),
135 ("winsize", ct.c_int32),
136 ("wintype", ct.c_int),
137 ("format", ct.c_int32),
138 ("framecount", ct.c_uint32),
139 ("frame", ct.POINTER(ct.c_float))]
140
141 # This structure holds the parameter hints for control channels
142 class ControlChannelHints(ct.Structure):
143 _fields_ = [("behav", ct.c_int),
144 ("dflt", MYFLT),
145 ("min", MYFLT),
146 ("max", MYFLT),
147 ("x", ct.c_int),
148 ("y", ct.c_int),
149 ("width", ct.c_int),
150 ("height", ct.c_int),
151 # This member must be set explicitly to None if not used
152 ("attributes", ct.c_char_p)]
153
154 class ControlChannelInfo(ct.Structure):
155 _fields_ = [("name", ct.c_char_p),
156 ("type", ct.c_int),
157 ("hints", ControlChannelHints)]
158
159 CAPSIZE = 60
160
161 class Windat(ct.Structure):
162 _fields_ = [("windid", ct.POINTER(ct.c_uint)), # set by makeGraph()
163 ("fdata", ct.POINTER(MYFLT)), # data passed to drawGraph()
164 ("npts", ct.c_int32), # size of above array
165 ("caption", ct.c_char * CAPSIZE), # caption string for graph
166 ("waitflg", ct.c_int16 ), # set =1 to wait for ms after Draw
167 ("polarity", ct.c_int16), # controls positioning of X axis
168 ("max", MYFLT), # workspace .. extrema this frame
169 ("min", MYFLT),
170 ("absmax", MYFLT), # workspace .. largest of above
171 ("oabsmax", MYFLT), # Y axis scaling factor
172 ("danflag", ct.c_int), # set to 1 for extra Yaxis mid span
173 ("absflag", ct.c_int)] # set to 1 to skip abs check
174
175 # Symbols for Windat.polarity field
176 NOPOL = 0
177 NEGPOL = 1
178 POSPOL = 2
179 BIPOL = 3
180
181 class NamedGen(ct.Structure):
182 pass
183
184 NamedGen._fields_ = [
185 ("name", ct.c_char_p),
186 ("genum", ct.c_int),
187 ("next", ct.POINTER(NamedGen))]
188
189
190 libcsound.csoundSetOpcodedir.argtypes = [ct.c_char_p]
191 libcsound.csoundCreate.restype = ct.c_void_p
192 libcsound.csoundCreate.argtypes = [ct.py_object]
193 libcsound.csoundLoadPlugins.argtypes = [ct.c_void_p, ct.c_char_p]
194 libcsound.csoundDestroy.argtypes = [ct.c_void_p]
195
196 libcsound.csoundParseOrc.restype = ct.c_void_p
197 libcsound.csoundParseOrc.argtypes = [ct.c_void_p, ct.c_char_p]
198
199 libcsound.csoundCompileTree.argtypes = [ct.c_void_p, ct.c_void_p]
200 libcsound.csoundCompileTreeAsync.argtypes = [ct.c_void_p, ct.c_void_p]
201 libcsound.csoundDeleteTree.argtypes = [ct.c_void_p, ct.c_void_p]
202 libcsound.csoundCompileOrc.argtypes = [ct.c_void_p, ct.c_char_p]
203 libcsound.csoundCompileOrcAsync.argtypes = [ct.c_void_p, ct.c_char_p]
204
205 libcsound.csoundEvalCode.restype = MYFLT
206 libcsound.csoundEvalCode.argtypes = [ct.c_void_p, ct.c_char_p]
207
208 libcsound.csoundCompileArgs.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(ct.c_char_p)]
209 libcsound.csoundStart.argtypes = [ct.c_void_p]
210 libcsound.csoundCompile.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(ct.c_char_p)]
211 libcsound.csoundCompileCsd.argtypes = [ct.c_void_p, ct.c_char_p]
212 libcsound.csoundCompileCsdText.argtypes = [ct.c_void_p, ct.c_char_p]
213
214 libcsound.csoundPerform.argtypes = [ct.c_void_p]
215 libcsound.csoundPerformKsmps.argtypes = [ct.c_void_p]
216 libcsound.csoundPerformBuffer.argtypes = [ct.c_void_p]
217 libcsound.csoundStop.argtypes = [ct.c_void_p]
218 libcsound.csoundCleanup.argtypes = [ct.c_void_p]
219 libcsound.csoundReset.argtypes = [ct.c_void_p]
220
221 libcsound.csoundUDPServerStart.argtypes = [ct.c_void_p, ct.c_uint]
222 libcsound.csoundUDPServerStatus.argtypes = [ct.c_void_p]
223 libcsound.csoundUDPServerClose.argtypes = [ct.c_void_p]
224 libcsound.csoundUDPConsole.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_uint, ct.c_uint]
225 libcsound.csoundStopUDPConsole.argtypes = [ct.c_void_p]
226
227 libcsound.csoundGetSr.restype = MYFLT
228 libcsound.csoundGetSr.argtypes = [ct.c_void_p]
229 libcsound.csoundGetKr.restype = MYFLT
230 libcsound.csoundGetKr.argtypes = [ct.c_void_p]
231 libcsound.csoundGetKsmps.restype = ct.c_uint32
232 libcsound.csoundGetKsmps.argtypes = [ct.c_void_p]
233 libcsound.csoundGetNchnls.restype = ct.c_uint32
234 libcsound.csoundGetNchnls.argtypes = [ct.c_void_p]
235 libcsound.csoundGetNchnlsInput.restype = ct.c_uint32
236 libcsound.csoundGetNchnlsInput.argtypes = [ct.c_void_p]
237 libcsound.csoundGet0dBFS.restype = MYFLT
238 libcsound.csoundGet0dBFS.argtypes = [ct.c_void_p]
239 libcsound.csoundGetA4.restype = MYFLT
240 libcsound.csoundGetA4.argtypes = [ct.c_void_p]
241 libcsound.csoundGetCurrentTimeSamples.restype = ct.c_int64
242 libcsound.csoundGetCurrentTimeSamples.argtypes = [ct.c_void_p]
243 libcsound.csoundGetHostData.restype = ct.py_object
244 libcsound.csoundGetHostData.argtypes = [ct.c_void_p]
245 libcsound.csoundSetHostData.argtypes = [ct.c_void_p, ct.py_object]
246 libcsound.csoundSetOption.argtypes = [ct.c_void_p, ct.c_char_p]
247 libcsound.csoundSetParams.argtypes = [ct.c_void_p, ct.POINTER(CsoundParams)]
248 libcsound.csoundGetParams.argtypes = [ct.c_void_p, ct.POINTER(CsoundParams)]
249 libcsound.csoundGetDebug.argtypes = [ct.c_void_p]
250 libcsound.csoundSetDebug.argtypes = [ct.c_void_p, ct.c_int]
251 libcsound.csoundSystemSr.restype = MYFLT
252 libcsound.csoundSystemSr.argtypes = [ct.c_void_p, MYFLT]
253
254 libcsound.csoundGetOutputName.restype = ct.c_char_p
255 libcsound.csoundGetOutputName.argtypes = [ct.c_void_p]
256 libcsound.csoundGetInputName.restype = ct.c_char_p
257 libcsound.csoundGetInputName.argtypes = [ct.c_void_p]
258 libcsound.csoundSetOutput.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_char_p, ct.c_char_p]
259 libcsound.csoundGetOutputFormat.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_char_p]
260 libcsound.csoundSetInput.argtypes = [ct.c_void_p, ct.c_char_p]
261 libcsound.csoundSetMIDIInput.argtypes = [ct.c_void_p, ct.c_char_p]
262 libcsound.csoundSetMIDIFileInput.argtypes = [ct.c_void_p, ct.c_char_p]
263 libcsound.csoundSetMIDIOutput.argtypes = [ct.c_void_p, ct.c_char_p]
264 libcsound.csoundSetMIDIFileOutput.argtypes = [ct.c_void_p, ct.c_char_p]
265 FILEOPENFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_char_p, ct.c_int, ct.c_int, ct.c_int)
266 libcsound.csoundSetFileOpenCallback.argtypes = [ct.c_void_p, FILEOPENFUNC]
267
268 libcsound.csoundSetRTAudioModule.argtypes = [ct.c_void_p, ct.c_char_p]
269 libcsound.csoundGetModule.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(ct.c_char_p), ct.POINTER(ct.c_char_p)]
270 libcsound.csoundGetInputBufferSize.restype = ct.c_long
271 libcsound.csoundGetInputBufferSize.argtypes = [ct.c_void_p]
272 libcsound.csoundGetOutputBufferSize.restype = ct.c_long
273 libcsound.csoundGetOutputBufferSize.argtypes = [ct.c_void_p]
274 libcsound.csoundGetInputBuffer.restype = ct.POINTER(MYFLT)
275 libcsound.csoundGetInputBuffer.argtypes = [ct.c_void_p]
276 libcsound.csoundGetOutputBuffer.restype = ct.POINTER(MYFLT)
277 libcsound.csoundGetOutputBuffer.argtypes = [ct.c_void_p]
278 libcsound.csoundGetSpin.restype = ct.POINTER(MYFLT)
279 libcsound.csoundGetSpin.argtypes = [ct.c_void_p]
280 libcsound.csoundClearSpin.argtypes = [ct.c_void_p]
281 libcsound.csoundAddSpinSample.argtypes = [ct.c_void_p, ct.c_int, ct.c_int, MYFLT]
282 libcsound.csoundSetSpinSample.argtypes = [ct.c_void_p, ct.c_int, ct.c_int, MYFLT]
283 libcsound.csoundGetSpout.restype = ct.POINTER(MYFLT)
284 libcsound.csoundGetSpout.argtypes = [ct.c_void_p]
285 libcsound.csoundGetSpoutSample.restype = MYFLT
286 libcsound.csoundGetSpoutSample.argtypes = [ct.c_void_p, ct.c_int, ct.c_int]
287 libcsound.csoundGetRtRecordUserData.restype = ct.POINTER(ct.c_void_p)
288 libcsound.csoundGetRtRecordUserData.argtypes = [ct.c_void_p]
289 libcsound.csoundGetRtPlayUserData.restype = ct.POINTER(ct.c_void_p)
290 libcsound.csoundGetRtPlayUserData.argtypes = [ct.c_void_p]
291 libcsound.csoundSetHostImplementedAudioIO.argtypes = [ct.c_void_p, ct.c_int, ct.c_int]
292 libcsound.csoundGetAudioDevList.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_int]
293 PLAYOPENFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(CsoundRtAudioParams))
294 libcsound.csoundSetPlayopenCallback.argtypes = [ct.c_void_p, PLAYOPENFUNC]
295 RTPLAYFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(MYFLT), ct.c_int)
296 libcsound.csoundSetRtplayCallback.argtypes = [ct.c_void_p, RTPLAYFUNC]
297 RECORDOPENFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(CsoundRtAudioParams))
298 libcsound.csoundSetRecopenCallback.argtypes = [ct.c_void_p, RECORDOPENFUNC]
299 RTRECORDFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(MYFLT), ct.c_int)
300 libcsound.csoundSetRtrecordCallback.argtypes = [ct.c_void_p, RTRECORDFUNC]
301 RTCLOSEFUNC = ct.CFUNCTYPE(None, ct.c_void_p)
302 libcsound.csoundSetRtcloseCallback.argtypes = [ct.c_void_p, RTCLOSEFUNC]
303 AUDIODEVLISTFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(CsoundAudioDevice), ct.c_int)
304 libcsound.csoundSetAudioDeviceListCallback.argtypes = [ct.c_void_p, AUDIODEVLISTFUNC]
305
306 libcsound.csoundSetMIDIModule.argtypes = [ct.c_void_p, ct.c_char_p]
307 libcsound.csoundSetHostImplementedMIDIIO.argtypes = [ct.c_void_p, ct.c_int]
308 libcsound.csoundGetMIDIDevList.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_int]
309 MIDIINOPENFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(ct.c_void_p), ct.c_char_p)
310 libcsound.csoundSetExternalMidiInOpenCallback.argtypes = [ct.c_void_p, MIDIINOPENFUNC]
311 MIDIREADFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_char_p, ct.c_int)
312 libcsound.csoundSetExternalMidiReadCallback.argtypes = [ct.c_void_p, MIDIREADFUNC]
313 MIDIINCLOSEFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p)
314 libcsound.csoundSetExternalMidiInCloseCallback.argtypes = [ct.c_void_p, MIDIINCLOSEFUNC]
315 MIDIOUTOPENFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(ct.c_void_p), ct.c_char_p)
316 libcsound.csoundSetExternalMidiOutOpenCallback.argtypes = [ct.c_void_p, MIDIOUTOPENFUNC]
317 MIDIWRITEFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_char_p, ct.c_int)
318 libcsound.csoundSetExternalMidiWriteCallback.argtypes = [ct.c_void_p, MIDIWRITEFUNC]
319 MIDIOUTCLOSEFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p)
320 libcsound.csoundSetExternalMidiOutCloseCallback.argtypes = [ct.c_void_p, MIDIOUTCLOSEFUNC]
321 MIDIERRORFUNC = ct.CFUNCTYPE(ct.c_char_p, ct.c_int)
322 libcsound.csoundSetExternalMidiErrorStringCallback.argtypes = [ct.c_void_p, MIDIERRORFUNC]
323 MIDIDEVLISTFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.POINTER(CsoundMidiDevice), ct.c_int)
324 libcsound.csoundSetMIDIDeviceListCallback.argtypes = [ct.c_void_p, MIDIDEVLISTFUNC]
325
326 libcsound.csoundReadScore.argtypes = [ct.c_void_p, ct.c_char_p]
327 libcsound.csoundReadScoreAsync.argtypes = [ct.c_void_p, ct.c_char_p]
328 libcsound.csoundGetScoreTime.restype = ct.c_double
329 libcsound.csoundGetScoreTime.argtypes = [ct.c_void_p]
330 libcsound.csoundIsScorePending.argtypes = [ct.c_void_p]
331 libcsound.csoundSetScorePending.argtypes = [ct.c_void_p, ct.c_int]
332 libcsound.csoundGetScoreOffsetSeconds.restype = MYFLT
333 libcsound.csoundGetScoreOffsetSeconds.argtypes = [ct.c_void_p]
334 libcsound.csoundSetScoreOffsetSeconds.argtypes = [ct.c_void_p, MYFLT]
335 libcsound.csoundRewindScore.argtypes = [ct.c_void_p]
336 CSCOREFUNC = ct.CFUNCTYPE(None, ct.c_void_p)
337 libcsound.csoundSetCscoreCallback.argtypes = [ct.c_void_p, CSCOREFUNC]
338
339 libcsound.csoundMessage.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_char_p]
340 libcsound.csoundMessageS.argtypes = [ct.c_void_p, ct.c_int, ct.c_char_p, ct.c_char_p]
341 DEFMSGFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_int, ct.c_char_p, ct.c_void_p)
342 libcsound.csoundSetDefaultMessageCallback.argtypes = [DEFMSGFUNC]
343 libcsound.csoundGetMessageLevel.argtypes = [ct.c_void_p]
344 libcsound.csoundSetMessageLevel.argtypes = [ct.c_void_p, ct.c_int]
345 libcsound.csoundCreateMessageBuffer.argtypes = [ct.c_void_p, ct.c_int]
346 libcsound.csoundGetFirstMessage.restype = ct.c_char_p
347 libcsound.csoundGetFirstMessage.argtypes = [ct.c_void_p]
348 libcsound.csoundGetFirstMessageAttr.argtypes = [ct.c_void_p]
349 libcsound.csoundPopFirstMessage.argtypes = [ct.c_void_p]
350 libcsound.csoundGetMessageCnt.argtypes = [ct.c_void_p]
351 libcsound.csoundDestroyMessageBuffer.argtypes = [ct.c_void_p]
352
353 libcsound.csoundGetChannelPtr.argtypes = [ct.c_void_p, ct.POINTER(ct.POINTER(MYFLT)), ct.c_char_p, ct.c_int]
354 libcsound.csoundListChannels.argtypes = [ct.c_void_p, ct.POINTER(ct.POINTER(ControlChannelInfo))]
355 libcsound.csoundDeleteChannelList.argtypes = [ct.c_void_p, ct.POINTER(ControlChannelInfo)]
356 libcsound.csoundSetControlChannelHints.argtypes = [ct.c_void_p, ct.c_char_p, ControlChannelHints]
357 libcsound.csoundGetControlChannelHints.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ControlChannelHints)]
358 libcsound.csoundGetChannelLock.restype = ct.POINTER(ct.c_int)
359 libcsound.csoundGetChannelLock.argtypes = [ct.c_void_p, ct.c_char_p]
360 libcsound.csoundGetControlChannel.restype = MYFLT
361 libcsound.csoundGetControlChannel.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ct.c_int)]
362 libcsound.csoundSetControlChannel.argtypes = [ct.c_void_p, ct.c_char_p, MYFLT]
363 libcsound.csoundGetAudioChannel.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ct.c_int)]
364 libcsound.csoundSetAudioChannel.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ct.c_int)]
365 libcsound.csoundGetStringChannel.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_char_p]
366 libcsound.csoundSetStringChannel.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_char_p]
367 libcsound.csoundGetChannelDatasize.argtypes = [ct.c_void_p, ct.c_char_p]
368 CHANNELFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_char_p, ct.c_void_p, ct.c_void_p)
369 libcsound.csoundSetInputChannelCallback.argtypes = [ct.c_void_p, CHANNELFUNC]
370 libcsound.csoundSetOutputChannelCallback.argtypes = [ct.c_void_p, CHANNELFUNC]
371 libcsound.csoundSetPvsChannel.argtypes = [ct.c_void_p, ct.POINTER(PvsdatExt), ct.c_char_p]
372 libcsound.csoundGetPvsChannel.argtypes = [ct.c_void_p, ct.POINTER(PvsdatExt), ct.c_char_p]
373 libcsound.csoundScoreEvent.argtypes = [ct.c_void_p, ct.c_char, ct.POINTER(MYFLT), ct.c_long]
374 libcsound.csoundScoreEventAsync.argtypes = [ct.c_void_p, ct.c_char, ct.POINTER(MYFLT), ct.c_long]
375 libcsound.csoundScoreEventAbsolute.argtypes = [ct.c_void_p, ct.c_char, ct.POINTER(MYFLT), ct.c_long, ct.c_double]
376 libcsound.csoundScoreEventAbsoluteAsync.argtypes = [ct.c_void_p, ct.c_char, ct.POINTER(MYFLT), ct.c_long, ct.c_double]
377 libcsound.csoundInputMessage.argtypes = [ct.c_void_p, ct.c_char_p]
378 libcsound.csoundInputMessageAsync.argtypes = [ct.c_void_p, ct.c_char_p]
379 libcsound.csoundKillInstance.argtypes = [ct.c_void_p, MYFLT, ct.c_char_p, ct.c_int, ct.c_int]
380 SENSEFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.py_object)
381 libcsound.csoundRegisterSenseEventCallback.argtypes = [ct.c_void_p, SENSEFUNC, ct.py_object]
382 libcsound.csoundKeyPress.argtypes = [ct.c_void_p, ct.c_char]
383 KEYBOARDFUNC = ct.CFUNCTYPE(ct.c_int, ct.py_object, ct.c_void_p, ct.c_uint)
384 libcsound.csoundRegisterKeyboardCallback.argtypes = [ct.c_void_p, KEYBOARDFUNC, ct.py_object, ct.c_uint]
385 libcsound.csoundRemoveKeyboardCallback.argtypes = [ct.c_void_p, KEYBOARDFUNC]
386
387 libcsound.csoundTableLength.argtypes = [ct.c_void_p, ct.c_int]
388 libcsound.csoundTableGet.restype = MYFLT
389 libcsound.csoundTableGet.argtypes = [ct.c_void_p, ct.c_int, ct.c_int]
390 libcsound.csoundTableSet.argtypes = [ct.c_void_p, ct.c_int, ct.c_int, MYFLT]
391 libcsound.csoundTableCopyOut.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(MYFLT)]
392 libcsound.csoundTableCopyOutAsync.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(MYFLT)]
393 libcsound.csoundTableCopyIn.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(MYFLT)]
394 libcsound.csoundTableCopyInAsync.argtypes = [ct.c_void_p, ct.c_int, ct.POINTER(MYFLT)]
395 libcsound.csoundGetTable.argtypes = [ct.c_void_p, ct.POINTER(ct.POINTER(MYFLT)), ct.c_int]
396 libcsound.csoundGetTableArgs.argtypes = [ct.c_void_p, ct.POINTER(ct.POINTER(MYFLT)), ct.c_int]
397 libcsound.csoundIsNamedGEN.argtypes = [ct.c_void_p, ct.c_int]
398 libcsound.csoundGetNamedGEN.argtypes = [ct.c_void_p, ct.c_int, ct.c_char_p, ct.c_int]
399
400 libcsound.csoundSetIsGraphable.argtypes = [ct.c_void_p, ct.c_int]
401 MAKEGRAPHFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(Windat), ct.c_char_p)
402 libcsound.csoundSetMakeGraphCallback.argtypes = [ct.c_void_p, MAKEGRAPHFUNC]
403 DRAWGRAPHFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(Windat))
404 libcsound.csoundSetDrawGraphCallback.argtypes = [ct.c_void_p, DRAWGRAPHFUNC]
405 KILLGRAPHFUNC = ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(Windat))
406 libcsound.csoundSetKillGraphCallback.argtypes = [ct.c_void_p, KILLGRAPHFUNC]
407 EXITGRAPHFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p)
408 libcsound.csoundSetExitGraphCallback.argtypes = [ct.c_void_p, EXITGRAPHFUNC]
409
410 libcsound.csoundGetNamedGens.restype = ct.c_void_p
411 libcsound.csoundGetNamedGens.argtypes = [ct.c_void_p]
412 libcsound.csoundNewOpcodeList.argtypes = [ct.c_void_p, ct.POINTER(ct.POINTER(OpcodeListEntry))]
413 libcsound.csoundDisposeOpcodeList.argtypes = [ct.c_void_p, ct.POINTER(OpcodeListEntry)]
414 OPCODEFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p)
415 libcsound.csoundAppendOpcode.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_int, ct.c_int, ct.c_int, \
416 ct.c_char_p, ct.c_char_p, OPCODEFUNC, OPCODEFUNC, OPCODEFUNC]
417
418 YIELDFUNC = ct.CFUNCTYPE(ct.c_int, ct.c_void_p)
419 libcsound.csoundSetYieldCallback.argtypes = [ct.c_void_p, YIELDFUNC]
420 THREADFUNC = ct.CFUNCTYPE(ct.POINTER(ct.c_uint), ct.py_object)
421 libcsound.csoundCreateThread.restype = ct.c_void_p
422 libcsound.csoundCreateThread.argtypes = [THREADFUNC, ct.py_object]
423 libcsound.csoundCreateThread2.restype = ct.c_void_p
424 libcsound.csoundCreateThread2.argtypes = [THREADFUNC, ct.c_uint, ct.py_object]
425 libcsound.csoundGetCurrentThreadId.restype = ct.c_void_p
426 libcsound.csoundJoinThread.restype = ct.POINTER(ct.c_uint)
427 libcsound.csoundJoinThread.argtypes = [ct.c_void_p]
428 libcsound.csoundCreateThreadLock.restype = ct.c_void_p
429 libcsound.csoundWaitThreadLock.argtypes = [ct.c_void_p, ct.c_uint]
430 libcsound.csoundWaitThreadLockNoTimeout.argtypes = [ct.c_void_p]
431 libcsound.csoundNotifyThreadLock.argtypes = [ct.c_void_p]
432 libcsound.csoundDestroyThreadLock.argtypes = [ct.c_void_p]
433 libcsound.csoundCreateMutex.restype = ct.c_void_p
434 libcsound.csoundCreateMutex.argtypes = [ct.c_int]
435 libcsound.csoundLockMutex.argtypes = [ct.c_void_p]
436 libcsound.csoundLockMutexNoWait.argtypes = [ct.c_void_p]
437 libcsound.csoundUnlockMutex.argtypes = [ct.c_void_p]
438 libcsound.csoundDestroyMutex.argtypes = [ct.c_void_p]
439 libcsound.csoundCreateBarrier.restype = ct.c_void_p
440 libcsound.csoundCreateBarrier.argtypes = [ct.c_uint]
441 libcsound.csoundDestroyBarrier.argtypes = [ct.c_void_p]
442 libcsound.csoundWaitBarrier.argtypes = [ct.c_void_p]
443 libcsound.csoundSleep.argtypes = [ct.c_uint]
444 libcsound.csoundSpinLockInit.argtypes = [ct.POINTER(ct.c_int32)]
445 libcsound.csoundSpinLock.argtypes = [ct.POINTER(ct.c_int32)]
446 libcsound.csoundSpinTryLock.argtypes = [ct.POINTER(ct.c_int32)]
447 libcsound.csoundSpinUnLock.argtypes = [ct.POINTER(ct.c_int32)]
448
449 libcsound.csoundRunCommand.restype = ct.c_long
450 libcsound.csoundRunCommand.argtypes = [ct.POINTER(ct.c_char_p), ct.c_int]
451 libcsound.csoundInitTimerStruct.argtypes = [ct.POINTER(RtClock)]
452 libcsound.csoundGetRealTime.restype = ct.c_double
453 libcsound.csoundGetRealTime.argtypes = [ct.POINTER(RtClock)]
454 libcsound.csoundGetCPUTime.restype = ct.c_double
455 libcsound.csoundGetCPUTime.argtypes = [ct.POINTER(RtClock)]
456 libcsound.csoundGetRandomSeedFromTime.restype = ct.c_uint32
457 libcsound.csoundGetEnv.restype = ct.c_char_p
458 libcsound.csoundGetEnv.argtypes = [ct.c_void_p, ct.c_char_p]
459 libcsound.csoundSetGlobalEnv.argtypes = [ct.c_char_p, ct.c_char_p]
460 libcsound.csoundCreateGlobalVariable.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_uint]
461 libcsound.csoundQueryGlobalVariable.restype = ct.c_void_p
462 libcsound.csoundQueryGlobalVariable.argtypes = [ct.c_void_p, ct.c_char_p]
463 libcsound.csoundQueryGlobalVariableNoCheck.restype = ct.c_void_p
464 libcsound.csoundQueryGlobalVariableNoCheck.argtypes = [ct.c_void_p, ct.c_char_p]
465 libcsound.csoundDestroyGlobalVariable.argtypes = [ct.c_void_p, ct.c_char_p]
466 libcsound.csoundRunUtility.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_int, ct.POINTER(ct.c_char_p)]
467 libcsound.csoundListUtilities.restype = ct.POINTER(ct.c_char_p)
468 libcsound.csoundListUtilities.argtypes = [ct.c_void_p]
469 libcsound.csoundDeleteUtilityList.argtypes = [ct.c_void_p, ct.POINTER(ct.c_char_p)]
470 libcsound.csoundGetUtilityDescription.restype = ct.c_char_p
471 libcsound.csoundGetUtilityDescription.argtypes = [ct.c_void_p, ct.c_char_p]
472 libcsound.csoundRand31.argtypes = [ct.POINTER(ct.c_int)]
473 libcsound.csoundSeedRandMT.argtypes = [ct.POINTER(CsoundRandMTState), ct.POINTER(ct.c_uint32), ct.c_uint32]
474 libcsound.csoundRandMT.restype = ct.c_uint32
475 libcsound.csoundRandMT.argtypes = [ct.POINTER(CsoundRandMTState)]
476 libcsound.csoundCreateCircularBuffer.restype = ct.c_void_p
477 libcsound.csoundCreateCircularBuffer.argtypes = [ct.c_void_p, ct.c_int, ct.c_int]
478 libcsound.csoundReadCircularBuffer.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_int]
479 libcsound.csoundPeekCircularBuffer.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_int]
480 libcsound.csoundWriteCircularBuffer.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_int]
481 libcsound.csoundFlushCircularBuffer.argtypes = [ct.c_void_p, ct.c_void_p]
482 libcsound.csoundDestroyCircularBuffer.argtypes = [ct.c_void_p, ct.c_void_p]
483 libcsound.csoundOpenLibrary.argtypes = [ct.POINTER(ct.c_void_p), ct.c_char_p]
484 libcsound.csoundCloseLibrary.argtypes = [ct.c_void_p]
485 libcsound.csoundGetLibrarySymbol.retype = ct.c_void_p
486 libcsound.csoundGetLibrarySymbol.argtypes = [ct.c_void_p, ct.c_char_p]
487
488
489 def cchar(s):
490 if sys.version_info[0] >= 3:
491 return ct.c_char(ord(s[0]))
492 return ct.c_char(s[0])
493
494 def cstring(s):
495 if sys.version_info[0] >= 3 and s != None:
496 return bytes(s, 'utf-8')
497 return s
498
499 def pstring(s):
500 if sys.version_info[0] >= 3 and s != None:
501 return str(s, 'utf-8')
502 return s
503
504 def csoundArgList(lst):
505 if len(lst) == 1 and type(lst[0]) is list:
506 lst = lst[0]
507 argc = len(lst)
508 argv = (ct.POINTER(ct.c_char_p) * argc)()
509 for i in range(argc):
510 v = cstring(lst[i])
511 argv[i] = ct.cast(ct.pointer(ct.create_string_buffer(v)), ct.POINTER(ct.c_char_p))
512 return ct.c_int(argc), ct.cast(argv, ct.POINTER(ct.c_char_p))
513
514
515 # message types (only one can be specified)
516 CSOUNDMSG_DEFAULT = 0x0000 # standard message
517 CSOUNDMSG_ERROR = 0x1000 # error message (initerror, perferror, etc.)
518 CSOUNDMSG_ORCH = 0x2000 # orchestra opcodes (e.g. printks)
519 CSOUNDMSG_REALTIME = 0x3000 # for progress display and heartbeat characters
520 CSOUNDMSG_WARNING = 0x4000 # warning messages
521 CSOUNDMSG_STDOUT = 0x5000
522
523 # format attributes (colors etc.), use the bitwise OR of any of these:
524 CSOUNDMSG_FG_BLACK = 0x0100
525 CSOUNDMSG_FG_RED = 0x0101
526 CSOUNDMSG_FG_GREEN = 0x0102
527 CSOUNDMSG_FG_YELLOW = 0x0103
528 CSOUNDMSG_FG_BLUE = 0x0104
529 CSOUNDMSG_FG_MAGENTA = 0x0105
530 CSOUNDMSG_FG_CYAN = 0x0106
531 CSOUNDMSG_FG_WHITE = 0x0107
532
533 CSOUNDMSG_FG_BOLD = 0x0008
534 CSOUNDMSG_FG_UNDERLINE = 0x0080
535
536 CSOUNDMSG_BG_BLACK = 0x0200
537 CSOUNDMSG_BG_RED = 0x0210
538 CSOUNDMSG_BG_GREEN = 0x0220
539 CSOUNDMSG_BG_ORANGE = 0x0230
540 CSOUNDMSG_BG_BLUE = 0x0240
541 CSOUNDMSG_BG_MAGENTA = 0x0250
542 CSOUNDMSG_BG_CYAN = 0x0260
543 CSOUNDMSG_BG_GREY = 0x0270
544
545 CSOUNDMSG_TYPE_MASK = 0x7000
546 CSOUNDMSG_FG_COLOR_MASK = 0x0107
547 CSOUNDMSG_FG_ATTR_MASK = 0x0088
548 CSOUNDMSG_BG_COLOR_MASK = 0x0270
549
550
551 # ERROR DEFINITIONS
552 CSOUND_SUCCESS = 0 # Completed successfully.
553 CSOUND_ERROR = -1 # Unspecified failure.
554 CSOUND_INITIALIZATION = -2 # Failed during initialization.
555 CSOUND_PERFORMANCE = -3 # Failed during performance.
556 CSOUND_MEMORY = -4 # Failed to allocate requested memory.
557 CSOUND_SIGNAL = -5 # Termination requested by SIGINT or SIGTERM.
558
559 # Flags for csoundInitialize().
560 CSOUNDINIT_NO_SIGNAL_HANDLER = 1
561 CSOUNDINIT_NO_ATEXIT = 2
562
563 # Types for keyboard callbacks set in registerKeyboardCallback()
564 CSOUND_CALLBACK_KBD_EVENT = 1
565 CSOUND_CALLBACK_KBD_TEXT = 2
566
567 # Constants used by the bus interface (csoundGetChannelPtr() etc.).
568 CSOUND_CONTROL_CHANNEL = 1
569 CSOUND_AUDIO_CHANNEL = 2
570 CSOUND_STRING_CHANNEL = 3
571 CSOUND_PVS_CHANNEL = 4
572 CSOUND_VAR_CHANNEL = 5
573
574 CSOUND_CHANNEL_TYPE_MASK = 15
575
576 CSOUND_INPUT_CHANNEL = 16
577 CSOUND_OUTPUT_CHANNEL = 32
578
579 CSOUND_CONTROL_CHANNEL_NO_HINTS = 0
580 CSOUND_CONTROL_CHANNEL_INT = 1
581 CSOUND_CONTROL_CHANNEL_LIN = 2
582 CSOUND_CONTROL_CHANNEL_EXP = 3
583
584 # list of languages
585 CSLANGUAGE_DEFAULT = 0
586 CSLANGUAGE_AFRIKAANS = 1
587 CSLANGUAGE_ALBANIAN = 2
588 CSLANGUAGE_ARABIC = 3
589 CSLANGUAGE_ARMENIAN = 4
590 CSLANGUAGE_ASSAMESE = 5
591 CSLANGUAGE_AZERI = 6
592 CSLANGUAGE_BASQUE = 7
593 CSLANGUAGE_BELARUSIAN = 8
594 CSLANGUAGE_BENGALI = 9
595 CSLANGUAGE_BULGARIAN = 10
596 CSLANGUAGE_CATALAN = 11
597 CSLANGUAGE_CHINESE = 12
598 CSLANGUAGE_CROATIAN = 13
599 CSLANGUAGE_CZECH = 14
600 CSLANGUAGE_DANISH = 15
601 CSLANGUAGE_DUTCH = 16
602 CSLANGUAGE_ENGLISH_UK = 17
603 CSLANGUAGE_ENGLISH_US = 18
604 CSLANGUAGE_ESTONIAN = 19
605 CSLANGUAGE_FAEROESE = 20
606 CSLANGUAGE_FARSI = 21
607 CSLANGUAGE_FINNISH = 22
608 CSLANGUAGE_FRENCH = 23
609 CSLANGUAGE_GEORGIAN = 24
610 CSLANGUAGE_GERMAN = 25
611 CSLANGUAGE_GREEK = 26
612 CSLANGUAGE_GUJARATI = 27
613 CSLANGUAGE_HEBREW = 28
614 CSLANGUAGE_HINDI = 29
615 CSLANGUAGE_HUNGARIAN = 30
616 CSLANGUAGE_ICELANDIC = 31
617 CSLANGUAGE_INDONESIAN = 32
618 CSLANGUAGE_ITALIAN = 33
619 CSLANGUAGE_JAPANESE = 34
620 CSLANGUAGE_KANNADA = 35
621 CSLANGUAGE_KASHMIRI = 36
622 CSLANGUAGE_KAZAK = 37
623 CSLANGUAGE_KONKANI = 38
624 CSLANGUAGE_KOREAN = 39
625 CSLANGUAGE_LATVIAN = 40
626 CSLANGUAGE_LITHUANIAN = 41
627 CSLANGUAGE_MACEDONIAN = 42
628 CSLANGUAGE_MALAY = 43
629 CSLANGUAGE_MALAYALAM = 44
630 CSLANGUAGE_MANIPURI = 45
631 CSLANGUAGE_MARATHI = 46
632 CSLANGUAGE_NEPALI = 47
633 CSLANGUAGE_NORWEGIAN = 48
634 CSLANGUAGE_ORIYA = 49
635 CSLANGUAGE_POLISH = 50
636 CSLANGUAGE_PORTUGUESE = 51
637 CSLANGUAGE_PUNJABI = 52
638 CSLANGUAGE_ROMANIAN = 53
639 CSLANGUAGE_RUSSIAN = 54
640 CSLANGUAGE_SANSKRIT = 55
641 CSLANGUAGE_SERBIAN = 56
642 CSLANGUAGE_SINDHI = 57
643 CSLANGUAGE_SLOVAK = 58
644 CSLANGUAGE_SLOVENIAN = 59
645 CSLANGUAGE_SPANISH = 60
646 CSLANGUAGE_SWAHILI = 61
647 CSLANGUAGE_SWEDISH = 62
648 CSLANGUAGE_TAMIL = 63
649 CSLANGUAGE_TATAR = 64
650 CSLANGUAGE_TELUGU = 65
651 CSLANGUAGE_THAI = 66
652 CSLANGUAGE_TURKISH = 67
653 CSLANGUAGE_UKRAINIAN = 68
654 CSLANGUAGE_URDU = 69
655 CSLANGUAGE_UZBEK = 70
656 CSLANGUAGE_VIETNAMESE = 71
657 CSLANGUAGE_COLUMBIAN = 72
658
659
660 #Instantiation
661 def csoundInitialize(flags):
662 """Initializes Csound library with specific flags.
663
664 This function is called internally by csoundCreate(), so there is generally
665 no need to use it explicitly unless you need to avoid default initialization
666 that sets signal handlers and atexit() callbacks.
667 Return value is zero on success, positive if initialization was
668 done already, and negative on error.
669 """
670 return libcsound.csoundInitialize(flags)
671
672 def setOpcodedir(s):
673 """Sets an opcodedir override for csoundCreate()."""
674 libcsound.csoundSetOpcodedir(cstring(s))
675
676 defaultMessageCbRef = None
677 def setDefaultMessageCallback(function):
678 """Not fully implemented. Do not use it yet except for disabling messaging:
679
680 def noMessage(csound, attr, flags, *args):
681 pass
682 ctcsound.setDefaultMessageCallback(noMessage)
683 """
684 global defaultMessageCbReg
685 defaultMessageCbRef = DEFMSGFUNC(function)
686 libcsound.csoundSetDefaultMessageCallback(defaultMessageCbRef)
687
688 class Csound:
689 #Instantiation
690 def __init__(self, hostData=None, pointer_=None):
691 """Creates an instance of Csound.
692
693 Gets an opaque pointer that must be passed to most Csound API
694 functions. The *hostData* parameter can be :code:`None`, or it can be
695 any sort of data; these data can be accessed from the Csound instance
696 that is passed to callback routines.
697 """
698 if pointer_:
699 self.cs = pointer_
700 self.fromPointer = True
701 else:
702 self.cs = libcsound.csoundCreate(ct.py_object(hostData))
703 self.fromPointer = False
704
705 def loadPlugins(self, directory):
706 """Loads all plugins from a given directory."""
707 return libcsound.csoundLoadPlugins(self.cs, cstring(directory))
708
709 def __del__(self):
710 """Destroys an instance of Csound."""
711 if not self.fromPointer and libcsound:
712 libcsound.csoundDestroy(self.cs)
713
714 def csound(self):
715 """Returns the opaque pointer to the running Csound instance."""
716 return self.cs
717
718 def version(self):
719 """Returns the version number times 1000 (5.00.0 = 5000)."""
720 return libcsound.csoundGetVersion()
721
722 def APIVersion(self):
723 """Returns the API version number times 100 (1.00 = 100)."""
724 return libcsound.csoundGetAPIVersion()
725
726 #Performance
727 def parseOrc(self, orc):
728 """Parses the given orchestra from an ASCII string into a TREE.
729
730 This can be called during performance to parse new code.
731 """
732 return libcsound.csoundParseOrc(self.cs, cstring(orc))
733
734 def compileTree(self, tree):
735 """Compiles the given TREE node into structs for Csound to use.
736
737 This can be called during performance to compile a new TREE.
738 """
739 return libcsound.csoundCompileTree(self.cs, tree)
740
741 def compileTreeAsync(self, tree):
742 """Asynchronous version of :py:meth:`compileTree()`."""
743 return libcsound.csoundCompileTreeAsync(self.cs, tree)
744
745 def deleteTree(self, tree):
746 """Frees the resources associated with the TREE *tree*.
747
748 This function should be called whenever the TREE was
749 created with :py:meth:`parseOrc` and memory can be deallocated.
750 """
751 libcsound.csoundDeleteTree(self.cs, tree)
752
753 def compileOrc(self, orc):
754 """Parses, and compiles the given orchestra from an ASCII string.
755
756 Also evaluating any global space code (i-time only).
757 This can be called during performance to compile a new orchestra::
758
759 orc = 'instr 1 \\n a1 rand 0dbfs/4 \\n out a1 \\n'
760 cs.compileOrc(orc)
761 """
762 return libcsound.csoundCompileOrc(self.cs, cstring(orc))
763
764 def compileOrcAsync(self, orc):
765 """Async version of :py:meth:`compileOrc()`.
766
767 The code is parsed and compiled, then placed on a queue for
768 asynchronous merge into the running engine, and evaluation.
769 The function returns following parsing and compilation.
770 """
771 return libcsound.csoundCompileOrcAsync(self.cs, cstring(orc))
772
773 def evalCode(self, code):
774 """Parses and compiles an orchestra given on an string.
775
776 Evaluating any global space code (i-time only).
777 On SUCCESS it returns a value passed to the
778 'return' opcode in global space::
779
780 code = 'i1 = 2 + 2 \\n return i1 \\n'
781 retval = cs.evalCode(code)
782 """
783 return libcsound.csoundEvalCode(self.cs, cstring(code))
784
785 #def initializeCscore(insco, outsco):
786
787 def compileArgs(self, *args):
788 """Compiles *args*.
789
790 Reads arguments, parses and compiles an orchestra,
791 reads, processes and loads a score.
792 """
793 argc, argv = csoundArgList(args)
794 return libcsound.csoundCompileArgs(self.cs, argc, argv)
795
796 def start(self):
797 """Prepares Csound for performance.
798
799 Normally called after compiling a csd file or an orc file, in which
800 case score preprocessing is performed and performance terminates
801 when the score terminates.
802
803 However, if called before compiling a csd file or an orc file,
804 score preprocessing is not performed and "i" statements are dispatched
805 as real-time events, the <CsOptions> tag is ignored, and performance
806 continues indefinitely or until ended using the API.
807
808 NB: this is called internally by :py:meth:`compile_()`, therefore
809 it is only required if performance is started without
810 a call to that function.
811 """
812 return libcsound.csoundStart(self.cs)
813
814 def compile_(self, *args):
815 """Compiles Csound input files (such as an orchestra and score).
816
817 As directed by the supplied command-line arguments,
818 but does not perform them. Returns a non-zero error code on failure.
819 This function cannot be called during performance, and before a
820 repeated call, :py:meth:`reset()` needs to be called.
821 In this (host-driven) mode, the sequence of calls should be as follows::
822
823 cs.compile_(args)
824 while cs.performBuffer() == 0:
825 pass
826 cs.cleanup()
827 cs.reset()
828
829 Calls :py:meth:`start()` internally.
830 """
831 argc, argv = csoundArgList(args)
832 return libcsound.csoundCompile(self.cs, argc, argv)
833
834 def compileCsd(self, csd_filename):
835 """Compiles a Csound input file (.csd file).
836
837 The input file includes command-line arguments, but does not
838 perform the file. Returns a non-zero error code on failure.
839 In this (host-driven) mode, the sequence of calls should be
840 as follows::
841
842 cs.compileCsd(args)
843 while cs.performBuffer() == 0:
844 pass
845 cs.cleanup()
846 cs.reset()
847
848 NB: this function can be called during performance to
849 replace or add new instruments and events.
850 On a first call and if called before :py:meth:`start()`, this function
851 behaves similarly to :py:meth:`compile_()`.
852 """
853 return libcsound.csoundCompileCsd(self.cs, cstring(csd_filename))
854
855 def compileCsdText(self, csd_text):
856 """Compiles a Csound input file contained in a string of text.
857
858 The string of text includes command-line arguments, orchestra, score,
859 etc., but it is not performed. Returns a non-zero error code on failure.
860 In this (host-driven) mode, the sequence of calls should be as follows::
861
862 cs.compileCsdText(csd_text)
863 while cs.performBuffer() == 0:
864 pass
865 cs.cleanup()
866 cs.reset()
867
868 NB: a temporary file is created, the csd_text is written to the
869 temporary file, and :py:meth:`compileCsd` is called with the name of
870 the temporary file, which is deleted after compilation. Behavior may
871 vary by platform.
872 """
873 return libcsound.csoundCompileCsdText(self.cs, cstring(csd_text))
874
875 def perform(self):
876 """Senses input events and performs audio output.
877
878 This is done until the end of score is reached (positive return value),
879 an error occurs (negative return value), or performance is stopped by
880 calling :py:meth:`stop()` from another thread (zero return value).
881
882 Note that :py:meth:`compile_()`, or :py:meth:`compileOrc()`,
883 :py:meth:`readScore()`, :py:meth:`start()` must be
884 called first.
885
886 In the case of zero return value, :py:meth:`perform()` can be called
887 again to continue the stopped performance. Otherwise, :py:meth:`reset()`
888 should be called to clean up after the finished or failed performance.
889 """
890 return libcsound.csoundPerform(self.cs)
891
892 def performKsmps(self):
893 """Senses input events, and performs audio output.
894
895 This is done for one control sample worth (ksmps).
896
897 Note that :py:meth:`compile_()`, or :py:meth:`compileOrc()`,
898 :py:meth:`readScore()`, :py:meth:`start()` must be called first.
899
900 Returns :code:`False` during performance, and :code:`True` when
901 performance is finished. If called until it returns :code:`True`,
902 it will perform an entire score.
903
904 Enables external software to control the execution of Csound,
905 and to synchronize performance with audio input and output.
906 """
907 return libcsound.csoundPerformKsmps(self.cs)
908
909 def performBuffer(self):
910 """Performs Csound, sensing real-time and score events.
911
912 Processing one buffer's worth (-b frames) of interleaved audio.
913
914 Note that :py:meth:`compile_()` must be called first, then call
915 :py:meth:`outputBuffer()` and :py:meth:`inputBuffer(`) to get ndarrays
916 pointing to Csound's I/O buffers.
917
918 Returns :code:`False` during performance, and :code:`true` when
919 performance is finished.
920 """
921 return libcsound.csoundPerformBuffer(self.cs)
922
923 def stop(self):
924 """Stops a :py:meth:`perform()` running in another thread.
925
926 Note that it is not guaranteed that :py:meth:`perform()` has already
927 stopped when this function returns.
928 """
929 libcsound.csoundStop(self.cs)
930
931 def cleanup(self):
932 """Prints information and closes audio and MIDI devices.
933
934 | The information is about the end of a performance.
935 | Note: after calling cleanup(), the operation of the perform
936 function is undefined.
937 """
938 return libcsound.csoundCleanup(self.cs)
939
940 def reset(self):
941 """Resets all internal memory and state.
942
943 In preparation for a new performance.
944 Enable external software to run successive Csound performances
945 without reloading Csound. Implies :py:meth:`cleanup()`, unless already
946 called.
947 """
948 libcsound.csoundReset(self.cs)
949
950 #UDP server
951 def UDPServerStart(self, port):
952 """Starts the UDP server on a supplied port number.
953
954 Returns CSOUND_SUCCESS if server has been started successfully,
955 otherwise, CSOUND_ERROR.
956 """
957 return libcsound.csoundUDPServerStart(self.cs, ct.c_uint(port))
958
959 def UDPServerStatus(self):
960 """Returns the port number on which the server is running.
961
962 If the server is not running, CSOUND_ERROR is returned.
963 """
964 return libcsound.csoundUDPServerStatus(self.cs)
965
966 def UDPServerClose(self):
967 """Closes the UDP server.
968
969 Returns CSOUND_SUCCESS if the running server was successfully closed,
970 CSOUND_ERROR otherwise.
971 """
972 return libcsound.csoundUDPServerClose(self.cs)
973
974 def UDPConsole(self, addr, port, mirror):
975 """Turns on the transmission of console messages to UDP on addr:port.
976
977 If mirror is one, the messages will continue to be sent to the usual
978 destination (see :py:meth:`setMessageCallback()`) as well as to UDP.
979 Returns CSOUND_SUCCESS or CSOUND_ERROR if the UDP transmission
980 could not be set up.
981 """
982 return libcsound.csoundUDPConsole(self.cs, cstring(addr), ct.c_uint(port), ct.c_uint(mirror))
983
984 def stopUDPConsole(self):
985 """Stops transmitting console messages via UDP."""
986 libcsound.csoundStopUDPConsole(self.cs)
987
988 #Attributes
989 def sr(self):
990 """Returns the number of audio sample frames per second."""
991 return libcsound.csoundGetSr(self.cs)
992
993 def kr(self):
994 """Returns the number of control samples per second."""
995 return libcsound.csoundGetKr(self.cs)
996
997 def ksmps(self):
998 """Returns the number of audio sample frames per control sample."""
999 return libcsound.csoundGetKsmps(self.cs)
1000
1001 def nchnls(self):
1002 """Returns the number of audio output channels.
1003
1004 Set through the :code:`nchnls` header variable in the csd file.
1005 """
1006 return libcsound.csoundGetNchnls(self.cs)
1007
1008 def nchnlsInput(self):
1009 """Returns the number of audio input channels.
1010
1011 Set through the :code:`nchnls_i` header variable in the csd file. If
1012 this variable is not set, the value is taken from :code:`nchnls`.
1013 """
1014 return libcsound.csoundGetNchnlsInput(self.cs)
1015
1016 def get0dBFS(self):
1017 """Returns the 0dBFS level of the spin/spout buffers."""
1018 return libcsound.csoundGet0dBFS(self.cs)
1019
1020 def A4(self):
1021 """Returns the A4 frequency reference."""
1022 return libcsound.csoundGetA4(self.cs)
1023
1024 def currentTimeSamples(self):
1025 """Returns the current performance time in samples."""
1026 return libcsound.csoundGetCurrentTimeSamples(self.cs)
1027
1028 def sizeOfMYFLT(self):
1029 """Returns the size of MYFLT in bytes."""
1030 return libcsound.csoundGetSizeOfMYFLT()
1031
1032 def hostData(self):
1033 """Returns host data."""
1034 return libcsound.csoundGetHostData(self.cs)
1035
1036 def setHostData(self, data):
1037 """Sets host data."""
1038 libcsound.csoundSetHostData(self.cs, ct.py_object(data))
1039
1040 def setOption(self, option):
1041 """Sets a single csound option (flag).
1042
1043 | Returns CSOUND_SUCCESS on success.
1044 | NB: blank spaces are not allowed.
1045 """
1046 return libcsound.csoundSetOption(self.cs, cstring(option))
1047
1048 def setParams(self, params):
1049 """Configures Csound with a given set of parameters.
1050
1051 These parameters are defined in the CsoundParams structure.
1052 They are the part of the OPARMS struct that are configurable through
1053 command line flags.
1054 The CsoundParams structure can be obtained using :py:meth:`params()`.
1055 These options should only be changed before performance has started.
1056 """
1057 libcsound.csoundSetParams(self.cs, ct.byref(params))
1058
1059 def params(self, params):
1060 """Gets the current set of parameters from a CSOUND instance.
1061
1062 These parameters are in a CsoundParams structure. See
1063 :py:meth:`setParams()`::
1064
1065 p = CsoundParams()
1066 cs.params(p)
1067 """
1068 libcsound.csoundGetParams(self.cs, ct.byref(params))
1069
1070 def debug(self):
1071 """Returns whether Csound is set to print debug messages.
1072
1073 Those messages are sent through the :code:`DebugMsg()` internal API
1074 function.
1075 """
1076 return libcsound.csoundGetDebug(self.cs) != 0
1077
1078 def setDebug(self, debug):
1079 """Sets whether Csound prints debug messages.
1080
1081 The debug argument must have value :code:`True` or :code:`False`.
1082 Those messages come from the :code:`DebugMsg()` internal API function.
1083 """
1084 libcsound.csoundSetDebug(self.cs, ct.c_int(debug))
1085
1086 def systemSr(self, val):
1087 """If val > 0, sets the internal variable holding the system HW sr.
1088
1089 Returns the stored value containing the system HW sr."""
1090 return libcsound.csoundSystemSr(self.cs, val)
1091
1092 #General Input/Output
1093 def outputName(self):
1094 """Returns the audio output name (-o)"""
1095 s = libcsound.csoundGetOutputName(self.cs)
1096 return pstring(s)
1097
1098 def inputName(self):
1099 """Returns the audio input name (-i)"""
1100 s = libcsound.csoundGetInputName(self.cs)
1101 return pstring(s)
1102
1103 def setOutput(self, name, type_, format):
1104 """Sets output destination, type and format.
1105
1106 | *type_* can be one of "wav", "aiff", "au", "raw", "paf", "svx", "nist",
1107 "voc", "ircam", "w64", "mat4", "mat5", "pvf", "xi", "htk", "sds",
1108 "avr", "wavex", "sd2", "flac", "caf", "wve", "ogg", "mpc2k", "rf64",
1109 or NULL (use default or realtime IO).
1110 | *format* can be one of "alaw", "schar", "uchar", "float", "double",
1111 "long", "short", "ulaw", "24bit", "vorbis", or NULL (use default or
1112 realtime IO).
1113
1114 For RT audio, use device_id from CS_AUDIODEVICE for a given audio
1115 device.
1116 """
1117 n = cstring(name)
1118 t = cstring(type_)
1119 f = cstring(format)
1120 libcsound.csoundSetOutput(self.cs, n, t, f)
1121
1122 def outputFormat(self):
1123 """Gets output type and format."""
1124 type_ = ct.create_string_buffer(6)
1125 format = ct.create_string_buffer(8)
1126 libcsound.csoundGetOutputFormat(self.cs, type_, format)
1127 return pstring(string_at(type_)), pstring(string_at(format))
1128
1129 def setInput(self, name):
1130 """Sets input source."""
1131 libcsound.csoundSetInput(self.cs, cstring(name))
1132
1133 def setMIDIInput(self, name):
1134 """Sets MIDI input device name/number."""
1135 libcsound.csoundSetMidiInput(self.cs, cstring(name))
1136
1137 def setMIDIFileInput(self, name):
1138 """Sets MIDI file input name."""
1139 libcsound.csoundSetMIDIFileInput(self.cs, cstring(name))
1140
1141 def setMIDIOutput(self, name):
1142 """Sets MIDI output device name/number."""
1143 libcsound.csoundSetMIDIOutput(self.cs, cstring(name))
1144
1145 def setMIDIFileOutput(self, name):
1146 """Sets MIDI file output name."""
1147 libcsound.csoundSetMIDIFileOutput(self.cs, cstring(name))
1148
1149 def setFileOpenCallback(self, function):
1150 """Sets a callback for receiving notices whenever Csound opens a file.
1151
1152 The callback is made after the file is successfully opened.
1153 The following information is passed to the callback:
1154
1155 bytes
1156 pathname of the file; either full or relative to current dir
1157 int
1158 a file type code from the enumeration CSOUND_FILETYPES
1159 int
1160 1 if Csound is writing the file, 0 if reading
1161 int
1162 1 if a temporary file that Csound will delete; 0 if not
1163
1164 Pass NULL to disable the callback.
1165 This callback is retained after a :py:meth:`reset()` call.
1166 """
1167 self.fileOpenCbRef = FILEOPENFUNC(function)
1168 libcsound.csoundSetFileOpenCallback(self.cs, self.fileOpenCbRef)
1169
1170 #Realtime Audio I/O
1171 def setRTAudioModule(self, module):
1172 """Sets the current RT audio module."""
1173 libcsound.csoundSetRTAudioModule(self.cs, cstring(module))
1174
1175 def module(self, number):
1176 """Retrieves a module name and type given a number.
1177
1178 Type is "audio" or "midi". Modules are added to list as csound loads
1179 them. Return CSOUND_SUCCESS on success and CSOUND_ERROR if module
1180 number was not found::
1181
1182 n = 0
1183 while True:
1184 name, type_, err = cs.module(n)
1185 if err == ctcsound.CSOUND_ERROR:
1186 break
1187 print("Module %d:%s (%s)\\n" % (n, name, type_))
1188 n = n + 1
1189 """
1190 name = ct.pointer(ct.c_char_p(cstring("dummy")))
1191 type_ = ct.pointer(ct.c_char_p(cstring("dummy")))
1192 err = libcsound.csoundGetModule(self.cs, number, name, type_)
1193 if err == CSOUND_ERROR:
1194 return None, None, err
1195 n = pstring(string_at(name.contents))
1196 t = pstring(string_at(type_.contents))
1197 return n, t, err
1198
1199 def inputBufferSize(self):
1200 """Returns the number of samples in Csound's input buffer."""
1201 return libcsound.csoundGetInputBufferSize(self.cs)
1202
1203 def outputBufferSize(self):
1204 """Returns the number of samples in Csound's output buffer."""
1205 return libcsound.csoundGetOutputBufferSize(self.cs)
1206
1207 def inputBuffer(self):
1208 """Returns the Csound audio input buffer as an ndarray.
1209
1210 Enables external software to write audio into Csound before
1211 calling :py:meth:`performBuffer()`.
1212 """
1213 buf = libcsound.csoundGetInputBuffer(self.cs)
1214 size = libcsound.csoundGetInputBufferSize(self.cs)
1215 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (size,), 'C_CONTIGUOUS')
1216 p = ct.cast(buf, arrayType)
1217 return arrFromPointer(p)
1218
1219 def outputBuffer(self):
1220 """Returns the Csound audio output buffer as an ndarray.
1221
1222 Enables external software to read audio from Csound after
1223 calling :py:meth:`performBuffer()`.
1224 """
1225 buf = libcsound.csoundGetOutputBuffer(self.cs)
1226 size = libcsound.csoundGetOutputBufferSize(self.cs)
1227 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (size,), 'C_CONTIGUOUS')
1228 p = ct.cast(buf, arrayType)
1229 return arrFromPointer(p)
1230
1231 def spin(self):
1232 """Returns the Csound audio input working buffer (spin) as an ndarray.
1233
1234 Enables external software to write audio into Csound before
1235 calling :py:meth:`performKsmps()`.
1236 """
1237 buf = libcsound.csoundGetSpin(self.cs)
1238 size = self.ksmps() * self.nchnlsInput()
1239 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (size,), 'C_CONTIGUOUS')
1240 p = ct.cast(buf, arrayType)
1241 return arrFromPointer(p)
1242
1243 def clearSpin(self):
1244 """Clears the input buffer (spin)."""
1245 libcsound.csoundClearSpin(self.cs)
1246
1247 def addSpinSample(self, frame, channel, sample):
1248 """Adds the indicated sample into the audio input working buffer (spin).
1249
1250 This only ever makes sense before calling :py:meth:`performKsmps()`.
1251 The frame and channel must be in bounds relative to :py:meth:`ksmps()`
1252 and :py:meth:`nchnlsInput()`.
1253
1254 NB: the spin buffer needs to be cleared at every k-cycle by calling
1255 :py:meth:`clearSpin()`.
1256 """
1257 libcsound.csoundAddSpinSample(self.cs, frame, channel, sample)
1258
1259 def setSpinSample(self, frame, channel, sample):
1260 """Sets the audio input working buffer (spin) to the indicated sample.
1261
1262 This only ever makes sense before calling :py:meth:`performKsmps()`.
1263 The frame and channel must be in bounds relative to :py:meth:`ksmps()`
1264 and :py:meth:`nchnlsInput()`.
1265 """
1266 libcsound.csoundSetSpinSample(self.cs, frame, channel, sample)
1267
1268 def spout(self):
1269 """Returns the address of the Csound audio output working buffer (spout).
1270
1271 Enables external software to read audio from Csound after
1272 calling :py:meth:`performKsmps`.
1273 """
1274 buf = libcsound.csoundGetSpout(self.cs)
1275 size = self.ksmps() * self.nchnls()
1276 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (size,), 'C_CONTIGUOUS')
1277 p = ct.cast(buf, arrayType)
1278 return arrFromPointer(p)
1279
1280 def spoutSample(self, frame, channel):
1281 """Returns one sample from the Csound audio output working buf (spout).
1282
1283 Only ever makes sense after calling :py:meth:`performKsmps()`. The
1284 *frame* and *channel* must be in bounds relative to :py:meth:`ksmps()`
1285 and :py:meth:`nchnls()`.
1286 """
1287 return libcsound.csoundGetSpoutSample(self.cs, frame, channel)
1288
1289 def rtRecordUserData(self):
1290 """Returns pointer to user data pointer for real time audio input."""
1291 return libcsound.csoundGetRtRecordUserData(self.cs)
1292
1293 def rtPlaydUserData(self):
1294 """Returns pointer to user data pointer for real time audio output."""
1295 return libcsound.csoundGetRtPlayUserData(self.cs)
1296
1297 def setHostImplementedAudioIO(self, state, bufSize):
1298 """Sets user handling of sound I/O.
1299
1300 Calling this function with a :code:`True` *state* value between creation
1301 of the Csound object and the start of performance will disable all
1302 default handling of sound I/O by the Csound library, allowing the host
1303 application to use the spin/spout/input/output buffers directly.
1304
1305 For applications using spin/spout, *bufSize* should be set to 0.
1306 If *bufSize* is greater than zero, the buffer size (-b) will be
1307 set to the integer multiple of :py:meth:`ksmps()` that is nearest to the
1308 value specified.
1309 """
1310 libcsound.csoundSetHostImplementedAudioIO(self.cs, ct.c_int(state), bufSize)
1311
1312 def audioDevList(self, isOutput):
1313 """Returns a list of available input or output audio devices.
1314
1315 Each item in the list is a dictionnary representing a device. The
1316 dictionnary keys are *device_name*, *device_id*, *rt_module* (value
1317 type string), *max_nchnls* (value type int), and *isOutput* (value
1318 type boolean).
1319
1320 Must be called after an orchestra has been compiled
1321 to get meaningful information.
1322 """
1323 n = libcsound.csoundGetAudioDevList(self.cs, None, ct.c_int(isOutput))
1324 devs = (CsoundAudioDevice * n)()
1325 libcsound.csoundGetAudioDevList(self.cs, ct.byref(devs), ct.c_int(isOutput))
1326 lst = []
1327 for dev in devs:
1328 d = {}
1329 d["device_name"] = pstring(dev.device_name)
1330 d["device_id"] = pstring(dev.device_id)
1331 d["rt_module"] = pstring(dev.rt_module)
1332 d["max_nchnls"] = dev.max_nchnls
1333 d["isOutput"] = (dev.isOutput == 1)
1334 lst.append(d)
1335 return lst
1336
1337 def setPlayOpenCallback(self, function):
1338 """Sets a callback for opening real-time audio playback."""
1339 self.playOpenCbRef = PLAYOPENFUNC(function)
1340 libcsound.csoundSetPlayopenCallback(self.cs, self.playOpenCbRef)
1341
1342 def setRtPlayCallback(self, function):
1343 """Sets a callback for performing real-time audio playback."""
1344 self.rtPlayCbRef = RTPLAYFUNC(function)
1345 libcsound.csoundSetRtplayCallback(self.cs, self.rtPlayCbRef)
1346
1347 def setRecordOpenCallback(self, function):
1348 """Sets a callback for opening real-time audio recording."""
1349 self.recordOpenCbRef = RECORDOPENFUNC(function)
1350 libcsound.csoundSetRecopenCallback(self.cs, self.recordOpenCbRef)
1351
1352 def setRtRecordCallback(self, function):
1353 """Sets a callback for performing real-time audio recording."""
1354 self.rtRecordCbRef = RTRECORDFUNC(function)
1355 libcsound.csoundSetRtrecordCallback(self.cs, self.rtRecordCbRef)
1356
1357 def setRtCloseCallback(self, function):
1358 """Sets a callback for closing real-time audio playback and recording."""
1359 self.rtCloseCbRef = RTCLOSEFUNC(function)
1360 libcsound.csoundSetRtcloseCallback(self.cs, self.rtCloseCbRef)
1361
1362 def setAudioDevListCallback(self, function):
1363 """Sets a callback for obtaining a list of audio devices.
1364
1365 This should be set by rtaudio modules and should not be set by hosts.
1366 (See :py:meth:`audioDevList()`).
1367 """
1368 self.audioDevListCbRef = AUDIODEVLISTFUNC(function)
1369 libcsound.csoundSetAudioDeviceListCallback(self.cs, self.audioDevListCbRef)
1370
1371 #Realtime MIDI I/O
1372 def setMIDIModule(self, module):
1373 """Sets the current MIDI IO module."""
1374 libcsound.csoundSetMIDIModule(self.cs, cstring(module))
1375
1376 def setHostImplementedMIDIIO(self, state):
1377 """Called with *state* :code:`True` if the host is implementing via callbacks."""
1378 libcsound.csoundSetHostImplementedMIDIIO(self.cs, ct.c_int(state))
1379
1380 def midiDevList(self, isOutput):
1381 """Returns a list of available input or output midi devices.
1382
1383 Each item in the list is a dictionnary representing a device. The
1384 dictionnary keys are *device_name*, *interface_name*, *device_id*,
1385 *midi_module* (value type string), *isOutput* (value type boolean).
1386
1387 Must be called after an orchestra has been compiled
1388 to get meaningful information.
1389 """
1390 n = libcsound.csoundGetMIDIDevList(self.cs, None, ct.c_int(isOutput))
1391 devs = (CsoundMidiDevice * n)()
1392 libcsound.csoundGetMIDIDevList(self.cs, ct.byref(devs), ct.c_int(isOutput))
1393 lst = []
1394 for dev in devs:
1395 d = {}
1396 d["device_name"] = pstring(dev.device_name)
1397 d["interface_name"] = pstring(dev.interface_name)
1398 d["device_id"] = pstring(dev.device_id)
1399 d["midi_module"] = pstring(dev.midi_module)
1400 d["isOutput"] = (dev.isOutput == 1)
1401 lst.append(d)
1402 return lst
1403
1404 def setExternalMidiInOpenCallback(self, function):
1405 """Sets a callback for opening real-time MIDI input."""
1406 self.extMidiInOpenCbRef = MIDIINOPENFUNC(function)
1407 libcsound.csoundSetExternalMidiInOpenCallback(self.cs, self.extMidiInOpenCbRef)
1408
1409 def setExternalMidiReadCallback(self, function):
1410 """Sets a callback for reading from real time MIDI input."""
1411 self.extMidiReadCbRef = MIDIREADFUNC(function)
1412 libcsound.csoundSetExternalMidiReadCallback(self.cs, self.extMidiReadCbRef)
1413
1414 def setExternalMidiInCloseCallback(self, function):
1415 """Sets a callback for closing real time MIDI input."""
1416 self.extMidiInCloseCbRef = MIDIINCLOSEFUNC(function)
1417 libcsound.csoundSetExternalMidiInCloseCallback(self.cs, self.extMidiInCloseCbRef)
1418
1419 def setExternalMidiOutOpenCallback(self, function):
1420 """Sets a callback for opening real-time MIDI input."""
1421 self.extMidiOutOpenCbRef = MIDIOUTOPENFUNC(function)
1422 libcsound.csoundSetExternalMidiOutOpenCallback(self.cs, self.extMidiOutOpenCbRef)
1423
1424 def setExternalMidiWriteCallback(self, function):
1425 """Sets a callback for reading from real time MIDI input."""
1426 self.extMidiWriteCbRef = MIDIWRITEFUNC(function)
1427 libcsound.csoundSetExternalMidiWriteCallback(self.cs, self.extMidiWriteCbRef)
1428
1429 def setExternalMidiOutCloseCallback(self, function):
1430 """Sets a callback for closing real time MIDI input."""
1431 self.extMidiOutCloseCbRef = MIDIOUTCLOSEFUNC(function)
1432 libcsound.csoundSetExternalMidiOutCloseCallback(self.cs, self.extMidiOutCloseCbRef)
1433
1434 def setExternalMidiErrorStringCallback(self, function):
1435 """ Sets a callback for converting MIDI error codes to strings."""
1436 self.extMidiErrStrCbRef = MIDIERRORFUNC(function)
1437 libcsound.csoundSetExternalMidiErrorStringCallback(self.cs, self.extMidiErrStrCbRef)
1438
1439 def setMidiDevListCallback(self, function):
1440 """Sets a callback for obtaining a list of MIDI devices.
1441
1442 This should be set by IO plugins and should not be set by hosts.
1443 (See :py:meth:`midiDevList()`).
1444 """
1445 self.midiDevListCbRef = MIDIDEVLISTFUNC(function)
1446 libcsound.csoundSetMIDIDeviceListCallback(self.cs, self.midiDevListCbRef)
1447
1448 #Score Handling
1449 def readScore(self, sco):
1450 """Reads, preprocesses, and loads a score from an ASCII string.
1451
1452 It can be called repeatedly, with the new score events
1453 being added to the currently scheduled ones.
1454 """
1455 return libcsound.csoundReadScore(self.cs, cstring(sco))
1456
1457 def readScoreAsync(self, sco):
1458 """Asynchronous version of :py:meth:`readScore()`."""
1459 libcsound.csoundReadScoreAsync(self.cs, cstring(sco))
1460
1461 def scoreTime(self):
1462 """Returns the current score time.
1463
1464 The return value is the time in seconds since the beginning of
1465 performance.
1466 """
1467 return libcsound.csoundGetScoreTime(self.cs)
1468
1469 def isScorePending(self):
1470 """Tells whether Csound score events are performed or not.
1471
1472 Independently of real-time MIDI events (see :py:meth:`setScorePending()`).
1473 """
1474 return libcsound.csoundIsScorePending(self.cs) != 0
1475
1476 def setScorePending(self, pending):
1477 """Sets whether Csound score events are performed or not.
1478
1479 Real-time events will continue to be performed. Can be used by external
1480 software, such as a VST host, to turn off performance of score events
1481 (while continuing to perform real-time events), for example to mute
1482 a Csound score while working on other tracks of a piece, or to play
1483 the Csound instruments live.
1484 """
1485 libcsound.csoundSetScorePending(self.cs, ct.c_int(pending))
1486
1487 def scoreOffsetSeconds(self):
1488 """Returns the score time beginning midway through a Csound score.
1489
1490 At this time score events will actually immediately be performed
1491 (see :py:meth:`setScoreOffsetSeconds()`).
1492 """
1493 return libcsound.csoundGetScoreOffsetSeconds(self.cs)
1494
1495 def setScoreOffsetSeconds(self, time):
1496 """Csound score events prior to the specified time are not performed.
1497
1498 Performance begins immediately at the specified time (real-time events
1499 will continue to be performed as they are received). Can be used by
1500 external software, such as a VST host, to begin score performance
1501 midway through a Csound score, for example to repeat a loop in a
1502 sequencer, or to synchronize other events with the Csound score.
1503 """
1504 libcsound.csoundSetScoreOffsetSeconds(self.cs, MYFLT(time))
1505
1506 def rewindScore(self):
1507 """Rewinds a compiled Csound score.
1508
1509 It is rewinded to the time specified with :py:meth:`setScoreOffsetSeconds()`.
1510 """
1511 libcsound.csoundRewindScore(self.cs)
1512
1513 def setCscoreCallback(self, function):
1514 """Sets an external callback for Cscore processing.
1515
1516 Pass :code:`None` to reset to the internal :code:`cscore()` function
1517 (which does nothing). This callback is retained after a
1518 :py:meth:`reset()` call.
1519 """
1520 self.cscoreCbRef = CSCOREFUNC(function)
1521 libcsound.csoundSetCscoreCallback(self.cs, self.cscoreCbRef)
1522
1523 #def scoreSort(self, inFile, outFile):
1524
1525 #def scoreExtract(self, inFile, outFile, extractFile)
1526
1527 #Messages and Text
1528 def message(self, fmt, *args):
1529 """Displays an informational message.
1530
1531 This is a workaround because :program:`ctypes` does not support
1532 variadic functions.
1533 The arguments are formatted in a string, using the python way, either
1534 old style or new style, and then this formatted string is passed to
1535 the Csound display message system.
1536 """
1537 if fmt[0] == '{':
1538 s = fmt.format(*args)
1539 else:
1540 s = fmt % args
1541 libcsound.csoundMessage(self.cs, cstring("%s"), cstring(s))
1542
1543 def messageS(self, attr, fmt, *args):
1544 """Prints message with special attributes.
1545
1546 (See msg_attr for the list of available attributes). With attr=0,
1547 messageS() is identical to :py:meth:`message()`.
1548 This is a workaround because :program:`ctypes` does not support
1549 variadic functions.
1550 The arguments are formatted in a string, using the python way, either
1551 old style or new style, and then this formatted string is passed to
1552 the csound display message system.
1553 """
1554 if fmt[0] == '{':
1555 s = fmt.format(*args)
1556 else:
1557 s = fmt % args
1558 libcsound.csoundMessageS(self.cs, attr, cstring("%s"), cstring(s))
1559
1560 #def setMessageCallback():
1561
1562 #def setMessageStringCallback()
1563
1564 def messageLevel(self):
1565 """Returns the Csound message level (from 0 to 231)."""
1566 return libcsound.csoundGetMessageLevel(self.cs)
1567
1568 def setMessageLevel(self, messageLevel):
1569 """Sets the Csound message level (from 0 to 231)."""
1570 libcsound.csoundSetMessageLevel(self.cs, messageLevel)
1571
1572 def createMessageBuffer(self, toStdOut):
1573 """Creates a buffer for storing messages printed by Csound.
1574
1575 Should be called after creating a Csound instance and the buffer
1576 can be freed by calling :py:meth:`destroyMessageBuffer()` before
1577 deleting the Csound instance. You will generally want to call
1578 :py:meth:`cleanup()` to make sure the last messages are flushed to
1579 the message buffer before destroying Csound.
1580
1581 If *toStdOut* is :code:`True`, the messages are also printed to
1582 stdout and stderr (depending on the type of the message),
1583 in addition to being stored in the buffer.
1584
1585 Using the message buffer ties up the internal message callback, so
1586 :py:meth:`setMessageCallback()` should not be called after creating the
1587 message buffer.
1588 """
1589 libcsound.csoundCreateMessageBuffer(self.cs, ct.c_int(toStdOut))
1590
1591 def firstMessage(self):
1592 """Returns the first message from the buffer."""
1593 s = libcsound.csoundGetFirstMessage(self.cs)
1594 return pstring(s)
1595
1596 def firstMessageAttr(self):
1597 """Returns the attribute parameter of the first message in the buffer."""
1598 return libcsound.csoundGetFirstMessageAttr(self.cs)
1599
1600 def popFirstMessage(self):
1601 """Removes the first message from the buffer."""
1602 libcsound.csoundPopFirstMessage(self.cs)
1603
1604 def messageCnt(self):
1605 """Returns the number of pending messages in the buffer."""
1606 return libcsound.csoundGetMessageCnt(self.cs)
1607
1608 def destroyMessageBuffer(self):
1609 """Releases all memory used by the message buffer."""
1610 libcsound.csoundDestroyMessageBuffer(self.cs)
1611
1612 #Channels, Control and Events
1613 def channelPtr(self, name, type_):
1614 """Returns a pointer to the specified channel and an error message.
1615
1616 If the channel is a control or an audio channel, the pointer is
1617 translated to an ndarray of MYFLT. If the channel is a string channel,
1618 the pointer is casted to :code:`ct.c_char_p`. The error message is either
1619 an empty string or a string describing the error that occured.
1620
1621 The channel is created first if it does not exist yet.
1622 *type_* must be the bitwise OR of exactly one of the following values,
1623
1624 CSOUND_CONTROL_CHANNEL
1625 control data (one MYFLT value)
1626 CSOUND_AUDIO_CHANNEL
1627 audio data (:py:meth:`ksmps()` MYFLT values)
1628 CSOUND_STRING_CHANNEL
1629 string data (MYFLT values with enough space to store
1630 :py:meth:`getChannelDatasize()` characters, including the
1631 NULL character at the end of the string)
1632
1633 and at least one of these:
1634
1635 CSOUND_INPUT_CHANNEL
1636
1637 CSOUND_OUTPUT_CHANNEL
1638
1639 If the channel already exists, it must match the data type
1640 (control, audio, or string), however, the input/output bits are
1641 OR'd with the new value. Note that audio and string channels
1642 can only be created after calling :py:meth:`compile_()`, because the
1643 storage size is not known until then.
1644
1645 Return value is zero on success, or a negative error code,
1646
1647 CSOUND_MEMORY
1648 there is not enough memory for allocating the channel
1649 CSOUND_ERROR
1650 the specified name or type is invalid
1651
1652 or, if a channel with the same name but incompatible type
1653 already exists, the type of the existing channel. In the case
1654 of any non-zero return value, \*p is set to NULL.
1655 Note: to find out the type of a channel without actually
1656 creating or changing it, set *type_* to zero, so that the return
1657 value will be either the type of the channel, or CSOUND_ERROR
1658 if it does not exist.
1659
1660 Operations on the pointer are not thread-safe by default. The host is
1661 required to take care of threadsafety by retrieving the channel lock
1662 with :py:meth:`channelLock()` and using :py:meth:`spinLock()` and
1663 :py:meth:`spinUnLock()` to protect access to the pointer.
1664
1665 See Top/threadsafe.c in the Csound library sources for
1666 examples. Optionally, use the channel get/set functions
1667 provided below, which are threadsafe by default.
1668 """
1669 length = 0
1670 chanType = type_ & CSOUND_CHANNEL_TYPE_MASK
1671 if chanType == CSOUND_CONTROL_CHANNEL:
1672 length = 1
1673 elif chanType == CSOUND_AUDIO_CHANNEL:
1674 length = libcsound.csoundGetKsmps(self.cs)
1675 ptr = ct.POINTER(MYFLT)()
1676 err = ''
1677 ret = libcsound.csoundGetChannelPtr(self.cs, ct.byref(ptr), cstring(name), type_)
1678 if ret == CSOUND_SUCCESS:
1679 if chanType == CSOUND_STRING_CHANNEL:
1680 return ct.cast(ptr, ct.c_char_p), err
1681 else:
1682 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (length,), 'C_CONTIGUOUS')
1683 p = ct.cast(ptr, arrayType)
1684 return arrFromPointer(p), err
1685 elif ret == CSOUND_MEMORY:
1686 err = 'Not enough memory for allocating channel'
1687 elif ret == CSOUND_ERROR:
1688 err = 'The specified channel name or type is not valid'
1689 elif ret == CSOUND_CONTROL_CHANNEL:
1690 err = 'A control channel named {} already exists'.format(name)
1691 elif ret == CSOUND_AUDIO_CHANNEL:
1692 err = 'An audio channel named {} already exists'.format(name)
1693 elif ret == CSOUND_STRING_CHANNEL:
1694 err = 'A string channel named {} already exists'.format(name)
1695 else:
1696 err = 'Unknown error'
1697 return None, err
1698
1699 def listChannels(self):
1700 """Returns a pointer and an error message.
1701
1702 The pointer points to a list of ControlChannelInfo objects for allocated
1703 channels. A ControlChannelInfo object contains the channel
1704 characteristics. The error message indicates if there is not enough
1705 memory for allocating the list or it is an empty string if there is no
1706 error. In the case of no channels or an error, the pointer is
1707 :code:`None`.
1708
1709 Notes: the caller is responsible for freeing the list returned by the
1710 C API with :py:meth:`deleteChannelList()`. The name pointers may become
1711 invalid after calling :py:meth:`reset()`.
1712 """
1713 cInfos = None
1714 err = ''
1715 ptr = ct.cast(ct.POINTER(ct.c_int)(), ct.POINTER(ControlChannelInfo))
1716 n = libcsound.csoundListChannels(self.cs, ct.byref(ptr))
1717 if n == CSOUND_MEMORY :
1718 err = 'There is not enough memory for allocating the list'
1719 if n > 0:
1720 cInfos = ct.cast(ptr, ct.POINTER(ControlChannelInfo * n)).contents
1721 return cInfos, err
1722
1723 def deleteChannelList(self, lst):
1724 """Releases a channel list previously returned by :py:meth:`listChannels()`."""
1725 ptr = ct.cast(lst, ct.POINTER(ControlChannelInfo))
1726 libcsound.csoundDeleteChannelList(self.cs, ptr)
1727
1728 def setControlChannelHints(self, name, hints):
1729 """Sets parameters hints for a control channel.
1730
1731 These hints have no internal function but can be used by front ends to
1732 construct GUIs or to constrain values. See the ControlChannelHints
1733 structure for details.
1734 Returns zero on success, or a non-zero error code on failure:
1735
1736 CSOUND_ERROR
1737 the channel does not exist, is not a control channel,
1738 or the specified parameters are invalid
1739 CSOUND_MEMORY
1740 could not allocate memory
1741 """
1742 return libcsound.csoundSetControlChannelHints(self.cs, cstring(name), hints)
1743
1744 def controlChannelHints(self, name):
1745 """Returns special parameters (if any) of a control channel.
1746
1747 Those parameters have been previously set with
1748 :py:meth:`setControlChannelHints()` or the :code:`chnparams` opcode.
1749
1750 The return values are a ControlChannelHints structure and
1751 CSOUND_SUCCESS if the channel exists and is a control channel,
1752 otherwise, :code:`None` and an error code are returned.
1753 """
1754 hints = ControlChannelHints()
1755 ret = libcsound.csoundGetControlChannelHints(self.cs, cstring(name), ct.byref(hints))
1756 if ret != CSOUND_SUCCESS:
1757 hints = None
1758 return hints, ret
1759
1760 def channelLock(self, name):
1761 """Recovers a pointer to a lock for the specified channel called *name*.
1762
1763 The returned lock can be locked/unlocked with the :py:meth:`spinLock()`
1764 and :py:meth:`spinUnLock()` functions.
1765 Returns the address of the lock or NULL if the channel does not exist.
1766 """
1767 return libcsound.csoundGetChannelLock(self.cs, cstring(name))
1768
1769 def controlChannel(self, name):
1770 """Retrieves the value of control channel identified by *name*.
1771
1772 A second value is returned, which is the error (or success) code
1773 finding or accessing the channel.
1774 """
1775 err = ct.c_int(0)
1776 ret = libcsound.csoundGetControlChannel(self.cs, cstring(name), ct.byref(err))
1777 return ret, err
1778
1779 def setControlChannel(self, name, val):
1780 """Sets the value of control channel identified by *name*."""
1781 libcsound.csoundSetControlChannel(self.cs, cstring(name), MYFLT(val))
1782
1783 def audioChannel(self, name, samples):
1784 """Copies the audio channel identified by *name* into ndarray samples.
1785
1786 *samples* should contain enough memory for :py:meth:`ksmps()` MYFLTs.
1787 """
1788 ptr = samples.ctypes.data_as(ct.POINTER(MYFLT))
1789 libcsound.csoundGetAudioChannel(self.cs, cstring(name), ptr)
1790
1791 def setAudioChannel(self, name, samples):
1792 """Sets the audio channel *name* with data from the ndarray *samples*.
1793
1794 *samples* should contain at least :py:meth:`ksmps()` MYFLTs.
1795 """
1796 ptr = samples.ctypes.data_as(ct.POINTER(MYFLT))
1797 libcsound.csoundSetAudioChannel(self.cs, cstring(name), ptr)
1798
1799 def stringChannel(self, name, string):
1800 """Copies the string channel identified by *name* into *string*.
1801
1802 *string* should contain enough memory for the string
1803 (see :py:meth:`channelDatasize()` below).
1804 """
1805 libcsound.csoundGetStringChannel(self.cs, cstring(name), cstring(string))
1806
1807 def setStringChannel(self, name, string):
1808 """Sets the string channel identified by *name* with *string*."""
1809 libcsound.csoundSetStringChannel(self.cs, cstring(name), cstring(string))
1810
1811 def channelDatasize(self, name):
1812 """Returns the size of data stored in a channel.
1813
1814 For string channels this might change if the channel space gets
1815 reallocated. Since string variables use dynamic memory allocation in
1816 Csound6, this function can be called to get the space required for
1817 :py:meth:`stringChannel()`.
1818 """
1819 return libcsound.csoundGetChannelDatasize(self.cs, cstring(name))
1820
1821 def setInputChannelCallback(self, function):
1822 """Sets the function to call whenever the :code:`invalue` opcode is used."""
1823 self.inputChannelCbRef = CHANNELFUNC(function)
1824 libcsound.csoundSetInputChannelCallback(self.cs, self.inputChannelCbRef)
1825
1826 def setOutputChannelCallback(self, function):
1827 """Sets the function to call whenever the :code:`outvalue` opcode is used."""
1828 self.outputChannelCbRef = CHANNELFUNC(function)
1829 libcsound.csoundSetOutputChannelCallback(self.cs, self.outputChannelCbRef)
1830
1831 def setPvsChannel(self, fin, name):
1832 """Sends a PvsdatExt *fin* to the :code:`pvsin` opcode (f-rate) for channel *name*.
1833
1834 | Returns zero on success, CSOUND_ERROR if the index is invalid or
1835 fsig framesizes are incompatible.
1836 | CSOUND_MEMORY if there is not enough memory to extend the bus.
1837 """
1838 return libcsound.csoundSetPvsChannel(self.cs, ct.byref(fin), cstring(name))
1839
1840 def pvsChannel(self, fout, name):
1841 """Receives a PvsdatExt *fout* from the :code:`pvsout` opcode (f-rate) at channel *name*.
1842
1843 | Returns zero on success, CSOUND_ERROR if the index is invalid or
1844 if fsig framesizes are incompatible.
1845 | CSOUND_MEMORY if there is not enough memory to extend the bus.
1846 """
1847 return libcsound.csoundGetPvsChannel(self.cs, ct.byref(fout), cstring(name))
1848
1849 def scoreEvent(self, type_, pFields):
1850 """Sends a new score event.
1851
1852 | *type_* is the score event type ('a', 'i', 'q', 'f', or 'e').
1853 | *pFields* is a tuple, a list, or an ndarray of MYFLTs with all the
1854 pfields for this event, starting with the p1 value specified in
1855 pFields[0].
1856 """
1857 p = np.asarray(pFields, dtype=MYFLT)
1858 ptr = p.ctypes.data_as(ct.POINTER(MYFLT))
1859 numFields = ct.c_long(p.size)
1860 return libcsound.csoundScoreEvent(self.cs, cchar(type_), ptr, numFields)
1861
1862 def scoreEventAsync(self, type_, pFields):
1863 """Asynchronous version of :py:meth:`scoreEvent()`."""
1864 p = np.asarray(pFields, dtype=MYFLT)
1865 ptr = p.ctypes.data_as(ct.POINTER(MYFLT))
1866 numFields = ct.c_long(p.size)
1867 libcsound.csoundScoreEventAsync(self.cs, cchar(type_), ptr, numFields)
1868
1869 def scoreEventAbsolute(self, type_, pFields, timeOffset):
1870 """Like :py:meth:`scoreEvent()`, this function inserts a score event.
1871
1872 The event is inserted at absolute time with respect to the start of
1873 performance, or from an offset set with timeOffset.
1874 """
1875 p = np.asarray(pFields, dtype=MYFLT)
1876 ptr = p.ctypes.data_as(ct.POINTER(MYFLT))
1877 numFields = ct.c_long(p.size)
1878 return libcsound.csoundScoreEventAbsolute(self.cs, cchar(type_), ptr, numFields, ct.c_double(timeOffset))
1879
1880 def scoreEventAbsoluteAsync(self, type_, pFields, timeOffset):
1881 """Asynchronous version of :py:meth:`scoreEventAbsolute()`."""
1882 p = np.asarray(pFields, dtype=MYFLT)
1883 ptr = p.ctypes.data_as(ct.POINTER(MYFLT))
1884 numFields = ct.c_long(p.size)
1885 libcsound.csoundScoreEventAbsoluteAsync(self.cs, cchar(type_), ptr, numFields, ct.c_double(timeOffset))
1886
1887 def inputMessage(self, message):
1888 """Inputs a NULL-terminated string (as if from a console).
1889
1890 Used for line events.
1891 """
1892 libcsound.csoundInputMessage(self.cs, cstring(message))
1893
1894 def inputMessageAsync(self, message):
1895 """Asynchronous version of :py:meth:`inputMessage()`."""
1896 libcsound.csoundInputMessageAsync(self.cs, cstring(message))
1897
1898 def killInstance(self, instr, instrName, mode, allowRelease):
1899 """Kills off one or more running instances of an instrument.
1900
1901 The instances are identified by *instr* (number) or *instrName* (name).
1902 If *instrName* is :code:`None`, the instrument number is used.
1903
1904 | *mode* is a sum of the following values:
1905 | 0, 1, 2: kill all instances (0), oldest only (1), or newest (2)
1906 | 4: only turnoff notes with exactly matching (fractional) instr number
1907 | 8: only turnoff notes with indefinite duration (p3 < 0 or MIDI).
1908
1909 If *allowRelease* is :code:`True`, the killed instances are allowed to
1910 release.
1911 """
1912 return libcsound.csoundKillInstance(self.cs, MYFLT(instr), cstring(instrName), mode, ct.c_int(allowRelease))
1913
1914 def registerSenseEventCallback(self, function, userData):
1915 """Registers a function to be called by :code:`sensevents()`.
1916
1917 This function will be called once in every control period. Any number
1918 of functions may be registered, and will be called in the order of
1919 registration.
1920
1921 The callback function takes two arguments: the Csound instance
1922 pointer, and the *userData* pointer as passed to this function.
1923
1924 This facility can be used to ensure a function is called synchronously
1925 before every csound control buffer processing. It is important
1926 to make sure no blocking operations are performed in the callback.
1927 The callbacks are cleared on :py:meth:`cleanup()`.
1928
1929 Returns zero on success.
1930 """
1931 self.senseEventCbRef = SENSEFUNC(function)
1932 return libcsound.csoundRegisterSenseEventCallback(self.cs, self.senseEventCbRef, ct.py_object(userData))
1933
1934 def keyPress(self, c):
1935 """Sets the ASCII code of the most recent key pressed.
1936
1937 This value is used by the :code:`sensekey` opcode if a callback for
1938 returning keyboard events is not set (see
1939 :py:meth:`registerKeyboardCallback()`).
1940 """
1941 libcsound.csoundKeyPress(self.cs, cchar(c))
1942
1943 def registerKeyboardCallback(self, function, userData, type_):
1944 """Registers general purpose callback functions for keyboard events.
1945
1946 These callbacks are called on every control period by the sensekey
1947 opcode.
1948
1949 The callback is preserved on :py:meth:`reset()`, and multiple
1950 callbacks may be set and will be called in reverse order of
1951 registration. If the same function is set again, it is only moved
1952 in the list of callbacks so that it will be called first, and the
1953 user data and type mask parameters are updated. *type_* can be the
1954 bitwise OR of callback types for which the function should be called,
1955 or zero for all types.
1956
1957 Returns zero on success, CSOUND_ERROR if the specified function
1958 pointer or type mask is invalid, and CSOUND_MEMORY if there is not
1959 enough memory.
1960
1961 The callback function takes the following arguments:
1962
1963 *userData*
1964 the "user data" pointer, as specified when setting the callback
1965 *p*
1966 data pointer, depending on the callback type
1967 *type_*
1968 callback type, can be one of the following (more may be added in
1969 future versions of Csound):
1970
1971 CSOUND_CALLBACK_KBD_EVENT
1972
1973 CSOUND_CALLBACK_KBD_TEXT
1974 called by the :code:`sensekey` opcode to fetch key codes. The
1975 data pointer is a pointer to a single value of type :code:`int`,
1976 for returning the key code, which can be in the range 1 to
1977 65535, or 0 if there is no keyboard event.
1978
1979 For CSOUND_CALLBACK_KBD_EVENT, both key press and release
1980 events should be returned (with 65536 (0x10000) added to the
1981 key code in the latter case) as unshifted ASCII codes.
1982 CSOUND_CALLBACK_KBD_TEXT expects key press events only as the
1983 actual text that is typed.
1984
1985 The return value should be zero on success, negative on error, and
1986 positive if the callback was ignored (for example because the type is
1987 not known).
1988 """
1989 if type_ == CSOUND_CALLBACK_KBD_EVENT:
1990 self.keyboardCbEventRef = KEYBOARDFUNC(function)
1991 else:
1992 self.keyboardCbTextRef = KEYBOARDFUNC(function)
1993 return libcsound.csoundRegisterKeyboardCallback(self.cs, KEYBOARDFUNC(function), ct.py_object(userData), ct.c_uint(type_))
1994
1995 def removeKeyboardCallback(self, function):
1996 """Removes a callback previously set with :py:meth:`registerKeyboardCallback()`."""
1997 libcsound.csoundRemoveKeyboardCallback(self.cs, KEYBOARDFUNC(function))
1998
1999 #Tables
2000 def tableLength(self, table):
2001 """Returns the length of a function table.
2002
2003 (Not including the guard point).
2004 If the table does not exist, returns -1.
2005 """
2006 return libcsound.csoundTableLength(self.cs, table)
2007
2008 def tableGet(self, table, index):
2009 """Returns the value of a slot in a function table.
2010
2011 The *table* number and *index* are assumed to be valid.
2012 """
2013 return libcsound.csoundTableGet(self.cs, table, index)
2014
2015 def tableSet(self, table, index, value):
2016 """Sets the value of a slot in a function table.
2017
2018 The *table* number and *index* are assumed to be valid.
2019 """
2020 libcsound.csoundTableSet(self.cs, table, index, MYFLT(value))
2021
2022 def tableCopyOut(self, table, dest):
2023 """Copies the contents of a function table into a supplied ndarray *dest*.
2024
2025 The *table* number is assumed to be valid, and the destination needs to
2026 have sufficient space to receive all the function table contents.
2027 """
2028 ptr = dest.ctypes.data_as(ct.POINTER(MYFLT))
2029 libcsound.csoundTableCopyOut(self.cs, table, ptr)
2030
2031 def tableCopyOutAsync(self, table, dest):
2032 """Asynchronous version of :py:meth:`tableCopyOut()`."""
2033 ptr = dest.ctypes.data_as(ct.POINTER(MYFLT))
2034 libcsound.csoundTableCopyOutAsync(self.cs, table, ptr)
2035
2036 def tableCopyIn(self, table, src):
2037 """Copies the contents of an ndarray *src* into a given function *table*.
2038
2039 The *table* number is assumed to be valid, and the table needs to
2040 have sufficient space to receive all the array contents.
2041 """
2042 ptr = src.ctypes.data_as(ct.POINTER(MYFLT))
2043 libcsound.csoundTableCopyIn(self.cs, table, ptr)
2044
2045 def tableCopyInAsync(self, table, src):
2046 """Asynchronous version of :py:meth:`tableCopyIn()`."""
2047 ptr = src.ctypes.data_as(ct.POINTER(MYFLT))
2048 libcsound.csoundTableCopyInAsync(self.cs, table, ptr)
2049
2050 def table(self, tableNum):
2051 """Returns a pointer to function table *tableNum* as an ndarray.
2052
2053 The ndarray does not include the guard point. If the table does not
2054 exist, :code:`None` is returned.
2055 """
2056 ptr = ct.POINTER(MYFLT)()
2057 size = libcsound.csoundGetTable(self.cs, ct.byref(ptr), tableNum)
2058 if size < 0:
2059 return None
2060 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (size,), 'C_CONTIGUOUS')
2061 p = ct.cast(ptr, arrayType)
2062 return arrFromPointer(p)
2063
2064 def tableArgs(self, tableNum):
2065 """Returns a pointer to the args used to generate a function table.
2066
2067 The pointer is returned as an ndarray. If the table does not exist,
2068 :code:`None` is returned.
2069
2070 NB: the argument list starts with the GEN number and is followed by
2071 its parameters. eg. f 1 0 1024 10 1 0.5 yields the list
2072 {10.0, 1.0, 0.5}
2073 """
2074 ptr = ct.POINTER(MYFLT)()
2075 size = libcsound.csoundGetTableArgs(self.cs, ct.byref(ptr), tableNum)
2076 if size < 0:
2077 return None
2078 arrayType = np.ctypeslib.ndpointer(MYFLT, 1, (size,), 'C_CONTIGUOUS')
2079 p = ct.cast(ptr, arrayType)
2080 return arrFromPointer(p)
2081
2082 def isNamedGEN(self, num):
2083 """Checks if a given GEN number *num* is a named GEN.
2084
2085 If so, it returns the string length. Otherwise it returns 0.
2086 """
2087 return libcsound.csoundIsNamedGEN(self.cs, num)
2088
2089 def namedGEN(self, num, nameLen):
2090 """Gets the GEN name from a GEN number, if this is a named GEN.
2091
2092 The final parameter is the max len of the string.
2093 """
2094 s = ct.create_string_buffer(nameLen)
2095 libcsound.csoundGetNamedGEN(self.cs, num, s, nameLen)
2096 return pstring(string_at(s, nameLen))
2097
2098 #Function Table Display
2099 def setIsGraphable(self, isGraphable):
2100 """Tells Csound whether external graphic table display is supported.
2101
2102 Return the previously set value (initially False).
2103 """
2104 ret = libcsound.csoundSetIsGraphable(self.cs, ct.c_int(isGraphable))
2105 return (ret != 0)
2106
2107 def setMakeGraphCallback(self, function):
2108 """Called by external software to set Csound's MakeGraph function."""
2109 self.makeGraphCbRef = MAKEGRAPHFUNC(function)
2110 libcsound.csoundSetMakeGraphCallback(self.cs, self.makeGraphCbRef)
2111
2112 def setDrawGraphCallback(self, function):
2113 """Called by external software to set Csound's DrawGraph function."""
2114 self.drawGraphCbRef = DRAWGRAPHFUNC(function)
2115 libcsound.csoundSetDrawGraphCallback(self.cs, self.drawGraphCbRef)
2116
2117 def setKillGraphCallback(self, function):
2118 """Called by external software to set Csound's KillGraph function."""
2119 self.killGraphCbRef = KILLGRAPHFUNC(function)
2120 libcsound.csoundSetKillGraphCallback(self.cs, self.killGraphCbRef)
2121
2122 def setExitGraphCallback(self, function):
2123 """Called by external software to set Csound's ExitGraph function."""
2124 self.exitGraphCbRef = EXITGRAPHFUNC(function)
2125 libcsound.csoundSetExitGraphCallback(self.cs, self.exitGraphCbRef)
2126
2127 #Opcodes
2128 def namedGens(self):
2129 """Finds the list of named gens."""
2130 lst = []
2131 ptr = libcsound.csoundGetNamedGens(self.cs)
2132 ptr = ct.cast(ptr, ct.POINTER(NamedGen))
2133 while (ptr):
2134 ng = ptr.contents
2135 lst.append((pstring(ng.name), int(ng.genum)))
2136 ptr = ng.next
2137 return lst
2138
2139 def newOpcodeList(self):
2140 """Gets an alphabetically sorted list of all opcodes.
2141
2142 Should be called after externals are loaded by :py:meth:`compile_()`.
2143 Returns a pointer to the list of OpcodeListEntry structures and the
2144 number of opcodes, or a negative error code on failure.
2145 Make sure to call :py:meth:`disposeOpcodeList()` when done with the
2146 list.
2147 """
2148 opcodes = None
2149 ptr = ct.cast(ct.POINTER(ct.c_int)(), ct.POINTER(OpcodeListEntry))
2150 n = libcsound.csoundNewOpcodeList(self.cs, ct.byref(ptr))
2151 if n > 0:
2152 opcodes = ct.cast(ptr, ct.POINTER(OpcodeListEntry * n)).contents
2153 return opcodes, n
2154
2155 def disposeOpcodeList(self, lst):
2156 """Releases an opcode list."""
2157 ptr = ct.cast(lst, ct.POINTER(OpcodeListEntry))
2158 libcsound.csoundDisposeOpcodeList(self.cs, ptr)
2159
2160 def appendOpcode(self, opname, dsblksiz, flags, thread, outypes, intypes, iopfunc, kopfunc, aopfunc):
2161 """Appends an opcode implemented by external software.
2162
2163 This opcode is added to Csound's internal opcode list.
2164 The opcode list is extended by one slot, and the parameters are copied
2165 into the new slot.
2166
2167 Returns zero on success.
2168 """
2169 return libcsound.csoundAppendOpcode(self.cs, cstring(opname), dsblksiz, flags, thread,\
2170 cstring(outypes), cstring(intypes),\
2171 OPCODEFUNC(iopfunc),\
2172 OPCODEFUNC(kopfunc),
2173 OPCODEFUNC(aopfunc))
2174
2175 #Threading and Concurrency
2176 def setYieldCallback(self, function):
2177 """
2178 Called by external software to set a yield function.
2179
2180 This callback is used for checking system events, yielding cpu time
2181 for coopertative multitasking, etc.
2182
2183 This function is optional. It is often used as a way to 'turn off'
2184 Csound, allowing it to exit gracefully. In addition, some operations
2185 like utility analysis routines are not reentrant and you should use
2186 this function to do any kind of updating during the operation.
2187
2188 Returns an 'OK to continue' boolean.
2189 """
2190 self.yieldCbRef = YIELDFUNC(function)
2191 libcsound.csoundSetYieldCallback(self.cs, self.yieldCbRef)
2192
2193 def createThread(self, function, userdata):
2194 """Creates and starts a new thread of execution.
2195
2196 Returns an opaque pointer that represents the thread on success,
2197 or :code:`None` for failure.
2198 The *userdata* pointer is passed to the thread routine.
2199 """
2200 ret = libcsound.csoundCreateThread(THREADFUNC(function), ct.py_object(userdata))
2201 if (ret):
2202 return ret
2203 return None
2204
2205 def createThread2(self, function, stack, userdata):
2206 """Creates and starts a new thread of execution with a user-defined
2207 stack size.
2208
2209 Returns an opaque pointer that represents the thread on success,
2210 or :code:`None` for failure.
2211 The *userdata* pointer is passed to the thread routine.
2212 """
2213 ret = libcsound.csoundCreateThread2(THREADFUNC(function),
2214 ct.c_uint(stack), ct.py_object(userdata))
2215 if (ret):
2216 return ret
2217 return None
2218
2219 def currentThreadId(self):
2220 """Returns the ID of the currently executing thread, or :code:`None`
2221 for failure.
2222
2223 NOTE: The return value can be used as a pointer
2224 to a thread object, but it should not be compared
2225 as a pointer. The pointed to values should be compared,
2226 and the user must free the pointer after use.
2227 """
2228 ret = libcsound.csoundGetCurrentThreadId()
2229 if (ret):
2230 return ret
2231 return None
2232
2233 def joinThread(self, thread):
2234 """Waits until the indicated thread's routine has finished.
2235
2236 Returns the value returned by the thread routine.
2237 """
2238 return libcsound.csoundJoinThread(thread)
2239
2240 def createThreadLock(self):
2241 """Creates and returns a monitor object, or :code:`None` if not successful.
2242
2243 The object is initially in signaled (notified) state.
2244 """
2245 ret = libcsound.csoundCreateThreadLock()
2246 if (ret):
2247 return ret
2248 return None
2249
2250 def waitThreadLock(self, lock, milliseconds):
2251 """Waits on the indicated monitor object for the indicated period.
2252
2253 The function returns either when the monitor object is notified,
2254 or when the period has elapsed, whichever is sooner; in the first case,
2255 zero is returned.
2256
2257 If *milliseconds* is zero and the object is not notified, the function
2258 will return immediately with a non-zero status.
2259 """
2260 return libcsound.csoundWaitThreadLock(lock, ct.c_uint(milliseconds))
2261
2262 def waitThreadLockNoTimeout(self, lock):
2263 """Waits on the indicated monitor object until it is notified.
2264
2265 This function is similar to :py:meth:`waitThreadLock()` with an infinite
2266 wait time, but may be more efficient.
2267 """
2268 libcsound.csoundWaitThreadLockNoTimeout(lock)
2269
2270 def notifyThreadLock(self, lock):
2271 """Notifies the indicated monitor object."""
2272 libcsound.csoundNotifyThreadLock(lock)
2273
2274 def destroyThreadLock(self, lock):
2275 """Destroys the indicated monitor object."""
2276 libcsound.csoundDestroyThreadLock(lock)
2277
2278 def createMutex(self, isRecursive):
2279 """Creates and returns a mutex object, or :code:`None` if not successful.
2280
2281 Mutexes can be faster than the more general purpose monitor objects
2282 returned by :py:meth:`createThreadLock()` on some platforms, and can
2283 also be recursive, but the result of unlocking a mutex that is owned by
2284 another thread or is not locked is undefined.
2285
2286 If *isRecursive'* id :code:`True`, the mutex can be re-locked multiple
2287 times by the same thread, requiring an equal number of unlock calls;
2288 otherwise, attempting to re-lock the mutex results in undefined
2289 behavior.
2290
2291 Note: the handles returned by :py:meth:`createThreadLock()` and
2292 :py:meth:`createMutex()` are not compatible.
2293 """
2294 ret = libcsound.csoundCreateMutex(ct.c_int(isRecursive))
2295 if ret:
2296 return ret
2297 return None
2298
2299 def lockMutex(self, mutex):
2300 """Acquires the indicated mutex object.
2301
2302 If it is already in use by another thread, the function waits until
2303 the mutex is released by the other thread.
2304 """
2305 libcsound.csoundLockMutex(mutex)
2306
2307 def lockMutexNoWait(self, mutex):
2308 """Acquire the indicated mutex object.
2309
2310 Returns zero, unless it is already in use by another thread, in which
2311 case a non-zero value is returned immediately, rather than waiting
2312 until the mutex becomes available.
2313
2314 Note: this function may be unimplemented on Windows.
2315 """
2316 return libcsound.csoundLockMutexNoWait(mutex)
2317
2318 def unlockMutex(self, mutex):
2319 """Releases the indicated mutex object.
2320
2321 The mutex should be owned by the current thread, otherwise the
2322 operation of this function is undefined. A recursive mutex needs
2323 to be unlocked as many times as it was locked previously.
2324 """
2325 libcsound.csoundUnlockMutex(mutex)
2326
2327 def destroyMutex(self, mutex):
2328 """Destroys the indicated mutex object.
2329
2330 Destroying a mutex that is currently owned by a thread results
2331 in undefined behavior.
2332 """
2333 libcsound.csoundDestroyMutex(mutex)
2334
2335 def createBarrier(self, max_):
2336 """Creates a Thread Barrier.
2337
2338 Max value parameter should be equal to the number of child threads
2339 using the barrier plus one for the master thread.
2340 """
2341 ret = libcsound.csoundCreateBarrier(ct.c_uint(max_))
2342 if (ret):
2343 return ret
2344 return None
2345
2346 def destroyBarrier(self, barrier):
2347 """Destroys a Thread Barrier."""
2348 return libcsound.csoundDestroyBarrier(barrier)
2349
2350 def waitBarrier(self, barrier):
2351 """Waits on the thread barrier."""
2352 return libcsound.csoundWaitBarrier(barrier)
2353
2354 #def createCondVar(self):
2355 #def condWait(self, condVar, mutex):
2356 #def condSignal(self, condVar):
2357 #def destroyCondVar(self, condVar):
2358
2359 def sleep(self, milliseconds):
2360 """Waits for at least the specified number of *milliseconds*.
2361
2362 It yields the CPU to other threads.
2363 """
2364 libcsound.csoundSleep(ct.c_uint(milliseconds))
2365
2366 def spinLockInit(self, spinlock):
2367 """Inits the spinlock.
2368
2369 If the spinlock is not locked, locks it and returns;
2370 if is is locked, waits until it is unlocked, then locks it and returns.
2371 Uses atomic compare and swap operations that are safe across processors
2372 and safe for out of order operations,
2373 and which are more efficient than operating system locks.
2374
2375 Use spinlocks to protect access to shared data, especially in functions
2376 that do little more than read or write such data, for example::
2377
2378 lock = ctypes.ct.c_int32(0)
2379 cs.spinLockInit(lock)
2380 def write(cs, frames, signal):
2381 cs.spinLock(lock)
2382 for frame in range(frames) :
2383 global_buffer[frame] += signal[frame];
2384 cs.spinUnlock(lock)
2385 """
2386 return libcsound.csoundSpinLockInit(ct.byref(spinlock))
2387
2388 def spinLock(self, spinlock):
2389 """Locks the spinlock."""
2390 libcsound.csoundSpinLock(ct.byref(spinlock))
2391
2392 def spinTryLock(self,spinlock):
2393 """Tries the spinlock.
2394
2395 returns CSOUND_SUCCESS if lock could be acquired,
2396 CSOUND_ERROR, otherwise.
2397 """
2398 return libcsound.csoundSpinLock(ct.byref(spinlock))
2399
2400 def spinUnlock(self, spinlock):
2401 """Unlocks the spinlock."""
2402 libcsound.csoundSpinUnLock(ct.byref(spinlock))
2403
2404 #Miscellaneous Functions
2405 def runCommand(self, args, noWait):
2406 """Runs an external command with the arguments specified in list *args*.
2407
2408 args[0] is the name of the program to execute (if not a full path
2409 file name, it is searched in the directories defined by the PATH
2410 environment variable).
2411
2412 If *noWait* is :code:`False`, the function waits until the external
2413 program finishes, otherwise it returns immediately. In the first case,
2414 a non-negative return value is the exit status of the command (0 to
2415 255), otherwise it is the PID of the newly created process.
2416 On error, a negative value is returned.
2417 """
2418 n = len(args)
2419 argv = (ct.POINTER(ct.c_char_p) * (n+1))()
2420 for i in range(n):
2421 v = cstring(args[i])
2422 argv[i] = ct.cast(ct.pointer(ct.create_string_buffer(v)), ct.POINTER(ct.c_char_p))
2423 argv[n] = None
2424 return libcsound.csoundRunCommand(ct.cast(argv, ct.POINTER(ct.c_char_p)), ct.c_int(noWait))
2425
2426 def initTimerStruct(self, timerStruct):
2427 """Initializes a timer structure."""
2428 libcsound.csoundInitTimerStruct(ct.byref(timerStruct))
2429
2430 def realTime(self, timerStruct):
2431 """Returns the elapsed real time (in seconds).
2432
2433 The time is measured since the specified timer structure was initialised.
2434 """
2435 return libcsound.csoundGetRealTime(ct.byref(timerStruct))
2436
2437 def CPUTime(self, timerStruct):
2438 """Returns the elapsed CPU time (in seconds).
2439
2440 The time is measured since the specified timer structure was initialised.
2441 """
2442 return libcsound.csoundGetCPUTime(ct.byref(timerStruct))
2443
2444 def randomSeedFromTime(self):
2445 """Returns a 32-bit unsigned integer to be used as seed from current time."""
2446 return libcsound.csoundGetRandomSeedFromTime()
2447
2448 def setLanguage(self, lang_code):
2449 """Sets language to *lang_code*.
2450
2451 *lang_code* can be for example CSLANGUAGE_ENGLISH_UK or
2452 CSLANGUAGE_FRENCH or many others, (see n_getstr.h for the list of
2453 languages). This affects all Csound instances running in the address
2454 space of the current process. The special language code
2455 CSLANGUAGE_DEFAULT can be used to disable translation of messages and
2456 free all memory allocated by a previous call to setLanguage().
2457 setLanguage() loads all files for the selected language
2458 from the directory specified by the CSSTRNGS environment
2459 variable.
2460 """
2461 libcsound.csoundSetLanguage(lang_code)
2462
2463 def env(self, name, withCsoundInstance = True):
2464 """Gets the value of environment variable *name*.
2465
2466 The searching order is: local environment of Csound (if
2467 *withCsoundInstance* is :code:`True`), variables set with
2468 :py:meth:`setGlobalEnv()`,
2469 and system environment variables. If *withCsoundInstance* is
2470 :code:`True`, should be called after :py:meth:`compile_()`.
2471
2472 Return value is :code:`None` if the variable is not set.
2473 """
2474 if withCsoundInstance:
2475 ret = libcsound.csoundGetEnv(self.cs, cstring(name))
2476 else:
2477 ret = libcsound.csoundGetEnv(None, cstring(name))
2478 if (ret):
2479 return pstring(ret)
2480 return None
2481
2482 def setGlobalEnv(self, name, value):
2483 """Sets the global value of environment variable *name* to *value*.
2484
2485 The variable is deleted if *value* is :code:`None`. It is not safe to
2486 call this function while any Csound instances are active.
2487
2488 Returns zero on success.
2489 """
2490 return libcsound.csoundSetGlobalEnv(cstring(name), cstring(value))
2491
2492 def createGlobalVariable(self, name, nbytes):
2493 """Allocates *nbytes* bytes of memory.
2494
2495 This memory can be accessed later by calling
2496 :py:meth`queryGlobalVariable()` with the specified name; the space is
2497 cleared to zero.
2498
2499 Returns CSOUND_SUCCESS on success, CSOUND_ERROR in case of invalid
2500 parameters (zero *nbytes*, invalid or already used *name*), or
2501 CSOUND_MEMORY if there is not enough memory.
2502 """
2503 return libcsound.csoundCreateGlobalVariable(self.cs, cstring(name), ct.c_uint(nbytes))
2504
2505 def queryGlobalVariable(self, name):
2506 """Gets pointer to space allocated with the name *name*.
2507
2508 Return :code:`None` if the specified *name* is not defined.
2509 """
2510 ret = libcsound.csoundQueryGlobalVariable(self.cs, cstring(name))
2511 if (ret):
2512 return ret
2513 return None
2514
2515 def queryGlobalVariableNoCheck(self, name):
2516 """This function is the similar to :py:meth`queryGlobalVariable()`.
2517
2518 Except the variable is assumed to exist and no error checking is done.
2519 Faster, but may crash or return an invalid pointer if *name* is
2520 not defined.
2521 """
2522 return libcsound.csoundQueryGlobalVariableNoCheck(self.cs, cstring(name))
2523
2524 def destroyGlobalVariable(self, name):
2525 """Frees memory allocated for *name* and remove *name* from the database.
2526
2527 Return value is CSOUND_SUCCESS on success, or CSOUND_ERROR if the *name*
2528 is not defined.
2529 """
2530 return libcsound.csoundDestroyGlobalVariable(self.cs, cstring(name))
2531
2532 def runUtility(self, name, args):
2533 """Runs utility with the specified *name* and command line arguments.
2534
2535 Should be called after loading utility plugins.
2536 Use :py:meth`reset()` to clean up after calling this function.
2537 Returns zero if the utility was run successfully.
2538 """
2539 argc, argv = csoundArgList(args)
2540 return libcsound.csoundRunUtility(self.cs, cstring(name), argc, argv)
2541
2542 def listUtilities(self):
2543 """Returns a list of registered utility names.
2544
2545 The return value may be :code:`None` in case of an error.
2546 """
2547 ptr = libcsound.csoundListUtilities(self.cs)
2548 if (ptr):
2549 i = 0
2550 lst = []
2551 while (ptr[i]):
2552 lst.append(pstring(ptr[i]))
2553 i += 1
2554 libcsound.csoundDeleteUtilityList(self.cs, ptr)
2555 return lst
2556 return None
2557
2558 def utilityDescription(self, name):
2559 """Gets utility description.
2560
2561 Returns :code:`None` if the utility was not found, or it has no
2562 description, or an error occured.
2563 """
2564 ptr = libcsound.csoundGetUtilityDescription(self.cs, cstring(name))
2565 if (ptr):
2566 return pstring(ptr)
2567 return None
2568
2569 def rand31(self, seed):
2570 """Simple linear congruential random number generator::
2571
2572 seed = seed * 742938285 % 2147483647
2573
2574 The initial value of *seed* must be in the range 1 to 2147483646.
2575 Returns the next number from the pseudo-random sequence, in the range
2576 1 to 2147483646.
2577 """
2578 n = ct.c_int(seed)
2579 return libcsound.csoundRand31(ct.byref(n))
2580
2581 def seedRandMT(self, initKey):
2582 """Initializes Mersenne Twister (MT19937) random number generator.
2583
2584 *initKey* can be a single int, a list of int, or an ndarray of int.
2585 Those int values are converted to unsigned 32 bit values and used for
2586 seeding.
2587
2588 Returns a CsoundRandMTState stuct to be used by :py:meth`csoundRandMT()`.
2589 """
2590 state = CsoundRandMTState()
2591 if type(initKey) == int:
2592 if initKey < 0:
2593 initKey = -initKey
2594 libcsound.csoundSeedRandMT(ct.byref(state), None, ct.c_uint32(initKey))
2595 elif type(initKey) == list or type(initKey) == np.ndarray:
2596 n = len(initKey)
2597 lst = (ct.c_uint32 * n)()
2598 for i in range(n):
2599 k = initKey[i]
2600 if k < 0 :
2601 k = -k
2602 lst[i] = ct.c_uint32(k)
2603 p = ct.pointer(lst)
2604 p = ct.cast(p, ct.POINTER(ct.c_uint32))
2605 libcsound.csoundSeedRandMT(ct.byref(state), p, ct.c_uint32(len(lst)))
2606 return state
2607
2608 def randMT(self, state):
2609 """Returns next random number from MT19937 generator.
2610
2611 The PRNG must be initialized first by calling :py:meth`csoundSeedRandMT()`.
2612 """
2613 return libcsound.csoundRandMT(ct.byref(state))
2614
2615 def createCircularBuffer(self, numelem, elemsize):
2616 """Creates a circular buffer with *numelem* number of elements.
2617
2618 The element's size is set from *elemsize*. It should be used like::
2619
2620 rb = cs.createCircularBuffer(1024, cs.sizeOfMYFLT())
2621 """
2622 return libcsound.csoundCreateCircularBuffer(self.cs, numelem, elemsize)
2623
2624 def readCircularBuffer(self, circularBuffer, out, items):
2625 """Reads from circular buffer.
2626
2627 *circular_buffer*
2628 pointer to an existing circular buffer
2629 *out*
2630 preallocated ndarray with at least items number of elements,
2631 where buffer contents will be read into
2632 *items*
2633 number of samples to be read
2634
2635 Returns the actual number of items read (0 <= n <= items).
2636 """
2637 if len(out) < items:
2638 return 0
2639 ptr = out.ctypes.data_as(ct.c_void_p)
2640 return libcsound.csoundReadCircularBuffer(self.cs, circularBuffer, ptr, items)
2641
2642 def peekCircularBuffer(self, circularBuffer, out, items):
2643 """Reads from circular buffer without removing them from the buffer.
2644
2645 *circular_buffer*
2646 pointer to an existing circular buffer
2647 *out*
2648 preallocated ndarray with at least items number of elements,
2649 where buffer contents will be read into
2650 *items*
2651 number of samples to be read
2652
2653 Returns the actual number of items read (0 <= n <= items).
2654 """
2655 if len(out) < items:
2656 return 0
2657 ptr = out.ctypes.data_as(ct.c_void_p)
2658 return libcsound.csoundPeekCircularBuffer(self.cs, circularBuffer, ptr, items)
2659
2660 def writeCircularBuffer(self, circularBuffer, in_, items):
2661 """Writes to circular buffer.
2662
2663 *circular_buffer*
2664 pointer to an existing circular buffer
2665 *in_*
2666 ndarray with at least items number of elements to be written
2667 into circular buffer
2668 *items*
2669 number of samples to write
2670
2671 Returns the actual number of items written (0 <= n <= items).
2672 """
2673 if len(in_) < items:
2674 return 0
2675 ptr = in_.ctypes.data_as(ct.c_void_p)
2676 return libcsound.csoundWriteCircularBuffer(self.cs, circularBuffer, ptr, items)
2677
2678 def flushCircularBuffer(self, circularBuffer):
2679 """Empties circular buffer of any remaining data.
2680
2681 This function should only be used if there is no reader actively
2682 getting data from the buffer.
2683
2684 *circular_buffer*
2685 pointer to an existing circular buffer
2686 """
2687 libcsound.csoundFlushCircularBuffer(self.cs, circularBuffer)
2688
2689 def destroyCircularBuffer(self, circularBuffer):
2690 """Frees circular buffer."""
2691 libcsound.csoundDestroyCircularBuffer(self.cs, circularBuffer)
2692
2693 def openLibrary(self, libraryPath):
2694 """Platform-independent function to load a shared library."""
2695 ptr = ct.POINTER(ct.c_int)()
2696 library = ct.cast(ptr, ct.c_void_p)
2697 ret = libcsound.csoundOpenLibrary(ct.byref(library), cstring(libraryPath))
2698 return ret, library
2699
2700 def closeLibrary(self, library):
2701 """Platform-independent function to unload a shared library."""
2702 return libcsound.csoundCloseLibrary(library)
2703
2704 def getLibrarySymbol(self, library, symbolName):
2705 """Platform-independent function to get a symbol address in a shared library."""
2706 return libcsound.csoundGetLibrarySymbol(library, cstring(symbolName))
2707
2708
2709 if sys.platform.startswith('linux'):
2710 libcspt = ct.CDLL("libcsnd6.so")
2711 elif sys.platform.startswith('win'):
2712 if sys.version_info.major <=3 and sys.version_info.minor < 8:
2713 libcspt = ct.cdll.csnd6
2714 else:
2715 libcspt = ct.CDLL(ctypes.util.find_library("csnd6"))
2716 elif sys.platform.startswith('darwin'):
2717 libcspt = ct.CDLL(ctypes.util.find_library('csnd6.6.0'))
2718 else:
2719 sys.exit("Don't know your system! Exiting...")
2720
2721 libcspt.NewCsoundPT.restype = ct.c_void_p
2722 libcspt.NewCsoundPT.argtypes = [ct.c_void_p]
2723 libcspt.DeleteCsoundPT.argtypes = [ct.c_void_p]
2724 libcspt.CsoundPTisRunning.argtypes = [ct.c_void_p]
2725 PROCESSFUNC = ct.CFUNCTYPE(None, ct.c_void_p)
2726 libcspt.CsoundPTgetProcessCB.restype = ct.c_void_p
2727 libcspt.CsoundPTgetProcessCB.argtypes = [ct.c_void_p]
2728 libcspt.CsoundPTsetProcessCB.argtypes = [ct.c_void_p, PROCESSFUNC, ct.c_void_p]
2729 libcspt.CsoundPTgetCsound.restype = ct.c_void_p
2730 libcspt.CsoundPTgetCsound.argtypes = [ct.c_void_p]
2731 libcspt.CsoundPTgetStatus.argtypes = [ct.c_void_p]
2732 libcspt.CsoundPTplay.argtypes = [ct.c_void_p]
2733 libcspt.CsoundPTpause.argtypes = [ct.c_void_p]
2734 libcspt.CsoundPTtogglePause.argtypes = [ct.c_void_p]
2735 libcspt.CsoundPTstop.argtypes = [ct.c_void_p]
2736 libcspt.CsoundPTrecord.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_int, ct.c_int]
2737 libcspt.CsoundPTstopRecord.argtypes = [ct.c_void_p]
2738 libcspt.CsoundPTscoreEvent.argtypes = [ct.c_void_p, ct.c_int, ct.c_char, ct.c_int, ct.POINTER(MYFLT)]
2739 libcspt.CsoundPTinputMessage.argtypes = [ct.c_void_p, ct.c_char_p]
2740 libcspt.CsoundPTsetScoreOffsetSeconds.argtypes = [ct.c_void_p, ct.c_double]
2741 libcspt.CsoundPTjoin.argtypes = [ct.c_void_p]
2742 libcspt.CsoundPTflushMessageQueue.argtypes = [ct.c_void_p]
2743
2744
2745 class CsoundPerformanceThread:
2746 """Performs a score in a separate thread until the end of score is reached.
2747
2748 The playback (which is paused by default) is stopped by calling
2749 :py:meth:`stop()`, or if an error occurs.
2750 The constructor takes a Csound instance pointer as argument; it assumes
2751 that :py:meth:`ctcsound.compile_()` was called successfully before creating
2752 the performance thread. Once the playback is stopped for one of the above
2753 mentioned reasons, the performance thread calls :py:meth:`ctcsound.cleanup()`
2754 and returns.
2755 """
2756 def __init__(self, csp):
2757 self.cpt = libcspt.NewCsoundPT(csp)
2758
2759 def __del__(self):
2760 libcspt.DeleteCsoundPT(self.cpt)
2761
2762 def isRunning(self):
2763 """Returns :code:`True` if the performance thread is running, :code:`False` otherwise."""
2764 return libcspt.CsoundPTisRunning(self.cpt) != 0
2765
2766 def processCB(self):
2767 """Returns the process callback."""
2768 return PROCESSFUNC(libcspt.CsoundPTgetProcessCB(self.cpt))
2769
2770 def setProcessCB(self, function, data):
2771 """Sets the process callback."""
2772 libcspt.CsoundPTsetProcessCB(self.cpt, PROCESSFUNC(function), ct.byref(data))
2773
2774 def csound(self):
2775 """Returns the Csound instance pointer."""
2776 return libcspt.CsoundPTgetCsound(self.cpt)
2777
2778 def status(self):
2779 """Returns the current status.
2780
2781 Zero if still playing, positive if the end of score was reached or
2782 performance was stopped, and negative if an error occured.
2783 """
2784 return libcspt.CsoundPTgetStatus(self.cpt)
2785
2786 def play(self):
2787 """Continues performance if it was paused."""
2788 libcspt.CsoundPTplay(self.cpt)
2789
2790 def pause(self):
2791 """Pauses performance (can be continued by calling :py:meth:`play()`)."""
2792 libcspt.CsoundPTpause(self.cpt)
2793
2794 def togglePause(self):
2795 """Pauses or continues performance, depending on current state."""
2796 libcspt.CsoundPTtogglePause(self.cpt)
2797
2798 def stop(self):
2799 """Stops performance (cannot be continued)."""
2800 libcspt.CsoundPTstop(self.cpt)
2801
2802 def record(self, filename, samplebits, numbufs):
2803 """Starts recording the output from Csound.
2804
2805 The sample rate and number of channels are taken directly from the
2806 running Csound instance.
2807 """
2808 libcspt.CsoundPTrecord(self.cpt, cstring(filename), samplebits, numbufs)
2809
2810 def stopRecord(self):
2811 """Stops recording and closes audio file."""
2812 libcspt.CsoundPTstopRecord(self.cpt)
2813
2814 def scoreEvent(self, absp2mode, opcod, pFields):
2815 """Sends a score event.
2816
2817 The event has type *opcod* (e.g. 'i' for a note event).
2818 *pFields* is tuple, a list, or an ndarray of MYFLTs with all the pfields
2819 for this event, starting with the p1 value specified in *pFields[0]*.
2820 If *absp2mode* is non-zero, the start time of the event is measured
2821 from the beginning of performance, instead of the default of relative
2822 to the current time.
2823 """
2824 p = np.array(pFields).astype(MYFLT)
2825 ptr = p.ctypes.data_as(ct.POINTER(MYFLT))
2826 numFields = p.size
2827 libcspt.CsoundPTscoreEvent(self.cpt, ct.c_int(absp2mode), cchar(opcod), numFields, ptr)
2828
2829 def inputMessage(self, s):
2830 """Sends a score event as a string, similarly to line events (-L)."""
2831 libcspt.CsoundPTinputMessage(self.cpt, cstring(s))
2832
2833 def setScoreOffsetSeconds(self, timeVal):
2834 """Sets the playback time pointer to the specified value (in seconds)."""
2835 libcspt.CsoundPTsetScoreOffsetSeconds(self.cpt, ct.c_double(timeVal))
2836
2837 def join(self):
2838 """Waits until the performance is finished or fails.
2839
2840 Returns a positive value if the end of score was reached or
2841 :py:meth:`stop()` was called, and a negative value if an error occured.
2842 Also releases any resources associated with the performance thread
2843 object.
2844 """
2845 return libcspt.CsoundPTjoin(self.cpt)
2846
2847 def flushMessageQueue(self):
2848 """Waits until all pending messages are actually received.
2849
2850 (pause, send score event, etc.)
2851 """
2852 libcspt.CsoundPTflushMessageQueue(self.cpt)
2853