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