Debian Codegraph @

src/host-examples/example-4-shreds.cpp

raw symbols SCIP
1 //-----------------------------------------------------------------------------
2 // file: example-4-shreds.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 various shred-related operations from c++, including adding,
6 // removing last, and getting the current VM status including info about
7 // shreds
8 //
9 // INITIALIZATION
10 // 1. #include "chuck.h"
11 // 2. make a new ChucK instance, e.g., the_chuck = new ChucK();
12 // 3. set up real-time audio (e.g., using RtAudio or another way)
13 // -- this also sets up an audio callback function that will
14 // be automatically called each time the system needs a new
15 // chunk of audio to process / playback
16 // 4. set ChucK parameters
17 // 5. initialize and start the ChucK instance
18 // 6. start real-time audio
19 // 7. use various parts of the API (see below) to work with
20 // ChucK shreds: adding (implictly done with compileCode() and
21 // compileFile()), removing previously added shreds, getting info
22 // on all shreds in the VM, and printing status info
23 //
24 // NOTE: in general, this example uses thread-safe versions of
25 // the shreds API, which means these functions can be called from
26 // a thread other than the audio thread / the thread that calls
27 // ChucK::run(...).
28 //
29 // RUNTIME
30 // ** from within the audio callback function -- audio_cb(...), set up
31 // in step #3 above -- call the_chuck->run() with the audio buffers
32 // and the I/O frame size
33 //
34 // author: Ge Wang (https://ccrma.stanford.edu/~ge/)
35 // date: Summer 2023
36 //-----------------------------------------------------------------------------
37 #include "chuck.h"
38 #include "chuck_vm.h" // since we will reaching deeper into engine
39 #include "util_platforms.h" // for ck_usleep() and ck_isatty()
40 #include "RtAudio.h"
41
42 #include <vector>
43 #include <iostream>
44 using namespace std;
45
46
47 //-----------------------------------------------------------------------------
48 // global things for this example
49 //-----------------------------------------------------------------------------
50 // our ChucK instance
51 ChucK * the_chuck = NULL;
52 // audio input buffer
53 SAMPLE * g_inputBuffer = NULL;
54 // audio output buffer
55 SAMPLE * g_outputBuffer = NULL;
56 // our audio buffer size
57 t_CKINT g_bufferSize = 0;
58
59 // real-time audio
60 RtAudio * the_rtaudio = NULL;
61
62
63 //-----------------------------------------------------------------------------
64 // function prototypes
65 //-----------------------------------------------------------------------------
66 // initialize real-time audio
67 t_CKBOOL init_realtime_audio( t_CKINT sampleRate,
68 t_CKINT inputChannels,
69 t_CKINT outputChannels,
70 t_CKINT preferredBufferSize );
71 // start real-time audio
72 t_CKBOOL start_realtime_audio();
73 // clean up real-time audio
74 t_CKBOOL cleanup_realtime_audio();
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 // VM message callback function (called by chuck VM in response to queue_msg())
95 //-----------------------------------------------------------------------------
96 void vm_msg_cb( const Chuck_Msg * msg )
97 {
98 // check the type
99 switch( msg->type )
100 {
101 // cases we'd like to handle
102 case CK_MSG_STATUS:
103 {
104 // get status info
105 Chuck_VM_Status * status = msg->status;
106 // verify
107 if( status )
108 {
109 // number shreds
110 cerr << "\n-------------------------------" << endl;
111 cerr << "printing from callback function" << endl;
112 cerr << "-------------------------------" << endl;
113 cerr << "# of shreds in VM: " << status->list.size() << endl;
114 // chuck time
115 cerr << "chuck time: " << status->now_system << "::samp ("
116 << status->t_hour << "h"
117 << status->t_minute << "m"
118 << status->t_second << "s)" << endl;
119
120 // print status
121 if( status->list.size() ) cerr << "--------" << endl;
122 for( t_CKUINT i = 0; i < status->list.size(); i++ )
123 {
124 // get shred info
125 Chuck_VM_Shred_Status * info = status->list[i];
126 // print shred info
127 cerr << "[shred] id: " << info->xid
128 << " source: " << info->name.c_str()
129 << " spork time: " << (status->now_system - info->start) / status->srate
130 << " state: " << (!info->has_event ? "ACTIVE" : "(waiting on event)") << endl;
131 }
132 if( status->list.size() ) cerr << "--------" << endl;
133
134 // clean up
135 CK_SAFE_DELETE( status );
136 }
137 }
138 break;
139 }
140
141 // our responsibility to delete
142 CK_SAFE_DELETE( msg );
143 }
144
145
146 //-----------------------------------------------------------------------------
147 // error callback function (called by RtAudio on warning or error)
148 //-----------------------------------------------------------------------------
149 void error_cb( RtAudioErrorType type, const std::string & errorText )
150 {
151 // print the type and error text from RtAudio
152 cerr << "[real-time audio](error " << (int)type << "): " << errorText << endl;
153 }
154
155
156 //-----------------------------------------------------------------------------
157 // print usage for the simple command prompt in this example
158 //-----------------------------------------------------------------------------
159 void usage()
160 {
161 // print
162 cerr << "-------------------" << endl;
163 cerr << "type '+' or 'add' to add a shred" << endl;
164 cerr << "type '^' or 'status' to get VM info and print shred status" << endl;
165 cerr << "type '--' or 'remove.last' to remove last shred" << endl;
166 cerr << "type 'remove.all' to remove all shreds" << endl;
167 cerr << "type 'time' to print time" << endl;
168 cerr << "type 'exit' to quit this program" << endl;
169 cerr << "-------------------" << endl << endl;
170 }
171
172 //-----------------------------------------------------------------------------
173 // host program entry point
174 //-----------------------------------------------------------------------------
175 int main( int argc, char ** argv )
176 {
177 //-------------------------------------------------------------------------
178 // ChucK initialization
179 //-------------------------------------------------------------------------
180 // instantiate a ChucK instance
181 the_chuck = new ChucK();
182
183 // set some parameters: sample rate
184 the_chuck->setParam( CHUCK_PARAM_SAMPLE_RATE, 44100 );
185 // number of input channels
186 the_chuck->setParam( CHUCK_PARAM_INPUT_CHANNELS, 0 );
187 // number of output channels
188 the_chuck->setParam( CHUCK_PARAM_OUTPUT_CHANNELS, 2 );
189 // set to false so a VM without shreds will keep running
190 the_chuck->setParam( CHUCK_PARAM_VM_HALT, FALSE );
191 // set hint so internally can advise things like async data writes etc.
192 the_chuck->setParam( CHUCK_PARAM_IS_REALTIME_AUDIO_HINT, TRUE );
193 // turn on color output mode
194 the_chuck->setParam( CHUCK_PARAM_TTY_COLOR, ck_isatty() );
195
196 // shred id
197 t_CKUINT shredID = 0;
198 // our shred ID stack
199 vector<t_CKUINT> shredIDs;
200 // filename
201 string filename = "ck/test-4-shreds.ck";
202 // chuck msg pointer; for communicating with VM
203 Chuck_Msg * msg = NULL;
204
205 // initialize real-time audio
206 if( !init_realtime_audio( the_chuck->getParamInt( CHUCK_PARAM_SAMPLE_RATE ),
207 the_chuck->getParamInt( CHUCK_PARAM_INPUT_CHANNELS ),
208 the_chuck->getParamInt( CHUCK_PARAM_OUTPUT_CHANNELS ),
209 512 ) )
210 { goto done; }
211
212 // initialize ChucK, after the parameters are set
213 the_chuck->init();
214
215 //-------------------------------------------------------------------------
216 // ChucK runtime
217 //-------------------------------------------------------------------------
218 // start ChucK VM and synthesis engine
219 the_chuck->start();
220
221 // start real-time audio
222 if( !start_realtime_audio() )
223 { goto cleanup; }
224
225 // print
226 cerr << "chuck running...(press ctrl-c or type 'exit' to quit)" << endl;
227
228 // wait a bit to give audio callback a chance to start up
229 ck_usleep( 200000 );
230
231 // keep going as long as a shred is still running
232 // (as long as CHUCK_PARAM_VM_HALT is set to TRUE)
233 while( the_chuck->vm_running() )
234 {
235 // wait a bit to give audio callback function a chance to receive
236 // message reply from chuck VM and print before we print usage
237 ck_usleep( 100000 );
238 // print usage
239 usage();
240
241 // prompt
242 cerr << "enter a command > ";
243 // command
244 string command; getline( cin, command );
245
246 // check
247 if( command == "+" || command == "add" )
248 {
249 // compile file; FALSE means deferred spork -- thread-safe since
250 // we are on a different thread as the audio thread that is calling
251 // the_chuck->run(...)
252 the_chuck->compileFile( filename, "", 1, FALSE );
253 // get the id of the previously sporked shred
254 shredID = the_chuck->vm()->last_id();
255 // print out the last VM shred id (should be the shred we just compiled)
256 cerr << "adding shred '" << filename << "' with ID: " << shredID << endl;
257 // push on stack
258 shredIDs.push_back( shredID );
259 }
260 else if( command == "--" || command == "remove" )
261 {
262 // if already added
263 if( !shredIDs.size() )
264 {
265 cerr << "no shred to remove!" << endl;
266 continue;
267 }
268 // create a message; VM will delete
269 msg = new Chuck_Msg;
270 // message type
271 msg->type = CK_MSG_REMOVE;
272 // signify no value (will remove last)
273 msg->param = shredIDs.back();
274 // queue on VM
275 the_chuck->vm()->queue_msg( msg );
276 // pop
277 shredIDs.pop_back();
278 }
279 else if( command == "^" || command == "status" )
280 {
281 // create a message, we will delete later on
282 msg = new Chuck_Msg;
283 // message type
284 msg->type = CK_MSG_STATUS;
285 // create a status info
286 msg->status = new Chuck_VM_Status();
287 // add callback function
288 msg->reply_cb = vm_msg_cb;
289 // queue msg in VM; reply will be received by the callback
290 the_chuck->vm()->queue_msg( msg );
291 }
292 else if( command == "status-2" )
293 {
294 // create a message; VM will delete
295 msg = new Chuck_Msg;
296 // message type
297 msg->type = CK_MSG_STATUS;
298 // is passed in without further argument
299 // this will cause VM to print shred status
300 // queue on VM
301 the_chuck->vm()->queue_msg( msg );
302 }
303 else if( command == "remove.all" )
304 {
305 // create a message; VM will delete
306 msg = new Chuck_Msg;
307 // message type
308 msg->type = CK_MSG_REMOVEALL;
309 // queue on VM
310 the_chuck->vm()->queue_msg( msg );
311 }
312 else if( command == "time" )
313 {
314 // create a message; VM will delete
315 msg = new Chuck_Msg;
316 // message type
317 msg->type = CK_MSG_TIME;
318 // queue on VM
319 the_chuck->vm()->queue_msg( msg );
320 }
321 else if( command == "exit" )
322 {
323 break;
324 }
325 else
326 {
327 // what
328 cerr << "*** unrecognized command: " << command << " ***" << endl;
329 }
330 }
331
332 cleanup:
333 // clean up real-time audio
334 cleanup_realtime_audio();
335
336 done:
337 // clean up ChucK
338 CK_SAFE_DELETE( the_chuck );
339
340 return 0;
341 }
342
343
344 //-----------------------------------------------------------------------------
345 // initialize real-time audio
346 //-----------------------------------------------------------------------------
347 t_CKBOOL init_realtime_audio( t_CKINT sampleRate,
348 t_CKINT inputChannels,
349 t_CKINT outputChannels,
350 t_CKINT preferredBufferSize )
351 {
352 // instantiate a new RtAudio
353 the_rtaudio = new RtAudio();
354
355 // check device count
356 if( the_rtaudio->getDeviceCount() < 1 )
357 {
358 cerr << "[real-time audio]: no audio device found!" << endl;
359 return FALSE;
360 }
361
362 // set error callback
363 the_rtaudio->setErrorCallback( error_cb );
364
365 // input params
366 RtAudio::StreamParameters iParams;
367 iParams.deviceId = the_rtaudio->getDefaultInputDevice();
368 iParams.nChannels = inputChannels;
369
370 // output params
371 RtAudio::StreamParameters oParams;
372 oParams.deviceId = the_rtaudio->getDefaultOutputDevice();
373 oParams.nChannels = outputChannels;
374
375 // buffer frames variable
376 unsigned int bufferFrames = preferredBufferSize;
377 // audio data type
378 t_CKUINT datatype = RTAUDIO_FLOAT32;
379 if( sizeof(SAMPLE) == 8 ) datatype = RTAUDIO_FLOAT64;
380
381 // open audio stream
382 RtAudioErrorType retval = the_rtaudio->openStream( &oParams,
383 inputChannels > 0 ? &iParams : NULL,
384 datatype, sampleRate, &bufferFrames,
385 &audio_cb, NULL );
386 // check
387 return retval == RTAUDIO_NO_ERROR;
388 }
389
390
391 //-----------------------------------------------------------------------------
392 // start real-time audio
393 //-----------------------------------------------------------------------------
394 t_CKBOOL start_realtime_audio()
395 {
396 // check
397 if( !the_rtaudio )
398 {
399 cerr << "[real-time audio]: uninitialized..." << endl;
400 return FALSE;
401 }
402
403 // start the stream
404 RtAudioErrorType retval = the_rtaudio->startStream();
405 // check
406 return retval == RTAUDIO_NO_ERROR;
407 }
408
409
410 //-----------------------------------------------------------------------------
411 // clean up real-time audio
412 //-----------------------------------------------------------------------------
413 t_CKBOOL cleanup_realtime_audio()
414 {
415 // check
416 if( !the_rtaudio )
417 {
418 cerr << "[real-time audio]: uninitialized..." << endl;
419 return FALSE;
420 }
421
422 // stop the stream
423 RtAudioErrorType retval = the_rtaudio->stopStream();
424 // clean up
425 if( the_rtaudio->isStreamOpen() ) the_rtaudio->closeStream();
426
427 // done
428 return retval == RTAUDIO_NO_ERROR;
429 }