jack2 codebase
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.

592 lines
21KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include "JackDriverLoader.h"
  16. #include "driver_interface.h"
  17. #include "JackPortAudioDriver.h"
  18. #include "JackEngineControl.h"
  19. #include "JackGraphManager.h"
  20. #include "JackError.h"
  21. #include "JackTime.h"
  22. #include "JackTools.h"
  23. #include "JackCompilerDeps.h"
  24. #include <iostream>
  25. #include <assert.h>
  26. #ifdef __linux__
  27. #include "JackServerGlobals.h"
  28. #endif
  29. using namespace std;
  30. namespace Jack
  31. {
  32. #ifdef __linux__
  33. static volatile bool device_reservation_loop_running = false;
  34. static void* on_device_reservation_loop(void*)
  35. {
  36. while (device_reservation_loop_running && JackServerGlobals::on_device_reservation_loop != NULL) {
  37. JackServerGlobals::on_device_reservation_loop();
  38. usleep(50*1000);
  39. }
  40. return NULL;
  41. }
  42. static bool name_to_num(const char* paDeviceName, char* entry)
  43. {
  44. if (const char* sep = strstr(paDeviceName, " (hw:"))
  45. {
  46. sep += 5;
  47. while (*sep != '\0' && *sep != ',' && *sep != ')')
  48. *entry++ = *sep++;
  49. *entry = '\0';
  50. return true;
  51. }
  52. return false;
  53. }
  54. #endif
  55. int JackPortAudioDriver::Render(const void* inputBuffer, void* outputBuffer,
  56. unsigned long framesPerBuffer,
  57. const PaStreamCallbackTimeInfo* timeInfo,
  58. PaStreamCallbackFlags statusFlags,
  59. void* userData)
  60. {
  61. return static_cast<JackPortAudioDriver*>(userData)->Render(inputBuffer, outputBuffer, statusFlags);
  62. }
  63. int JackPortAudioDriver::Render(const void* inputBuffer, void* outputBuffer, PaStreamCallbackFlags statusFlags)
  64. {
  65. fInputBuffer = (jack_default_audio_sample_t**)inputBuffer;
  66. fOutputBuffer = (jack_default_audio_sample_t**)outputBuffer;
  67. if (statusFlags) {
  68. if (statusFlags & paOutputUnderflow)
  69. jack_error("JackPortAudioDriver::Render paOutputUnderflow");
  70. if (statusFlags & paInputUnderflow)
  71. jack_error("JackPortAudioDriver::Render paInputUnderflow");
  72. if (statusFlags & paOutputOverflow)
  73. jack_error("JackPortAudioDriver::Render paOutputOverflow");
  74. if (statusFlags & paInputOverflow)
  75. jack_error("JackPortAudioDriver::Render paInputOverflow");
  76. if (statusFlags & paPrimingOutput)
  77. jack_error("JackPortAudioDriver::Render paOutputUnderflow");
  78. if (statusFlags != paPrimingOutput) {
  79. jack_time_t cur_time = GetMicroSeconds();
  80. NotifyXRun(cur_time, float(cur_time - fBeginDateUst)); // Better this value than nothing...
  81. }
  82. }
  83. // Setup threaded based log function
  84. set_threaded_log_function();
  85. CycleTakeBeginTime();
  86. return (Process() == 0) ? paContinue : paAbort;
  87. }
  88. int JackPortAudioDriver::Read()
  89. {
  90. for (int i = 0; i < fCaptureChannels; i++) {
  91. memcpy(GetInputBuffer(i), fInputBuffer[i], sizeof(jack_default_audio_sample_t) * fEngineControl->fBufferSize);
  92. }
  93. return 0;
  94. }
  95. int JackPortAudioDriver::Write()
  96. {
  97. for (int i = 0; i < fPlaybackChannels; i++) {
  98. memcpy(fOutputBuffer[i], GetOutputBuffer(i), sizeof(jack_default_audio_sample_t) * fEngineControl->fBufferSize);
  99. }
  100. return 0;
  101. }
  102. PaError JackPortAudioDriver::OpenStream(jack_nframes_t buffer_size)
  103. {
  104. PaStreamParameters inputParameters;
  105. PaStreamParameters outputParameters;
  106. jack_log("JackPortAudioDriver::OpenStream buffer_size = %d", buffer_size);
  107. // Update parameters
  108. inputParameters.device = fInputDevice;
  109. inputParameters.channelCount = fCaptureChannels;
  110. inputParameters.sampleFormat = paFloat32 | paNonInterleaved; // 32 bit floating point input
  111. inputParameters.suggestedLatency = (fInputDevice != paNoDevice) // TODO: check how to setup this on ASIO
  112. ? ((fPaDevices->GetHostFromDevice(fInputDevice) == "ASIO") ? 0 : Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency)
  113. : 0;
  114. inputParameters.hostApiSpecificStreamInfo = NULL;
  115. outputParameters.device = fOutputDevice;
  116. outputParameters.channelCount = fPlaybackChannels;
  117. outputParameters.sampleFormat = paFloat32 | paNonInterleaved; // 32 bit floating point output
  118. outputParameters.suggestedLatency = (fOutputDevice != paNoDevice) // TODO: check how to setup this on ASIO
  119. ? ((fPaDevices->GetHostFromDevice(fOutputDevice) == "ASIO") ? 0 : Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency)
  120. : 0;
  121. outputParameters.hostApiSpecificStreamInfo = NULL;
  122. return Pa_OpenStream(&fStream,
  123. (fInputDevice == paNoDevice) ? 0 : &inputParameters,
  124. (fOutputDevice == paNoDevice) ? 0 : &outputParameters,
  125. fEngineControl->fSampleRate,
  126. buffer_size,
  127. paNoFlag, // Clipping is on...
  128. Render,
  129. this);
  130. }
  131. void JackPortAudioDriver::UpdateLatencies()
  132. {
  133. jack_latency_range_t input_range;
  134. jack_latency_range_t output_range;
  135. jack_latency_range_t monitor_range;
  136. const PaStreamInfo* info = Pa_GetStreamInfo(fStream);
  137. assert(info);
  138. for (int i = 0; i < fCaptureChannels; i++) {
  139. input_range.max = input_range.min = fEngineControl->fBufferSize + (info->inputLatency * fEngineControl->fSampleRate) + fCaptureLatency;
  140. fGraphManager->GetPort(fCapturePortList[i])->SetLatencyRange(JackCaptureLatency, &input_range);
  141. }
  142. for (int i = 0; i < fPlaybackChannels; i++) {
  143. output_range.max = output_range.min = (info->outputLatency * fEngineControl->fSampleRate) + fPlaybackLatency;
  144. if (fEngineControl->fSyncMode) {
  145. output_range.max = output_range.min += fEngineControl->fBufferSize;
  146. } else {
  147. output_range.max = output_range.min += fEngineControl->fBufferSize * 2;
  148. }
  149. fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &output_range);
  150. if (fWithMonitorPorts) {
  151. monitor_range.min = monitor_range.max = fEngineControl->fBufferSize;
  152. fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &monitor_range);
  153. }
  154. }
  155. }
  156. int JackPortAudioDriver::Open(jack_nframes_t buffer_size,
  157. jack_nframes_t samplerate,
  158. bool capturing,
  159. bool playing,
  160. int inchannels,
  161. int outchannels,
  162. bool monitor,
  163. const char* capture_driver_uid,
  164. const char* playback_driver_uid,
  165. jack_nframes_t capture_latency,
  166. jack_nframes_t playback_latency)
  167. {
  168. int in_max = 0;
  169. int out_max = 0;
  170. PaError err = paNoError;
  171. if (!fPaDevices) {
  172. fPaDevices = new PortAudioDevices();
  173. }
  174. fCaptureLatency = capture_latency;
  175. fPlaybackLatency = playback_latency;
  176. jack_log("JackPortAudioDriver::Open nframes = %ld in = %ld out = %ld capture name = %s playback name = %s samplerate = %ld",
  177. buffer_size, inchannels, outchannels, capture_driver_uid, playback_driver_uid, samplerate);
  178. // Get devices
  179. if (capturing) {
  180. if (fPaDevices->GetInputDeviceFromName(capture_driver_uid, fInputDevice, in_max) < 0) {
  181. goto error;
  182. }
  183. }
  184. if (playing) {
  185. if (fPaDevices->GetOutputDeviceFromName(playback_driver_uid, fOutputDevice, out_max) < 0) {
  186. goto error;
  187. }
  188. }
  189. // If ASIO, request for preferred size (assuming fInputDevice and fOutputDevice are the same)
  190. if (buffer_size == 0) {
  191. buffer_size = fPaDevices->GetPreferredBufferSize(fInputDevice);
  192. jack_log("JackPortAudioDriver::Open preferred buffer_size = %d", buffer_size);
  193. }
  194. // Generic JackAudioDriver Open
  195. char capture_driver_name[JACK_CLIENT_NAME_SIZE];
  196. char playback_driver_name[JACK_CLIENT_NAME_SIZE];
  197. snprintf(capture_driver_name, sizeof(capture_driver_name), "%s", capture_driver_uid);
  198. snprintf(playback_driver_name, sizeof(playback_driver_name), "%s", playback_driver_uid);
  199. if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor,
  200. capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0) {
  201. return -1;
  202. }
  203. jack_log("JackPortAudioDriver::Open fInputDevice = %d, fOutputDevice %d", fInputDevice, fOutputDevice);
  204. // Default channels number required
  205. if (inchannels == 0) {
  206. jack_log("JackPortAudioDriver::Open setup max in channels = %ld", in_max);
  207. inchannels = in_max;
  208. }
  209. if (outchannels == 0) {
  210. jack_log("JackPortAudioDriver::Open setup max out channels = %ld", out_max);
  211. outchannels = out_max;
  212. }
  213. // Too many channels required, take max available
  214. if (inchannels > in_max) {
  215. jack_error("This device has only %d available input channels.", in_max);
  216. inchannels = in_max;
  217. }
  218. if (outchannels > out_max) {
  219. jack_error("This device has only %d available output channels.", out_max);
  220. outchannels = out_max;
  221. }
  222. // Core driver may have changed the in/out values
  223. fCaptureChannels = inchannels;
  224. fPlaybackChannels = outchannels;
  225. #ifdef __linux__
  226. if (JackServerGlobals::on_device_acquire != NULL) {
  227. char audio_name[32];
  228. snprintf(audio_name, sizeof(audio_name), "Audio");
  229. if (name_to_num(capture_driver_name, audio_name+5)) {
  230. if (!JackServerGlobals::on_device_acquire(audio_name)) {
  231. jack_error("Audio device %s cannot be acquired...", capture_driver_name);
  232. return -1;
  233. }
  234. }
  235. if (strcmp(capture_driver_name, playback_driver_name) && name_to_num(playback_driver_name, audio_name+5)) {
  236. if (!JackServerGlobals::on_device_acquire(audio_name)) {
  237. jack_error("Audio device %s cannot be acquired...", playback_driver_name);
  238. return -1;
  239. }
  240. }
  241. }
  242. #endif
  243. err = OpenStream(buffer_size);
  244. if (err != paNoError) {
  245. jack_error("Pa_OpenStream error = %s", Pa_GetErrorText(err));
  246. goto error;
  247. }
  248. #ifdef __APPLE__
  249. fEngineControl->fPeriod = fEngineControl->fPeriodUsecs * 1000;
  250. fEngineControl->fComputation = JackTools::ComputationMicroSec(fEngineControl->fBufferSize) * 1000;
  251. fEngineControl->fConstraint = fEngineControl->fPeriodUsecs * 1000;
  252. #endif
  253. #ifdef __linux__
  254. if (JackServerGlobals::on_device_reservation_loop != NULL) {
  255. device_reservation_loop_running = true;
  256. if (JackPosixThread::StartImp(&fReservationLoopThread, 0, 0, on_device_reservation_loop, NULL) != 0) {
  257. device_reservation_loop_running = false;
  258. }
  259. }
  260. #endif
  261. return 0;
  262. error:
  263. JackAudioDriver::Close();
  264. jack_error("Can't open default PortAudio device");
  265. return -1;
  266. }
  267. int JackPortAudioDriver::Close()
  268. {
  269. // Generic audio driver close
  270. jack_log("JackPortAudioDriver::Close");
  271. JackAudioDriver::Close();
  272. PaError err = Pa_CloseStream(fStream);
  273. if (err != paNoError) {
  274. jack_error("Pa_CloseStream error = %s", Pa_GetErrorText(err));
  275. }
  276. #ifdef __linux__
  277. if (device_reservation_loop_running) {
  278. device_reservation_loop_running = false;
  279. JackPosixThread::StopImp(fReservationLoopThread);
  280. }
  281. if (JackServerGlobals::on_device_release != NULL)
  282. {
  283. char audio_name[32];
  284. snprintf(audio_name, sizeof(audio_name), "Audio");
  285. if (name_to_num(fCaptureDriverName, audio_name+5)) {
  286. JackServerGlobals::on_device_release(audio_name);
  287. }
  288. if (strcmp(fCaptureDriverName, fPlaybackDriverName) && name_to_num(fPlaybackDriverName, audio_name+5)) {
  289. JackServerGlobals::on_device_release(audio_name);
  290. }
  291. }
  292. #endif
  293. delete fPaDevices;
  294. fPaDevices = NULL;
  295. return (err != paNoError) ? -1 : 0;
  296. }
  297. int JackPortAudioDriver::Attach()
  298. {
  299. if (JackAudioDriver::Attach() == 0) {
  300. #if defined(HAVE_ASIO)
  301. const char* alias;
  302. if (fInputDevice != paNoDevice && fPaDevices->GetHostFromDevice(fInputDevice) == "ASIO") {
  303. for (int i = 0; i < fCaptureChannels; i++) {
  304. if (PaAsio_GetInputChannelName(fInputDevice, i, &alias) == paNoError) {
  305. JackPort* port = fGraphManager->GetPort(fCapturePortList[i]);
  306. port->SetAlias(alias);
  307. }
  308. }
  309. }
  310. if (fOutputDevice != paNoDevice && fPaDevices->GetHostFromDevice(fOutputDevice) == "ASIO") {
  311. for (int i = 0; i < fPlaybackChannels; i++) {
  312. if (PaAsio_GetOutputChannelName(fOutputDevice, i, &alias) == paNoError) {
  313. JackPort* port = fGraphManager->GetPort(fPlaybackPortList[i]);
  314. port->SetAlias(alias);
  315. }
  316. }
  317. }
  318. #endif
  319. return 0;
  320. } else {
  321. return -1;
  322. }
  323. }
  324. int JackPortAudioDriver::Start()
  325. {
  326. jack_log("JackPortAudioDriver::Start");
  327. if (JackAudioDriver::Start() == 0) {
  328. PaError err;
  329. if ((err = Pa_StartStream(fStream)) == paNoError) {
  330. return 0;
  331. }
  332. jack_error("Pa_StartStream error = %s", Pa_GetErrorText(err));
  333. JackAudioDriver::Stop();
  334. }
  335. return -1;
  336. }
  337. int JackPortAudioDriver::Stop()
  338. {
  339. jack_log("JackPortAudioDriver::Stop");
  340. PaError err;
  341. if ((err = Pa_StopStream(fStream)) != paNoError) {
  342. jack_error("Pa_StopStream error = %s", Pa_GetErrorText(err));
  343. }
  344. if (JackAudioDriver::Stop() < 0) {
  345. return -1;
  346. } else {
  347. return (err == paNoError) ? 0 : -1;
  348. }
  349. }
  350. int JackPortAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  351. {
  352. PaError err;
  353. if (fStream && (err = Pa_CloseStream(fStream)) != paNoError) {
  354. jack_error("Pa_CloseStream error = %s", Pa_GetErrorText(err));
  355. goto error;
  356. }
  357. err = OpenStream(buffer_size);
  358. if (err != paNoError) {
  359. jack_error("Pa_OpenStream error = %s", Pa_GetErrorText(err));
  360. goto error;
  361. } else {
  362. JackAudioDriver::SetBufferSize(buffer_size); // Generic change, never fails
  363. return 0;
  364. }
  365. error:
  366. fStream = NULL;
  367. return -1;
  368. }
  369. } // end of namespace
  370. #ifdef __cplusplus
  371. extern "C"
  372. {
  373. #endif
  374. #include "JackCompilerDeps.h"
  375. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  376. {
  377. jack_driver_desc_t * desc;
  378. jack_driver_desc_filler_t filler;
  379. jack_driver_param_value_t value;
  380. desc = jack_driver_descriptor_construct("portaudio", JackDriverMaster, "PortAudio API based audio backend", &filler);
  381. value.ui = 0;
  382. jack_driver_descriptor_add_parameter(desc, &filler, "channels", 'c', JackDriverParamUInt, &value, NULL, "Maximum number of channels", NULL);
  383. jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamUInt, &value, NULL, "Maximum number of input channels", NULL);
  384. jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamUInt, &value, NULL, "Maximum number of output channels", NULL);
  385. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Provide capture ports. Optionally set PortAudio device name", NULL);
  386. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Provide playback ports. Optionally set PortAudio device name", NULL);
  387. value.i = 0;
  388. jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);
  389. value.i = true;
  390. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  391. value.ui = 44100U;
  392. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  393. value.ui = 512U;
  394. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", "Frames per period. If 0 and ASIO driver, will take preferred value");
  395. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "PortAudio device name", NULL);
  396. value.ui = 0;
  397. jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency", NULL);
  398. jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency", NULL);
  399. value.i = true;
  400. jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available PortAudio devices", NULL);
  401. return desc;
  402. }
  403. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  404. {
  405. jack_nframes_t srate = 44100;
  406. jack_nframes_t frames_per_interrupt = 512;
  407. const char* capture_pcm_name = "";
  408. const char* playback_pcm_name = "";
  409. bool capture = false;
  410. bool playback = false;
  411. int chan_in = 0;
  412. int chan_out = 0;
  413. bool monitor = false;
  414. const JSList *node;
  415. const jack_driver_param_t *param;
  416. jack_nframes_t systemic_input_latency = 0;
  417. jack_nframes_t systemic_output_latency = 0;
  418. PortAudioDevices* pa_devices = new PortAudioDevices();
  419. for (node = params; node; node = jack_slist_next(node))
  420. {
  421. param = (const jack_driver_param_t *) node->data;
  422. switch (param->character) {
  423. case 'd':
  424. capture_pcm_name = param->value.str;
  425. playback_pcm_name = param->value.str;
  426. break;
  427. case 'D':
  428. capture = true;
  429. playback = true;
  430. break;
  431. case 'c':
  432. chan_in = chan_out = (int)param->value.ui;
  433. break;
  434. case 'i':
  435. chan_in = (int)param->value.ui;
  436. break;
  437. case 'o':
  438. chan_out = (int)param->value.ui;
  439. break;
  440. case 'C':
  441. capture = true;
  442. if (strcmp(param->value.str, "none") != 0) {
  443. capture_pcm_name = param->value.str;
  444. }
  445. break;
  446. case 'P':
  447. playback = true;
  448. if (strcmp(param->value.str, "none") != 0) {
  449. playback_pcm_name = param->value.str;
  450. }
  451. break;
  452. case 'm':
  453. monitor = param->value.i;
  454. break;
  455. case 'r':
  456. srate = param->value.ui;
  457. break;
  458. case 'p':
  459. frames_per_interrupt = (unsigned int)param->value.ui;
  460. break;
  461. case 'I':
  462. systemic_input_latency = param->value.ui;
  463. break;
  464. case 'O':
  465. systemic_output_latency = param->value.ui;
  466. break;
  467. case 'l':
  468. pa_devices->DisplayDevicesNames();
  469. // Stops the server in this case
  470. return NULL;
  471. }
  472. }
  473. // duplex is the default
  474. if (!capture && !playback) {
  475. capture = true;
  476. playback = true;
  477. }
  478. Jack::JackDriverClientInterface* driver = new Jack::JackPortAudioDriver("system", "portaudio", engine, table, pa_devices);
  479. if (driver->Open(frames_per_interrupt, srate, capture, playback,
  480. chan_in, chan_out, monitor, capture_pcm_name,
  481. playback_pcm_name, systemic_input_latency,
  482. systemic_output_latency) == 0) {
  483. return driver;
  484. } else {
  485. delete driver;
  486. return NULL;
  487. }
  488. }
  489. #ifdef __cplusplus
  490. }
  491. #endif