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