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