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