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