You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

382 lines
12KB

  1. // Eguitar.cpp
  2. //
  3. // This is a program to create a simple electric guitar model using
  4. // the STK Guitar class. The is model is derived in part from an
  5. // implementation made by Nicholas Donaldson at McGill University in
  6. // 2009. The distortion model is poor, using a simple soft-clipping
  7. // expression provided by Charles R. Sullivan in "Extending the
  8. // Karplus-String Algorithm to Synthesize Electric Guitar Timbres with
  9. // Distortion and Feedback," Computer Music Journal, Vol.14 No.3, Fall
  10. // 1990. Other distortion models would be better, such as that found
  11. // in Pakarinen and Yeh's "A Review of Digital Techniques for Modeling
  12. // Vacuum-Tube Guitar Amplifiers," Computer Music Journal, Vol 33
  13. // No. 2, Summer 2009.
  14. //
  15. // This program performs simple voice management if all noteOn and
  16. // noteOff events are on channel 0. Otherwise, channel values > 0 are
  17. // mapped to specific string numbers. By default, the program creates
  18. // a 6-string guitar. If the normalized noteOn() velocity is < 0.2, a
  19. // string is undamped but not plucked (this is implemented in the
  20. // stk::Guitar class). Thus, you can lightly depress a key on a MIDI
  21. // keyboard and then experiment with string coupling.
  22. //
  23. // The Tcl/Tk GUI allows you to experiment with various parameter
  24. // settings and that can be used in conjunction with a MIDI keyboard
  25. // as: wish < tcl/EGuitar.tcl | ./eguitar -or -ip -im 1
  26. //
  27. // For the moment, this program does not support pitch bends.
  28. //
  29. // Gary P. Scavone, McGill University 2012.
  30. #include "Guitar.h"
  31. #include "SKINImsg.h"
  32. #include "WvOut.h"
  33. #include "JCRev.h"
  34. #include "Skini.h"
  35. #include "RtAudio.h"
  36. #include "Delay.h"
  37. #include "Cubic.h"
  38. // Miscellaneous command-line parsing and instrument allocation
  39. // functions are defined in utilites.cpp ... specific to this program.
  40. #include "utilities.h"
  41. #include <signal.h>
  42. #include <iostream>
  43. #include <algorithm>
  44. #include <cmath>
  45. using std::min;
  46. bool done;
  47. static void finish(int ignore){ done = true; }
  48. using namespace stk;
  49. const unsigned int nStrings = 6;
  50. // Data structure for string information.
  51. struct StringInfo{
  52. bool inUse; // is this string being used?
  53. unsigned int iNote; // note number associated with this string
  54. StringInfo() : inUse(false), iNote(0) {};
  55. };
  56. // The TickData structure holds all the class instances and data that
  57. // are shared by the various processing functions.
  58. struct TickData {
  59. WvOut **wvout;
  60. Guitar *guitar;
  61. StringInfo voices[nStrings];
  62. JCRev reverb;
  63. Messager messager;
  64. Skini::Message message;
  65. StkFloat volume;
  66. StkFloat t60;
  67. unsigned int nWvOuts;
  68. int channels;
  69. int counter;
  70. bool realtime;
  71. bool settling;
  72. bool haveMessage;
  73. int keysDown;
  74. StkFloat feedbackGain;
  75. StkFloat oldFeedbackGain;
  76. StkFloat distortionGain;
  77. StkFloat distortionMix;
  78. Delay feedbackDelay;
  79. Cubic distortion;
  80. StkFloat feedbackSample;
  81. // Default constructor.
  82. TickData()
  83. : wvout(0), volume(1.0), t60(0.75),
  84. nWvOuts(0), channels(2), counter(0),
  85. realtime( false ), settling( false ), haveMessage( false ),
  86. keysDown(0), feedbackSample( 0.0 ) {}
  87. };
  88. #define DELTA_CONTROL_TICKS 30 // default sample frames between control input checks
  89. // The processMessage() function encapsulates the handling of control
  90. // messages. It can be easily relocated within a program structure
  91. // depending on the desired scheduling scheme.
  92. void processMessage( TickData* data )
  93. {
  94. register StkFloat value1 = data->message.floatValues[0];
  95. register StkFloat value2 = data->message.floatValues[1];
  96. unsigned int channel = (unsigned int) data->message.channel;
  97. switch( data->message.type ) {
  98. case __SK_Exit_:
  99. if ( data->settling == false ) goto settle;
  100. done = true;
  101. return;
  102. case __SK_NoteOn_:
  103. if ( value2 > 0.0 ) { // velocity > 0
  104. unsigned int iNote = data->message.intValues[0];
  105. if ( channel == 0 ) { // do basic voice management
  106. unsigned int s;
  107. if ( data->keysDown >= (int) nStrings ) break; // ignore extra note on's
  108. // Find first unused string
  109. for ( s=0; s<nStrings; s++ )
  110. if ( !data->voices[s].inUse ) break;
  111. if ( s == nStrings ) break;
  112. data->voices[s].inUse = true;
  113. data->voices[s].iNote = iNote;
  114. data->guitar->noteOn( Midi2Pitch[iNote], value2 * ONE_OVER_128, s );
  115. data->keysDown++;
  116. // If first key down, turn on feedback gain
  117. if ( data->keysDown == 1 )
  118. data->feedbackGain = data->oldFeedbackGain;
  119. }
  120. else if ( channel <= nStrings )
  121. data->guitar->noteOn( Midi2Pitch[iNote], value2 * ONE_OVER_128, channel-1 );
  122. break;
  123. }
  124. // else a note off, so continue to next case
  125. case __SK_NoteOff_:
  126. if ( channel == 0 ) { // do basic voice management
  127. if ( !data->keysDown ) break;
  128. // Search for the released note
  129. unsigned int s, iNote;
  130. iNote = data->message.intValues[0];
  131. for ( s=0; s<nStrings; s++ )
  132. if ( data->voices[s].inUse && iNote == data->voices[s].iNote )
  133. break;
  134. if ( s == nStrings ) break;
  135. data->voices[s].inUse = false;
  136. data->guitar->noteOff( value2 * ONE_OVER_128, s );
  137. data->keysDown--;
  138. if ( data->keysDown == 0 ) { // turn off feedback gain and clear delay
  139. data->feedbackDelay.clear();
  140. data->feedbackGain = 0.0;
  141. }
  142. }
  143. else if ( channel <= nStrings )
  144. data->guitar->noteOff( value2 * ONE_OVER_128, channel-1 );
  145. break;
  146. case __SK_ControlChange_:
  147. if ( value1 == 44.0 )
  148. data->reverb.setEffectMix( value2 * ONE_OVER_128 );
  149. else if ( value1 == 7.0 )
  150. data->volume = value2 * ONE_OVER_128;
  151. else if ( value1 == 27 ) // feedback delay
  152. data->feedbackDelay.setDelay( (value2 * Stk::sampleRate() / 127) + 1 );
  153. else if ( value1 == 28 ) { // feedback gain
  154. //data->oldFeedbackGain = value2 * 0.01 / 127.0;
  155. data->oldFeedbackGain = value2 * 0.02 / 127.0;
  156. data->feedbackGain = data->oldFeedbackGain;
  157. }
  158. else if ( value1 == 71 ) // pre-distortion gain
  159. data->distortionGain = 2.0 * value2 * ONE_OVER_128;
  160. else if ( value1 == 72 ) // distortion mix
  161. data->distortionMix = value2 * ONE_OVER_128;
  162. else
  163. data->guitar->controlChange( (int) value1, value2 );
  164. break;
  165. case __SK_AfterTouch_:
  166. data->guitar->controlChange( 128, value1 );
  167. break;
  168. case __SK_PitchBend_:
  169. // Implement me!
  170. break;
  171. case __SK_Volume_:
  172. data->volume = value1 * ONE_OVER_128;
  173. break;
  174. } // end of switch
  175. data->haveMessage = false;
  176. return;
  177. settle:
  178. // Exit and program change messages are preceeded with a short settling period.
  179. for ( unsigned int s=0; s<nStrings; s++ )
  180. if ( data->voices[s].inUse ) data->guitar->noteOff( 0.6, s );
  181. data->counter = (int) (0.3 * data->t60 * Stk::sampleRate());
  182. data->settling = true;
  183. }
  184. // The tick() function handles sample computation and scheduling of
  185. // control updates. If doing realtime audio output, it will be called
  186. // automatically when the system needs a new buffer of audio samples.
  187. int tick( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
  188. double streamTime, RtAudioStreamStatus status, void *dataPointer )
  189. {
  190. TickData *data = (TickData *) dataPointer;
  191. register StkFloat temp, sample, *samples = (StkFloat *) outputBuffer;
  192. int counter, nTicks = (int) nBufferFrames;
  193. while ( nTicks > 0 && !done ) {
  194. if ( !data->haveMessage ) {
  195. data->messager.popMessage( data->message );
  196. if ( data->message.type > 0 ) {
  197. data->counter = (long) (data->message.time * Stk::sampleRate());
  198. data->haveMessage = true;
  199. }
  200. else
  201. data->counter = DELTA_CONTROL_TICKS;
  202. }
  203. counter = min( nTicks, data->counter );
  204. data->counter -= counter;
  205. for ( int i=0; i<counter; i++ ) {
  206. // Put the previous distorted sample thru feedback
  207. sample = data->feedbackDelay.tick( data->feedbackSample * data->feedbackGain );
  208. sample = data->guitar->tick( sample );
  209. // Apply distortion (x - x^3/3) and mix
  210. temp = data->distortionGain * sample;
  211. if ( temp > 0.6666667 ) temp = 0.6666667;
  212. else if ( temp < -0.6666667 ) temp = -0.6666667;
  213. else temp = data->distortion.tick( temp );
  214. sample = (data->distortionMix * temp) + ((1 - data->distortionMix) * sample );
  215. data->feedbackSample = sample;
  216. // Tick instrument and apply reverb
  217. sample = data->volume * data->reverb.tick( sample );
  218. for ( unsigned int j=0; j<data->nWvOuts; j++ ) data->wvout[j]->tick( sample );
  219. if ( data->realtime )
  220. for ( int k=0; k<data->channels; k++ ) *samples++ = sample;
  221. nTicks--;
  222. }
  223. if ( nTicks == 0 ) break;
  224. // Process control messages.
  225. if ( data->haveMessage ) processMessage( data );
  226. }
  227. return 0;
  228. }
  229. int main( int argc, char *argv[] )
  230. {
  231. TickData data;
  232. int i;
  233. #if defined(__STK_REALTIME__)
  234. RtAudio dac;
  235. #endif
  236. // If you want to change the default sample rate (set in Stk.h), do
  237. // it before instantiating any objects! If the sample rate is
  238. // specified in the command line, it will override this setting.
  239. Stk::setSampleRate( 44100.0 );
  240. // By default, warning messages are not printed. If we want to see
  241. // them, we need to specify that here.
  242. Stk::showWarnings( true );
  243. // Check the command-line arguments for errors and to determine
  244. // the number of WvOut objects to be instantiated (in utilities.cpp).
  245. data.nWvOuts = checkArgs( argc, argv );
  246. data.wvout = (WvOut **) calloc( data.nWvOuts, sizeof(WvOut *) );
  247. // Parse the command-line flags, instantiate WvOut objects, and
  248. // instantiate the input message controller (in utilities.cpp).
  249. try {
  250. data.realtime = parseArgs( argc, argv, data.wvout, data.messager );
  251. }
  252. catch (StkError &) {
  253. goto cleanup;
  254. }
  255. // If realtime output, allocate the dac here.
  256. #if defined(__STK_REALTIME__)
  257. if ( data.realtime ) {
  258. RtAudioFormat format = ( sizeof(StkFloat) == 8 ) ? RTAUDIO_FLOAT64 : RTAUDIO_FLOAT32;
  259. RtAudio::StreamParameters parameters;
  260. parameters.deviceId = dac.getDefaultOutputDevice();
  261. parameters.nChannels = data.channels;
  262. unsigned int bufferFrames = RT_BUFFER_SIZE;
  263. try {
  264. dac.openStream( &parameters, NULL, format, (unsigned int)Stk::sampleRate(), &bufferFrames, &tick, (void *)&data );
  265. }
  266. catch ( RtAudioError& error ) {
  267. error.printMessage();
  268. goto cleanup;
  269. }
  270. }
  271. #endif
  272. // Set the reverb parameters.
  273. data.reverb.setT60( data.t60 );
  274. data.reverb.setEffectMix( 0.2 );
  275. // Allocate guitar
  276. data.guitar = new Guitar( nStrings );
  277. // Configure distortion and feedback.
  278. data.distortion.setThreshold( 2.0 / 3.0 );
  279. data.distortion.setA1( 1.0 );
  280. data.distortion.setA2( 0.0 );
  281. data.distortion.setA3( -1.0 / 3.0 );
  282. data.distortionMix = 0.9;
  283. data.distortionGain = 1.0;
  284. data.feedbackDelay.setMaximumDelay( (unsigned long int)( 1.1 * Stk::sampleRate() ) );
  285. data.feedbackDelay.setDelay( 20000 );
  286. data.feedbackGain = 0.001;
  287. data.oldFeedbackGain = 0.001;
  288. // Install an interrupt handler function.
  289. (void) signal(SIGINT, finish);
  290. // If realtime output, set our callback function and start the dac.
  291. #if defined(__STK_REALTIME__)
  292. if ( data.realtime ) {
  293. try {
  294. dac.startStream();
  295. }
  296. catch ( RtAudioError &error ) {
  297. error.printMessage();
  298. goto cleanup;
  299. }
  300. }
  301. #endif
  302. // Setup finished.
  303. while ( !done ) {
  304. #if defined(__STK_REALTIME__)
  305. if ( data.realtime )
  306. // Periodically check "done" status.
  307. Stk::sleep( 200 );
  308. else
  309. #endif
  310. // Call the "tick" function to process data.
  311. tick( NULL, NULL, 256, 0, 0, (void *)&data );
  312. }
  313. // Shut down the output stream.
  314. #if defined(__STK_REALTIME__)
  315. if ( data.realtime ) {
  316. try {
  317. dac.closeStream();
  318. }
  319. catch ( RtAudioError& error ) {
  320. error.printMessage();
  321. }
  322. }
  323. #endif
  324. cleanup:
  325. for ( i=0; i<(int)data.nWvOuts; i++ ) delete data.wvout[i];
  326. free( data.wvout );
  327. delete data.guitar;
  328. std::cout << "\nStk eguitar finished ... goodbye.\n\n";
  329. return 0;
  330. }