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.

404 lines
11KB

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