2 Copyright (C) 2002 Paul Davis
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.
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.
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.
27 #include <glibmm/timer.h>
28 #include <jack/jack.h>
29 #include <jack/thread.h>
31 #include "pbd/pthread_utils.h"
32 #include "pbd/stacktrace.h"
33 #include "pbd/unknown_type.h"
35 #include "midi++/jack.h"
36 #include "midi++/mmc.h"
38 #include "ardour/amp.h"
39 #include "ardour/audio_port.h"
40 #include "ardour/audioengine.h"
41 #include "ardour/buffer.h"
42 #include "ardour/buffer_set.h"
43 #include "ardour/cycle_timer.h"
44 #include "ardour/delivery.h"
45 #include "ardour/event_type_map.h"
46 #include "ardour/internal_return.h"
47 #include "ardour/io.h"
48 #include "ardour/meter.h"
49 #include "ardour/midi_port.h"
50 #include "ardour/process_thread.h"
51 #include "ardour/port.h"
52 #include "ardour/port_set.h"
53 #include "ardour/session.h"
54 #include "ardour/timestamps.h"
55 #include "ardour/utils.h"
60 using namespace ARDOUR;
63 gint AudioEngine::m_meter_exit;
64 AudioEngine* AudioEngine::_instance = 0;
66 #define GET_PRIVATE_JACK_POINTER(j) jack_client_t* _priv_jack = (jack_client_t*) (j); if (!_priv_jack) { return; }
67 #define GET_PRIVATE_JACK_POINTER_RET(j,r) jack_client_t* _priv_jack = (jack_client_t*) (j); if (!_priv_jack) { return r; }
69 AudioEngine::AudioEngine (string client_name, string session_uuid)
72 _instance = this; /* singleton */
74 session_remove_pending = false;
77 last_monitor_check = 0;
78 monitor_check_interval = max_frames;
79 _processed_frames = 0;
84 _freewheeling = false;
88 g_atomic_int_set (&m_meter_exit, 0);
90 if (connect_to_jack (client_name, session_uuid)) {
91 throw NoBackendAvailable ();
94 Port::set_engine (this);
96 // Initialize parameter metadata (e.g. ranges)
97 Evoral::Parameter p(NullAutomation);
98 p = EventTypeMap::instance().new_parameter(NullAutomation);
99 p = EventTypeMap::instance().new_parameter(GainAutomation);
100 p = EventTypeMap::instance().new_parameter(PanAutomation);
101 p = EventTypeMap::instance().new_parameter(PluginAutomation);
102 p = EventTypeMap::instance().new_parameter(SoloAutomation);
103 p = EventTypeMap::instance().new_parameter(MuteAutomation);
104 p = EventTypeMap::instance().new_parameter(MidiCCAutomation);
105 p = EventTypeMap::instance().new_parameter(MidiPgmChangeAutomation);
106 p = EventTypeMap::instance().new_parameter(MidiPitchBenderAutomation);
107 p = EventTypeMap::instance().new_parameter(MidiChannelPressureAutomation);
108 p = EventTypeMap::instance().new_parameter(FadeInAutomation);
109 p = EventTypeMap::instance().new_parameter(FadeOutAutomation);
110 p = EventTypeMap::instance().new_parameter(EnvelopeAutomation);
111 p = EventTypeMap::instance().new_parameter(MidiCCAutomation);
114 AudioEngine::~AudioEngine ()
117 Glib::Mutex::Lock tm (_process_lock);
118 session_removed.signal ();
121 jack_client_close (_jack);
125 stop_metering_thread ();
130 AudioEngine::jack() const
136 _thread_init_callback (void * /*arg*/)
138 /* make sure that anybody who needs to know about this thread
142 pthread_set_name (X_("audioengine"));
144 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
145 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
147 SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
149 MIDI::JACK_MidiPort::set_process_thread (pthread_self());
150 MIDI::MachineControl::set_sending_thread (pthread_self ());
153 typedef void (*_JackInfoShutdownCallback)(jack_status_t code, const char* reason, void *arg);
155 static void (*on_info_shutdown)(jack_client_t*, _JackInfoShutdownCallback, void *);
156 extern void jack_on_info_shutdown (jack_client_t*, _JackInfoShutdownCallback, void *) __attribute__((weak));
158 static void check_jack_symbols () __attribute__((constructor));
160 void check_jack_symbols ()
162 /* use weak linking to see if we really have various late-model JACK function */
163 on_info_shutdown = jack_on_info_shutdown;
167 ardour_jack_error (const char* msg)
169 error << "JACK: " << msg << endmsg;
173 AudioEngine::start ()
175 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
179 nframes_t blocksize = jack_get_buffer_size (_priv_jack);
182 BootMessage (_("Connect session to engine"));
184 _session->set_block_size (blocksize);
185 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
187 /* page in as much of the session process code as we
188 can before we really start running.
191 _session->process (blocksize);
192 _session->process (blocksize);
193 _session->process (blocksize);
194 _session->process (blocksize);
195 _session->process (blocksize);
196 _session->process (blocksize);
197 _session->process (blocksize);
198 _session->process (blocksize);
201 _processed_frames = 0;
202 last_monitor_check = 0;
204 if (on_info_shutdown) {
205 jack_on_info_shutdown (_priv_jack, halted_info, this);
207 jack_on_shutdown (_priv_jack, halted, this);
209 jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
210 jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
211 // jack_set_process_callback (_priv_jack, _process_callback, this);
212 jack_set_process_thread (_priv_jack, _process_thread, this);
213 jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
214 jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
215 jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
216 #ifdef HAVE_JACK_SESSION
217 if( jack_set_session_callback )
218 jack_set_session_callback (_priv_jack, _session_callback, this);
220 jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
221 jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
222 jack_set_port_registration_callback (_priv_jack, _registration_callback, this);
223 jack_set_port_connect_callback (_priv_jack, _connect_callback, this);
225 if (_session && _session->config.get_jack_time_master()) {
226 jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
229 jack_set_error_function (ardour_jack_error);
231 if (jack_activate (_priv_jack) == 0) {
234 Running(); /* EMIT SIGNAL */
236 // error << _("cannot activate JACK client") << endmsg;
239 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
241 jack_port_t* midi_port = jack_port_register (_priv_jack, "m", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
243 error << _("Cannot create temporary MIDI port to determine MIDI buffer size") << endmsg;
245 _raw_buffer_sizes[DataType::MIDI] = jack_midi_max_event_size (jack_port_get_buffer(midi_port, blocksize));
246 cerr << "MIDI port buffers = " << _raw_buffer_sizes[DataType::MIDI] << endl;
247 jack_port_unregister (_priv_jack, midi_port);
251 return _running ? 0 : -1;
255 AudioEngine::stop (bool forever)
257 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
261 disconnect_from_jack ();
263 jack_deactivate (_priv_jack);
264 Stopped(); /* EMIT SIGNAL */
265 MIDI::JACK_MidiPort::JackHalted (); /* EMIT SIGNAL */
269 return _running ? -1 : 0;
274 AudioEngine::get_sync_offset (nframes_t& offset) const
277 #ifdef HAVE_JACK_VIDEO_SUPPORT
279 GET_PRIVATE_JACK_POINTER_RET (_jack, false);
284 (void) jack_transport_query (_priv_jack, &pos);
286 if (pos.valid & JackVideoFrameOffset) {
287 offset = pos.video_offset;
300 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
301 jack_position_t* pos, int new_position, void *arg)
303 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
307 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
308 jack_position_t* pos, int new_position)
310 if (_jack && _session && _session->synced_to_jack()) {
311 _session->jack_timebase_callback (state, nframes, pos, new_position);
316 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
318 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
322 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
324 if (_jack && _session) {
325 return _session->jack_sync_callback (state, pos);
332 AudioEngine::_xrun_callback (void *arg)
334 AudioEngine* ae = static_cast<AudioEngine*> (arg);
335 if (ae->connected()) {
336 ae->Xrun (); /* EMIT SIGNAL */
341 #ifdef HAVE_JACK_SESSION
343 AudioEngine::_session_callback (jack_session_event_t *event, void *arg)
345 printf( "helo.... " );
346 AudioEngine* ae = static_cast<AudioEngine*> (arg);
347 if (ae->connected()) {
348 ae->JackSessionEvent ( event ); /* EMIT SIGNAL */
353 AudioEngine::_graph_order_callback (void *arg)
355 AudioEngine* ae = static_cast<AudioEngine*> (arg);
356 if (ae->connected()) {
357 ae->GraphReordered (); /* EMIT SIGNAL */
362 /** Wrapped which is called by JACK as its process callback. It is just
363 * here to get us back into C++ land by calling AudioEngine::process_callback()
364 * @param nframes Number of frames passed by JACK.
365 * @param arg User argument passed by JACK, which will be the AudioEngine*.
368 AudioEngine::_process_callback (nframes_t nframes, void *arg)
370 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
374 AudioEngine::_process_thread (void *arg)
376 return static_cast<AudioEngine *> (arg)->process_thread ();
380 AudioEngine::_freewheel_callback (int onoff, void *arg)
382 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
386 AudioEngine::_registration_callback (jack_port_id_t /*id*/, int /*reg*/, void* arg)
388 AudioEngine* ae = static_cast<AudioEngine*> (arg);
389 ae->PortRegisteredOrUnregistered (); /* EMIT SIGNAL */
393 AudioEngine::_connect_callback (jack_port_id_t /*id_a*/, jack_port_id_t /*id_b*/, int /*conn*/, void* arg)
395 AudioEngine* ae = static_cast<AudioEngine*> (arg);
396 ae->PortConnectedOrDisconnected (); /* EMIT SIGNAL */
400 AudioEngine::split_cycle (nframes_t offset)
402 /* caller must hold process lock */
404 Port::increment_port_offset (offset);
406 /* tell all Ports that we're going to start a new (split) cycle */
408 boost::shared_ptr<Ports> p = ports.reader();
410 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
411 (*i)->cycle_split ();
416 AudioEngine::finish_process_cycle (int status)
418 GET_PRIVATE_JACK_POINTER(_jack);
419 jack_cycle_signal (_jack, 0);
423 AudioEngine::process_thread ()
425 /* JACK doesn't do this for us when we use the wait API
428 _thread_init_callback (0);
430 _main_thread = new ProcessThread;
433 GET_PRIVATE_JACK_POINTER_RET(_jack,0);
434 jack_nframes_t nframes = jack_cycle_wait (_jack);
436 if (process_callback (nframes)) {
437 cerr << "--- process\n";
441 finish_process_cycle (0);
447 /** Method called by JACK (via _process_callback) which says that there
448 * is work to be done.
449 * @param nframes Number of frames to process.
452 AudioEngine::process_callback (nframes_t nframes)
454 GET_PRIVATE_JACK_POINTER_RET(_jack,0);
455 // CycleTimer ct ("AudioEngine::process");
456 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
458 /// The number of frames that will have been processed when we've finished
459 nframes_t next_processed_frames;
461 /* handle wrap around of total frames counter */
463 if (max_frames - _processed_frames < nframes) {
464 next_processed_frames = nframes - (max_frames - _processed_frames);
466 next_processed_frames = _processed_frames + nframes;
469 if (!tm.locked() || _session == 0) {
470 /* return having done nothing */
471 _processed_frames = next_processed_frames;
475 if (session_remove_pending) {
476 /* perform the actual session removal */
478 session_remove_pending = false;
479 session_removed.signal();
480 _processed_frames = next_processed_frames;
484 /* tell all relevant objects that we're starting a new cycle */
486 Delivery::CycleStart (nframes);
487 Port::set_port_offset (0);
488 InternalReturn::CycleStart (nframes);
490 /* tell all Ports that we're starting a new cycle */
492 boost::shared_ptr<Ports> p = ports.reader();
494 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
495 (*i)->cycle_start (nframes);
499 /* emit the Freewheel signal and stop freewheeling in the event of trouble
501 boost::optional<int> r = Freewheel (nframes);
502 if (r.get_value_or (0)) {
503 jack_set_freewheel (_priv_jack, false);
508 _session->process (nframes);
518 _processed_frames = next_processed_frames;
522 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
524 boost::shared_ptr<Ports> p = ports.reader();
526 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
531 if (port->_last_monitor != (x = port->monitoring_input ())) {
532 port->_last_monitor = x;
533 /* XXX I think this is dangerous, due to
534 a likely mutex in the signal handlers ...
536 port->MonitorInputChanged (x); /* EMIT SIGNAL */
539 last_monitor_check = next_processed_frames;
542 if (_session->silent()) {
544 boost::shared_ptr<Ports> p = ports.reader();
546 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
550 if (port->sends_output()) {
551 port->get_buffer(nframes).silence(nframes);
558 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
559 (*i)->cycle_end (nframes);
562 _processed_frames = next_processed_frames;
567 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
569 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
573 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
575 _frame_rate = nframes;
576 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
578 /* check for monitor input change every 1/10th of second */
580 monitor_check_interval = nframes / 10;
581 last_monitor_check = 0;
584 _session->set_frame_rate (nframes);
587 SampleRateChanged (nframes); /* EMIT SIGNAL */
593 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
595 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
599 AudioEngine::jack_bufsize_callback (nframes_t nframes)
601 bool need_midi_size = true;
602 bool need_audio_size = true;
604 _buffer_size = nframes;
605 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
606 last_monitor_check = 0;
608 boost::shared_ptr<Ports> p = ports.reader();
610 /* crude guesses, see below where we try to get the right answers.
612 Note that our guess for MIDI deliberatey tries to overestimate
613 by a little. It would be nicer if we could get the actual
614 size from a port, but we have to use this estimate in the
615 event that there are no MIDI ports currently. If there are
616 the value will be adjusted below.
619 _raw_buffer_sizes[DataType::AUDIO] = nframes * sizeof (Sample);
620 _raw_buffer_sizes[DataType::MIDI] = nframes * 4 - (nframes/2);
622 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
624 if (need_audio_size && (*i)->type() == DataType::AUDIO) {
625 _raw_buffer_sizes[DataType::AUDIO] = (*i)->raw_buffer_size (nframes);
626 need_audio_size = false;
630 if (need_midi_size && (*i)->type() == DataType::MIDI) {
631 _raw_buffer_sizes[DataType::MIDI] = (*i)->raw_buffer_size (nframes);
632 need_midi_size = false;
639 _session->set_block_size (_buffer_size);
646 AudioEngine::stop_metering_thread ()
648 if (m_meter_thread) {
649 g_atomic_int_set (&m_meter_exit, 1);
650 m_meter_thread->join ();
656 AudioEngine::start_metering_thread ()
658 if (m_meter_thread == 0) {
659 g_atomic_int_set (&m_meter_exit, 0);
660 m_meter_thread = Glib::Thread::create (boost::bind (&AudioEngine::meter_thread, this),
661 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
666 AudioEngine::meter_thread ()
668 pthread_set_name (X_("meter"));
671 Glib::usleep (10000); /* 1/100th sec interval */
672 if (g_atomic_int_get(&m_meter_exit)) {
680 AudioEngine::set_session (Session *s)
682 Glib::Mutex::Lock pl (_process_lock);
684 SessionHandlePtr::set_session (s);
688 start_metering_thread ();
690 nframes_t blocksize = jack_get_buffer_size (_jack);
692 /* page in as much of the session process code as we
693 can before we really start running.
696 boost::shared_ptr<Ports> p = ports.reader();
698 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
699 (*i)->cycle_start (blocksize);
702 _session->process (blocksize);
703 _session->process (blocksize);
704 _session->process (blocksize);
705 _session->process (blocksize);
706 _session->process (blocksize);
707 _session->process (blocksize);
708 _session->process (blocksize);
709 _session->process (blocksize);
711 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
712 (*i)->cycle_end (blocksize);
718 AudioEngine::remove_session ()
720 Glib::Mutex::Lock lm (_process_lock);
724 stop_metering_thread ();
727 session_remove_pending = true;
728 session_removed.wait(_process_lock);
732 SessionHandlePtr::set_session (0);
739 AudioEngine::port_registration_failure (const std::string& portname)
741 GET_PRIVATE_JACK_POINTER (_jack);
742 string full_portname = jack_client_name;
743 full_portname += ':';
744 full_portname += portname;
747 jack_port_t* p = jack_port_by_name (_priv_jack, full_portname.c_str());
751 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
753 reason = string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with ports if you need this many tracks."), PROGRAM_NAME);
756 throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
760 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
765 if (dtype == DataType::AUDIO) {
766 newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
767 } else if (dtype == DataType::MIDI) {
768 newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
770 throw PortRegistrationFailure("unable to create port (unknown type)");
773 size_t& old_buffer_size = _raw_buffer_sizes[newport->type()];
774 size_t port_buffer_size = newport->raw_buffer_size(0);
775 if (port_buffer_size > old_buffer_size) {
776 old_buffer_size = port_buffer_size;
779 RCUWriter<Ports> writer (ports);
780 boost::shared_ptr<Ports> ps = writer.get_copy ();
781 ps->insert (ps->begin(), newport);
783 /* writer goes out of scope, forces update */
788 catch (PortRegistrationFailure& err) {
790 } catch (std::exception& e) {
791 throw PortRegistrationFailure(string_compose(
792 _("unable to create port: %1"), e.what()).c_str());
794 throw PortRegistrationFailure("unable to create port (unknown error)");
799 AudioEngine::register_input_port (DataType type, const string& portname)
801 return register_port (type, portname, true);
805 AudioEngine::register_output_port (DataType type, const string& portname)
807 return register_port (type, portname, false);
811 AudioEngine::unregister_port (Port& port)
813 /* caller must hold process lock */
816 /* probably happening when the engine has been halted by JACK,
817 in which case, there is nothing we can do here.
823 RCUWriter<Ports> writer (ports);
824 boost::shared_ptr<Ports> ps = writer.get_copy ();
826 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
834 /* writer goes out of scope, forces update */
841 AudioEngine::connect (const string& source, const string& destination)
843 /* caller must hold process lock */
849 fatal << _("connect called before engine was started") << endmsg;
856 string s = make_port_name_non_relative (source);
857 string d = make_port_name_non_relative (destination);
860 Port* src = get_port_by_name_locked (s);
861 Port* dst = get_port_by_name_locked (d);
864 ret = src->connect (d);
866 ret = dst->connect (s);
868 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
873 /* already exists - no error, no warning */
874 } else if (ret < 0) {
875 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
876 source, s, destination, d)
884 AudioEngine::disconnect (const string& source, const string& destination)
886 /* caller must hold process lock */
892 fatal << _("disconnect called before engine was started") << endmsg;
899 string s = make_port_name_non_relative (source);
900 string d = make_port_name_non_relative (destination);
902 Port* src = get_port_by_name_locked (s);
903 Port* dst = get_port_by_name_locked (d);
906 ret = src->disconnect (d);
908 ret = dst->disconnect (s);
910 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
917 AudioEngine::disconnect (Port& port)
919 GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
923 fatal << _("disconnect called before engine was started") << endmsg;
930 return port.disconnect_all ();
934 AudioEngine::frame_rate () const
936 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
937 if (_frame_rate == 0) {
938 return (_frame_rate = jack_get_sample_rate (_priv_jack));
945 AudioEngine::raw_buffer_size (DataType t)
947 std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
948 return (s != _raw_buffer_sizes.end()) ? s->second : 0;
952 AudioEngine::frames_per_cycle () const
954 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
955 if (_buffer_size == 0) {
956 return (_buffer_size = jack_get_buffer_size (_jack));
962 /** @param name Full name of port (including prefix:)
963 * @return Corresponding Port*, or 0. This object remains the property of the AudioEngine
964 * so must not be deleted.
967 AudioEngine::get_port_by_name (const string& portname)
970 if (portname.find_first_of (':') == string::npos) {
971 s = make_port_name_non_relative (portname);
976 Glib::Mutex::Lock lm (_process_lock);
977 return get_port_by_name_locked (s);
981 AudioEngine::get_port_by_name_locked (const string& portname)
983 /* caller must hold process lock */
987 fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
994 if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
995 /* not an ardour: port */
999 std::string const rel = make_port_name_relative (portname);
1001 boost::shared_ptr<Ports> pr = ports.reader();
1003 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
1004 if (rel == (*i)->name()) {
1013 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
1015 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1018 fatal << _("get_ports called before engine was started") << endmsg;
1024 return jack_get_ports (_priv_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
1028 AudioEngine::halted_info (jack_status_t code, const char* reason, void *arg)
1030 /* called from jack shutdown handler */
1032 AudioEngine* ae = static_cast<AudioEngine *> (arg);
1033 bool was_running = ae->_running;
1035 ae->stop_metering_thread ();
1037 ae->_running = false;
1038 ae->_buffer_size = 0;
1039 ae->_frame_rate = 0;
1043 #ifdef HAVE_JACK_ON_INFO_SHUTDOWN
1045 case JackBackendError:
1046 ae->Halted(reason); /* EMIT SIGNAL */
1049 ae->Halted(""); /* EMIT SIGNAL */
1052 ae->Halted(""); /* EMIT SIGNAL */
1058 AudioEngine::halted (void *arg)
1060 cerr << "HALTED by JACK\n";
1062 /* called from jack shutdown handler */
1064 AudioEngine* ae = static_cast<AudioEngine *> (arg);
1065 bool was_running = ae->_running;
1067 ae->stop_metering_thread ();
1069 ae->_running = false;
1070 ae->_buffer_size = 0;
1071 ae->_frame_rate = 0;
1075 ae->Halted(""); /* EMIT SIGNAL */
1076 MIDI::JACK_MidiPort::JackHalted (); /* EMIT SIGNAL */
1081 AudioEngine::died ()
1083 /* called from a signal handler for SIGPIPE */
1085 stop_metering_thread ();
1094 AudioEngine::can_request_hardware_monitoring ()
1096 GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1097 const char ** ports;
1099 if ((ports = jack_get_ports (_priv_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
1110 AudioEngine::n_physical_outputs (DataType type) const
1112 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1113 const char ** ports;
1116 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
1120 for (uint32_t i = 0; ports[i]; ++i) {
1121 if (!strstr (ports[i], "Midi-Through")) {
1132 AudioEngine::n_physical_inputs (DataType type) const
1134 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1135 const char ** ports;
1138 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
1142 for (uint32_t i = 0; ports[i]; ++i) {
1143 if (!strstr (ports[i], "Midi-Through")) {
1154 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
1156 GET_PRIVATE_JACK_POINTER (_jack);
1157 const char ** ports;
1159 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
1164 for (uint32_t i = 0; ports[i]; ++i) {
1165 if (strstr (ports[i], "Midi-Through")) {
1168 ins.push_back (ports[i]);
1175 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
1177 GET_PRIVATE_JACK_POINTER (_jack);
1178 const char ** ports;
1181 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
1185 for (i = 0; ports[i]; ++i) {
1186 if (strstr (ports[i], "Midi-Through")) {
1189 outs.push_back (ports[i]);
1195 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1197 GET_PRIVATE_JACK_POINTER_RET (_jack,"");
1198 const char ** ports;
1203 assert(type != DataType::NIL);
1205 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag)) == 0) {
1209 for (i = 0, idx = 0; idx < n && ports[i]; ++i) {
1210 if (!strstr (ports[i], "Midi-Through")) {
1219 free ((const char **) ports);
1225 AudioEngine::update_total_latency (const Port& port)
1227 port.recompute_total_latency ();
1231 AudioEngine::transport_stop ()
1233 GET_PRIVATE_JACK_POINTER (_jack);
1234 jack_transport_stop (_priv_jack);
1238 AudioEngine::transport_start ()
1240 GET_PRIVATE_JACK_POINTER (_jack);
1241 jack_transport_start (_priv_jack);
1245 AudioEngine::transport_locate (nframes_t where)
1247 GET_PRIVATE_JACK_POINTER (_jack);
1248 // cerr << "tell JACK to locate to " << where << endl;
1249 jack_transport_locate (_priv_jack, where);
1252 AudioEngine::TransportState
1253 AudioEngine::transport_state ()
1255 GET_PRIVATE_JACK_POINTER_RET (_jack, ((TransportState) JackTransportStopped));
1256 jack_position_t pos;
1257 return (TransportState) jack_transport_query (_priv_jack, &pos);
1261 AudioEngine::reset_timebase ()
1263 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1265 if (_session->config.get_jack_time_master()) {
1266 return jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1268 return jack_release_timebase (_jack);
1275 AudioEngine::freewheel (bool onoff)
1277 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1279 if (onoff != _freewheeling) {
1280 return jack_set_freewheel (_priv_jack, onoff);
1283 /* already doing what has been asked for */
1289 AudioEngine::remove_all_ports ()
1291 /* process lock MUST be held */
1294 RCUWriter<Ports> writer (ports);
1295 boost::shared_ptr<Ports> ps = writer.get_copy ();
1297 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
1304 /* clear dead wood list too */
1310 AudioEngine::connect_to_jack (string client_name, string session_uuid)
1312 jack_options_t options = JackNullOption;
1313 jack_status_t status;
1314 const char *server_name = NULL;
1316 jack_client_name = client_name; /* might be reset below */
1317 #ifdef HAVE_JACK_SESSION
1318 if (! session_uuid.empty())
1319 _jack = jack_client_open (jack_client_name.c_str(), JackSessionID, &status, session_uuid.c_str());
1322 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1324 if (_jack == NULL) {
1325 // error message is not useful here
1329 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1331 if (status & JackNameNotUnique) {
1332 jack_client_name = jack_get_client_name (_priv_jack);
1339 AudioEngine::disconnect_from_jack ()
1341 GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
1344 stop_metering_thread ();
1348 Glib::Mutex::Lock lm (_process_lock);
1349 jack_client_close (_priv_jack);
1355 _raw_buffer_sizes.clear();
1359 Stopped(); /* EMIT SIGNAL */
1360 MIDI::JACK_MidiPort::JackHalted (); /* EMIT SIGNAL */
1367 AudioEngine::reconnect_to_jack ()
1370 disconnect_from_jack ();
1371 /* XXX give jackd a chance */
1372 Glib::usleep (250000);
1375 if (connect_to_jack (jack_client_name, "")) {
1376 error << _("failed to connect to JACK") << endmsg;
1382 boost::shared_ptr<Ports> p = ports.reader ();
1384 for (i = p->begin(); i != p->end(); ++i) {
1385 if ((*i)->reestablish ()) {
1390 if (i != p->end()) {
1392 remove_all_ports ();
1396 GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
1399 _session->reset_jack_connection (_priv_jack);
1400 jack_bufsize_callback (jack_get_buffer_size (_priv_jack));
1401 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
1404 last_monitor_check = 0;
1406 jack_on_shutdown (_priv_jack, halted, this);
1407 jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
1408 jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
1409 // jack_set_process_callback (_priv_jack, _process_callback, this);
1410 jack_set_process_thread (_priv_jack, _process_thread, this);
1411 jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
1412 jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
1413 jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
1414 #ifdef HAVE_JACK_SESSION
1415 if( jack_set_session_callback )
1416 jack_set_session_callback (_priv_jack, _session_callback, this);
1418 jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
1419 jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
1421 if (_session && _session->config.get_jack_time_master()) {
1422 jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1425 if (jack_activate (_priv_jack) == 0) {
1432 /* re-establish connections */
1434 for (i = p->begin(); i != p->end(); ++i) {
1438 Running (); /* EMIT SIGNAL*/
1440 start_metering_thread ();
1446 AudioEngine::request_buffer_size (nframes_t nframes)
1448 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1450 if (nframes == jack_get_buffer_size (_priv_jack)) {
1454 return jack_set_buffer_size (_priv_jack, nframes);
1458 AudioEngine::update_total_latencies ()
1460 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1461 GET_PRIVATE_JACK_POINTER (_jack);
1462 jack_recompute_total_latencies (_priv_jack);
1467 AudioEngine::make_port_name_relative (string portname)
1469 string::size_type len;
1470 string::size_type n;
1472 len = portname.length();
1474 for (n = 0; n < len; ++n) {
1475 if (portname[n] == ':') {
1480 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1481 return portname.substr (n+1);
1488 AudioEngine::make_port_name_non_relative (string portname)
1492 if (portname.find_first_of (':') != string::npos) {
1496 str = jack_client_name;
1504 AudioEngine::is_realtime () const
1506 GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1507 return jack_is_realtime (_priv_jack);
1511 AudioEngine::create_process_thread (boost::function<void()> f, size_t stacksize)
1513 GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
1515 ThreadData* td = new ThreadData (this, f, stacksize);
1517 if (jack_client_create_thread (_priv_jack, &thread, jack_client_real_time_priority (_priv_jack),
1518 jack_is_realtime (_priv_jack), _start_process_thread, td)) {
1526 AudioEngine::_start_process_thread (void* arg)
1528 ThreadData* td = reinterpret_cast<ThreadData*> (arg);
1529 boost::function<void()> f = td->f;