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