LADSPA logarithmic handling patches from nickm and robsch
[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         remove_all_ports ();
584 }
585
586 void
587 AudioEngine::port_registration_failure (const std::string& portname)
588 {
589         string full_portname = jack_client_name;
590         full_portname += ':';
591         full_portname += portname;
592         
593         
594         jack_port_t* p = jack_port_by_name (_jack, full_portname.c_str());
595         string reason;
596         
597         if (p) {
598                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
599         } else {
600                 reason = _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.");
601         }
602         
603         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
604 }       
605
606 Port *
607 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
608 {
609         Port* newport = 0;
610
611         try {
612                 if (dtype == DataType::AUDIO) {
613                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
614                 } else if (dtype == DataType::MIDI) {
615                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
616                 } else {
617                         throw PortRegistrationFailure("unable to create port (unknown type)");
618                 }
619                 
620                 size_t& old_buffer_size  = _raw_buffer_sizes[newport->type()];
621                 size_t  port_buffer_size = newport->raw_buffer_size(0);
622                 if (port_buffer_size > old_buffer_size) {
623                         old_buffer_size = port_buffer_size;
624                 }
625
626                 RCUWriter<Ports> writer (ports);
627                 boost::shared_ptr<Ports> ps = writer.get_copy ();
628                 ps->insert (ps->begin(), newport);
629
630                 /* writer goes out of scope, forces update */
631
632                 return newport;
633         }
634
635         catch (PortRegistrationFailure& err) {
636                 throw err;
637         } catch (std::exception& e) {
638                 throw PortRegistrationFailure(string_compose(
639                                 _("unable to create port: %1"), e.what()).c_str());
640         } catch (...) {
641                 throw PortRegistrationFailure("unable to create port (unknown error)");
642         }
643 }
644
645 Port *
646 AudioEngine::register_input_port (DataType type, const string& portname)
647 {
648         return register_port (type, portname, true);
649 }
650
651 Port *
652 AudioEngine::register_output_port (DataType type, const string& portname)
653 {
654         return register_port (type, portname, false);
655 }
656
657 int
658 AudioEngine::unregister_port (Port& port)
659 {
660         /* caller must hold process lock */
661
662         if (!_running) { 
663                 /* probably happening when the engine has been halted by JACK,
664                    in which case, there is nothing we can do here.
665                    */
666                 return 0;
667         }
668
669         {
670                 RCUWriter<Ports> writer (ports);
671                 boost::shared_ptr<Ports> ps = writer.get_copy ();
672                 
673                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
674                         if ((*i) == &port) {
675                                 delete *i;
676                                 ps->erase (i);
677                                 break;
678                         }
679                 }
680                 
681                 /* writer goes out of scope, forces update */
682         }
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                 /* already exists - no error, no warning */
720         } else if (ret < 0) {
721                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"), 
722                                         source, s, destination, d) 
723                       << endmsg;
724         }
725
726         return ret;
727 }
728
729 int 
730 AudioEngine::disconnect (const string& source, const string& destination)
731 {
732         /* caller must hold process lock */
733         
734         int ret;
735
736         if (!_running) {
737                 if (!_has_run) {
738                         fatal << _("disconnect called before engine was started") << endmsg;
739                         /*NOTREACHED*/
740                 } else {
741                         return -1;
742                 }
743         }
744         
745         string s = make_port_name_non_relative (source);
746         string d = make_port_name_non_relative (destination);
747
748         Port* src = get_port_by_name_locked (s);
749         Port* dst = get_port_by_name_locked (d);
750
751         if (src) {
752                         ret = src->disconnect (d);
753         } else if (dst) {
754                         ret = dst->disconnect (s);
755         } else {
756                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
757                 ret = -1;
758         }
759         return ret;
760 }
761
762 int
763 AudioEngine::disconnect (Port& port)
764 {
765         if (!_running) {
766                 if (!_has_run) {
767                         fatal << _("disconnect called before engine was started") << endmsg;
768                         /*NOTREACHED*/
769                 } else {
770                         return -1;
771                 }
772         }
773
774         return port.disconnect_all ();
775 }
776
777 ARDOUR::nframes_t
778 AudioEngine::frame_rate ()
779 {
780         if (_jack) {
781                 if (_frame_rate == 0) {
782                         return (_frame_rate = jack_get_sample_rate (_jack));
783                 } else {
784                         return _frame_rate;
785                 }
786         } else {
787                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
788                       << endmsg;
789                 /*NOTREACHED*/
790                 return 0;
791         }
792 }
793
794 size_t
795 AudioEngine::raw_buffer_size (DataType t)
796 {
797         std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
798         return (s != _raw_buffer_sizes.end()) ? s->second : 0;
799 }
800
801 ARDOUR::nframes_t
802 AudioEngine::frames_per_cycle ()
803 {
804         if (_jack) {
805                 if (_buffer_size == 0) {
806                         return (_buffer_size = jack_get_buffer_size (_jack));
807                 } else {
808                         return _buffer_size;
809                 }
810         } else {
811                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
812                       << endmsg;
813                 /*NOTREACHED*/
814                 return 0;
815         }
816 }
817
818 /** @param name Full name of port (including prefix:)
819  *  @return Corresponding Port*, or 0.  This object remains the property of the AudioEngine
820  *  so must not be deleted.
821  */
822 Port *
823 AudioEngine::get_port_by_name (const string& portname)
824 {
825         string s;
826         if (portname.find_first_of (':') == string::npos) {
827                 s = make_port_name_non_relative (portname);
828         } else {
829                 s = portname;
830         }
831         
832         Glib::Mutex::Lock lm (_process_lock);
833         return get_port_by_name_locked (s);
834 }
835
836 Port *
837 AudioEngine::get_port_by_name_locked (const string& portname)
838 {
839         /* caller must hold process lock */
840
841         if (!_running) {
842                 if (!_has_run) {
843                         fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
844                         /*NOTREACHED*/
845                 } else {
846                         return 0;
847                 }
848         }
849
850         if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
851                 /* not an ardour: port */
852                 return 0;
853         }
854
855         std::string const rel = make_port_name_relative (portname);
856
857         boost::shared_ptr<Ports> pr = ports.reader();
858
859         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
860                 if (rel == (*i)->name()) {
861                         return *i;
862                 }
863         }
864
865         return 0;
866 }
867
868
869
870
871
872 const char **
873 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
874 {
875         if (!_running) {
876                 if (!_has_run) {
877                         fatal << _("get_ports called before engine was started") << endmsg;
878                         /*NOTREACHED*/
879                 } else {
880                         return 0;
881                 }
882         }
883         return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
884 }
885
886 void
887 AudioEngine::halted (void *arg)
888 {
889         AudioEngine* ae = static_cast<AudioEngine *> (arg);
890         bool was_running = ae->_running;
891
892         ae->stop_metering_thread ();
893
894         ae->_running = false;
895         ae->_buffer_size = 0;
896         ae->_frame_rate = 0;
897
898         if (was_running) {
899                 ae->Halted(); /* EMIT SIGNAL */
900         }
901 }
902
903 bool
904 AudioEngine::can_request_hardware_monitoring () 
905 {
906         const char ** ports;
907
908         if (!_jack) {
909                 return 0;
910         }
911
912         if ((ports = jack_get_ports (_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
913                 return false;
914         }
915
916         free (ports);
917
918         return true;
919 }
920
921
922 uint32_t
923 AudioEngine::n_physical_outputs (DataType type) const
924 {
925         const char ** ports;
926         uint32_t i = 0;
927
928         if (!_jack) {
929                 return 0;
930         }
931
932         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
933                 return 0;
934         }
935
936         for (i = 0; ports[i]; ++i) {}
937         free (ports);
938
939         return i;
940 }
941
942 uint32_t
943 AudioEngine::n_physical_inputs (DataType type) const
944 {
945         const char ** ports;
946         uint32_t i = 0;
947         
948         if (!_jack) {
949                 return 0;
950         }
951         
952         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
953                 return 0;
954         }
955
956         if (ports) {
957                 for (i = 0; ports[i]; ++i) {}
958                 free (ports);
959         }
960         return i;
961 }
962
963 void
964 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
965 {
966         const char ** ports;
967         uint32_t i = 0;
968         
969         if (!_jack) {
970                 return;
971         }
972         
973         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
974                 return;
975         }
976
977         if (ports) {
978                 for (i = 0; ports[i]; ++i) {
979                         ins.push_back (ports[i]);
980                 }
981                 free (ports);
982         }
983 }
984
985 void
986 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
987 {
988         const char ** ports;
989         uint32_t i = 0;
990         
991         if (!_jack) {
992                 return;
993         }
994         
995         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
996                 return;
997         }
998
999         if (ports) {
1000                 for (i = 0; ports[i]; ++i) {
1001                         outs.push_back (ports[i]);
1002                 }
1003                 free (ports);
1004         }
1005 }
1006
1007 string
1008 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1009 {
1010         const char ** ports;
1011         uint32_t i;
1012         string ret;
1013
1014         assert(type != DataType::NIL);
1015
1016         if (!_running || !_jack) {
1017                 if (!_has_run) {
1018                         fatal << _("get_nth_physical called before engine was started") << endmsg;
1019                         /*NOTREACHED*/
1020                 } else {
1021                         return "";
1022                 }
1023         }
1024
1025         ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
1026         
1027         if (ports == 0) {
1028                 return "";
1029         }
1030
1031         for (i = 0; i < n && ports[i]; ++i) {}
1032
1033         if (ports[i]) {
1034                 ret = ports[i];
1035         }
1036
1037         free ((char *) ports);
1038
1039         return ret;
1040 }
1041
1042 void
1043 AudioEngine::update_total_latency (const Port& port)
1044 {
1045         if (!_jack) {
1046                 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
1047                 /*NOTREACHED*/
1048         }
1049
1050         if (!_running) {
1051                 if (!_has_run) {
1052                         fatal << _("update_total_latency() called before engine was started") << endmsg;
1053                         /*NOTREACHED*/
1054                 } 
1055         }
1056
1057         port.recompute_total_latency ();
1058 }
1059
1060 void
1061 AudioEngine::transport_stop ()
1062 {
1063         if (_jack) {
1064                 jack_transport_stop (_jack);
1065         }
1066 }
1067
1068 void
1069 AudioEngine::transport_start ()
1070 {
1071         if (_jack) {
1072                 jack_transport_start (_jack);
1073         }
1074 }
1075
1076 void
1077 AudioEngine::transport_locate (nframes_t where)
1078 {
1079         // cerr << "tell JACK to locate to " << where << endl;
1080         if (_jack) {
1081                 jack_transport_locate (_jack, where);
1082         }
1083 }
1084
1085 AudioEngine::TransportState
1086 AudioEngine::transport_state ()
1087 {
1088         if (_jack) {
1089                 jack_position_t pos;
1090                 return (TransportState) jack_transport_query (_jack, &pos);
1091         } else {
1092                 return (TransportState) JackTransportStopped;
1093         }
1094 }
1095
1096 int
1097 AudioEngine::reset_timebase ()
1098 {
1099         if (_jack && session) {
1100                 if (session->config.get_jack_time_master()) {
1101                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1102                 } else {
1103                         return jack_release_timebase (_jack);
1104                 }
1105         } else {
1106                 return -1;
1107         }
1108 }
1109
1110 int
1111 AudioEngine::freewheel (bool onoff)
1112 {
1113         if (_jack) {
1114
1115                 if (onoff != _freewheeling) {
1116
1117                         if (onoff) {
1118                                 _freewheel_thread_registered = false;
1119                         }
1120
1121                         return jack_set_freewheel (_jack, onoff);
1122
1123                 } else {
1124                         /* already doing what has been asked for */
1125                         return 0;
1126                 }
1127
1128         } else {
1129                 return -1;
1130         }
1131 }
1132
1133 void
1134 AudioEngine::remove_all_ports ()
1135 {
1136         /* process lock MUST be held */
1137
1138         {
1139                 RCUWriter<Ports> writer (ports);
1140                 boost::shared_ptr<Ports> ps = writer.get_copy ();
1141
1142                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
1143                         delete *i;
1144                 }
1145                 
1146                 ps->clear ();
1147         }
1148 }
1149
1150 static void 
1151 ardour_jack_error (const char* msg) 
1152 {
1153         error << "JACK: " << msg << endmsg;
1154 }
1155
1156 int
1157 AudioEngine::connect_to_jack (string client_name)
1158 {
1159         jack_options_t options = JackNullOption;
1160         jack_status_t status;
1161         const char *server_name = NULL;
1162
1163         jack_client_name = client_name; /* might be reset below */
1164         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1165
1166         if (_jack == NULL) {
1167                 // error message is not useful here
1168                 return -1;
1169         }
1170
1171         if (status & JackNameNotUnique) {
1172                 jack_client_name = jack_get_client_name (_jack);
1173         }
1174
1175         jack_set_error_function (ardour_jack_error);
1176         
1177         return 0;
1178 }
1179
1180 int 
1181 AudioEngine::disconnect_from_jack ()
1182 {
1183         if (!_jack) {
1184                 return 0;
1185         }
1186
1187         if (_running) {
1188                 stop_metering_thread ();
1189         }
1190
1191         { 
1192                 Glib::Mutex::Lock lm (_process_lock);
1193                 jack_client_close (_jack);
1194                 _jack = 0;
1195         }
1196
1197         _buffer_size = 0;
1198         _frame_rate = 0;
1199         _raw_buffer_sizes.clear();
1200
1201         if (_running) {
1202                 _running = false;
1203                 Stopped(); /* EMIT SIGNAL */
1204         }
1205
1206         return 0;
1207 }
1208
1209 int
1210 AudioEngine::reconnect_to_jack ()
1211 {
1212         if (_running) {
1213                 disconnect_from_jack ();
1214                 /* XXX give jackd a chance */
1215                 Glib::usleep (250000);
1216         }
1217
1218         if (connect_to_jack (jack_client_name)) {
1219                 error << _("failed to connect to JACK") << endmsg;
1220                 return -1;
1221         }
1222
1223         Ports::iterator i;
1224
1225         boost::shared_ptr<Ports> p = ports.reader ();
1226
1227         for (i = p->begin(); i != p->end(); ++i) {
1228                 if ((*i)->reestablish ()) {
1229                         break;
1230                 } 
1231         }
1232
1233         if (i != p->end()) {
1234                 /* failed */
1235                 remove_all_ports ();
1236                 return -1;
1237         } 
1238
1239
1240         if (session) {
1241                 session->reset_jack_connection (_jack);
1242                 nframes_t blocksize = jack_get_buffer_size (_jack);
1243                 session->set_block_size (blocksize);
1244                 session->set_frame_rate (jack_get_sample_rate (_jack));
1245                 
1246                 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
1247                 cout << "FIXME: Assuming maximum MIDI buffer size " << blocksize * 4 << "bytes" << endl;
1248                 _raw_buffer_sizes[DataType::MIDI] = blocksize * 4;
1249         }
1250
1251         last_monitor_check = 0;
1252         
1253         jack_on_shutdown (_jack, halted, this);
1254         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1255         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1256         jack_set_process_callback (_jack, _process_callback, this);
1257         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1258         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1259         jack_set_xrun_callback (_jack, _xrun_callback, this);
1260         jack_set_sync_callback (_jack, _jack_sync_callback, this);
1261         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1262         
1263         if (session && session->config.get_jack_time_master()) {
1264                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1265         } 
1266         
1267         if (jack_activate (_jack) == 0) {
1268                 _running = true;
1269                 _has_run = true;
1270         } else {
1271                 return -1;
1272         }
1273
1274         /* re-establish connections */
1275         
1276         for (i = p->begin(); i != p->end(); ++i) {
1277                 (*i)->reconnect ();
1278         }
1279
1280         Running (); /* EMIT SIGNAL*/
1281
1282         start_metering_thread ();
1283
1284         return 0;
1285 }
1286
1287 int
1288 AudioEngine::request_buffer_size (nframes_t nframes)
1289 {
1290         if (_jack) {
1291
1292                 if (nframes == jack_get_buffer_size (_jack)) {
1293                         return 0;
1294                 }
1295
1296                 return jack_set_buffer_size (_jack, nframes);
1297
1298         } else {
1299                 return -1;
1300         }
1301 }
1302
1303 void
1304 AudioEngine::update_total_latencies ()
1305 {
1306 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1307         if (_jack) {
1308                 jack_recompute_total_latencies (_jack);
1309         }
1310 #endif
1311 }
1312                 
1313 string
1314 AudioEngine::make_port_name_relative (string portname)
1315 {
1316         string::size_type len;
1317         string::size_type n;
1318         
1319         len = portname.length();
1320
1321         for (n = 0; n < len; ++n) {
1322                 if (portname[n] == ':') {
1323                         break;
1324                 }
1325         }
1326         
1327         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1328                 return portname.substr (n+1);
1329         }
1330
1331         return portname;
1332 }
1333
1334 string
1335 AudioEngine::make_port_name_non_relative (string portname)
1336 {
1337         string str;
1338
1339         if (portname.find_first_of (':') != string::npos) {
1340                 return portname;
1341         }
1342
1343         str  = jack_client_name;
1344         str += ':';
1345         str += portname;
1346         
1347         return str;
1348 }
1349
1350 bool
1351 AudioEngine::is_realtime () const
1352 {
1353         if (_jack) {
1354                 return jack_is_realtime (_jack);
1355         } else {
1356                 return false;
1357         }
1358 }