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 <glibmm/pattern.h>
29 #include <glibmm/module.h>
32 #include "pbd/file_utils.h"
33 #include "pbd/pthread_utils.h"
34 #include "pbd/stacktrace.h"
35 #include "pbd/unknown_type.h"
37 #include <jack/weakjack.h>
39 #include "midi++/port.h"
40 #include "midi++/jack_midi_port.h"
41 #include "midi++/mmc.h"
42 #include "midi++/manager.h"
44 #include "ardour/audio_port.h"
45 #include "ardour/audio_backend.h"
46 #include "ardour/audioengine.h"
47 #include "ardour/backend_search_path.h"
48 #include "ardour/buffer.h"
49 #include "ardour/cycle_timer.h"
50 #include "ardour/internal_send.h"
51 #include "ardour/meter.h"
52 #include "ardour/midi_port.h"
53 #include "ardour/port.h"
54 #include "ardour/process_thread.h"
55 #include "ardour/session.h"
60 using namespace ARDOUR;
63 gint AudioEngine::m_meter_exit;
64 AudioEngine* AudioEngine::_instance = 0;
66 AudioEngine::AudioEngine (const std::string& bcn, const std::string& bsu)
68 , session_remove_pending (false)
69 , session_removal_countdown (-1)
70 , monitor_check_interval (INT32_MAX)
71 , last_monitor_check (0)
72 , _processed_frames (0)
73 , _freewheeling (false)
74 , _pre_freewheel_mmc_enabled (false)
75 , _usecs_per_cycle (0)
76 , port_remove_in_progress (false)
79 , backend_client_name (bcn)
80 , backend_session_uuid (bsu)
82 g_atomic_int_set (&m_meter_exit, 0);
85 AudioEngine::~AudioEngine ()
89 config_connection.disconnect ();
92 Glib::Threads::Mutex::Lock tm (_process_lock);
93 session_removed.signal ();
94 stop_metering_thread ();
99 AudioEngine::create (const std::string& bcn, const std::string& bsu)
104 return new AudioEngine (bcn, bsu);
108 AudioEngine::drop_backend ()
118 AudioEngine::set_backend (const std::string& name)
120 BackendMap::iterator b = _backends.find (name);
122 if (b == _backends.end()) {
128 _backend = b->second;
134 _thread_init_callback (void * /*arg*/)
136 /* make sure that anybody who needs to know about this thread
140 pthread_set_name (X_("audioengine"));
142 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
143 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
145 SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
147 MIDI::JackMIDIPort::set_process_thread (pthread_self());
153 AudioEngine::split_cycle (pframes_t offset)
155 /* caller must hold process lock */
157 Port::increment_global_port_buffer_offset (offset);
159 /* tell all Ports that we're going to start a new (split) cycle */
161 boost::shared_ptr<Ports> p = ports.reader();
163 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
164 i->second->cycle_split ();
169 AudioEngine::sample_rate_change (pframes_t nframes)
171 /* check for monitor input change every 1/10th of second */
173 monitor_check_interval = nframes / 10;
174 last_monitor_check = 0;
177 _session->set_frame_rate (nframes);
180 SampleRateChanged (nframes); /* EMIT SIGNAL */
186 AudioEngine::buffer_size_change (pframes_t bufsiz)
189 _session->set_block_size (bufsiz);
190 last_monitor_check = 0;
196 /** Method called by our ::process_thread when there is work to be done.
197 * @param nframes Number of frames to process.
200 AudioEngine::process_callback (pframes_t nframes)
202 Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
207 /// The number of frames that will have been processed when we've finished
208 pframes_t next_processed_frames;
210 /* handle wrap around of total frames counter */
212 if (max_framepos - _processed_frames < nframes) {
213 next_processed_frames = nframes - (max_framepos - _processed_frames);
215 next_processed_frames = _processed_frames + nframes;
219 /* return having done nothing */
220 _processed_frames = next_processed_frames;
224 if (session_remove_pending) {
226 /* perform the actual session removal */
228 if (session_removal_countdown < 0) {
230 /* fade out over 1 second */
231 session_removal_countdown = _frame_rate/2;
232 session_removal_gain = 1.0;
233 session_removal_gain_step = 1.0/session_removal_countdown;
235 } else if (session_removal_countdown > 0) {
237 /* we'll be fading audio out.
239 if this is the last time we do this as part
240 of session removal, do a MIDI panic now
241 to get MIDI stopped. This relies on the fact
242 that "immediate data" (aka "out of band data") from
243 MIDI tracks is *appended* after any other data,
244 so that it emerges after any outbound note ons, etc.
247 if (session_removal_countdown <= nframes) {
248 _session->midi_panic ();
254 session_removal_countdown = -1; // reset to "not in progress"
255 session_remove_pending = false;
256 session_removed.signal(); // wakes up thread that initiated session removal
262 if (!_freewheeling) {
263 MIDI::Manager::instance()->cycle_start(nframes);
264 MIDI::Manager::instance()->cycle_end();
267 _processed_frames = next_processed_frames;
272 /* tell all relevant objects that we're starting a new cycle */
274 InternalSend::CycleStart (nframes);
275 Port::set_global_port_buffer_offset (0);
276 Port::set_cycle_framecnt (nframes);
278 /* tell all Ports that we're starting a new cycle */
280 boost::shared_ptr<Ports> p = ports.reader();
282 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
283 i->second->cycle_start (nframes);
286 /* test if we are freewheeling and there are freewheel signals connected.
287 ardour should act normally even when freewheeling unless /it/ is
291 if (_freewheeling && !Freewheel.empty()) {
296 MIDI::Manager::instance()->cycle_start(nframes);
299 _session->process (nframes);
302 MIDI::Manager::instance()->cycle_end();
310 _processed_frames = next_processed_frames;
314 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
316 boost::shared_ptr<Ports> p = ports.reader();
318 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
322 if (i->second->last_monitor() != (x = i->second->monitoring_input ())) {
323 i->second->set_last_monitor (x);
324 /* XXX I think this is dangerous, due to
325 a likely mutex in the signal handlers ...
327 i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
330 last_monitor_check = next_processed_frames;
333 if (_session->silent()) {
335 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
337 if (i->second->sends_output()) {
338 i->second->get_buffer(nframes).silence(nframes);
343 if (session_remove_pending && session_removal_countdown) {
345 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
347 if (i->second->sends_output()) {
349 boost::shared_ptr<AudioPort> ap = boost::dynamic_pointer_cast<AudioPort> (i->second);
351 Sample* s = ap->engine_get_whole_audio_buffer ();
352 gain_t g = session_removal_gain;
354 for (pframes_t n = 0; n < nframes; ++n) {
356 g -= session_removal_gain_step;
362 if (session_removal_countdown > nframes) {
363 session_removal_countdown -= nframes;
365 session_removal_countdown = 0;
368 session_removal_gain -= (nframes * session_removal_gain_step);
373 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
374 i->second->cycle_end (nframes);
377 _processed_frames = next_processed_frames;
386 AudioEngine::stop_metering_thread ()
388 if (m_meter_thread) {
389 g_atomic_int_set (&m_meter_exit, 1);
390 m_meter_thread->join ();
396 AudioEngine::start_metering_thread ()
398 if (m_meter_thread == 0) {
399 g_atomic_int_set (&m_meter_exit, 0);
400 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
405 AudioEngine::meter_thread ()
407 pthread_set_name (X_("meter"));
410 Glib::usleep (10000); /* 1/100th sec interval */
411 if (g_atomic_int_get(&m_meter_exit)) {
419 AudioEngine::set_session (Session *s)
421 Glib::Threads::Mutex::Lock pl (_process_lock);
423 SessionHandlePtr::set_session (s);
427 start_metering_thread ();
429 pframes_t blocksize = _backend->buffer_size ();
431 /* page in as much of the session process code as we
432 can before we really start running.
435 boost::shared_ptr<Ports> p = ports.reader();
437 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
438 i->second->cycle_start (blocksize);
441 _session->process (blocksize);
442 _session->process (blocksize);
443 _session->process (blocksize);
444 _session->process (blocksize);
445 _session->process (blocksize);
446 _session->process (blocksize);
447 _session->process (blocksize);
448 _session->process (blocksize);
450 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
451 i->second->cycle_end (blocksize);
457 AudioEngine::remove_session ()
459 Glib::Threads::Mutex::Lock lm (_process_lock);
463 stop_metering_thread ();
466 session_remove_pending = true;
467 session_removed.wait(_process_lock);
471 SessionHandlePtr::set_session (0);
481 /* called from a signal handler for SIGPIPE */
483 stop_metering_thread ();
491 AudioEngine::reset_timebase ()
494 if (_session->config.get_jack_time_master()) {
495 _backend->set_time_master (true);
497 _backend->set_time_master (false);
505 AudioEngine::destroy ()
512 AudioEngine::discover_backends ()
514 vector<std::string> backend_modules;
515 AudioBackend* backend;
519 Glib::PatternSpec so_extension_pattern("*.so");
520 Glib::PatternSpec dylib_extension_pattern("*.dylib");
522 find_matching_files_in_search_path (backend_search_path (),
523 so_extension_pattern, backend_modules);
525 find_matching_files_in_search_path (backend_search_path (),
526 dylib_extension_pattern, backend_modules);
528 DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1"), backend_search_path().to_string()));
530 for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
531 if ((backend = backend_discover (*i)) != 0) {
532 _backends.insert (make_pair (backend->name(), backend));
536 return _backends.size();
540 AudioEngine::backend_discover (const string& path)
542 Glib::Module* module = new Glib::Module(path);
543 AudioBackend* (*dfunc)(void);
547 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
548 Glib::Module::get_last_error()) << endmsg;
553 if (!module->get_symbol("backend_factory", func)) {
554 error << string_compose(_("AudioEngine: module \"%1\" has no factory function."), path) << endmsg;
555 error << Glib::Module::get_last_error() << endmsg;
560 dfunc = (AudioBackend* (*)(void))func;
561 AudioBackend* backend = dfunc();
566 /* BACKEND PROXY WRAPPERS */
569 AudioEngine::start ()
578 BootMessage (_("Connect session to engine"));
579 _session->set_frame_rate (_backend->sample_rate());
582 _processed_frames = 0;
583 last_monitor_check = 0;
585 if (_backend->start() == 0) {
588 last_monitor_check = 0;
590 if (_session && _session->config.get_jack_time_master()) {
591 _backend->set_time_master (true);
594 Running(); /* EMIT SIGNAL */
596 /* should report error? */
600 return _running ? 0 : -1;
610 Glib::Threads::Mutex::Lock lm (_process_lock);
612 if (_backend->stop () == 0) {
614 stop_metering_thread ();
616 Stopped (); /* EMIT SIGNAL */
625 AudioEngine::pause ()
631 if (_backend->pause () == 0) {
633 Stopped(); /* EMIT SIGNAL */
641 AudioEngine::freewheel (bool start_stop)
647 /* _freewheeling will be set when first Freewheel signal occurs */
649 return _backend->freewheel (start_stop);
653 AudioEngine::get_cpu_load() const
658 return _backend->cpu_load ();
662 AudioEngine::is_realtime() const
668 return _backend->is_realtime();
672 AudioEngine::transport_start ()
677 return _backend->transport_start ();
681 AudioEngine::transport_stop ()
686 return _backend->transport_stop ();
690 AudioEngine::transport_state ()
693 return TransportStopped;
695 return _backend->transport_state ();
699 AudioEngine::transport_locate (framepos_t pos)
704 return _backend->transport_locate (pos);
708 AudioEngine::transport_frame()
713 return _backend->transport_frame ();
717 AudioEngine::sample_rate () const
722 return _backend->sample_rate ();
726 AudioEngine::samples_per_cycle () const
731 return _backend->buffer_size ();
735 AudioEngine::usecs_per_cycle () const
740 return _backend->usecs_per_cycle ();
744 AudioEngine::raw_buffer_size (DataType t)
749 return _backend->raw_buffer_size (t);
753 AudioEngine::sample_time ()
758 return _backend->sample_time ();
762 AudioEngine::sample_time_at_cycle_start ()
767 return _backend->sample_time_at_cycle_start ();
771 AudioEngine::samples_since_cycle_start ()
776 return _backend->samples_since_cycle_start ();
780 AudioEngine::get_sync_offset (pframes_t& offset) const
785 return _backend->get_sync_offset (offset);
789 AudioEngine::create_process_thread (boost::function<void()> func, pthread_t* thr, size_t stacksize)
794 return _backend->create_process_thread (func, thr, stacksize);
799 AudioEngine::thread_init_callback (void* arg)
801 /* make sure that anybody who needs to know about this thread
805 pthread_set_name (X_("audioengine"));
807 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
808 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
810 SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
812 MIDI::JackMIDIPort::set_process_thread (pthread_self());
815 AudioEngine* ae = static_cast<AudioEngine*> (arg);
816 /* the special thread created/managed by the backend */
817 ae->_main_thread = new ProcessThread;
823 AudioEngine::timebase_callback (TransportState state, pframes_t nframes, jack_position_t pos, int new_position)
825 if (_session && _session->synced_to_jack()) {
826 // _session->timebase_callback (state, nframes, pos, new_position);
832 AudioEngine::sync_callback (TransportState state, framepos_t position)
835 return _session->jack_sync_callback (state, position);
841 AudioEngine::freewheel_callback (bool onoff)
844 _pre_freewheel_mmc_enabled = MIDI::Manager::instance()->mmc()->send_enabled ();
845 MIDI::Manager::instance()->mmc()->enable_send (false);
847 MIDI::Manager::instance()->mmc()->enable_send (_pre_freewheel_mmc_enabled);
852 AudioEngine::latency_callback (bool for_playback)
855 _session->update_latency (for_playback);
860 AudioEngine::halted_callback (const char* why)
862 stop_metering_thread ();
864 MIDI::JackMIDIPort::EngineHalted (); /* EMIT SIGNAL */
865 Halted (why); /* EMIT SIGNAL */