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 (int i = 0; i < JACK_CHANNELS_MAX; i++)
46  m_ports[i] = nullptr;
47  for (int i = 0; i < JACK_CHANNELS_MAX; i++)
48  m_chan_volumes[i] = 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  AudioOutputSettings *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 = _jack_get_ports();
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_main_device));
138 
139  // Setup volume control
140  if (internal_vol)
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 = _jack_get_ports();
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_fragment_size = jack_get_buffer_size(m_client) * m_output_bytes_per_frame;
189 
190  // Allocate a new temp buffer to de-interleave our audio data
191  delete[] m_aubuf;
192  m_aubuf = new unsigned char[m_fragment_size];
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, _JackCallback, this))
198  JERROR(tr("Error. Unable to set process callback?!"));
199  if (jack_set_xrun_callback(m_client, _JackXRunCallback, this))
200  JERROR(tr("Error. Unable to set xrun callback?!"));
201  if (jack_set_graph_order_callback(m_client, _JackGraphOrderCallback, 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 (! _jack_connect_ports(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_fragment_size));
250  return (m_fragment_size * 2) - (frames_played * m_output_bytes_per_frame);
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[m_channels];
269  for (int channel = 0; channel < m_channels; channel++)
270  {
271  if (internal_vol)
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::_JackCallback(jack_nframes_t nframes, void *arg)
346 {
347  AudioOutputJACK *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_output_bytes_per_frame;
364  int bytes_read = 0;
365  int i;
366 
367  // Check for stale_client set during shutdown callback
369 
370  // Deal with xruns which may have occured
371  // Basically read and discard the data which should have been played
372  int t_jack_xruns = m_jack_xruns;
373  for (i = 0; i < t_jack_xruns; i++)
374  {
375  bytes_read = GetAudioData(m_aubuf, m_fragment_size, true);
376  VBERROR("Discarded one audio fragment to compensate for xrun");
377  }
378  m_jack_xruns -= t_jack_xruns;
379 
380  // Get jack output buffers
381  for (i = 0; i < m_channels; i++)
382  bufs[i] = (float*)jack_port_get_buffer(m_ports[i], nframes);
383 
384  if (m_pauseaudio || m_killaudio)
385  {
386  if (!m_actually_paused)
387  {
388  VBAUDIO("JackCallback: audio paused");
390  dispatch(e);
391  m_was_paused = true;
392  }
393 
394  m_actually_paused = true;
395  }
396  else
397  {
398  if (m_was_paused)
399  {
400  VBAUDIO("JackCallback: Play Event");
402  dispatch(e);
403  m_was_paused = false;
404  }
405  bytes_read = GetAudioData(m_aubuf, bytes_needed, false);
406  }
407 
408  // Pad with silence
409  if (bytes_needed > bytes_read)
410  {
411  // play silence on buffer underrun
412  memset(m_aubuf + bytes_read, 0, bytes_needed - bytes_read);
413  if (!m_pauseaudio)
414  VBERROR(QString("Having to insert silence because GetAudioData "
415  "hasn't returned enough data. Wanted: %1 Got: %2")
416  .arg(bytes_needed).arg(bytes_read));
417  }
418  // Now deinterleave audio (and convert to float)
419  DeinterleaveAudio((float*)m_aubuf, bufs, nframes, m_chan_volumes);
420 
421  if (!m_pauseaudio)
422  {
423  // Output a status event - needed for Music player
424  Status();
425  }
426 
427  return 0;
428 }
429 
430 
431 /* Our Jack XRun callback.
432  Jack will call this from a separate thread whenever an xrun occurs
433  Simply calls our real code
434 */
436 {
437  AudioOutputJACK *aoj = static_cast<AudioOutputJACK*>(arg);
438  return aoj->JackXRunCallback();
439 }
440 
441 /* Useful bit of the XRun callback
442  Return: 0 on success, non zero on error
443 */
445 {
446  float delay = jack_get_xrun_delayed_usecs(m_client); // usecs
447  // Increment our counter of "callbacks missed".
448  // All we want to do is chuck away some audio from the ring buffer
449  // to keep our audio output roughly where it should be if we didn't xrun
450  int fragments = (int)ceilf( ((delay / 1000000.0F) * m_samplerate )
452  m_jack_xruns += fragments; //should be at least 1...
453  VBERROR(QString("Jack XRun Callback: %1 usecs delayed, xruns now %2")
454  .arg(delay).arg(m_jack_xruns) );
455 
456  return 0;
457 }
458 
459 /* Our Jack Graph Order Change callback.
460  Jack will call this from a separate thread whenever an xrun occurs
461  Simply calls our real code
462 */
464 {
465  AudioOutputJACK *aoj = static_cast<AudioOutputJACK*>(arg);
466  return aoj->JackGraphOrderCallback();
467 }
468 
469 /* Useful bit of the Graph Order Change callback
470  Called when the Jack graph changes. We update our latency info
471  Return: 0 on success, non zero on error
472 */
474 {
475  int i;
476  jack_latency_range_t latency_range;
477  jack_nframes_t port_latency, max_latency = 0;
478 
479  for (i = 0; i < m_channels; ++i)
480  {
481  jack_port_get_latency_range( m_ports[i], JackPlaybackLatency, &latency_range );
482  port_latency = latency_range.max;
483  if (port_latency > max_latency)
484  max_latency = port_latency;
485  }
486 
487  m_jack_latency = max_latency;
488  VBAUDIO(QString("JACK graph reordered. Maximum latency=%1")
489  .arg(m_jack_latency));
490 
491  return 0;
492 }
493 
494 
495 /* Volume related handling */
497 {
498  int volume = 100;
499  if (m_set_initial_vol)
500  {
501  QString controlLabel = gCoreContext->GetSetting("MixerControl", "PCM");
502  controlLabel += "MixerVolume";
503  volume = gCoreContext->GetNumSetting(controlLabel, 80);
504  }
505 
506  for (int i=0; i<JACK_CHANNELS_MAX; i++)
507  m_chan_volumes[i] = volume;
508 }
509 
510 int AudioOutputJACK::GetVolumeChannel(int channel) const
511 {
512  unsigned int vol = 0;
513 
514  if (!internal_vol)
515  return 100;
516 
517  if (channel < JACK_CHANNELS_MAX)
518  vol = m_chan_volumes[channel];
519 
520  return vol;
521 }
522 
523 void AudioOutputJACK::SetVolumeChannel(int channel, int volume)
524 {
525  if (internal_vol && (channel < JACK_CHANNELS_MAX))
526  {
527  m_chan_volumes[channel] = volume;
528  if (channel == 0)
529  {
530  // Left
531  m_chan_volumes[2] = volume; // left rear
532  }
533  else if (channel == 1)
534  {
535  // Right
536  m_chan_volumes[3] = volume; // right rear
537  }
538 
539  // LFE and Center
541  (m_chan_volumes[0] + m_chan_volumes[1]) / 2;
542  }
543 }
544 
545 
546 /* We don't need an audio output thread for Jack
547  Everything handled by callbacks here
548  Therefore we can loose all the Start/StopOutputThread, WriteAudio, etc
549 */
551 {
552  return true;
553 }
554 
556 {
557 }
558 
559 // Don't need WriteAudio - this is only for the base class audio loop
560 void AudioOutputJACK::WriteAudio(unsigned char *aubuf, int size)
561 {
562  (void)aubuf;
563  (void)size;
564  // unneeded and unused in JACK
565 }
566 
567 /* **********************************************
568  Jack wrapper and convenience functions
569  ***********************************************/
570 
572 {
573  QString client_name = QString("mythtv_%1").arg(getpid());
574  jack_options_t open_options =
575  (jack_options_t)(JackUseExactName | JackNoStartServer);
576  jack_status_t open_status;
577 
578  jack_client_t *client = jack_client_open(client_name.toLatin1().constData(),
579  open_options, &open_status);
580 
581  return client;
582 }
583 
585 {
586  const char **matching_ports = nullptr;
587  unsigned long port_flags=JackPortIsInput;
588  const char *port_name = nullptr;
589 
590  // Have we been given a target port to connect to
591  if (!m_main_device.isEmpty())
592  {
593  port_name = m_main_device.toLatin1().constData();
594  }
595  else
596  {
597  port_flags |= JackPortIsPhysical;
598  }
599 
600  // list matching ports
601  matching_ports = jack_get_ports(m_client, port_name, nullptr, port_flags);
602  return matching_ports;
603 }
604 
605 
606 bool AudioOutputJACK::_jack_connect_ports(const char** matching_ports)
607 {
608  int i=0;
609 
610  // Connect our output ports
611  for (i = 0; i < m_channels; i++)
612  {
613  if (jack_connect(m_client, jack_port_name(m_ports[i]), matching_ports[i]))
614  {
615  JERROR(tr("Calling jack_connect failed on port: %1\n").arg(i));
616  return false;
617  }
618  }
619 
620  return true;
621 }
622 
623 void AudioOutputJACK::_jack_client_close(jack_client_t **client)
624 {
625  if (*client)
626  {
627  int err = jack_client_close(*client);
628  if (err != 0)
629  JERROR(tr("Error closing Jack output device. Error: %1")
630  .arg(err));
631  *client = nullptr;
632  }
633 }
634 
635 /* 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
const char ** _jack_get_ports(void)
int GetBufferedOnSoundcard(void) const override
Return the size in bytes of frames currently in the audio buffer adjusted with the audio playback lat...
jack_client_t * _jack_client_open(void)
void DeinterleaveAudio(const float *aubuf, float **bufs, int nframes, const int *channel_volumes)
static Type Playing
Definition: output.h:61
AudioOutputJACK(const AudioSettings &settings)
static int _JackGraphOrderCallback(void *arg)
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.
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
void _jack_client_close(jack_client_t **client)
#define VBERROR(str)
static int _JackCallback(jack_nframes_t nframes, void *arg)
int GetVolumeChannel(int channel) const override
void dispatch(const MythEvent &event)
Dispatch an event to all listeners.
jack_client_t * m_stale_client
QString GetSetting(const QString &key, const QString &defaultval="")
bool _jack_connect_ports(const char **)
static int _JackXRunCallback(void *arg)
virtual void Status(void)
Report status via an OutputEvent.
void SetVolumeChannel(int channel, int volume) override
bool OpenDevice(void) override
bool internal_vol
Definition: volumebase.h:41
~AudioOutputJACK() override
int JackCallback(jack_nframes_t nframes)
int GetNumSetting(const QString &key, int defaultval=0)
jack_port_t * m_ports[JACK_CHANNELS_MAX]
#define LOG(_MASK_, _LEVEL_, _STRING_)
Definition: mythlogging.h:41
void AddSupportedRate(int rate)
void KillAudio(void)
Kill the output thread and cleanup.
void Reconfigure(const AudioSettings &settings) override
(Re)Configure AudioOutputBase
#define JERROR(str)
unsigned char * m_aubuf
int m_chan_volumes[JACK_CHANNELS_MAX]
void AddSupportedFormat(AudioFormat format)
void AddSupportedChannels(int channels)
static Type Paused
Definition: output.h:64
bool StartOutputThread(void) override
AudioOutputSettings * GetOutputSettings(bool digital) override
bool m_init
If set to false, AudioOutput instance will not try to initially open the audio device.
Definition: audiosettings.h:80
#define VBAUDIO(str)
void StopOutputThread(void) override
static Type Stopped
Definition: output.h:65