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