fe9c064efaf49275bc7f11e58a727f2ff343ef83
[ardour.git] / libs / ardour / audioengine.cc
1 /*
2     Copyright (C) 2002 Paul Davis 
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 <unistd.h>
21 #include <cerrno>
22 #include <vector>
23 #include <exception>
24 #include <stdexcept>
25 #include <sstream>
26
27 #include <glibmm/timer.h>
28 #include "pbd/pthread_utils.h"
29 #include "pbd/stacktrace.h"
30 #include "pbd/unknown_type.h"
31
32 #include "midi++/jack.h"
33
34 #include "ardour/audioengine.h"
35 #include "ardour/buffer.h"
36 #include "ardour/port.h"
37 #include "ardour/audio_port.h"
38 #include "ardour/midi_port.h"
39 #include "ardour/session.h"
40 #include "ardour/cycle_timer.h"
41 #include "ardour/utils.h"
42 #include "ardour/event_type_map.h"
43 #include "ardour/io.h"
44 #include "ardour/amp.h"
45 #include "ardour/port_set.h"
46 #include "ardour/buffer_set.h"
47
48 #include "ardour/timestamps.h"
49
50 #include "i18n.h"
51
52 using namespace std;
53 using namespace ARDOUR;
54 using namespace PBD;
55
56 gint AudioEngine::m_meter_exit;
57
58 AudioEngine::AudioEngine (string client_name) 
59         : ports (new Ports)
60 {
61         session = 0;
62         session_remove_pending = false;
63         _running = false;
64         _has_run = false;
65         last_monitor_check = 0;
66         monitor_check_interval = max_frames;
67         _processed_frames = 0;
68         _usecs_per_cycle = 0;
69         _jack = 0;
70         _frame_rate = 0;
71         _buffer_size = 0;
72         _freewheel_thread_registered = false;
73         _freewheeling = false;
74
75         m_meter_thread = 0;
76         g_atomic_int_set (&m_meter_exit, 0);
77
78         if (connect_to_jack (client_name)) {
79                 throw NoBackendAvailable ();
80         }
81
82         Port::set_engine (this);
83         
84         // Initialize parameter metadata (e.g. ranges)
85         Evoral::Parameter p(NullAutomation);
86         p = EventTypeMap::instance().new_parameter(NullAutomation);
87         p = EventTypeMap::instance().new_parameter(GainAutomation);
88         p = EventTypeMap::instance().new_parameter(PanAutomation);
89         p = EventTypeMap::instance().new_parameter(PluginAutomation);
90         p = EventTypeMap::instance().new_parameter(SoloAutomation);
91         p = EventTypeMap::instance().new_parameter(MuteAutomation);
92         p = EventTypeMap::instance().new_parameter(MidiCCAutomation);
93         p = EventTypeMap::instance().new_parameter(MidiPgmChangeAutomation);
94         p = EventTypeMap::instance().new_parameter(MidiPitchBenderAutomation);
95         p = EventTypeMap::instance().new_parameter(MidiChannelPressureAutomation);
96         p = EventTypeMap::instance().new_parameter(FadeInAutomation);
97         p = EventTypeMap::instance().new_parameter(FadeOutAutomation);
98         p = EventTypeMap::instance().new_parameter(EnvelopeAutomation);
99         p = EventTypeMap::instance().new_parameter(MidiCCAutomation);
100 }
101
102 AudioEngine::~AudioEngine ()
103 {
104         {
105                 Glib::Mutex::Lock tm (_process_lock);
106                 session_removed.signal ();
107                 
108                 if (_running) {
109                         jack_client_close (_jack);
110                         _jack = 0;
111                 }
112                 
113                 stop_metering_thread ();
114         }
115 }
116
117 jack_client_t*
118 AudioEngine::jack() const
119 {
120         return _jack;
121 }
122
123 void
124 _thread_init_callback (void *arg)
125 {
126         /* make sure that anybody who needs to know about this thread
127            knows about it.
128         */
129
130         PBD::notify_gui_about_thread_creation (pthread_self(), X_("Audioengine"), 4096);
131 #ifdef WITH_JACK_MIDI
132         MIDI::JACK_MidiPort::set_process_thread (pthread_self());
133 #endif // WITH_JACK_MIDI
134 }
135
136 int
137 AudioEngine::start ()
138 {
139         if (!_jack) {
140                 error << _("AudioEngine::start() called while disconnected from JACK") << endmsg;
141                 return -1;
142         }
143
144         if (!_running) {
145
146                 nframes_t blocksize = jack_get_buffer_size (_jack);
147                 
148                 if (session) {
149                         BootMessage (_("Connect session to engine"));
150
151                         session->set_block_size (blocksize);
152                         session->set_frame_rate (jack_get_sample_rate (_jack));
153                         
154                         /* page in as much of the session process code as we
155                            can before we really start running.
156                         */
157
158                         session->process (blocksize);
159                         session->process (blocksize);
160                         session->process (blocksize);
161                         session->process (blocksize);
162                         session->process (blocksize);
163                         session->process (blocksize);
164                         session->process (blocksize);
165                         session->process (blocksize);
166                 }
167
168                 _processed_frames = 0;
169                 last_monitor_check = 0;
170
171                 jack_on_shutdown (_jack, halted, this);
172                 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
173                 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
174                 jack_set_process_callback (_jack, _process_callback, this);
175                 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
176                 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
177                 jack_set_xrun_callback (_jack, _xrun_callback, this);
178                 jack_set_sync_callback (_jack, _jack_sync_callback, this);
179                 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
180
181                 if (session && session->config.get_jack_time_master()) {
182                         jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
183                 }
184
185                 if (jack_activate (_jack) == 0) {
186                         _running = true;
187                         _has_run = true;
188                         Running(); /* EMIT SIGNAL */
189                 } else {
190                         // error << _("cannot activate JACK client") << endmsg;
191                 }
192
193                 start_metering_thread();
194
195                 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
196         }
197
198         return _running ? 0 : -1;
199 }
200
201 int
202 AudioEngine::stop (bool forever)
203 {
204         if (_jack) {
205                 if (forever) {
206                         disconnect_from_jack ();
207                 } else {
208                         jack_deactivate (_jack);
209                         Stopped(); /* EMIT SIGNAL */
210                 }
211         }
212
213         return _running ? -1 : 0;
214 }
215
216
217 bool
218 AudioEngine::get_sync_offset (nframes_t& offset) const
219 {
220
221 #ifdef HAVE_JACK_VIDEO_SUPPORT
222
223         jack_position_t pos;
224         
225         if (_jack) {
226                 (void) jack_transport_query (_jack, &pos);
227                 
228                 if (pos.valid & JackVideoFrameOffset) {
229                         offset = pos.video_offset;
230                         return true;
231                 }
232         }
233
234 #endif
235
236         return false;
237 }
238
239 void
240 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
241                                       jack_position_t* pos, int new_position, void *arg)
242 {
243         static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
244 }
245
246 void
247 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
248                                      jack_position_t* pos, int new_position)
249 {
250         if (_jack && session && session->synced_to_jack()) {
251                 session->jack_timebase_callback (state, nframes, pos, new_position);
252         }
253 }
254
255 int
256 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
257 {
258         return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
259 }
260
261 int
262 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
263 {
264         if (_jack && session) {
265                 return session->jack_sync_callback (state, pos);
266         }
267
268         return true;
269 }
270
271 int
272 AudioEngine::_xrun_callback (void *arg)
273 {
274         AudioEngine* ae = static_cast<AudioEngine*> (arg);
275         if (ae->connected()) {
276                 ae->Xrun (); /* EMIT SIGNAL */
277         }
278         return 0;
279 }
280
281 int
282 AudioEngine::_graph_order_callback (void *arg)
283 {
284         AudioEngine* ae = static_cast<AudioEngine*> (arg);
285         if (ae->connected()) {
286                 ae->GraphReordered (); /* EMIT SIGNAL */
287         }
288         return 0;
289 }
290
291 /** Wrapped which is called by JACK as its process callback.  It is just
292  * here to get us back into C++ land by calling AudioEngine::process_callback()
293  * @param nframes Number of frames passed by JACK.
294  * @param arg User argument passed by JACK, which will be the AudioEngine*.
295  */
296 int
297 AudioEngine::_process_callback (nframes_t nframes, void *arg)
298 {
299         return static_cast<AudioEngine *> (arg)->process_callback (nframes);
300 }
301
302 void
303 AudioEngine::_freewheel_callback (int onoff, void *arg)
304 {
305         static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
306 }
307
308 void
309 AudioEngine::split_cycle (nframes_t offset)
310 {
311         /* caller must hold process lock */
312
313         Port::increment_port_offset (offset);
314
315         /* tell all Ports that we're going to start a new (split) cycle */
316
317         boost::shared_ptr<Ports> p = ports.reader();
318
319         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
320                 (*i)->cycle_split ();
321         }
322 }
323
324 /** Method called by JACK (via _process_callback) which says that there
325  * is work to be done.
326  * @param nframes Number of frames to process.
327  */
328 int
329 AudioEngine::process_callback (nframes_t nframes)
330 {
331         // CycleTimer ct ("AudioEngine::process");
332
333         Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
334
335         /// The number of frames that will have been processed when we've finished
336         nframes_t next_processed_frames;
337         
338         /* handle wrap around of total frames counter */
339
340         if (max_frames - _processed_frames < nframes) {
341                 next_processed_frames = nframes - (max_frames - _processed_frames);
342         } else {
343                 next_processed_frames = _processed_frames + nframes;
344         }
345
346         if (!tm.locked() || session == 0) {
347                 /* return having done nothing */
348                 _processed_frames = next_processed_frames;
349                 return 0;
350         }
351
352         if (session_remove_pending) {
353                 /* perform the actual session removal */
354                 session = 0;
355                 session_remove_pending = false;
356                 session_removed.signal();
357                 _processed_frames = next_processed_frames;
358                 return 0;
359         }
360
361         /* tell all IO objects that we're starting a new cycle */
362
363         IO::CycleStart (nframes);
364         Port::set_port_offset (0);
365
366         /* tell all Ports that we're starting a new cycle */
367
368         boost::shared_ptr<Ports> p = ports.reader();
369
370         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
371                 (*i)->cycle_start (nframes);
372         }
373
374         if (_freewheeling) {
375                 /* emit the Freewheel signal and stop freewheeling in the event of trouble */
376                 if (Freewheel (nframes)) {
377                         jack_set_freewheel (_jack, false);
378                 }
379
380         } else {
381                 if (session) {
382                         session->process (nframes);
383                 }
384         }
385         
386         if (_freewheeling) {
387                 return 0;
388         }
389
390         if (!_running) {
391                 _processed_frames = next_processed_frames;
392                 return 0;
393         }
394
395         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
396
397                 boost::shared_ptr<Ports> p = ports.reader();
398
399                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
400                         
401                         Port *port = (*i);
402                         bool x;
403                         
404                         if (port->_last_monitor != (x = port->monitoring_input ())) {
405                                 port->_last_monitor = x;
406                                 /* XXX I think this is dangerous, due to 
407                                    a likely mutex in the signal handlers ...
408                                 */
409                                  port->MonitorInputChanged (x); /* EMIT SIGNAL */
410                         }
411                 }
412                 last_monitor_check = next_processed_frames;
413         }
414
415         if (session->silent()) {
416
417                 boost::shared_ptr<Ports> p = ports.reader();
418
419                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
420                         
421                         Port *port = (*i);
422                         
423                         if (port->sends_output()) {
424                                 port->get_buffer(nframes).silence(nframes);
425                         }
426                 }
427         } 
428
429         // Finalize ports
430
431         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
432                 (*i)->cycle_end (nframes);
433         }
434
435         _processed_frames = next_processed_frames;
436         return 0;
437 }
438
439 int
440 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
441 {
442         return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
443 }
444
445 int
446 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
447 {
448         _frame_rate = nframes;
449         _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
450         
451         /* check for monitor input change every 1/10th of second */
452
453         monitor_check_interval = nframes / 10;
454         last_monitor_check = 0;
455         
456         if (session) {
457                 session->set_frame_rate (nframes);
458         }
459
460         SampleRateChanged (nframes); /* EMIT SIGNAL */
461
462         return 0;
463 }
464
465 int
466 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
467 {
468         return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
469 }
470
471 int
472 AudioEngine::jack_bufsize_callback (nframes_t nframes)
473 {
474         _buffer_size = nframes;
475         _raw_buffer_sizes[DataType::AUDIO] = nframes * sizeof(float);
476         cout << "FIXME: Assuming maximum MIDI buffer size " << nframes * 4 << "bytes" << endl;
477         _raw_buffer_sizes[DataType::MIDI] = nframes * 4;
478         _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
479         last_monitor_check = 0;
480
481         boost::shared_ptr<Ports> p = ports.reader();
482
483         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
484                 (*i)->reset();
485         }
486
487         if (session) {
488                 session->set_block_size (_buffer_size);
489         }
490
491         return 0;
492 }
493
494 void
495 AudioEngine::stop_metering_thread ()
496 {
497         if (m_meter_thread) {
498                 g_atomic_int_set (&m_meter_exit, 1);
499                 m_meter_thread->join ();
500                 m_meter_thread = 0;
501         }
502 }
503
504 void
505 AudioEngine::start_metering_thread ()
506 {
507         if (m_meter_thread == 0) {
508                 g_atomic_int_set (&m_meter_exit, 0);
509                 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
510                                                        500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
511         }
512 }
513
514 void
515 AudioEngine::meter_thread ()
516 {
517         while (true) {
518                 Glib::usleep (10000); /* 1/100th sec interval */
519                 if (g_atomic_int_get(&m_meter_exit)) {
520                         break;
521                 }
522                 IO::update_meters ();
523         }
524 }
525
526 void 
527 AudioEngine::set_session (Session *s)
528 {
529         Glib::Mutex::Lock pl (_process_lock);
530
531         if (!session) {
532
533                 session = s;
534
535                 nframes_t blocksize = jack_get_buffer_size (_jack);
536                 
537                 /* page in as much of the session process code as we
538                    can before we really start running.
539                 */
540                 
541                 boost::shared_ptr<Ports> p = ports.reader();
542
543                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
544                         (*i)->cycle_start (blocksize);
545                 }
546
547                 s->process (blocksize);
548                 s->process (blocksize);
549                 s->process (blocksize);
550                 s->process (blocksize);
551                 s->process (blocksize);
552                 s->process (blocksize);
553                 s->process (blocksize);
554                 s->process (blocksize);
555
556                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
557                         (*i)->cycle_end (blocksize);
558                 }
559         }
560 }
561
562 void 
563 AudioEngine::remove_session ()
564 {
565         Glib::Mutex::Lock lm (_process_lock);
566
567         if (_running) {
568
569                 if (session) {
570                         session_remove_pending = true;
571                         session_removed.wait(_process_lock);
572                 }
573
574         } else {
575                 session = 0;
576         }
577         
578         //FIXME: Preliminary bugfix for  http://tracker.ardour.org/view.php?id=1985
579         //remove_all_ports ();
580 }
581
582 void
583 AudioEngine::port_registration_failure (const std::string& portname)
584 {
585         string full_portname = jack_client_name;
586         full_portname += ':';
587         full_portname += portname;
588         
589         
590         jack_port_t* p = jack_port_by_name (_jack, full_portname.c_str());
591         string reason;
592         
593         if (p) {
594                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
595         } else {
596                 reason = _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.");
597         }
598         
599         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
600 }       
601
602 Port *
603 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
604 {
605         Port* newport = 0;
606
607         try {
608                 if (dtype == DataType::AUDIO) {
609                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
610                 } else if (dtype == DataType::MIDI) {
611                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
612                 } else {
613                         throw PortRegistrationFailure("unable to create port (unknown type)");
614                 }
615                 
616                 size_t& old_buffer_size  = _raw_buffer_sizes[newport->type()];
617                 size_t  port_buffer_size = newport->raw_buffer_size(0);
618                 if (port_buffer_size > old_buffer_size) {
619                         old_buffer_size = port_buffer_size;
620                 }
621
622                 RCUWriter<Ports> writer (ports);
623                 boost::shared_ptr<Ports> ps = writer.get_copy ();
624                 ps->insert (ps->begin(), newport);
625
626                 /* writer goes out of scope, forces update */
627
628                 return newport;
629         }
630
631         catch (PortRegistrationFailure& err) {
632                 throw err;
633         } catch (std::exception& e) {
634                 throw PortRegistrationFailure(string_compose(
635                                 _("unable to create port: %1"), e.what()).c_str());
636         } catch (...) {
637                 throw PortRegistrationFailure("unable to create port (unknown error)");
638         }
639 }
640
641 Port *
642 AudioEngine::register_input_port (DataType type, const string& portname)
643 {
644         return register_port (type, portname, true);
645 }
646
647 Port *
648 AudioEngine::register_output_port (DataType type, const string& portname)
649 {
650         return register_port (type, portname, false);
651 }
652
653 int
654 AudioEngine::unregister_port (Port& port)
655 {
656         /* caller must hold process lock */
657
658         if (!_running) { 
659                 /* probably happening when the engine has been halted by JACK,
660                    in which case, there is nothing we can do here.
661                    */
662                 return 0;
663         }
664
665         {
666                 RCUWriter<Ports> writer (ports);
667                 boost::shared_ptr<Ports> ps = writer.get_copy ();
668                 
669                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
670                         if ((*i) == &port) {
671                                 delete *i;
672                                 ps->erase (i);
673                                 break;
674                         }
675                 }
676                 
677                 /* writer goes out of scope, forces update */
678         }
679                 
680         remove_connections_for (port);
681
682         return 0;
683 }
684
685 int 
686 AudioEngine::connect (const string& source, const string& destination)
687 {
688         /* caller must hold process lock */
689         
690         int ret;
691
692         if (!_running) {
693                 if (!_has_run) {
694                         fatal << _("connect called before engine was started") << endmsg;
695                         /*NOTREACHED*/
696                 } else {
697                         return -1;
698                 }
699         }
700
701         string s = make_port_name_non_relative (source);
702         string d = make_port_name_non_relative (destination);
703
704         Port* src = get_port_by_name_locked (s);
705         Port* dst = get_port_by_name_locked (d);
706
707                 if (src) {
708                         ret = src->connect (d);
709         } else if (dst) {
710                         ret = dst->connect (s);
711         } else {
712                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
713                 ret = -1;
714         }
715         
716         if (ret > 0) {
717                 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"), 
718                                         source, s, destination, d) 
719                       << endmsg;
720         } else if (ret < 0) {
721                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"), 
722                                         source, s, destination, d) 
723                       << endmsg;
724         }
725
726         return ret;
727 }
728
729 int 
730 AudioEngine::disconnect (const string& source, const string& destination)
731 {
732         /* caller must hold process lock */
733         
734         int ret;
735
736         if (!_running) {
737                 if (!_has_run) {
738                         fatal << _("disconnect called before engine was started") << endmsg;
739                         /*NOTREACHED*/
740                 } else {
741                         return -1;
742                 }
743         }
744         
745         string s = make_port_name_non_relative (source);
746         string d = make_port_name_non_relative (destination);
747
748         Port* src = get_port_by_name_locked (s);
749         Port* dst = get_port_by_name_locked (d);
750
751         if (src) {
752                         ret = src->disconnect (d);
753         } else if (dst) {
754                         ret = dst->disconnect (s);
755         } else {
756                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
757                 ret = -1;
758         }
759         return ret;
760 }
761
762 int
763 AudioEngine::disconnect (Port& port)
764 {
765         if (!_running) {
766                 if (!_has_run) {
767                         fatal << _("disconnect called before engine was started") << endmsg;
768                         /*NOTREACHED*/
769                 } else {
770                         return -1;
771                 }
772         }
773
774         return port.disconnect_all ();
775 }
776
777 ARDOUR::nframes_t
778 AudioEngine::frame_rate ()
779 {
780         if (_jack) {
781                 if (_frame_rate == 0) {
782                         return (_frame_rate = jack_get_sample_rate (_jack));
783                 } else {
784                         return _frame_rate;
785                 }
786         } else {
787                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
788                       << endmsg;
789                 /*NOTREACHED*/
790                 return 0;
791         }
792 }
793
794 size_t
795 AudioEngine::raw_buffer_size (DataType t)
796 {
797         std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
798         return (s != _raw_buffer_sizes.end()) ? s->second : 0;
799 }
800
801 ARDOUR::nframes_t
802 AudioEngine::frames_per_cycle ()
803 {
804         if (_jack) {
805                 if (_buffer_size == 0) {
806                         return (_buffer_size = jack_get_buffer_size (_jack));
807                 } else {
808                         return _buffer_size;
809                 }
810         } else {
811                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
812                       << endmsg;
813                 /*NOTREACHED*/
814                 return 0;
815         }
816 }
817
818 /** @param name Full name of port (including prefix:)
819  *  @return Corresponding Port*, or 0.  This object remains the property of the AudioEngine
820  *  so must not be deleted.
821  */
822 Port *
823 AudioEngine::get_port_by_name (const string& portname)
824 {
825         assert (portname.find_first_of (':') != string::npos);
826         
827         Glib::Mutex::Lock lm (_process_lock);
828         return get_port_by_name_locked (portname);
829 }
830
831 Port *
832 AudioEngine::get_port_by_name_locked (const string& portname)
833 {
834         /* caller must hold process lock */
835
836         if (!_running) {
837                 if (!_has_run) {
838                         fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
839                         /*NOTREACHED*/
840                 } else {
841                         return 0;
842                 }
843         }
844
845         if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
846                 /* not an ardour: port */
847                 return 0;
848         }
849
850         std::string const rel = make_port_name_relative (portname);
851
852         boost::shared_ptr<Ports> pr = ports.reader();
853
854         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
855                 if (rel == (*i)->name()) {
856                         return *i;
857                 }
858         }
859
860         return 0;
861 }
862
863
864
865
866
867 const char **
868 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
869 {
870         if (!_running) {
871                 if (!_has_run) {
872                         fatal << _("get_ports called before engine was started") << endmsg;
873                         /*NOTREACHED*/
874                 } else {
875                         return 0;
876                 }
877         }
878         return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
879 }
880
881 void
882 AudioEngine::halted (void *arg)
883 {
884         AudioEngine* ae = static_cast<AudioEngine *> (arg);
885         bool was_running = ae->_running;
886
887         ae->stop_metering_thread ();
888
889         ae->_running = false;
890         ae->_buffer_size = 0;
891         ae->_frame_rate = 0;
892
893         if (was_running) {
894                 ae->Halted(); /* EMIT SIGNAL */
895         }
896 }
897
898 bool
899 AudioEngine::can_request_hardware_monitoring () 
900 {
901         const char ** ports;
902
903         if (!_jack) {
904                 return 0;
905         }
906
907         if ((ports = jack_get_ports (_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
908                 return false;
909         }
910
911         free (ports);
912
913         return true;
914 }
915
916
917 uint32_t
918 AudioEngine::n_physical_outputs (DataType type) const
919 {
920         const char ** ports;
921         uint32_t i = 0;
922
923         if (!_jack) {
924                 return 0;
925         }
926
927         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
928                 return 0;
929         }
930
931         for (i = 0; ports[i]; ++i) {}
932         free (ports);
933
934         return i;
935 }
936
937 uint32_t
938 AudioEngine::n_physical_inputs (DataType type) const
939 {
940         const char ** ports;
941         uint32_t i = 0;
942         
943         if (!_jack) {
944                 return 0;
945         }
946         
947         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
948                 return 0;
949         }
950
951         if (ports) {
952                 for (i = 0; ports[i]; ++i) {}
953                 free (ports);
954         }
955         return i;
956 }
957
958 void
959 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
960 {
961         const char ** ports;
962         uint32_t i = 0;
963         
964         if (!_jack) {
965                 return;
966         }
967         
968         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
969                 return;
970         }
971
972         if (ports) {
973                 for (i = 0; ports[i]; ++i) {
974                         ins.push_back (ports[i]);
975                 }
976                 free (ports);
977         }
978 }
979
980 void
981 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
982 {
983         const char ** ports;
984         uint32_t i = 0;
985         
986         if (!_jack) {
987                 return;
988         }
989         
990         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
991                 return;
992         }
993
994         if (ports) {
995                 for (i = 0; ports[i]; ++i) {
996                         outs.push_back (ports[i]);
997                 }
998                 free (ports);
999         }
1000 }
1001
1002 string
1003 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1004 {
1005         const char ** ports;
1006         uint32_t i;
1007         string ret;
1008
1009         assert(type != DataType::NIL);
1010
1011         if (!_running || !_jack) {
1012                 if (!_has_run) {
1013                         fatal << _("get_nth_physical called before engine was started") << endmsg;
1014                         /*NOTREACHED*/
1015                 } else {
1016                         return "";
1017                 }
1018         }
1019
1020         ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
1021         
1022         if (ports == 0) {
1023                 return "";
1024         }
1025
1026         for (i = 0; i < n && ports[i]; ++i) {}
1027
1028         if (ports[i]) {
1029                 ret = ports[i];
1030         }
1031
1032         free ((char *) ports);
1033
1034         return ret;
1035 }
1036
1037 void
1038 AudioEngine::update_total_latency (const Port& port)
1039 {
1040         if (!_jack) {
1041                 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
1042                 /*NOTREACHED*/
1043         }
1044
1045         if (!_running) {
1046                 if (!_has_run) {
1047                         fatal << _("update_total_latency() called before engine was started") << endmsg;
1048                         /*NOTREACHED*/
1049                 } 
1050         }
1051
1052         port.recompute_total_latency ();
1053 }
1054
1055 void
1056 AudioEngine::transport_stop ()
1057 {
1058         if (_jack) {
1059                 jack_transport_stop (_jack);
1060         }
1061 }
1062
1063 void
1064 AudioEngine::transport_start ()
1065 {
1066         if (_jack) {
1067                 jack_transport_start (_jack);
1068         }
1069 }
1070
1071 void
1072 AudioEngine::transport_locate (nframes_t where)
1073 {
1074         // cerr << "tell JACK to locate to " << where << endl;
1075         if (_jack) {
1076                 jack_transport_locate (_jack, where);
1077         }
1078 }
1079
1080 AudioEngine::TransportState
1081 AudioEngine::transport_state ()
1082 {
1083         if (_jack) {
1084                 jack_position_t pos;
1085                 return (TransportState) jack_transport_query (_jack, &pos);
1086         } else {
1087                 return (TransportState) JackTransportStopped;
1088         }
1089 }
1090
1091 int
1092 AudioEngine::reset_timebase ()
1093 {
1094         if (_jack && session) {
1095                 if (session->config.get_jack_time_master()) {
1096                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1097                 } else {
1098                         return jack_release_timebase (_jack);
1099                 }
1100         } else {
1101                 return -1;
1102         }
1103 }
1104
1105 int
1106 AudioEngine::freewheel (bool onoff)
1107 {
1108         if (_jack) {
1109
1110                 if (onoff != _freewheeling) {
1111
1112                         if (onoff) {
1113                                 _freewheel_thread_registered = false;
1114                         }
1115
1116                         return jack_set_freewheel (_jack, onoff);
1117
1118                 } else {
1119                         /* already doing what has been asked for */
1120                         return 0;
1121                 }
1122
1123         } else {
1124                 return -1;
1125         }
1126 }
1127
1128 void
1129 AudioEngine::remove_all_ports ()
1130 {
1131         /* process lock MUST be held */
1132
1133         {
1134                 RCUWriter<Ports> writer (ports);
1135                 boost::shared_ptr<Ports> ps = writer.get_copy ();
1136                 ps->clear ();
1137         }
1138 }
1139
1140 void
1141 AudioEngine::remove_connections_for (Port& port)
1142 {
1143         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1144                 PortConnections::iterator tmp;
1145                 
1146                 tmp = i;
1147                 ++tmp;
1148                 
1149                 if ((*i).first == port.name()) {
1150                         port_connections.erase (i);
1151                 }
1152
1153                 i = tmp;
1154         }
1155 }
1156
1157
1158 #ifdef HAVE_JACK_CLIENT_OPEN
1159
1160 static void 
1161 ardour_jack_error (const char* msg) 
1162 {
1163         error << "JACK: " << msg << endmsg;
1164 }
1165
1166 int
1167 AudioEngine::connect_to_jack (string client_name)
1168 {
1169         jack_options_t options = JackNullOption;
1170         jack_status_t status;
1171         const char *server_name = NULL;
1172
1173         jack_client_name = client_name; /* might be reset below */
1174         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1175
1176         if (_jack == NULL) {
1177                 // error message is not useful here
1178                 return -1;
1179         }
1180
1181         if (status & JackNameNotUnique) {
1182                 jack_client_name = jack_get_client_name (_jack);
1183         }
1184
1185         jack_set_error_function (ardour_jack_error);
1186         
1187         return 0;
1188 }
1189
1190 #else
1191
1192 int
1193 AudioEngine::connect_to_jack (string client_name)
1194 {
1195         jack_client_name = client_name;
1196
1197         if ((_jack = jack_client_new (client_name.c_str())) == 0) {
1198                 return -1;
1199         }
1200
1201         return 0;
1202 }
1203
1204 #endif /* HAVE_JACK_CLIENT_OPEN */
1205
1206 int 
1207 AudioEngine::disconnect_from_jack ()
1208 {
1209         if (!_jack) {
1210                 return 0;
1211         }
1212
1213         if (_running) {
1214                 stop_metering_thread ();
1215         }
1216
1217         { 
1218                 Glib::Mutex::Lock lm (_process_lock);
1219                 jack_client_close (_jack);
1220                 _jack = 0;
1221         }
1222
1223         _buffer_size = 0;
1224         _frame_rate = 0;
1225         _raw_buffer_sizes.clear();
1226
1227         if (_running) {
1228                 _running = false;
1229                 Stopped(); /* EMIT SIGNAL */
1230         }
1231
1232         return 0;
1233 }
1234
1235 int
1236 AudioEngine::reconnect_to_jack ()
1237 {
1238         if (_running) {
1239                 disconnect_from_jack ();
1240                 /* XXX give jackd a chance */
1241                 Glib::usleep (250000);
1242         }
1243
1244         if (connect_to_jack (jack_client_name)) {
1245                 error << _("failed to connect to JACK") << endmsg;
1246                 return -1;
1247         }
1248
1249         Ports::iterator i;
1250
1251         boost::shared_ptr<Ports> p = ports.reader ();
1252
1253         for (i = p->begin(); i != p->end(); ++i) {
1254                 if ((*i)->reestablish ()) {
1255                         break;
1256                 } 
1257         }
1258
1259         if (i != p->end()) {
1260                 /* failed */
1261                 remove_all_ports ();
1262                 return -1;
1263         } 
1264
1265
1266         if (session) {
1267                 session->reset_jack_connection (_jack);
1268                 nframes_t blocksize = jack_get_buffer_size (_jack);
1269                 session->set_block_size (blocksize);
1270                 session->set_frame_rate (jack_get_sample_rate (_jack));
1271                 
1272                 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
1273                 cout << "FIXME: Assuming maximum MIDI buffer size " << blocksize * 4 << "bytes" << endl;
1274                 _raw_buffer_sizes[DataType::MIDI] = blocksize * 4;
1275         }
1276
1277         last_monitor_check = 0;
1278         
1279         jack_on_shutdown (_jack, halted, this);
1280         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1281         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1282         jack_set_process_callback (_jack, _process_callback, this);
1283         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1284         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1285         jack_set_xrun_callback (_jack, _xrun_callback, this);
1286         jack_set_sync_callback (_jack, _jack_sync_callback, this);
1287         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1288         
1289         if (session && session->config.get_jack_time_master()) {
1290                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1291         } 
1292         
1293         if (jack_activate (_jack) == 0) {
1294                 _running = true;
1295                 _has_run = true;
1296         } else {
1297                 return -1;
1298         }
1299
1300         /* re-establish connections */
1301         
1302         for (i = p->begin(); i != p->end(); ++i) {
1303                 (*i)->reconnect ();
1304         }
1305
1306         Running (); /* EMIT SIGNAL*/
1307
1308         start_metering_thread ();
1309
1310         return 0;
1311 }
1312
1313 int
1314 AudioEngine::request_buffer_size (nframes_t nframes)
1315 {
1316         if (_jack) {
1317
1318                 if (nframes == jack_get_buffer_size (_jack)) {
1319                         return 0;
1320                 }
1321
1322                 return jack_set_buffer_size (_jack, nframes);
1323
1324         } else {
1325                 return -1;
1326         }
1327 }
1328
1329 void
1330 AudioEngine::update_total_latencies ()
1331 {
1332 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1333         if (_jack) {
1334                 jack_recompute_total_latencies (_jack);
1335         }
1336 #endif
1337 }
1338                 
1339 string
1340 AudioEngine::make_port_name_relative (string portname)
1341 {
1342         string::size_type len;
1343         string::size_type n;
1344         
1345         len = portname.length();
1346
1347         for (n = 0; n < len; ++n) {
1348                 if (portname[n] == ':') {
1349                         break;
1350                 }
1351         }
1352         
1353         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1354                 return portname.substr (n+1);
1355         }
1356
1357         return portname;
1358 }
1359
1360 string
1361 AudioEngine::make_port_name_non_relative (string portname)
1362 {
1363         string str;
1364
1365         if (portname.find_first_of (':') != string::npos) {
1366                 return portname;
1367         }
1368
1369         str  = jack_client_name;
1370         str += ':';
1371         str += portname;
1372         
1373         return str;
1374 }
1375
1376 bool
1377 AudioEngine::is_realtime () const
1378 {
1379         if (_jack) {
1380                 return jack_is_realtime (_jack);
1381         } else {
1382                 return false;
1383         }
1384 }