MythTV  master
audiooutputjack.cpp
Go to the documentation of this file.
1 /*
2  * JACK AudioOutput module
3  * Written by Ed Wildgoose in 2010 with improvements from various authors
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 
20 #include <cerrno>
21 #include <cmath>
22 #include <cstdio>
23 #include <cstdlib>
24 #include <cstring>
25 #include <ctime>
26 #include <fcntl.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29 
30 #include <iostream>
31 
32 using namespace std;
33 
34 #include "mythcorecontext.h"
35 #include "audiooutputjack.h"
36 #include "mythdate.h"
37 
38 #define LOC QString("AOJack: ")
39 
40 #define JERROR(str) Error(LOC + (str))
41 
43  AudioOutputBase(settings)
44 {
45  for (auto & port : m_ports)
46  port = nullptr;
47  for (int & volume : m_chanVolumes)
48  volume = 100;
49 
50  // Set everything up
51  InitSettings(settings);
52  if (settings.m_init)
53  Reconfigure(settings);
54 }
55 
57 {
58  int rate = 0;
59  int i = 0;
60  const char **matching_ports = nullptr;
61  auto *settings = new AudioOutputSettings();
62 
64  if (!m_client)
65  {
66  JERROR(tr("Cannot start/connect to jack server "
67  "(to check supported rate/channels)"));
68  delete settings;
69  return nullptr;
70  }
71 
72  if (m_client)
73  rate = jack_get_sample_rate(m_client);
74 
75  if (!rate)
76  {
77  JERROR(tr("Unable to retrieve jack server sample rate"));
78  goto err_out;
79  }
80  else
81  settings->AddSupportedRate(rate);
82 
83  // Jack only wants float format samples (de-interleaved for preference)
84  settings->AddSupportedFormat(FORMAT_FLT);
85 
86  // Find some Jack ports to connect to
87  matching_ports = JackGetPorts();
88 
89  if (!matching_ports || !matching_ports[0])
90  {
91  JERROR(tr("No ports available to connect to"));
92  goto err_out;
93  }
94  // Count matching ports from 2nd port upwards
95  i = 1;
96  while ((i < JACK_CHANNELS_MAX) && matching_ports[i])
97  {
98  settings->AddSupportedChannels(i+1);
99  VBAUDIO(QString("Adding channels: %1").arg(i+1));
100  i++;
101  }
102 
103  // Currently this looks very similar to error code - duplicated for safety
104  free(matching_ports);
106  return settings;
107 
108 err_out:
109  // Our abstracted exit point in case of error
110  free(matching_ports);
112  delete settings;
113  return nullptr;
114 }
115 
116 
118 {
119  // Close down all audio stuff
120  KillAudio();
121 }
122 
124 {
125  const char **matching_ports = nullptr;
126  int i = 0;
127 
128  // We have a hard coded channel limit - check we haven't exceeded it
130  {
131  JERROR(tr("Requested more channels: (%1), than the maximum: %2")
132  .arg(m_channels).arg(JACK_CHANNELS_MAX));
133  return false;
134  }
135 
136  VBAUDIO( QString("Opening JACK audio device: '%1'.")
137  .arg(m_mainDevice));
138 
139  // Setup volume control
140  if (m_internalVol)
141  VolumeInit();
142 
143  // Connect to the Jack audio server
145  if (!m_client)
146  {
147  JERROR(tr("Cannot start/connect to jack server"));
148  goto err_out;
149  }
150 
151  // Find some Jack ports to connect to
152  matching_ports = JackGetPorts();
153  if (!matching_ports || !matching_ports[0])
154  {
155  JERROR(tr("No ports available to connect to"));
156  goto err_out;
157  }
158 
159  // Count matching ports
160  i = 1;
161  while (matching_ports[i])
162  i++;
163  // ensure enough ports to satisfy request
164  if (m_channels > i)
165  {
166  JERROR(tr("Not enough ports available to connect to"));
167  goto err_out;
168  }
169 
170  // Create our output ports
171  for (i = 0; i < m_channels; i++)
172  {
173  QString port_name = QString("out_%1").arg(i);
174  m_ports[i] = jack_port_register(m_client, port_name.toLatin1().constData(),
175  JACK_DEFAULT_AUDIO_TYPE,
176  JackPortIsOutput, 0);
177  if (!m_ports[i])
178  {
179  JERROR(tr("Error while registering new jack port: %1").arg(i));
180  goto err_out;
181  }
182  }
183 
184  // Note some basic soundserver parameters
185  m_sampleRate = jack_get_sample_rate(m_client);
186 
187  // Get the size of our callback buffer in bytes
188  m_fragmentSize = jack_get_buffer_size(m_client) * m_outputBytesPerFrame;
189 
190  // Allocate a new temp buffer to de-interleave our audio data
191  delete[] m_auBuf;
192  m_auBuf = new unsigned char[m_fragmentSize];
193 
194  // Set our callbacks
195  // These will actually get called after jack_activate()!
196  // ...Possibly even before this OpenDevice sub returns...
197  if (jack_set_process_callback(m_client, JackCallbackHelper, this))
198  JERROR(tr("Error. Unable to set process callback?!"));
199  if (jack_set_xrun_callback(m_client, JackXRunCallbackHelper, this))
200  JERROR(tr("Error. Unable to set xrun callback?!"));
201  if (jack_set_graph_order_callback(m_client, JackGraphOrderCallbackHelper, this))
202  JERROR(tr("Error. Unable to set graph order change callback?!"));
203 
204  // Activate! Everything comes into life after here. Beware races
205  if (jack_activate(m_client))
206  {
207  JERROR(tr("Calling jack_activate failed"));
208  goto err_out;
209  }
210 
211  // Connect our output ports
212  if (! JackConnectPorts(matching_ports))
213  goto err_out;
214 
215  // Free up some stuff
216  free(matching_ports);
217 
218  // Device opened successfully
219  return true;
220 
221 err_out:
222  // Our abstracted exit point in case of error
223  free(matching_ports);
225  return false;
226 }
227 
229 {
232  if (m_auBuf)
233  {
234  delete[] m_auBuf;
235  m_auBuf = nullptr;
236  }
237 
238  VBAUDIO("Jack: Stop Event");
240  dispatch(e);
241 }
242 
243 
245 {
246  int frames_played = jack_frames_since_cycle_start (this->m_client);
247  LOG(VB_AUDIO | VB_TIMESTAMP, LOG_INFO,
248  QString("Stats: frames_since_cycle_start:%1 fragment_size:%2")
249  .arg(frames_played).arg(m_fragmentSize));
250  return (m_fragmentSize * 2) - (frames_played * m_outputBytesPerFrame);
251 }
252 
253 /* Converts buffer to jack buffers
254  Input: aubuf: interleaved buffer of currently assumed to be 32bit floats
255  nframes: number of frames of output required
256  Output: bufs: non interleaved float values.
257 */
258 void AudioOutputJACK::DeinterleaveAudio(const float *aubuf, float **bufs, int nframes,
259  const int* channel_volumes)
260 {
261  // Convert to floats and de-interleave
262  // TODO: Implicit assumption dealing with float input only.
263  short sample = 0;
264 
265  // Create a local float version of the channel_volumes array
266  // TODO: This can probably be removed
267  // if we have float software volume control in AOB?
268  float volumes[JACK_CHANNELS_MAX];
269  for (int channel = 0; channel < m_channels; channel++)
270  {
271  if (m_internalVol)
272  {
273  // Software volume control - we use an exponential adjustment
274  // (perhaps should be log?)
275  volumes[channel] = (float) (( channel_volumes[channel] *
276  channel_volumes[channel] ) /
277  10000.0);
278  }
279  else
280  volumes[channel] = 1.0 / 1.0; // ie no effect
281  }
282 
283  if (m_channels == 2)
284  {
285  for (int frame = 0; frame < nframes; frame++)
286  {
287  bufs[0][frame] = aubuf[sample++] * volumes[0];
288  bufs[1][frame] = aubuf[sample++] * volumes[1];
289  }
290  }
291  else if (m_channels == 6)
292  {
293  for (int frame = 0; frame < nframes; frame++)
294  {
295  // Audio supplied in SMPTE l,r,ce,lfe,lr,rr
296  // We probably want it in ALSA format l,r,lr,rr,ce,lfe
297  bufs[0][frame] = aubuf[sample++] * volumes[0];
298  bufs[1][frame] = aubuf[sample++] * volumes[1];
299  bufs[4][frame] = aubuf[sample++] * volumes[4];
300  bufs[5][frame] = aubuf[sample++] * volumes[5];
301  bufs[2][frame] = aubuf[sample++] * volumes[2];
302  bufs[3][frame] = aubuf[sample++] * volumes[3];
303  }
304  }
305  else if (m_channels == 8)
306  {
307  for (int frame = 0; frame < nframes; frame++)
308  {
309  // Audio supplied in SMPTE l,r,ce,lfe,lr,rr,ml,mr ?
310  // We probably want it in ALSA format l,r,lr,rr,ce,lfe,ml,mr ?
311  // TODO - unknown if this channel ordering is correct?
312  bufs[0][frame] = aubuf[sample++] * volumes[0];
313  bufs[1][frame] = aubuf[sample++] * volumes[1];
314  bufs[4][frame] = aubuf[sample++] * volumes[4];
315  bufs[5][frame] = aubuf[sample++] * volumes[5];
316  bufs[2][frame] = aubuf[sample++] * volumes[2];
317  bufs[3][frame] = aubuf[sample++] * volumes[3];
318  bufs[6][frame] = aubuf[sample++] * volumes[6];
319  bufs[7][frame] = aubuf[sample++] * volumes[7];
320  }
321  }
322  else
323  {
324  for (int frame = 0; frame < nframes; frame++)
325  {
326  // Straightforward de-interleave for all other cases.
327  // Note no channel re-ordering...
328  for (int channel = 0; channel < m_channels; channel++)
329  {
330  bufs[channel][frame] = aubuf[sample++] * volumes[channel];
331  }
332  }
333  }
334 
335 }
336 
337 /* ***************************************************************************
338  Jack Callbacks
339  ****************************************************************************/
340 
341 /* Our Jack callback.
342  Jack will call this from a separate thread whenever it needs "feeding"
343  Simply calls our real code
344 */
345 int AudioOutputJACK::JackCallbackHelper(jack_nframes_t nframes, void *arg)
346 {
347  auto *aoj = static_cast<AudioOutputJACK*>(arg);
348  return aoj->JackCallback(nframes);
349 }
350 
351 /* Useful bit of the callback
352  This callback is called when the sound system requests
353  data. We don't want to block here, because that would
354  just cause dropouts anyway, so we always return whatever
355  data is available. If we haven't received enough, either
356  because we've finished playing or we have a buffer
357  underrun, we play silence to fill the unused space.
358  Return: 0 on success, non zero on error
359 */
360 int AudioOutputJACK::JackCallback(jack_nframes_t nframes)
361 {
362  float *bufs[JACK_CHANNELS_MAX];
363  int bytes_needed = nframes * m_outputBytesPerFrame;
364  int bytes_read = 0;
365 
366  // Check for stale_client set during shutdown callback
368 
369  // Deal with xruns which may have occured
370  // Basically read and discard the data which should have been played
371  int t_jack_xruns = m_jackXruns;
372  for (int i = 0; i < t_jack_xruns; i++)
373  {
374  bytes_read = GetAudioData(m_auBuf, m_fragmentSize, true);
375  VBERROR("Discarded one audio fragment to compensate for xrun");
376  }
377  m_jackXruns -= t_jack_xruns;
378 
379  // Get jack output buffers. Zero out the extra space in the array
380  // to prevent clang-tidy from complaining that DeinterleaveAudio()
381  // can reference a garbage value.
382  int i = 0;
383  for ( ; i < m_channels; i++)
384  bufs[i] = (float*)jack_port_get_buffer(m_ports[i], nframes);
385  for ( ; i < JACK_CHANNELS_MAX; i++)
386  bufs[i] = nullptr;
387 
388  if (m_pauseAudio || m_killAudio)
389  {
390  if (!m_actuallyPaused)
391  {
392  VBAUDIO("JackCallback: audio paused");
394  dispatch(e);
395  m_wasPaused = true;
396  }
397 
398  m_actuallyPaused = true;
399  }
400  else
401  {
402  if (m_wasPaused)
403  {
404  VBAUDIO("JackCallback: Play Event");
406  dispatch(e);
407  m_wasPaused = false;
408  }
409  bytes_read = GetAudioData(m_auBuf, bytes_needed, false);
410  }
411 
412  // Pad with silence
413  if (bytes_needed > bytes_read)
414  {
415  // play silence on buffer underrun
416  memset(m_auBuf + bytes_read, 0, bytes_needed - bytes_read);
417  if (!m_pauseAudio)
418  {
419  VBERROR(QString("Having to insert silence because GetAudioData "
420  "hasn't returned enough data. Wanted: %1 Got: %2")
421  .arg(bytes_needed).arg(bytes_read));
422  }
423  }
424  // Now deinterleave audio (and convert to float)
425  DeinterleaveAudio((float*)m_auBuf, bufs, nframes, m_chanVolumes);
426 
427  if (!m_pauseAudio)
428  {
429  // Output a status event - needed for Music player
430  Status();
431  }
432 
433  return 0;
434 }
435 
436 
437 /* Our Jack XRun callback.
438  Jack will call this from a separate thread whenever an xrun occurs
439  Simply calls our real code
440 */
442 {
443  auto *aoj = static_cast<AudioOutputJACK*>(arg);
444  return aoj->JackXRunCallback();
445 }
446 
447 /* Useful bit of the XRun callback
448  Return: 0 on success, non zero on error
449 */
451 {
452  float delay = jack_get_xrun_delayed_usecs(m_client); // usecs
453  // Increment our counter of "callbacks missed".
454  // All we want to do is chuck away some audio from the ring buffer
455  // to keep our audio output roughly where it should be if we didn't xrun
456  int fragments = (int)ceilf( ((delay / 1000000.0F) * m_sampleRate )
457  / ((float)m_fragmentSize / m_outputBytesPerFrame) );
458  m_jackXruns += fragments; //should be at least 1...
459  VBERROR(QString("Jack XRun Callback: %1 usecs delayed, xruns now %2")
460  .arg(delay).arg(m_jackXruns) );
461 
462  return 0;
463 }
464 
465 /* Our Jack Graph Order Change callback.
466  Jack will call this from a separate thread whenever an xrun occurs
467  Simply calls our real code
468 */
470 {
471  auto *aoj = static_cast<AudioOutputJACK*>(arg);
472  return aoj->JackGraphOrderCallback();
473 }
474 
475 /* Useful bit of the Graph Order Change callback
476  Called when the Jack graph changes. We update our latency info
477  Return: 0 on success, non zero on error
478 */
480 {
481  jack_latency_range_t latency_range;
482  jack_nframes_t max_latency = 0;
483 
484  for (int i = 0; i < m_channels; ++i)
485  {
486  jack_port_get_latency_range( m_ports[i], JackPlaybackLatency, &latency_range );
487  jack_nframes_t port_latency = latency_range.max;
488  if (port_latency > max_latency)
489  max_latency = port_latency;
490  }
491 
492  m_jackLatency = max_latency;
493  VBAUDIO(QString("JACK graph reordered. Maximum latency=%1")
494  .arg(m_jackLatency));
495 
496  return 0;
497 }
498 
499 
500 /* Volume related handling */
502 {
503  int volume = 100;
504  if (m_setInitialVol)
505  {
506  QString controlLabel = gCoreContext->GetSetting("MixerControl", "PCM");
507  controlLabel += "MixerVolume";
508  volume = gCoreContext->GetNumSetting(controlLabel, 80);
509  }
510 
511  for (int & cvolume : m_chanVolumes)
512  cvolume = volume;
513 }
514 
516 {
517  unsigned int vol = 0;
518 
519  if (!m_internalVol)
520  return 100;
521 
523  vol = m_chanVolumes[channel];
524 
525  return vol;
526 }
527 
529 {
531  {
532  m_chanVolumes[channel] = volume;
533  if (channel == 0)
534  {
535  // Left
536  m_chanVolumes[2] = volume; // left rear
537  }
538  else if (channel == 1)
539  {
540  // Right
541  m_chanVolumes[3] = volume; // right rear
542  }
543 
544  // LFE and Center
545  m_chanVolumes[4] = m_chanVolumes[5] =
546  (m_chanVolumes[0] + m_chanVolumes[1]) / 2;
547  }
548 }
549 
550 
551 /* We don't need an audio output thread for Jack
552  Everything handled by callbacks here
553  Therefore we can loose all the Start/StopOutputThread, WriteAudio, etc
554 */
556 {
557  return true;
558 }
559 
561 {
562 }
563 
564 // Don't need WriteAudio - this is only for the base class audio loop
565 void AudioOutputJACK::WriteAudio(unsigned char *aubuf, int size)
566 {
567  (void)aubuf;
568  (void)size;
569  // unneeded and unused in JACK
570 }
571 
572 /* **********************************************
573  Jack wrapper and convenience functions
574  ***********************************************/
575 
577 {
578  QString client_name = QString("mythtv_%1").arg(getpid());
579  auto open_options = (jack_options_t)(JackUseExactName | JackNoStartServer);
580  jack_status_t open_status = JackFailure;
581 
582  jack_client_t *client = jack_client_open(client_name.toLatin1().constData(),
583  open_options, &open_status);
584 
585  return client;
586 }
587 
589 {
590  const char **matching_ports = nullptr;
591  unsigned long port_flags=JackPortIsInput;
592  const char *port_name = nullptr;
593 
594  // Have we been given a target port to connect to
595  if (!m_mainDevice.isEmpty())
596  {
597  port_name = m_mainDevice.toLatin1().constData();
598  }
599  else
600  {
601  port_flags |= JackPortIsPhysical;
602  }
603 
604  // list matching ports
605  matching_ports = jack_get_ports(m_client, port_name, nullptr, port_flags);
606  return matching_ports;
607 }
608 
609 
610 bool AudioOutputJACK::JackConnectPorts(const char** matching_ports)
611 {
612  int i=0;
613 
614  // Connect our output ports
615  for (i = 0; i < m_channels; i++)
616  {
617  if (jack_connect(m_client, jack_port_name(m_ports[i]), matching_ports[i]))
618  {
619  JERROR(tr("Calling jack_connect failed on port: %1\n").arg(i));
620  return false;
621  }
622  }
623 
624  return true;
625 }
626 
627 void AudioOutputJACK::JackClientClose(jack_client_t **client)
628 {
629  if (*client)
630  {
631  int err = jack_client_close(*client);
632  if (err != 0)
633  JERROR(tr("Error closing Jack output device. Error: %1")
634  .arg(err));
635  *client = nullptr;
636  }
637 }
638 
639 /* vim: set expandtab tabstop=4 shiftwidth=4: */
void InitSettings(const AudioSettings &settings)
jack_client_t * m_client
#define JACK_CHANNELS_MAX
void CloseDevice(void) override
int GetBufferedOnSoundcard(void) const override
Return the size in bytes of frames currently in the audio buffer adjusted with the audio playback lat...
void DeinterleaveAudio(const float *aubuf, float **bufs, int nframes, const int *channel_volumes)
static int JackCallbackHelper(jack_nframes_t nframes, void *arg)
static Type Playing
Definition: output.h:63
AudioOutputJACK(const AudioSettings &settings)
bool m_internalVol
Definition: volumebase.h:41
void WriteAudio(unsigned char *aubuf, int size) override
int GetAudioData(uchar *buffer, int buf_size, bool full_buffer, volatile uint *local_raud=nullptr)
Copy frames from the audiobuffer into the buffer provided.
static int JackGraphOrderCallbackHelper(void *arg)
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
#define VBERROR(str)
int GetVolumeChannel(int channel) const override
void dispatch(const MythEvent &event)
Dispatch an event to all listeners.
QString GetSetting(const QString &key, const QString &defaultval="")
static int JackXRunCallbackHelper(void *arg)
virtual void Status(void)
Report status via an OutputEvent.
void SetVolumeChannel(int channel, int volume) override
bool OpenDevice(void) override
~AudioOutputJACK() override
int JackCallback(jack_nframes_t nframes)
int GetNumSetting(const QString &key, int defaultval=0)
jack_port_t * m_ports[JACK_CHANNELS_MAX]
unsigned char * m_auBuf
void KillAudio(void)
Kill the output thread and cleanup.
void Reconfigure(const AudioSettings &settings) override
(Re)Configure AudioOutputBase
#define JERROR(str)
void JackClientClose(jack_client_t **client)
static jack_client_t * JackClientOpen(void)
int m_chanVolumes[JACK_CHANNELS_MAX]
static Type Paused
Definition: output.h:66
bool StartOutputThread(void) override
AudioOutputSettings * GetOutputSettings(bool digital) override
jack_client_t * m_staleClient
bool m_init
If set to false, AudioOutput instance will not try to initially open the audio device.
Definition: audiosettings.h:84
const char ** JackGetPorts(void)
#define VBAUDIO(str)
bool JackConnectPorts(const char **)
void StopOutputThread(void) override
static Type Stopped
Definition: output.h:67
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23