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