rename interface_ stuff in the engine dialog to device_, since that feels a bit clear...
[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 <glibmm/pattern.h>
29 #include <glibmm/module.h>
30
31 #include "pbd/epa.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/pthread_utils.h"
34 #include "pbd/stacktrace.h"
35 #include "pbd/unknown_type.h"
36
37 #include <jack/weakjack.h>
38
39 #include "midi++/port.h"
40 #include "midi++/mmc.h"
41
42 #include "ardour/async_midi_port.h"
43 #include "ardour/audio_port.h"
44 #include "ardour/audio_backend.h"
45 #include "ardour/audioengine.h"
46 #include "ardour/backend_search_path.h"
47 #include "ardour/buffer.h"
48 #include "ardour/cycle_timer.h"
49 #include "ardour/internal_send.h"
50 #include "ardour/meter.h"
51 #include "ardour/midi_port.h"
52 #include "ardour/midiport_manager.h"
53 #include "ardour/port.h"
54 #include "ardour/process_thread.h"
55 #include "ardour/session.h"
56
57 #include "i18n.h"
58
59 using namespace std;
60 using namespace ARDOUR;
61 using namespace PBD;
62
63 gint AudioEngine::m_meter_exit;
64 AudioEngine* AudioEngine::_instance = 0;
65
66 AudioEngine::AudioEngine ()
67         : session_remove_pending (false)
68         , session_removal_countdown (-1)
69         , _running (false)
70         , _freewheeling (false)
71         , monitor_check_interval (INT32_MAX)
72         , last_monitor_check (0)
73         , _processed_frames (0)
74         , _pre_freewheel_mmc_enabled (false)
75         , m_meter_thread (0)
76         , _main_thread (0)
77 {
78         g_atomic_int_set (&m_meter_exit, 0);
79         discover_backends ();
80 }
81
82 AudioEngine::~AudioEngine ()
83 {
84         drop_backend ();
85
86         config_connection.disconnect ();
87
88         {
89                 Glib::Threads::Mutex::Lock tm (_process_lock);
90                 session_removed.signal ();
91                 stop_metering_thread ();
92         }
93 }
94
95 AudioEngine*
96 AudioEngine::create ()
97 {
98         if (_instance) {
99                 return _instance;
100         }
101
102         _instance = new AudioEngine ();
103         
104         return _instance;
105 }
106
107 void
108 _thread_init_callback (void * /*arg*/)
109 {
110         /* make sure that anybody who needs to know about this thread
111            knows about it.
112         */
113
114         pthread_set_name (X_("audioengine"));
115
116         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
117         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
118
119         SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
120
121         AsyncMIDIPort::set_process_thread (pthread_self());
122 }
123
124 void
125 AudioEngine::split_cycle (pframes_t offset)
126 {
127         /* caller must hold process lock */
128
129         Port::increment_global_port_buffer_offset (offset);
130
131         /* tell all Ports that we're going to start a new (split) cycle */
132
133         boost::shared_ptr<Ports> p = ports.reader();
134
135         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
136                 i->second->cycle_split ();
137         }
138 }
139
140 int
141 AudioEngine::sample_rate_change (pframes_t nframes)
142 {
143         /* check for monitor input change every 1/10th of second */
144
145         monitor_check_interval = nframes / 10;
146         last_monitor_check = 0;
147
148         if (_session) {
149                 _session->set_frame_rate (nframes);
150         }
151
152         SampleRateChanged (nframes); /* EMIT SIGNAL */
153
154         return 0;
155 }
156
157 int 
158 AudioEngine::buffer_size_change (pframes_t bufsiz)
159 {
160         if (_session) {
161                 _session->set_block_size (bufsiz);
162                 last_monitor_check = 0;
163         }
164
165         return 0;
166 }
167
168 /** Method called by our ::process_thread when there is work to be done.
169  *  @param nframes Number of frames to process.
170  */
171 int
172 AudioEngine::process_callback (pframes_t nframes)
173 {
174         Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
175
176         PT_TIMING_REF;
177         PT_TIMING_CHECK (1);
178
179         /// The number of frames that will have been processed when we've finished
180         pframes_t next_processed_frames;
181
182         /* handle wrap around of total frames counter */
183
184         if (max_framepos - _processed_frames < nframes) {
185                 next_processed_frames = nframes - (max_framepos - _processed_frames);
186         } else {
187                 next_processed_frames = _processed_frames + nframes;
188         }
189
190         if (!tm.locked()) {
191                 /* return having done nothing */
192                 _processed_frames = next_processed_frames;
193                 return 0;
194         }
195
196         if (session_remove_pending) {
197
198                 /* perform the actual session removal */
199
200                 if (session_removal_countdown < 0) {
201
202                         /* fade out over 1 second */
203                         session_removal_countdown = sample_rate()/2;
204                         session_removal_gain = 1.0;
205                         session_removal_gain_step = 1.0/session_removal_countdown;
206
207                 } else if (session_removal_countdown > 0) {
208
209                         /* we'll be fading audio out.
210                            
211                            if this is the last time we do this as part 
212                            of session removal, do a MIDI panic now
213                            to get MIDI stopped. This relies on the fact
214                            that "immediate data" (aka "out of band data") from
215                            MIDI tracks is *appended* after any other data, 
216                            so that it emerges after any outbound note ons, etc.
217                         */
218
219                         if (session_removal_countdown <= nframes) {
220                                 _session->midi_panic ();
221                         }
222
223                 } else {
224                         /* fade out done */
225                         _session = 0;
226                         session_removal_countdown = -1; // reset to "not in progress"
227                         session_remove_pending = false;
228                         session_removed.signal(); // wakes up thread that initiated session removal
229                 }
230         }
231
232         if (_session == 0) {
233
234                 if (!_freewheeling) {
235                         PortManager::cycle_start (nframes);
236                         PortManager::cycle_end (nframes);
237                 }
238
239                 _processed_frames = next_processed_frames;
240
241                 return 0;
242         }
243
244         /* tell all relevant objects that we're starting a new cycle */
245
246         InternalSend::CycleStart (nframes);
247
248         /* tell all Ports that we're starting a new cycle */
249
250         PortManager::cycle_start (nframes);
251
252         /* test if we are freewheeling and there are freewheel signals connected.
253            ardour should act normally even when freewheeling unless /it/ is
254            exporting (which is what Freewheel.empty() tests for).
255         */
256
257         if (_freewheeling && !Freewheel.empty()) {
258                 Freewheel (nframes);
259         } else {
260                 if (_session) {
261                         _session->process (nframes);
262                 }
263         }
264
265         if (_freewheeling) {
266                 return 0;
267         }
268
269         if (!_running) {
270                 _processed_frames = next_processed_frames;
271                 return 0;
272         }
273
274         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
275                 
276                 PortManager::check_monitoring ();
277                 last_monitor_check = next_processed_frames;
278         }
279
280         if (_session->silent()) {
281                 PortManager::silence (nframes);
282         }
283
284         if (session_remove_pending && session_removal_countdown) {
285
286                 PortManager::fade_out (session_removal_gain, session_removal_gain_step, nframes);
287                 
288                 if (session_removal_countdown > nframes) {
289                         session_removal_countdown -= nframes;
290                 } else {
291                         session_removal_countdown = 0;
292                 }
293
294                 session_removal_gain -= (nframes * session_removal_gain_step);
295         }
296
297         PortManager::cycle_end (nframes);
298
299         _processed_frames = next_processed_frames;
300
301         PT_TIMING_CHECK (2);
302         
303         return 0;
304 }
305
306
307 void
308 AudioEngine::stop_metering_thread ()
309 {
310         if (m_meter_thread) {
311                 g_atomic_int_set (&m_meter_exit, 1);
312                 m_meter_thread->join ();
313                 m_meter_thread = 0;
314         }
315 }
316
317 void
318 AudioEngine::start_metering_thread ()
319 {
320         if (m_meter_thread == 0) {
321                 g_atomic_int_set (&m_meter_exit, 0);
322                 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
323         }
324 }
325
326 void
327 AudioEngine::meter_thread ()
328 {
329         pthread_set_name (X_("meter"));
330
331         while (true) {
332                 Glib::usleep (10000); /* 1/100th sec interval */
333                 if (g_atomic_int_get(&m_meter_exit)) {
334                         break;
335                 }
336                 Metering::Meter ();
337         }
338 }
339
340 void
341 AudioEngine::set_session (Session *s)
342 {
343         Glib::Threads::Mutex::Lock pl (_process_lock);
344
345         SessionHandlePtr::set_session (s);
346
347         if (_session) {
348
349                 pframes_t blocksize = samples_per_cycle ();
350
351                 PortManager::cycle_start (blocksize);
352
353                 _session->process (blocksize);
354                 _session->process (blocksize);
355                 _session->process (blocksize);
356                 _session->process (blocksize);
357                 _session->process (blocksize);
358                 _session->process (blocksize);
359                 _session->process (blocksize);
360                 _session->process (blocksize);
361
362                 PortManager::cycle_end (blocksize);
363         }
364 }
365
366 void
367 AudioEngine::remove_session ()
368 {
369         Glib::Threads::Mutex::Lock lm (_process_lock);
370
371         if (_running) {
372
373                 stop_metering_thread ();
374
375                 if (_session) {
376                         session_remove_pending = true;
377                         session_removal_countdown = 0;
378                         session_removed.wait(_process_lock);
379                 }
380
381         } else {
382                 SessionHandlePtr::set_session (0);
383         }
384
385         remove_all_ports ();
386 }
387
388
389 void
390 AudioEngine::died ()
391 {
392         /* called from a signal handler for SIGPIPE */
393
394         stop_metering_thread ();
395
396         _running = false;
397 }
398
399 int
400 AudioEngine::reset_timebase ()
401 {
402         if (_session) {
403                 if (_session->config.get_jack_time_master()) {
404                         _backend->set_time_master (true);
405                 } else {
406                         _backend->set_time_master (false);
407                 }
408         }
409         return 0;
410 }
411
412
413 void
414 AudioEngine::destroy ()
415 {
416         delete _instance;
417         _instance = 0;
418 }
419
420 int
421 AudioEngine::discover_backends ()
422 {
423         vector<std::string> backend_modules;
424
425         _backends.clear ();
426
427         Glib::PatternSpec so_extension_pattern("*backend.so");
428         Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
429
430         find_matching_files_in_search_path (backend_search_path (),
431                                             so_extension_pattern, backend_modules);
432
433         find_matching_files_in_search_path (backend_search_path (),
434                                             dylib_extension_pattern, backend_modules);
435
436         DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1\n"), backend_search_path().to_string()));
437
438         for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
439
440                 AudioBackendInfo* info;
441
442                 if ((info = backend_discover (*i)) != 0) {
443                         _backends.insert (make_pair (info->name, info));
444                 }
445         }
446
447         return _backends.size();
448 }
449
450 AudioBackendInfo*
451 AudioEngine::backend_discover (const string& path)
452 {
453         Glib::Module module (path);
454         AudioBackendInfo* info;
455         void* sym = 0;
456
457         if (!module) {
458                 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
459                                         Glib::Module::get_last_error()) << endmsg;
460                 return 0;
461         }
462         
463         if (!module.get_symbol ("descriptor", sym)) {
464                 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor."), path) << endmsg;
465                 error << Glib::Module::get_last_error() << endmsg;
466                 return 0;
467         }
468
469         module.make_resident ();
470         
471         info = (AudioBackendInfo*) sym;
472         
473         return info;
474 }
475
476 vector<const AudioBackendInfo*>
477 AudioEngine::available_backends() const
478 {
479         vector<const AudioBackendInfo*> r;
480         
481         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
482                 r.push_back (i->second);
483         }
484
485         return r;
486 }
487
488 string
489 AudioEngine::current_backend_name() const
490 {
491         if (_backend) {
492                 return _backend->name();
493         } 
494         return string();
495 }
496
497 void
498 AudioEngine::drop_backend ()
499 {
500         if (_backend) {
501                 _backend->stop ();
502                 _backend.reset ();
503         }
504 }
505
506 boost::shared_ptr<AudioBackend>
507 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
508 {
509         BackendMap::iterator b = _backends.find (name);
510
511         if (b == _backends.end()) {
512                 return boost::shared_ptr<AudioBackend>();
513         }
514
515         drop_backend ();
516         
517         try {
518                 if (b->second->instantiate (arg1, arg2)) {
519                         throw failed_constructor ();
520                 }
521
522                 _backend = b->second->backend_factory (*this);
523                 _impl = b->second->portengine_factory (*this);
524
525         } catch (exception& e) {
526                 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
527                 return boost::shared_ptr<AudioBackend>();
528         }
529
530         return _backend;
531 }
532
533 /* BACKEND PROXY WRAPPERS */
534
535 int
536 AudioEngine::start ()
537 {
538         if (!_backend) {
539                 return -1;
540         }
541
542         if (_running) {
543                 return 0;
544         }
545
546         /* if we're still connected (i.e. previously paused), no need to
547          * re-register ports.
548          */
549          
550         bool have_ports = (!ports.reader()->empty());
551
552         _processed_frames = 0;
553         last_monitor_check = 0;
554         
555         if (_backend->start()) {
556                 return -1;
557         }
558
559         _running = true;
560         
561         if (_session) {
562                 _session->set_frame_rate (_backend->sample_rate());
563                 
564                 if (_session->config.get_jack_time_master()) {
565                         _backend->set_time_master (true);
566                 }
567         }
568         
569         if (!have_ports) {
570                 PortManager::create_ports ();
571                 _mmc.set_ports (mmc_input_port(), mmc_output_port());
572         }
573         
574         start_metering_thread ();
575         
576         Running(); /* EMIT SIGNAL */
577         
578         return 0;
579 }
580
581 int
582 AudioEngine::stop ()
583 {
584         if (!_backend) {
585                 return 0;
586         }
587
588         Glib::Threads::Mutex::Lock lm (_process_lock);
589
590         if (_backend->stop ()) {
591                 return -1;
592         }
593         
594         _running = false;
595         _processed_frames = 0;
596         stop_metering_thread ();
597         
598         Port::PortDrop ();
599         Stopped (); /* EMIT SIGNAL */
600         
601         return 0;
602 }
603
604 int
605 AudioEngine::pause ()
606 {
607         if (!_backend) {
608                 return 0;
609         }
610         
611         if (_backend->pause ()) {
612                 return -1;
613         }
614
615         _running = false;
616         
617         Stopped(); /* EMIT SIGNAL */
618         return 0;
619 }
620
621 int
622 AudioEngine::freewheel (bool start_stop)
623 {
624         if (!_backend) {
625                 return -1;
626         }
627
628         /* _freewheeling will be set when first Freewheel signal occurs */
629
630         return _backend->freewheel (start_stop);
631 }
632
633 float
634 AudioEngine::get_cpu_load() const 
635 {
636         if (!_backend) {
637                 return 0.0;
638         }
639         return _backend->cpu_load ();
640 }
641
642 bool
643 AudioEngine::is_realtime() const 
644 {
645         if (!_backend) {
646                 return false;
647         }
648
649         return _backend->is_realtime();
650 }
651
652 bool
653 AudioEngine::connected() const 
654 {
655         if (!_backend) {
656                 return false;
657         }
658
659         return _backend->connected();
660 }
661
662 void
663 AudioEngine::transport_start ()
664 {
665         if (!_backend) {
666                 return;
667         }
668         return _backend->transport_start ();
669 }
670
671 void
672 AudioEngine::transport_stop ()
673 {
674         if (!_backend) {
675                 return;
676         }
677         return _backend->transport_stop ();
678 }
679
680 TransportState
681 AudioEngine::transport_state ()
682 {
683         if (!_backend) {
684                 return TransportStopped;
685         }
686         return _backend->transport_state ();
687 }
688
689 void
690 AudioEngine::transport_locate (framepos_t pos)
691 {
692         if (!_backend) {
693                 return;
694         }
695         return _backend->transport_locate (pos);
696 }
697
698 framepos_t
699 AudioEngine::transport_frame()
700 {
701         if (!_backend) {
702                 return 0;
703         }
704         return _backend->transport_frame ();
705 }
706
707 framecnt_t
708 AudioEngine::sample_rate () const
709 {
710         if (!_backend) {
711                 return 0;
712         }
713         return _backend->sample_rate ();
714 }
715
716 pframes_t
717 AudioEngine::samples_per_cycle () const
718 {
719         if (!_backend) {
720                 return 0;
721         }
722         return _backend->buffer_size ();
723 }
724
725 int
726 AudioEngine::usecs_per_cycle () const
727 {
728         if (!_backend) {
729                 return -1;
730         }
731         return _backend->usecs_per_cycle ();
732 }
733
734 size_t
735 AudioEngine::raw_buffer_size (DataType t)
736 {
737         if (!_backend) {
738                 return -1;
739         }
740         return _backend->raw_buffer_size (t);
741 }
742
743 pframes_t
744 AudioEngine::sample_time ()
745 {
746         if (!_backend) {
747                 return 0;
748         }
749         return _backend->sample_time ();
750 }
751
752 pframes_t
753 AudioEngine::sample_time_at_cycle_start ()
754 {
755         if (!_backend) {
756                 return 0;
757         }
758         return _backend->sample_time_at_cycle_start ();
759 }
760
761 pframes_t
762 AudioEngine::samples_since_cycle_start ()
763 {
764         if (!_backend) {
765                 return 0;
766         }
767         return _backend->samples_since_cycle_start ();
768 }
769
770 bool
771 AudioEngine::get_sync_offset (pframes_t& offset) const
772 {
773         if (!_backend) {
774                 return false;
775         }
776         return _backend->get_sync_offset (offset);
777 }
778
779 int
780 AudioEngine::create_process_thread (boost::function<void()> func, pthread_t* thr, size_t stacksize)
781 {
782         if (!_backend) {
783                 return -1;
784         }
785         return _backend->create_process_thread (func, thr, stacksize);
786 }
787
788
789 int
790 AudioEngine::set_device_name (const std::string& name)
791 {
792         if (!_backend) {
793                 return -1;
794         }
795         return _backend->set_device_name  (name);
796 }
797
798 int
799 AudioEngine::set_sample_rate (float sr)
800 {
801         if (!_backend) {
802                 return -1;
803         }
804         return _backend->set_sample_rate  (sr);
805 }
806
807 int
808 AudioEngine::set_buffer_size (uint32_t bufsiz)
809 {
810         if (!_backend) {
811                 return -1;
812         }
813         return _backend->set_buffer_size  (bufsiz);
814 }
815
816 int
817 AudioEngine::set_sample_format (SampleFormat sf)
818 {
819         if (!_backend) {
820                 return -1;
821         }
822         return _backend->set_sample_format  (sf);
823 }
824
825 int
826 AudioEngine::set_interleaved (bool yn)
827 {
828         if (!_backend) {
829                 return -1;
830         }
831         return _backend->set_interleaved  (yn);
832 }
833
834 int
835 AudioEngine::set_input_channels (uint32_t ic)
836 {
837         if (!_backend) {
838                 return -1;
839         }
840         return _backend->set_input_channels  (ic);
841 }
842
843 int
844 AudioEngine::set_output_channels (uint32_t oc)
845 {
846         if (!_backend) {
847                 return -1;
848         }
849         return _backend->set_output_channels (oc);
850 }
851
852 int
853 AudioEngine::set_systemic_input_latency (uint32_t il)
854 {
855         if (!_backend) {
856                 return -1;
857         }
858         return _backend->set_systemic_input_latency  (il);
859 }
860
861 int
862 AudioEngine::set_systemic_output_latency (uint32_t ol)
863 {
864         if (!_backend) {
865                 return -1;
866         }
867         return _backend->set_systemic_output_latency  (ol);
868 }
869
870 /* END OF BACKEND PROXY API */
871
872 void
873 AudioEngine::thread_init_callback (void* arg)
874 {
875         /* make sure that anybody who needs to know about this thread
876            knows about it.
877         */
878
879         pthread_set_name (X_("audioengine"));
880
881         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
882         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
883
884         SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
885
886         AsyncMIDIPort::set_process_thread (pthread_self());
887
888         if (arg) {
889                 /* the special thread created/managed by the backend */
890                 AudioEngine::instance()->_main_thread = new ProcessThread;
891         }
892 }
893
894 int
895 AudioEngine::sync_callback (TransportState state, framepos_t position)
896 {
897         if (_session) {
898                 return _session->backend_sync_callback (state, position);
899         }
900         return 0;
901 }
902
903 void
904 AudioEngine::freewheel_callback (bool onoff)
905 {
906         if (onoff) {
907                 _pre_freewheel_mmc_enabled = _mmc.send_enabled ();
908                 _mmc.enable_send (false);
909         } else {
910                 _mmc.enable_send (_pre_freewheel_mmc_enabled);
911         }
912
913         _freewheeling = onoff;
914 }
915
916 void
917 AudioEngine::latency_callback (bool for_playback)
918 {
919         if (_session) {
920                 _session->update_latency (for_playback);
921         }
922 }
923
924 void
925 AudioEngine::update_latencies ()
926 {
927         if (_backend) {
928                 _backend->update_latencies ();
929         }
930 }
931
932 void
933 AudioEngine::halted_callback (const char* why)
934 {
935         stop_metering_thread ();
936         _running = false;
937
938         Port::PortDrop (); /* EMIT SIGNAL */
939         Halted (why);      /* EMIT SIGNAL */
940 }
941
942 bool
943 AudioEngine::setup_required () const
944 {
945         if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
946                 return false;
947         }
948
949         return true;
950 }
951