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