Debian Codegraph @

src/host-examples/example-5-custom-api.cpp

raw symbols SCIP
1 //-----------------------------------------------------------------------------
2 // file: example-5-custom-api.cpp
3 // desc: Looking to integrate ChucK as a component inside another host program?
4 // Here is an example of using ChucK as a library, with real-time audio,
5 // and shows a C++ host can add a custom API that can be called from
6 // the ChucK language side. This custom API bindings would be specific to
7 // the c++ host, and is a powerful way to further integrate ChucK into a
8 // a system.
9 //
10 // INITIALIZATION
11 // 1. #include "chuck.h"
12 // 2. set up ChucK and real-time audio (see example-2-audio.cpp)
13 // 3. initialize ChucK, but don't start real-time audio just yet.
14 // This is so ChucK's compiler and type system can be initialized;
15 // we don't want to start real-time audio yet, since our next
16 // step is not thread-safe, meaning it must be done before
17 // starting real-time audio OR it must be done on the audio
18 // thread; in this example, we will do the former.
19 // 4. provide a QUERY function to ChucK to call via ChucK::bind();
20 // the function that a c++ host can use to programmatically add
21 // custom classes to the ChucK type system
22 // NOTE: this process is similar to defining a chugin (ChucK plugin)
23 // -- and in fact uses the same Chuck_DL QUERY interface as chugins;
24 // the only difference is that in this approach, the custom bindings
25 // are statically compiled into the host, whereas chugins are
26 // dynamically loaded libraries.
27 // 5. add code for ChucK to compile and run...
28 // NOTE: this ChucK code can use the custom classes we've added
29 // in the above step (#4).
30 // 6. start real-time audio
31 //
32 // author: Ge Wang (https://ccrma.stanford.edu/~ge/)
33 // date: Winter 2025
34 //-----------------------------------------------------------------------------
35 #include "chuck.h"
36 #include "util_platforms.h" // for ck_usleep()
37 #include "RtAudio.h"
38
39 #include <iostream>
40 using namespace std;
41
42
43 //-----------------------------------------------------------------------------
44 // global things for this example
45 //-----------------------------------------------------------------------------
46 // our ChucK instance
47 ChucK * the_chuck = NULL;
48 // audio input buffer
49 SAMPLE * g_inputBuffer = NULL;
50 // audio output buffer
51 SAMPLE * g_outputBuffer = NULL;
52 // our audio buffer size
53 t_CKINT g_bufferSize = 0;
54
55 // real-time audio
56 RtAudio * the_rtaudio = NULL;
57
58
59 //-----------------------------------------------------------------------------
60 // function prototypes
61 //-----------------------------------------------------------------------------
62 // initialize real-time audio
63 t_CKBOOL init_realtime_audio( t_CKINT sampleRate,
64 t_CKINT inputChannels,
65 t_CKINT outputChannels,
66 t_CKINT preferredBufferSize );
67 // start real-time audio
68 t_CKBOOL start_realtime_audio();
69 // clean up real-time audio
70 t_CKBOOL cleanup_realtime_audio();
71 // custom API query function
72 DLL_QUERY host_query( Chuck_DL_Query * QUERY );
73
74
75
76
77 //-----------------------------------------------------------------------------
78 // audio callback function (called by RtAudio)
79 //-----------------------------------------------------------------------------
80 int audio_cb( void * outputBuffer, void * inputBuffer, unsigned int nBufferFrames,
81 double streamTime, RtAudioStreamStatus status, void * data )
82 {
83 SAMPLE * input = (SAMPLE *)inputBuffer;
84 SAMPLE * output = (SAMPLE *)outputBuffer;
85
86 // run ChucK for # of frames
87 the_chuck->run( input, output, nBufferFrames );
88
89 return 0;
90 }
91
92
93 //-----------------------------------------------------------------------------
94 // error callback function (called by RtAudio on warning or error)
95 //-----------------------------------------------------------------------------
96 void error_cb( RtAudioErrorType type, const std::string & errorText )
97 {
98 // print the type and error text from RtAudio
99 cerr << "[real-time audio](error " << (int)type << "): " << errorText << endl;
100 }
101
102
103 //-----------------------------------------------------------------------------
104 // host program entry point
105 //-----------------------------------------------------------------------------
106 int main( int argc, char ** argv )
107 {
108 //-------------------------------------------------------------------------
109 // ChucK initialization
110 //-------------------------------------------------------------------------
111 // instantiate a ChucK instance
112 the_chuck = new ChucK();
113
114 // set some parameters: sample rate
115 the_chuck->setParam( CHUCK_PARAM_SAMPLE_RATE, 44100 );
116 // number of input channels
117 the_chuck->setParam( CHUCK_PARAM_INPUT_CHANNELS, 0 );
118 // number of output channels
119 the_chuck->setParam( CHUCK_PARAM_OUTPUT_CHANNELS, 2 );
120 // whether to halt the VM when there is no more shred running
121 the_chuck->setParam( CHUCK_PARAM_VM_HALT, TRUE );
122 // set hint so internally can advise things like async data writes etc.
123 the_chuck->setParam( CHUCK_PARAM_IS_REALTIME_AUDIO_HINT, TRUE );
124 // turn on logging to see what ChucK is up to; higher == more info
125 // the_chuck->setLogLevel( 3 );
126
127 // initialize real-time audio
128 if( !init_realtime_audio( the_chuck->getParamInt( CHUCK_PARAM_SAMPLE_RATE ),
129 the_chuck->getParamInt( CHUCK_PARAM_INPUT_CHANNELS ),
130 the_chuck->getParamInt( CHUCK_PARAM_OUTPUT_CHANNELS ),
131 512 ) )
132 { goto done; }
133
134 // initialize ChucK, after the parameters are set
135 the_chuck->init();
136
137 //-------------------------------------------------------------------------
138 // bind custom API here (must be after init())
139 //-------------------------------------------------------------------------
140 the_chuck->bind( host_query, "ExampleCustomAPI" );
141
142 // start ChucK VM and synthesis engine
143 the_chuck->start();
144
145 // compile ChucK program from file
146 // NOTE: this code can immediately use the custom types we just added
147 // through using the query function
148 if( !the_chuck->compileFile( "ck/test-5-custom.ck" ) )
149 {
150 // got error, baillng out...
151 goto done;
152 }
153
154 // start real-time audio
155 if( !start_realtime_audio() )
156 { goto cleanup; }
157
158 // print
159 cerr << "chuck running...(press ctrl-c to quit)" << endl;
160
161 // keep going as long as a shred is still running
162 // (as long as CHUCK_PARAM_VM_HALT is set to TRUE)
163 while( the_chuck->vm_running() )
164 {
165 // wait a bit
166 ck_usleep( 10000 );
167 }
168
169 cleanup:
170 // clean up real-time audio
171 cleanup_realtime_audio();
172
173 done:
174 // clean up ChucK
175 CK_SAFE_DELETE( the_chuck );
176
177 return 0;
178 }
179
180
181 //-----------------------------------------------------------------------------
182 // initialize real-time audio
183 //-----------------------------------------------------------------------------
184 t_CKBOOL init_realtime_audio( t_CKINT sampleRate,
185 t_CKINT inputChannels,
186 t_CKINT outputChannels,
187 t_CKINT preferredBufferSize )
188 {
189 // instantiate a new RtAudio
190 the_rtaudio = new RtAudio();
191
192 // check device count
193 if( the_rtaudio->getDeviceCount() < 1 )
194 {
195 cerr << "[real-time audio]: no audio device found!" << endl;
196 return FALSE;
197 }
198
199 // set error callback
200 the_rtaudio->setErrorCallback( error_cb );
201
202 // input params
203 RtAudio::StreamParameters iParams;
204 iParams.deviceId = the_rtaudio->getDefaultInputDevice();
205 iParams.nChannels = inputChannels;
206
207 // output params
208 RtAudio::StreamParameters oParams;
209 oParams.deviceId = the_rtaudio->getDefaultOutputDevice();
210 oParams.nChannels = outputChannels;
211
212 // buffer frames variable
213 unsigned int bufferFrames = preferredBufferSize;
214 // audio data type
215 t_CKUINT datatype = RTAUDIO_FLOAT32;
216 if( sizeof(SAMPLE) == 8 ) datatype = RTAUDIO_FLOAT64;
217
218 // open audio stream
219 RtAudioErrorType retval = the_rtaudio->openStream( &oParams,
220 inputChannels > 0 ? &iParams : NULL,
221 datatype, sampleRate, &bufferFrames,
222 &audio_cb, NULL );
223 // check
224 return retval == RTAUDIO_NO_ERROR;
225 }
226
227
228 //-----------------------------------------------------------------------------
229 // start real-time audio
230 //-----------------------------------------------------------------------------
231 t_CKBOOL start_realtime_audio()
232 {
233 // check
234 if( !the_rtaudio )
235 {
236 cerr << "[real-time audio]: uninitialized..." << endl;
237 return FALSE;
238 }
239
240 // start the stream
241 RtAudioErrorType retval = the_rtaudio->startStream();
242 // check
243 return retval == RTAUDIO_NO_ERROR;
244 }
245
246
247 //-----------------------------------------------------------------------------
248 // clean up real-time audio
249 //-----------------------------------------------------------------------------
250 t_CKBOOL cleanup_realtime_audio()
251 {
252 // check
253 if( !the_rtaudio )
254 {
255 cerr << "[real-time audio]: uninitialized..." << endl;
256 return FALSE;
257 }
258
259 // stop the stream
260 RtAudioErrorType retval = the_rtaudio->stopStream();
261 // clean up
262 if( the_rtaudio->isStreamOpen() ) the_rtaudio->closeStream();
263
264 // done
265 return retval == RTAUDIO_NO_ERROR;
266 }
267
268
269 // function prototype for c++ hooks; these are the implementation for various functions
270 CK_DLL_CTOR( FooFoo_ctor );
271 CK_DLL_CTOR( FooFoo_ctor_value );
272 CK_DLL_DTOR( FooFoo_dtor );
273 CK_DLL_MFUN( FooFoo_getValue );
274 CK_DLL_MFUN( FooFoo_setValue );
275 CK_DLL_MFUN( FooFoo_increment );
276 CK_DLL_SFUN( FooFoo_add );
277
278 // offset for internal instanced data; this is typically used to associate
279 // a pointer of a c++ data structure to an instance of a ChucK object (see below)
280 static t_CKINT host_offset_data = 0;
281
282
283 //-----------------------------------------------------------------------------
284 // query fuction for adding custom API
285 //-----------------------------------------------------------------------------
286 DLL_QUERY host_query( Chuck_DL_Query * QUERY )
287 {
288 // get global
289 Chuck_Env * env = QUERY->env();
290 // name (optional)
291 QUERY->setname( QUERY, "OurCustomHostAPI" );
292
293 // add a class, and specify its parent class
294 QUERY->begin_class( QUERY, "FooFoo", "Object" );
295 // add documentatiopn for the class
296 QUERY->doc_class( QUERY, "created for the sake of this example, FooFoo is a custom class" );
297
298 // add a default contructor
299 QUERY->add_ctor( QUERY, FooFoo_ctor );
300 // add destructor
301 QUERY->add_dtor( QUERY, FooFoo_dtor );
302
303 // add a overloaded contructor, with arguments
304 QUERY->add_ctor( QUERY, FooFoo_ctor_value );
305 // add arguments
306 QUERY->add_arg( QUERY, "float", "value" );
307 // add documentation for this function
308 QUERY->doc_func( QUERY, "construct a FooFoo instance with value" );
309
310 // add a *member* function (mfun) by providing a hook, return type, and name
311 QUERY->add_mfun( QUERY, FooFoo_setValue, "float", "setValue" );
312 // add arguments
313 QUERY->add_arg( QUERY, "float", "value" );
314 // add documentation for this function
315 QUERY->doc_func( QUERY, "set FooFoo's value!" );
316
317 // add a *member* function (mfun) by providing a hook, return type, and name
318 QUERY->add_mfun( QUERY, FooFoo_getValue, "float", "getValue" );
319 // add documentation for this function
320 QUERY->doc_func( QUERY, "get FooFoo's value!" );
321
322 // add a *member* function (mfun) by providing a hook, return type, and name
323 QUERY->add_mfun( QUERY, FooFoo_increment, "float", "increment" );
324 // add arguments
325 QUERY->add_arg( QUERY, "float", "x" );
326 // add documentation for this function
327 QUERY->doc_func( QUERY, "increment FooFoo's value by x" );
328
329 // add a *static* function (sfun) by providing a hook, return type, and name
330 QUERY->add_sfun( QUERY, FooFoo_add, "float", "add" );
331 // add arguments
332 QUERY->add_arg( QUERY, "float", "x" );
333 QUERY->add_arg( QUERY, "float", "y" );
334 // add documentation for this function
335 QUERY->doc_func( QUERY, "add two floating point numbers" );
336
337 // add member variable (not usable from chuck)
338 host_offset_data = QUERY->add_mvar( QUERY, "int", "@host_data", FALSE );
339
340 // NOTE: there are many additional kinds of things that can be added in
341 // in an custom API query, including member variables, static variables,
342 // Event that can triggered, and more; see various chugins for reference,
343 // (e.g., ChuGL, which contains an extensive API)
344
345 // end class definition
346 QUERY->end_class( QUERY );
347
348 // return success!
349 return TRUE;
350 }
351
352 // example of host-side c++ data strcture
353 // these serve as internal implementation to the ChucK types we are binding
354 struct HostData
355 {
356 // some state
357 float theValue;
358 // add any other state and behaviors here...
359
360 // constructor
361 HostData() { theValue = 0; }
362 };
363
364 // implementation for FooFoo's default constructor
365 CK_DLL_CTOR( FooFoo_ctor )
366 {
367 // create internal host-side data structure
368 HostData * data = new HostData;
369 // set into chuck object's data field
370 OBJ_MEMBER_INT( SELF, host_offset_data ) = (t_CKINT)data;
371 }
372
373 // implementation for FooFoo's overloaded constructor FooFoo( float )
374 CK_DLL_CTOR( FooFoo_ctor_value )
375 {
376 // create internal host-side data structure
377 HostData * data = new HostData;
378 // retrieve argument
379 t_CKFLOAT arg = GET_NEXT_FLOAT( ARGS );
380 // set into chuck object's data field
381 OBJ_MEMBER_INT( SELF, host_offset_data ) = (t_CKINT)data;
382 // set the value
383 data->theValue = arg;
384 }
385
386 // implementation for FooFoo's destructor
387 CK_DLL_DTOR( FooFoo_dtor )
388 {
389 // retrieve our c++/host-side data structure
390 HostData * data = (HostData *)OBJ_MEMBER_INT( SELF, host_offset_data );
391 // release the memory
392 CK_SAFE_DELETE( data );
393 // set the data field to zero, in the corresponding chuck object instance
394 OBJ_MEMBER_INT( SELF, host_offset_data ) = 0;
395 }
396
397 // implementation of FooFoo.getValue()
398 CK_DLL_MFUN( FooFoo_getValue )
399 {
400 // retrieve our c++/host-side data structure
401 HostData * data = (HostData *)OBJ_MEMBER_INT( SELF, host_offset_data );
402 // set the return value
403 RETURN->v_float = data->theValue;
404 }
405
406 // implementation of FooFoo.getValue( float )
407 CK_DLL_MFUN( FooFoo_setValue )
408 {
409 // retrieve our c++/host-side data structure
410 HostData * data = (HostData *)OBJ_MEMBER_INT( SELF, host_offset_data );
411 // retrieve argument
412 t_CKFLOAT arg = GET_NEXT_FLOAT( ARGS );
413 // set the value from the argument
414 data->theValue = arg;
415 // set the return value
416 RETURN->v_float = data->theValue;
417 }
418
419 // implementation of FooFoo.increment( float )
420 CK_DLL_MFUN( FooFoo_increment )
421 {
422 // retrieve our c++/host-side data structure
423 HostData * data = (HostData *)OBJ_MEMBER_INT( SELF, host_offset_data );
424 // retrieve argument
425 t_CKFLOAT arg = GET_NEXT_FLOAT( ARGS );
426 // set the value from the argument
427 data->theValue += arg;
428 // set the return value
429 RETURN->v_float = data->theValue;
430 }
431
432 // implementation of STATIC function FooFoo.add( float, float )
433 CK_DLL_SFUN( FooFoo_add )
434 {
435 // retrieve arguments
436 t_CKFLOAT x = GET_NEXT_FLOAT( ARGS );
437 t_CKFLOAT y = GET_NEXT_FLOAT( ARGS );
438 // set sum to be returned as a float
439 RETURN->v_float = x + y;
440 }