Audio plugin host https://kx.studio/carla
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.

AlsaEngine.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. AlsaEngine.cpp - ALSA Driver
  4. Copyright (C) 2009 Alan Calvert
  5. Copyright (C) 2014 Mark McCurry
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or (at your option) any later version.
  10. */
  11. #include <stdlib.h>
  12. #include <iostream>
  13. #include <cmath>
  14. using namespace std;
  15. #include "../Misc/Util.h"
  16. #include "../Misc/Config.h"
  17. #include "InMgr.h"
  18. #include "AlsaEngine.h"
  19. #include "Compressor.h"
  20. #include "Nio.h"
  21. AlsaEngine::AlsaEngine(const SYNTH_T &synth)
  22. :AudioOut(synth)
  23. {
  24. audio.buffer = new short[synth.buffersize * 2];
  25. name = "ALSA";
  26. audio.handle = NULL;
  27. audio.peaks[0] = 0;
  28. midi.handle = NULL;
  29. midi.alsaId = -1;
  30. midi.pThread = 0;
  31. }
  32. AlsaEngine::~AlsaEngine()
  33. {
  34. Stop();
  35. delete[] audio.buffer;
  36. }
  37. void *AlsaEngine::_AudioThread(void *arg)
  38. {
  39. return (static_cast<AlsaEngine *>(arg))->AudioThread();
  40. }
  41. void *AlsaEngine::AudioThread()
  42. {
  43. set_realtime();
  44. return processAudio();
  45. }
  46. bool AlsaEngine::Start()
  47. {
  48. return openAudio() && openMidi();
  49. }
  50. void AlsaEngine::Stop()
  51. {
  52. if(getMidiEn())
  53. setMidiEn(false);
  54. if(getAudioEn())
  55. setAudioEn(false);
  56. snd_config_update_free_global();
  57. }
  58. void AlsaEngine::setMidiEn(bool nval)
  59. {
  60. if(nval)
  61. openMidi();
  62. else
  63. stopMidi();
  64. }
  65. bool AlsaEngine::getMidiEn() const
  66. {
  67. return midi.handle;
  68. }
  69. void AlsaEngine::setAudioEn(bool nval)
  70. {
  71. if(nval)
  72. openAudio();
  73. else
  74. stopAudio();
  75. }
  76. bool AlsaEngine::getAudioEn() const
  77. {
  78. return audio.handle;
  79. }
  80. void *AlsaEngine::_MidiThread(void *arg)
  81. {
  82. return static_cast<AlsaEngine *>(arg)->MidiThread();
  83. }
  84. void *AlsaEngine::MidiThread(void)
  85. {
  86. snd_seq_event_t *event;
  87. MidiEvent ev;
  88. set_realtime();
  89. while(1) {
  90. if(midi.exiting)
  91. break;
  92. if(snd_seq_event_input_pending(midi.handle, 1) <= 0) {
  93. usleep(10);
  94. continue;
  95. }
  96. if(snd_seq_event_input(midi.handle, &event) < 0)
  97. break;
  98. //ensure ev is empty
  99. ev.channel = 0;
  100. ev.num = 0;
  101. ev.value = 0;
  102. ev.type = 0;
  103. if(!event)
  104. continue;
  105. switch(event->type) {
  106. case SND_SEQ_EVENT_NOTEON:
  107. if(event->data.note.note) {
  108. ev.type = M_NOTE;
  109. ev.channel = event->data.note.channel;
  110. ev.num = event->data.note.note;
  111. ev.value = event->data.note.velocity;
  112. InMgr::getInstance().putEvent(ev);
  113. }
  114. break;
  115. case SND_SEQ_EVENT_NOTEOFF:
  116. ev.type = M_NOTE;
  117. ev.channel = event->data.note.channel;
  118. ev.num = event->data.note.note;
  119. ev.value = 0;
  120. InMgr::getInstance().putEvent(ev);
  121. break;
  122. case SND_SEQ_EVENT_KEYPRESS:
  123. ev.type = M_PRESSURE;
  124. ev.channel = event->data.note.channel;
  125. ev.num = event->data.note.note;
  126. ev.value = event->data.note.velocity;
  127. InMgr::getInstance().putEvent(ev);
  128. break;
  129. case SND_SEQ_EVENT_PITCHBEND:
  130. ev.type = M_CONTROLLER;
  131. ev.channel = event->data.control.channel;
  132. ev.num = C_pitchwheel;
  133. ev.value = event->data.control.value;
  134. InMgr::getInstance().putEvent(ev);
  135. break;
  136. case SND_SEQ_EVENT_CONTROLLER:
  137. ev.type = M_CONTROLLER;
  138. ev.channel = event->data.control.channel;
  139. ev.num = event->data.control.param;
  140. ev.value = event->data.control.value;
  141. InMgr::getInstance().putEvent(ev);
  142. break;
  143. case SND_SEQ_EVENT_PGMCHANGE:
  144. ev.type = M_PGMCHANGE;
  145. ev.channel = event->data.control.channel;
  146. ev.num = event->data.control.value;
  147. InMgr::getInstance().putEvent(ev);
  148. break;
  149. case SND_SEQ_EVENT_RESET: // reset to power-on state
  150. ev.type = M_CONTROLLER;
  151. ev.channel = event->data.control.channel;
  152. ev.num = C_resetallcontrollers;
  153. ev.value = 0;
  154. InMgr::getInstance().putEvent(ev);
  155. break;
  156. case SND_SEQ_EVENT_PORT_SUBSCRIBED: // ports connected
  157. if(true)
  158. cout << "Info, alsa midi port connected" << endl;
  159. break;
  160. case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: // ports disconnected
  161. if(true)
  162. cout << "Info, alsa midi port disconnected" << endl;
  163. break;
  164. case SND_SEQ_EVENT_SYSEX: // system exclusive
  165. case SND_SEQ_EVENT_SENSING: // midi device still there
  166. break;
  167. default:
  168. if(true)
  169. cout << "Info, other non-handled midi event, type: "
  170. << (int)event->type << endl;
  171. break;
  172. }
  173. snd_seq_free_event(event);
  174. }
  175. return NULL;
  176. }
  177. bool AlsaEngine::openMidi()
  178. {
  179. if(getMidiEn())
  180. return true;
  181. int alsaport;
  182. midi.handle = NULL;
  183. if(snd_seq_open(&midi.handle, "default", SND_SEQ_OPEN_INPUT, 0) != 0)
  184. return false;
  185. string clientname = "ZynAddSubFX";
  186. string postfix = Nio::getPostfix();
  187. if (!postfix.empty())
  188. clientname += "_" + postfix;
  189. if(Nio::pidInClientName)
  190. clientname += "_" + os_pid_as_padded_string();
  191. snd_seq_set_client_name(midi.handle, clientname.c_str());
  192. alsaport = snd_seq_create_simple_port(
  193. midi.handle,
  194. "ZynAddSubFX",
  195. SND_SEQ_PORT_CAP_WRITE
  196. | SND_SEQ_PORT_CAP_SUBS_WRITE,
  197. SND_SEQ_PORT_TYPE_SYNTH);
  198. if(alsaport < 0)
  199. return false;
  200. midi.exiting = false;
  201. pthread_attr_t attr;
  202. pthread_attr_init(&attr);
  203. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  204. pthread_create(&midi.pThread, &attr, _MidiThread, this);
  205. return true;
  206. }
  207. void AlsaEngine::stopMidi()
  208. {
  209. if(!getMidiEn())
  210. return;
  211. snd_seq_t *handle = midi.handle;
  212. if((NULL != midi.handle) && midi.pThread) {
  213. midi.exiting = true;
  214. pthread_join(midi.pThread, 0);
  215. }
  216. midi.handle = NULL;
  217. if(handle)
  218. snd_seq_close(handle);
  219. }
  220. short *AlsaEngine::interleave(const Stereo<float *> &smps)
  221. {
  222. /**\todo TODO fix repeated allocation*/
  223. short *shortInterleaved = audio.buffer;
  224. memset(shortInterleaved, 0, bufferSize * 2 * sizeof(short));
  225. int idx = 0; //possible off by one error here
  226. double scaled;
  227. for(int frame = 0; frame < bufferSize; ++frame) { // with a nod to libsamplerate ...
  228. float l = smps.l[frame];
  229. float r = smps.r[frame];
  230. stereoCompressor(synth.samplerate, audio.peaks[0], l, r);
  231. scaled = l * (8.0f * 0x10000000);
  232. shortInterleaved[idx++] = (short int)(lrint(scaled) >> 16);
  233. scaled = r * (8.0f * 0x10000000);
  234. shortInterleaved[idx++] = (short int)(lrint(scaled) >> 16);
  235. }
  236. return shortInterleaved;
  237. }
  238. bool AlsaEngine::openAudio()
  239. {
  240. if(getAudioEn())
  241. return true;
  242. int rc = 0;
  243. /* Open PCM device for playback. */
  244. audio.handle = NULL;
  245. const char *device = getenv("ALSA_DEVICE");
  246. if(device == 0)
  247. device = "hw:0";
  248. rc = snd_pcm_open(&audio.handle, device,
  249. SND_PCM_STREAM_PLAYBACK, 0);
  250. if(rc < 0) {
  251. fprintf(stderr,
  252. "unable to open pcm device: %s\n",
  253. snd_strerror(rc));
  254. return false;
  255. }
  256. /* Allocate a hardware parameters object. */
  257. snd_pcm_hw_params_alloca(&audio.params);
  258. /* Fill it in with default values. */
  259. snd_pcm_hw_params_any(audio.handle, audio.params);
  260. /* Set the desired hardware parameters. */
  261. /* Interleaved mode */
  262. snd_pcm_hw_params_set_access(audio.handle, audio.params,
  263. SND_PCM_ACCESS_RW_INTERLEAVED);
  264. /* Signed 16-bit little-endian format */
  265. snd_pcm_hw_params_set_format(audio.handle, audio.params,
  266. SND_PCM_FORMAT_S16_LE);
  267. /* Two channels (stereo) */
  268. snd_pcm_hw_params_set_channels(audio.handle, audio.params, 2);
  269. audio.sampleRate = synth.samplerate;
  270. snd_pcm_hw_params_set_rate_near(audio.handle, audio.params,
  271. &audio.sampleRate, NULL);
  272. audio.frames = 512;
  273. snd_pcm_hw_params_set_period_size_near(audio.handle,
  274. audio.params, &audio.frames, NULL);
  275. audio.periods = 4;
  276. snd_pcm_hw_params_set_periods_near(audio.handle,
  277. audio.params, &audio.periods, NULL);
  278. /* Set buffer size (in frames). The resulting latency is given by */
  279. /* latency = periodsize * periods / (rate * bytes_per_frame) */
  280. snd_pcm_uframes_t alsa_buffersize = synth.buffersize;
  281. rc = snd_pcm_hw_params_set_buffer_size_near(audio.handle,
  282. audio.params,
  283. &alsa_buffersize);
  284. /* At this place, ALSA's and zyn's buffer sizes may differ. */
  285. /* This should not be a problem. */
  286. if((int)alsa_buffersize != synth.buffersize)
  287. cerr << "ALSA buffer size: " << alsa_buffersize << endl;
  288. /* Write the parameters to the driver */
  289. rc = snd_pcm_hw_params(audio.handle, audio.params);
  290. if(rc < 0) {
  291. fprintf(stderr,
  292. "unable to set hw parameters: %s\n",
  293. snd_strerror(rc));
  294. return false;
  295. }
  296. //snd_pcm_hw_params_get_period_size(audio.params, &audio.frames, NULL);
  297. //snd_pcm_hw_params_get_period_time(audio.params, &val, NULL);
  298. pthread_attr_t attr;
  299. pthread_attr_init(&attr);
  300. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  301. pthread_create(&audio.pThread, &attr, _AudioThread, this);
  302. return true;
  303. }
  304. void AlsaEngine::stopAudio()
  305. {
  306. if(!getAudioEn())
  307. return;
  308. snd_pcm_t *handle = audio.handle;
  309. audio.handle = NULL;
  310. pthread_join(audio.pThread, NULL);
  311. snd_pcm_drain(handle);
  312. if(snd_pcm_close(handle))
  313. cout << "Error: in snd_pcm_close " << __LINE__ << ' ' << __FILE__
  314. << endl;
  315. }
  316. void *AlsaEngine::processAudio()
  317. {
  318. while(audio.handle) {
  319. audio.buffer = interleave(getNext());
  320. snd_pcm_t *handle = audio.handle;
  321. int rc = snd_pcm_writei(handle, audio.buffer, synth.buffersize);
  322. if(rc == -EPIPE) {
  323. /* EPIPE means underrun */
  324. cerr << "underrun occurred" << endl;
  325. snd_pcm_prepare(handle);
  326. }
  327. else
  328. if(rc < 0) {
  329. cerr << "AlsaEngine: Recovering connection..." << endl;
  330. rc = snd_pcm_recover(handle, rc, 0);
  331. if(rc < 0)
  332. throw "Could not recover ALSA connection";
  333. }
  334. }
  335. return NULL;
  336. }