merge pre- and post-fader processor boxes; start removing Placement (not finished...
[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/amp.h"
35 #include "ardour/audio_port.h"
36 #include "ardour/audioengine.h"
37 #include "ardour/buffer.h"
38 #include "ardour/buffer_set.h"
39 #include "ardour/cycle_timer.h"
40 #include "ardour/delivery.h"
41 #include "ardour/event_type_map.h"
42 #include "ardour/internal_return.h"
43 #include "ardour/io.h"
44 #include "ardour/meter.h"
45 #include "ardour/midi_port.h"
46 #include "ardour/port.h"
47 #include "ardour/port_set.h"
48 #include "ardour/session.h"
49 #include "ardour/timestamps.h"
50 #include "ardour/utils.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         InternalReturn::CycleStart (nframes);
368
369         /* tell all Ports that we're starting a new cycle */
370
371         boost::shared_ptr<Ports> p = ports.reader();
372
373         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
374                 (*i)->cycle_start (nframes);
375         }
376
377         if (_freewheeling) {
378                 /* emit the Freewheel signal and stop freewheeling in the event of trouble */
379                 if (Freewheel (nframes)) {
380                         jack_set_freewheel (_jack, false);
381                 }
382
383         } else {
384                 if (session) {
385                         session->process (nframes);
386                 }
387         }
388         
389         if (_freewheeling) {
390                 return 0;
391         }
392
393         if (!_running) {
394                 _processed_frames = next_processed_frames;
395                 return 0;
396         }
397
398         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
399
400                 boost::shared_ptr<Ports> p = ports.reader();
401
402                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
403                         
404                         Port *port = (*i);
405                         bool x;
406                         
407                         if (port->_last_monitor != (x = port->monitoring_input ())) {
408                                 port->_last_monitor = x;
409                                 /* XXX I think this is dangerous, due to 
410                                    a likely mutex in the signal handlers ...
411                                 */
412                                  port->MonitorInputChanged (x); /* EMIT SIGNAL */
413                         }
414                 }
415                 last_monitor_check = next_processed_frames;
416         }
417
418         if (session->silent()) {
419
420                 boost::shared_ptr<Ports> p = ports.reader();
421
422                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
423                         
424                         Port *port = (*i);
425                         
426                         if (port->sends_output()) {
427                                 port->get_buffer(nframes).silence(nframes);
428                         }
429                 }
430         } 
431
432         // Finalize ports
433
434         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
435                 (*i)->cycle_end (nframes);
436         }
437
438         _processed_frames = next_processed_frames;
439         return 0;
440 }
441
442 int
443 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
444 {
445         return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
446 }
447
448 int
449 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
450 {
451         _frame_rate = nframes;
452         _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
453         
454         /* check for monitor input change every 1/10th of second */
455
456         monitor_check_interval = nframes / 10;
457         last_monitor_check = 0;
458         
459         if (session) {
460                 session->set_frame_rate (nframes);
461         }
462
463         SampleRateChanged (nframes); /* EMIT SIGNAL */
464
465         return 0;
466 }
467
468 int
469 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
470 {
471         return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
472 }
473
474 int
475 AudioEngine::jack_bufsize_callback (nframes_t nframes)
476 {
477         _buffer_size = nframes;
478         _raw_buffer_sizes[DataType::AUDIO] = nframes * sizeof(float);
479         cout << "FIXME: Assuming maximum MIDI buffer size " << nframes * 4 << "bytes" << endl;
480         _raw_buffer_sizes[DataType::MIDI] = nframes * 4;
481         _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
482         last_monitor_check = 0;
483
484         boost::shared_ptr<Ports> p = ports.reader();
485
486         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
487                 (*i)->reset();
488         }
489
490         if (session) {
491                 session->set_block_size (_buffer_size);
492         }
493
494         return 0;
495 }
496
497 void
498 AudioEngine::stop_metering_thread ()
499 {
500         if (m_meter_thread) {
501                 g_atomic_int_set (&m_meter_exit, 1);
502                 m_meter_thread->join ();
503                 m_meter_thread = 0;
504         }
505 }
506
507 void
508 AudioEngine::start_metering_thread ()
509 {
510         if (m_meter_thread == 0) {
511                 g_atomic_int_set (&m_meter_exit, 0);
512                 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
513                                                        500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
514         }
515 }
516
517 void
518 AudioEngine::meter_thread ()
519 {
520         while (true) {
521                 Glib::usleep (10000); /* 1/100th sec interval */
522                 if (g_atomic_int_get(&m_meter_exit)) {
523                         break;
524                 }
525                 Metering::update_meters ();
526         }
527 }
528
529 void 
530 AudioEngine::set_session (Session *s)
531 {
532         Glib::Mutex::Lock pl (_process_lock);
533
534         if (!session) {
535
536                 session = s;
537
538                 nframes_t blocksize = jack_get_buffer_size (_jack);
539                 
540                 /* page in as much of the session process code as we
541                    can before we really start running.
542                 */
543                 
544                 boost::shared_ptr<Ports> p = ports.reader();
545
546                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
547                         (*i)->cycle_start (blocksize);
548                 }
549
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                 s->process (blocksize);
558
559                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
560                         (*i)->cycle_end (blocksize);
561                 }
562         }
563 }
564
565 void 
566 AudioEngine::remove_session ()
567 {
568         Glib::Mutex::Lock lm (_process_lock);
569
570         if (_running) {
571
572                 if (session) {
573                         session_remove_pending = true;
574                         session_removed.wait(_process_lock);
575                 }
576
577         } else {
578                 session = 0;
579         }
580         
581         //FIXME: Preliminary bugfix for  http://tracker.ardour.org/view.php?id=1985
582         //remove_all_ports ();
583 }
584
585 void
586 AudioEngine::port_registration_failure (const std::string& portname)
587 {
588         string full_portname = jack_client_name;
589         full_portname += ':';
590         full_portname += portname;
591         
592         
593         jack_port_t* p = jack_port_by_name (_jack, full_portname.c_str());
594         string reason;
595         
596         if (p) {
597                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
598         } else {
599                 reason = _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.");
600         }
601         
602         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
603 }       
604
605 Port *
606 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
607 {
608         Port* newport = 0;
609
610         try {
611                 if (dtype == DataType::AUDIO) {
612                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
613                 } else if (dtype == DataType::MIDI) {
614                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
615                 } else {
616                         throw PortRegistrationFailure("unable to create port (unknown type)");
617                 }
618                 
619                 size_t& old_buffer_size  = _raw_buffer_sizes[newport->type()];
620                 size_t  port_buffer_size = newport->raw_buffer_size(0);
621                 if (port_buffer_size > old_buffer_size) {
622                         old_buffer_size = port_buffer_size;
623                 }
624
625                 RCUWriter<Ports> writer (ports);
626                 boost::shared_ptr<Ports> ps = writer.get_copy ();
627                 ps->insert (ps->begin(), newport);
628
629                 /* writer goes out of scope, forces update */
630
631                 return newport;
632         }
633
634         catch (PortRegistrationFailure& err) {
635                 throw err;
636         } catch (std::exception& e) {
637                 throw PortRegistrationFailure(string_compose(
638                                 _("unable to create port: %1"), e.what()).c_str());
639         } catch (...) {
640                 throw PortRegistrationFailure("unable to create port (unknown error)");
641         }
642 }
643
644 Port *
645 AudioEngine::register_input_port (DataType type, const string& portname)
646 {
647         return register_port (type, portname, true);
648 }
649
650 Port *
651 AudioEngine::register_output_port (DataType type, const string& portname)
652 {
653         return register_port (type, portname, false);
654 }
655
656 int
657 AudioEngine::unregister_port (Port& port)
658 {
659         /* caller must hold process lock */
660
661         if (!_running) { 
662                 /* probably happening when the engine has been halted by JACK,
663                    in which case, there is nothing we can do here.
664                    */
665                 return 0;
666         }
667
668         {
669                 RCUWriter<Ports> writer (ports);
670                 boost::shared_ptr<Ports> ps = writer.get_copy ();
671                 
672                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
673                         if ((*i) == &port) {
674                                 delete *i;
675                                 ps->erase (i);
676                                 break;
677                         }
678                 }
679                 
680                 /* writer goes out of scope, forces update */
681         }
682                 
683         remove_connections_for (port);
684
685         return 0;
686 }
687
688 int 
689 AudioEngine::connect (const string& source, const string& destination)
690 {
691         /* caller must hold process lock */
692         
693         int ret;
694
695         if (!_running) {
696                 if (!_has_run) {
697                         fatal << _("connect called before engine was started") << endmsg;
698                         /*NOTREACHED*/
699                 } else {
700                         return -1;
701                 }
702         }
703
704         string s = make_port_name_non_relative (source);
705         string d = make_port_name_non_relative (destination);
706
707         Port* src = get_port_by_name_locked (s);
708         Port* dst = get_port_by_name_locked (d);
709
710                 if (src) {
711                         ret = src->connect (d);
712         } else if (dst) {
713                         ret = dst->connect (s);
714         } else {
715                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
716                 ret = -1;
717         }
718         
719         if (ret > 0) {
720                 /* already exists - no error, no warning */
721         } else if (ret < 0) {
722                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"), 
723                                         source, s, destination, d) 
724                       << endmsg;
725         }
726
727         return ret;
728 }
729
730 int 
731 AudioEngine::disconnect (const string& source, const string& destination)
732 {
733         /* caller must hold process lock */
734         
735         int ret;
736
737         if (!_running) {
738                 if (!_has_run) {
739                         fatal << _("disconnect called before engine was started") << endmsg;
740                         /*NOTREACHED*/
741                 } else {
742                         return -1;
743                 }
744         }
745         
746         string s = make_port_name_non_relative (source);
747         string d = make_port_name_non_relative (destination);
748
749         Port* src = get_port_by_name_locked (s);
750         Port* dst = get_port_by_name_locked (d);
751
752         if (src) {
753                         ret = src->disconnect (d);
754         } else if (dst) {
755                         ret = dst->disconnect (s);
756         } else {
757                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
758                 ret = -1;
759         }
760         return ret;
761 }
762
763 int
764 AudioEngine::disconnect (Port& port)
765 {
766         if (!_running) {
767                 if (!_has_run) {
768                         fatal << _("disconnect called before engine was started") << endmsg;
769                         /*NOTREACHED*/
770                 } else {
771                         return -1;
772                 }
773         }
774
775         return port.disconnect_all ();
776 }
777
778 ARDOUR::nframes_t
779 AudioEngine::frame_rate ()
780 {
781         if (_jack) {
782                 if (_frame_rate == 0) {
783                         return (_frame_rate = jack_get_sample_rate (_jack));
784                 } else {
785                         return _frame_rate;
786                 }
787         } else {
788                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
789                       << endmsg;
790                 /*NOTREACHED*/
791                 return 0;
792         }
793 }
794
795 size_t
796 AudioEngine::raw_buffer_size (DataType t)
797 {
798         std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
799         return (s != _raw_buffer_sizes.end()) ? s->second : 0;
800 }
801
802 ARDOUR::nframes_t
803 AudioEngine::frames_per_cycle ()
804 {
805         if (_jack) {
806                 if (_buffer_size == 0) {
807                         return (_buffer_size = jack_get_buffer_size (_jack));
808                 } else {
809                         return _buffer_size;
810                 }
811         } else {
812                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
813                       << endmsg;
814                 /*NOTREACHED*/
815                 return 0;
816         }
817 }
818
819 /** @param name Full name of port (including prefix:)
820  *  @return Corresponding Port*, or 0.  This object remains the property of the AudioEngine
821  *  so must not be deleted.
822  */
823 Port *
824 AudioEngine::get_port_by_name (const string& portname)
825 {
826         string s;
827         if (portname.find_first_of (':') == string::npos) {
828                 s = make_port_name_non_relative (portname);
829         } else {
830                 s = portname;
831         }
832         
833         Glib::Mutex::Lock lm (_process_lock);
834         return get_port_by_name_locked (s);
835 }
836
837 Port *
838 AudioEngine::get_port_by_name_locked (const string& portname)
839 {
840         /* caller must hold process lock */
841
842         if (!_running) {
843                 if (!_has_run) {
844                         fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
845                         /*NOTREACHED*/
846                 } else {
847                         return 0;
848                 }
849         }
850
851         if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
852                 /* not an ardour: port */
853                 return 0;
854         }
855
856         std::string const rel = make_port_name_relative (portname);
857
858         boost::shared_ptr<Ports> pr = ports.reader();
859
860         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
861                 if (rel == (*i)->name()) {
862                         return *i;
863                 }
864         }
865
866         return 0;
867 }
868
869
870
871
872
873 const char **
874 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
875 {
876         if (!_running) {
877                 if (!_has_run) {
878                         fatal << _("get_ports called before engine was started") << endmsg;
879                         /*NOTREACHED*/
880                 } else {
881                         return 0;
882                 }
883         }
884         return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
885 }
886
887 void
888 AudioEngine::halted (void *arg)
889 {
890         AudioEngine* ae = static_cast<AudioEngine *> (arg);
891         bool was_running = ae->_running;
892
893         ae->stop_metering_thread ();
894
895         ae->_running = false;
896         ae->_buffer_size = 0;
897         ae->_frame_rate = 0;
898
899         if (was_running) {
900                 ae->Halted(); /* EMIT SIGNAL */
901         }
902 }
903
904 bool
905 AudioEngine::can_request_hardware_monitoring () 
906 {
907         const char ** ports;
908
909         if (!_jack) {
910                 return 0;
911         }
912
913         if ((ports = jack_get_ports (_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
914                 return false;
915         }
916
917         free (ports);
918
919         return true;
920 }
921
922
923 uint32_t
924 AudioEngine::n_physical_outputs (DataType type) const
925 {
926         const char ** ports;
927         uint32_t i = 0;
928
929         if (!_jack) {
930                 return 0;
931         }
932
933         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
934                 return 0;
935         }
936
937         for (i = 0; ports[i]; ++i) {}
938         free (ports);
939
940         return i;
941 }
942
943 uint32_t
944 AudioEngine::n_physical_inputs (DataType type) const
945 {
946         const char ** ports;
947         uint32_t i = 0;
948         
949         if (!_jack) {
950                 return 0;
951         }
952         
953         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
954                 return 0;
955         }
956
957         if (ports) {
958                 for (i = 0; ports[i]; ++i) {}
959                 free (ports);
960         }
961         return i;
962 }
963
964 void
965 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
966 {
967         const char ** ports;
968         uint32_t i = 0;
969         
970         if (!_jack) {
971                 return;
972         }
973         
974         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
975                 return;
976         }
977
978         if (ports) {
979                 for (i = 0; ports[i]; ++i) {
980                         ins.push_back (ports[i]);
981                 }
982                 free (ports);
983         }
984 }
985
986 void
987 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
988 {
989         const char ** ports;
990         uint32_t i = 0;
991         
992         if (!_jack) {
993                 return;
994         }
995         
996         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
997                 return;
998         }
999
1000         if (ports) {
1001                 for (i = 0; ports[i]; ++i) {
1002                         outs.push_back (ports[i]);
1003                 }
1004                 free (ports);
1005         }
1006 }
1007
1008 string
1009 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1010 {
1011         const char ** ports;
1012         uint32_t i;
1013         string ret;
1014
1015         assert(type != DataType::NIL);
1016
1017         if (!_running || !_jack) {
1018                 if (!_has_run) {
1019                         fatal << _("get_nth_physical called before engine was started") << endmsg;
1020                         /*NOTREACHED*/
1021                 } else {
1022                         return "";
1023                 }
1024         }
1025
1026         ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
1027         
1028         if (ports == 0) {
1029                 return "";
1030         }
1031
1032         for (i = 0; i < n && ports[i]; ++i) {}
1033
1034         if (ports[i]) {
1035                 ret = ports[i];
1036         }
1037
1038         free ((char *) ports);
1039
1040         return ret;
1041 }
1042
1043 void
1044 AudioEngine::update_total_latency (const Port& port)
1045 {
1046         if (!_jack) {
1047                 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
1048                 /*NOTREACHED*/
1049         }
1050
1051         if (!_running) {
1052                 if (!_has_run) {
1053                         fatal << _("update_total_latency() called before engine was started") << endmsg;
1054                         /*NOTREACHED*/
1055                 } 
1056         }
1057
1058         port.recompute_total_latency ();
1059 }
1060
1061 void
1062 AudioEngine::transport_stop ()
1063 {
1064         if (_jack) {
1065                 jack_transport_stop (_jack);
1066         }
1067 }
1068
1069 void
1070 AudioEngine::transport_start ()
1071 {
1072         if (_jack) {
1073                 jack_transport_start (_jack);
1074         }
1075 }
1076
1077 void
1078 AudioEngine::transport_locate (nframes_t where)
1079 {
1080         // cerr << "tell JACK to locate to " << where << endl;
1081         if (_jack) {
1082                 jack_transport_locate (_jack, where);
1083         }
1084 }
1085
1086 AudioEngine::TransportState
1087 AudioEngine::transport_state ()
1088 {
1089         if (_jack) {
1090                 jack_position_t pos;
1091                 return (TransportState) jack_transport_query (_jack, &pos);
1092         } else {
1093                 return (TransportState) JackTransportStopped;
1094         }
1095 }
1096
1097 int
1098 AudioEngine::reset_timebase ()
1099 {
1100         if (_jack && session) {
1101                 if (session->config.get_jack_time_master()) {
1102                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1103                 } else {
1104                         return jack_release_timebase (_jack);
1105                 }
1106         } else {
1107                 return -1;
1108         }
1109 }
1110
1111 int
1112 AudioEngine::freewheel (bool onoff)
1113 {
1114         if (_jack) {
1115
1116                 if (onoff != _freewheeling) {
1117
1118                         if (onoff) {
1119                                 _freewheel_thread_registered = false;
1120                         }
1121
1122                         return jack_set_freewheel (_jack, onoff);
1123
1124                 } else {
1125                         /* already doing what has been asked for */
1126                         return 0;
1127                 }
1128
1129         } else {
1130                 return -1;
1131         }
1132 }
1133
1134 void
1135 AudioEngine::remove_all_ports ()
1136 {
1137         /* process lock MUST be held */
1138
1139         {
1140                 RCUWriter<Ports> writer (ports);
1141                 boost::shared_ptr<Ports> ps = writer.get_copy ();
1142                 ps->clear ();
1143         }
1144 }
1145
1146 void
1147 AudioEngine::remove_connections_for (Port& port)
1148 {
1149         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1150                 PortConnections::iterator tmp;
1151                 
1152                 tmp = i;
1153                 ++tmp;
1154                 
1155                 if ((*i).first == port.name()) {
1156                         port_connections.erase (i);
1157                 }
1158
1159                 i = tmp;
1160         }
1161 }
1162
1163
1164 static void 
1165 ardour_jack_error (const char* msg) 
1166 {
1167         error << "JACK: " << msg << endmsg;
1168 }
1169
1170 int
1171 AudioEngine::connect_to_jack (string client_name)
1172 {
1173         jack_options_t options = JackNullOption;
1174         jack_status_t status;
1175         const char *server_name = NULL;
1176
1177         jack_client_name = client_name; /* might be reset below */
1178         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1179
1180         if (_jack == NULL) {
1181                 // error message is not useful here
1182                 return -1;
1183         }
1184
1185         if (status & JackNameNotUnique) {
1186                 jack_client_name = jack_get_client_name (_jack);
1187         }
1188
1189         jack_set_error_function (ardour_jack_error);
1190         
1191         return 0;
1192 }
1193
1194 int 
1195 AudioEngine::disconnect_from_jack ()
1196 {
1197         if (!_jack) {
1198                 return 0;
1199         }
1200
1201         if (_running) {
1202                 stop_metering_thread ();
1203         }
1204
1205         { 
1206                 Glib::Mutex::Lock lm (_process_lock);
1207                 jack_client_close (_jack);
1208                 _jack = 0;
1209         }
1210
1211         _buffer_size = 0;
1212         _frame_rate = 0;
1213         _raw_buffer_sizes.clear();
1214
1215         if (_running) {
1216                 _running = false;
1217                 Stopped(); /* EMIT SIGNAL */
1218         }
1219
1220         return 0;
1221 }
1222
1223 int
1224 AudioEngine::reconnect_to_jack ()
1225 {
1226         if (_running) {
1227                 disconnect_from_jack ();
1228                 /* XXX give jackd a chance */
1229                 Glib::usleep (250000);
1230         }
1231
1232         if (connect_to_jack (jack_client_name)) {
1233                 error << _("failed to connect to JACK") << endmsg;
1234                 return -1;
1235         }
1236
1237         Ports::iterator i;
1238
1239         boost::shared_ptr<Ports> p = ports.reader ();
1240
1241         for (i = p->begin(); i != p->end(); ++i) {
1242                 if ((*i)->reestablish ()) {
1243                         break;
1244                 } 
1245         }
1246
1247         if (i != p->end()) {
1248                 /* failed */
1249                 remove_all_ports ();
1250                 return -1;
1251         } 
1252
1253
1254         if (session) {
1255                 session->reset_jack_connection (_jack);
1256                 nframes_t blocksize = jack_get_buffer_size (_jack);
1257                 session->set_block_size (blocksize);
1258                 session->set_frame_rate (jack_get_sample_rate (_jack));
1259                 
1260                 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
1261                 cout << "FIXME: Assuming maximum MIDI buffer size " << blocksize * 4 << "bytes" << endl;
1262                 _raw_buffer_sizes[DataType::MIDI] = blocksize * 4;
1263         }
1264
1265         last_monitor_check = 0;
1266         
1267         jack_on_shutdown (_jack, halted, this);
1268         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1269         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1270         jack_set_process_callback (_jack, _process_callback, this);
1271         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1272         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1273         jack_set_xrun_callback (_jack, _xrun_callback, this);
1274         jack_set_sync_callback (_jack, _jack_sync_callback, this);
1275         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1276         
1277         if (session && session->config.get_jack_time_master()) {
1278                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1279         } 
1280         
1281         if (jack_activate (_jack) == 0) {
1282                 _running = true;
1283                 _has_run = true;
1284         } else {
1285                 return -1;
1286         }
1287
1288         /* re-establish connections */
1289         
1290         for (i = p->begin(); i != p->end(); ++i) {
1291                 (*i)->reconnect ();
1292         }
1293
1294         Running (); /* EMIT SIGNAL*/
1295
1296         start_metering_thread ();
1297
1298         return 0;
1299 }
1300
1301 int
1302 AudioEngine::request_buffer_size (nframes_t nframes)
1303 {
1304         if (_jack) {
1305
1306                 if (nframes == jack_get_buffer_size (_jack)) {
1307                         return 0;
1308                 }
1309
1310                 return jack_set_buffer_size (_jack, nframes);
1311
1312         } else {
1313                 return -1;
1314         }
1315 }
1316
1317 void
1318 AudioEngine::update_total_latencies ()
1319 {
1320 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1321         if (_jack) {
1322                 jack_recompute_total_latencies (_jack);
1323         }
1324 #endif
1325 }
1326                 
1327 string
1328 AudioEngine::make_port_name_relative (string portname)
1329 {
1330         string::size_type len;
1331         string::size_type n;
1332         
1333         len = portname.length();
1334
1335         for (n = 0; n < len; ++n) {
1336                 if (portname[n] == ':') {
1337                         break;
1338                 }
1339         }
1340         
1341         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1342                 return portname.substr (n+1);
1343         }
1344
1345         return portname;
1346 }
1347
1348 string
1349 AudioEngine::make_port_name_non_relative (string portname)
1350 {
1351         string str;
1352
1353         if (portname.find_first_of (':') != string::npos) {
1354                 return portname;
1355         }
1356
1357         str  = jack_client_name;
1358         str += ':';
1359         str += portname;
1360         
1361         return str;
1362 }
1363
1364 bool
1365 AudioEngine::is_realtime () const
1366 {
1367         if (_jack) {
1368                 return jack_is_realtime (_jack);
1369         } else {
1370                 return false;
1371         }
1372 }