Debian Codegraph @

src/host-examples/example-3-globals.cpp

raw symbols SCIP
1 //-----------------------------------------------------------------------------
2 // file: example-3-globals.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 communication betweeh C++ and ChucK through ChucK global variables!
6 //
7 // NOTE: the Chuck_Globals_Manager API has TWO variants for communicating
8 // between C++ and ChucK; (see chuck_globals.h for more information)
9 // -- CamelCase named functions in C++ are to be used from outside the
10 // audio thread (e.g., setGlobalInt())
11 // -- lower_case named functions in C++ are to be used from within the
12 // audio thread (e.g., get_global_int_value())
13 //
14 // INITIALIZATION
15 // 1. #include "chuck.h"
16 // 2. make a new ChucK instance, e.g., the_chuck = new ChucK();
17 // 3. set up real-time audio (e.g., using RtAudio or another way)
18 // -- this also sets up an audio callback function that will
19 // be automatically called each time the system needs a new
20 // chunk of audio to process / playback
21 // 4. set ChucK parameters
22 // 5. initialize and start the ChucK instance
23 // 6. add code for ChucK to compile and run...
24 // using the_chuck->compileCode() or the_chuck->compileFile()
25 // (after starting real-time audio, this should only be done
26 // from the audio thread (same thread as the_chuck->run())
27 // 7. start real-time audio
28 //
29 // RUNTIME
30 // 1. 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 // 2. the main thread waits for user input and then use
34 // the_chuck()->globals() to signal a ChucK Event from C++
35 // 3. the audio thread get the value of a ChucK global variable
36 // and if it changed from last time, prints its value
37 // 4. additionally, on input a request is made to retrieve all
38 // global variables current in VM by name and type
39 //
40 // author: Ge Wang (https://ccrma.stanford.edu/~ge/)
41 // date: Summer 2023
42 //-----------------------------------------------------------------------------
43 #include "chuck.h"
44 #include "chuck_globals.h" // for globals
45 #include "RtAudio.h"
46
47 #include <iostream>
48 using namespace std;
49
50
51 //-----------------------------------------------------------------------------
52 // global things for this example
53 //-----------------------------------------------------------------------------
54 // our ChucK instance
55 ChucK * the_chuck = NULL;
56 // audio input buffer
57 SAMPLE * g_inputBuffer = NULL;
58 // audio output buffer
59 SAMPLE * g_outputBuffer = NULL;
60 // our audio buffer size
61 t_CKINT g_bufferSize = 0;
62
63 // real-time audio
64 RtAudio * the_rtaudio = NULL;
65
66 // last frequency
67 t_CKFLOAT g_last_frequency = 0;
68
69
70 //-----------------------------------------------------------------------------
71 // function prototypes
72 //-----------------------------------------------------------------------------
73 // initialize real-time audio
74 t_CKBOOL init_realtime_audio( t_CKINT sampleRate,
75 t_CKINT inputChannels,
76 t_CKINT outputChannels,
77 t_CKINT preferredBufferSize );
78 // start real-time audio
79 t_CKBOOL start_realtime_audio();
80 // clean up real-time audio
81 t_CKBOOL cleanup_realtime_audio();
82
83
84
85 //-----------------------------------------------------------------------------
86 // audio callback function (called by RtAudio)
87 //-----------------------------------------------------------------------------
88 int audio_cb( void * outputBuffer, void * inputBuffer, unsigned int nBufferFrames,
89 double streamTime, RtAudioStreamStatus status, void * data )
90 {
91 SAMPLE * input = (SAMPLE *)inputBuffer;
92 SAMPLE * output = (SAMPLE *)outputBuffer;
93
94 // run ChucK for # of frames
95 the_chuck->run( input, output, nBufferFrames );
96
97 // get global variable from chuck
98 // NOTE: this is using lower_case version (calling from audio thread)
99 t_CKFLOAT f = the_chuck->globals()->get_global_float_value( "the_frequency" );
100 // if different
101 if( f != g_last_frequency )
102 {
103 // print
104 cerr << " getting global value from ChucK: " << f << endl;
105 // set
106 g_last_frequency = f;
107 }
108
109 return 0;
110 }
111
112
113 //-----------------------------------------------------------------------------
114 // error callback function (called by RtAudio on warning or error)
115 //-----------------------------------------------------------------------------
116 void error_cb( RtAudioErrorType type, const std::string &errorText )
117 {
118 // print the type and error text from RtAudio
119 cerr << "[real-time audio](error " << (int)type << "): " << errorText << endl;
120 }
121
122
123 //-----------------------------------------------------------------------------
124 // globals callback function (called by ChucK on request)
125 // args: `list` a vector of [type,name] pairs, each corresponding to a global
126 // `data` whatever data was passed into getAllGlobalVariables()
127 //-----------------------------------------------------------------------------
128 void all_globals_cb( const vector<Chuck_Globals_TypeValue> & list, void * data )
129 {
130 for( t_CKUINT i = 0; i < list.size(); i++ )
131 {
132 // print
133 cerr << " global variable: " << list[i].type << " " << list[i].name << endl;
134 }
135 }
136
137
138 //-----------------------------------------------------------------------------
139 // host program entry point
140 //-----------------------------------------------------------------------------
141 int main( int argc, char ** argv )
142 {
143 //-------------------------------------------------------------------------
144 // ChucK initialization
145 //-------------------------------------------------------------------------
146 // instantiate a ChucK instance
147 the_chuck = new ChucK();
148
149 // set some parameters: sample rate
150 the_chuck->setParam( CHUCK_PARAM_SAMPLE_RATE, 44100 );
151 // number of input channels
152 the_chuck->setParam( CHUCK_PARAM_INPUT_CHANNELS, 0 );
153 // number of output channels
154 the_chuck->setParam( CHUCK_PARAM_OUTPUT_CHANNELS, 2 );
155 // whether to halt the VM when there is no more shred running
156 the_chuck->setParam( CHUCK_PARAM_VM_HALT, TRUE );
157 // set hint so internally can advise things like async data writes etc.
158 the_chuck->setParam( CHUCK_PARAM_IS_REALTIME_AUDIO_HINT, TRUE );
159 // turn on logging to see what ChucK is up to; higher == more info
160 // the_chuck->setLogLevel( 3 );
161
162 // initialize real-time audio
163 if( !init_realtime_audio( the_chuck->getParamInt( CHUCK_PARAM_SAMPLE_RATE ),
164 the_chuck->getParamInt( CHUCK_PARAM_INPUT_CHANNELS ),
165 the_chuck->getParamInt( CHUCK_PARAM_OUTPUT_CHANNELS ),
166 512 ) )
167 { goto done; }
168
169 // initialize ChucK, after the parameters are set
170 the_chuck->init();
171
172 //-------------------------------------------------------------------------
173 // ChucK runtime
174 //-------------------------------------------------------------------------
175 // start ChucK VM and synthesis engine
176 the_chuck->start();
177
178 // compile ChucK program from file (this can be called on-the-fly and repeatedly)
179 if( !the_chuck->compileFile( "ck/test-3-globals.ck", "", 1 ) )
180 {
181 // got error, baillng out...
182 goto done;
183 }
184
185 // start real-time audio
186 if( !start_realtime_audio() )
187 { goto cleanup; }
188
189 // keep going as long as a shred is still running
190 // (as long as CHUCK_PARAM_VM_HALT is set to TRUE)
191 while( the_chuck->vm_running() )
192 {
193 // print
194 cerr << "press [CTRL-C] to quit" << endl;
195 cerr << "press [ENTER] to signal next note" << endl;;
196 // get a character
197 char c; cin.get(c);
198
199 // signal the event in ChucK
200 // NOTE: this is using CamelCase version (calling from outside of audio thread)
201 the_chuck->globals()->broadcastGlobalEvent( "the_nextNote" );
202 // also request a list of all globals in ChucK
203 the_chuck->globals()->getAllGlobalVariables( all_globals_cb, NULL );
204 }
205
206 cleanup:
207 // clean up real-time audio
208 cleanup_realtime_audio();
209
210 done:
211 // clean up ChucK
212 CK_SAFE_DELETE( the_chuck );
213
214 return 0;
215 }
216
217
218 //-----------------------------------------------------------------------------
219 // initialize real-time audio
220 //-----------------------------------------------------------------------------
221 t_CKBOOL init_realtime_audio( t_CKINT sampleRate,
222 t_CKINT inputChannels,
223 t_CKINT outputChannels,
224 t_CKINT preferredBufferSize )
225 {
226 // instantiate a new RtAudio
227 the_rtaudio = new RtAudio();
228
229 // check device count
230 if( the_rtaudio->getDeviceCount() < 1 )
231 {
232 cerr << "[real-time audio]: no audio device found!" << endl;
233 return FALSE;
234 }
235
236 // set error callback
237 the_rtaudio->setErrorCallback( error_cb );
238
239 // input params
240 RtAudio::StreamParameters iParams;
241 iParams.deviceId = the_rtaudio->getDefaultInputDevice();
242 iParams.nChannels = inputChannels;
243
244 // output params
245 RtAudio::StreamParameters oParams;
246 oParams.deviceId = the_rtaudio->getDefaultOutputDevice();
247 oParams.nChannels = outputChannels;
248
249 // buffer frames variable
250 unsigned int bufferFrames = preferredBufferSize;
251 // audio data type
252 t_CKUINT datatype = RTAUDIO_FLOAT32;
253 if( sizeof(SAMPLE) == 8 ) datatype = RTAUDIO_FLOAT64;
254
255 // open audio stream
256 RtAudioErrorType retval = the_rtaudio->openStream( &oParams,
257 inputChannels > 0 ? &iParams : NULL,
258 datatype, sampleRate, &bufferFrames,
259 &audio_cb, NULL );
260 // check
261 return retval == RTAUDIO_NO_ERROR;
262 }
263
264
265 //-----------------------------------------------------------------------------
266 // start real-time audio
267 //-----------------------------------------------------------------------------
268 t_CKBOOL start_realtime_audio()
269 {
270 // check
271 if( !the_rtaudio )
272 {
273 cerr << "[real-time audio]: uninitialized..." << endl;
274 return FALSE;
275 }
276
277 // start the stream
278 RtAudioErrorType retval = the_rtaudio->startStream();
279 // check
280 return retval == RTAUDIO_NO_ERROR;
281 }
282
283
284 //-----------------------------------------------------------------------------
285 // clean up real-time audio
286 //-----------------------------------------------------------------------------
287 t_CKBOOL cleanup_realtime_audio()
288 {
289 // check
290 if( !the_rtaudio )
291 {
292 cerr << "[real-time audio]: uninitialized..." << endl;
293 return FALSE;
294 }
295
296 // stop the stream
297 RtAudioErrorType retval = the_rtaudio->stopStream();
298 // clean up
299 if( the_rtaudio->isStreamOpen() ) the_rtaudio->closeStream();
300
301 // done
302 return retval == RTAUDIO_NO_ERROR;
303 }