lots and lots of work to correctly deduce AU IO configurations and related issues
[ardour.git] / libs / ardour / globals.cc
1 /*
2     Copyright (C) 2000 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 <cstdio> // Needed so that libraptor (included in lrdf) won't complain
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <sys/time.h>
24 #include <sys/resource.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <locale.h>
28 #include <errno.h>
29
30 #ifdef VST_SUPPORT
31 #include <fst.h>
32 #endif
33
34 #ifdef HAVE_AUDIOUNITS
35 #include <ardour/audio_unit.h>
36 #endif
37
38 #ifdef __SSE__
39 #include <xmmintrin.h>
40 #endif
41
42 #include <glibmm/fileutils.h>
43 #include <glibmm/miscutils.h>
44
45 #include <lrdf.h>
46
47 #include <pbd/error.h>
48 #include <pbd/id.h>
49 #include <pbd/strsplit.h>
50 #include <pbd/fpu.h>
51 #include <pbd/pathscanner.h>
52
53 #include <midi++/port.h>
54 #include <midi++/manager.h>
55 #include <midi++/mmc.h>
56
57 #include <ardour/ardour.h>
58 #include <ardour/analyser.h>
59 #include <ardour/audio_library.h>
60 #include <ardour/configuration.h>
61 #include <ardour/profile.h>
62 #include <ardour/plugin_manager.h>
63 #include <ardour/audiosource.h>
64 #include <ardour/utils.h>
65 #include <ardour/session.h>
66 #include <ardour/source_factory.h>
67 #include <ardour/control_protocol_manager.h>
68
69 #ifdef HAVE_LIBLO
70 #include <ardour/osc.h>
71 #endif
72
73 #include <ardour/mix.h>
74
75 #if defined (__APPLE__)
76        #include <Carbon/Carbon.h> // For Gestalt
77 #endif
78        
79 #include "i18n.h"
80
81 ARDOUR::Configuration* ARDOUR::Config = 0;
82 ARDOUR::RuntimeProfile* ARDOUR::Profile = 0;
83 ARDOUR::AudioLibrary* ARDOUR::Library = 0;
84
85 #ifdef HAVE_LIBLO
86 ARDOUR::OSC* ARDOUR::osc = 0;
87 #endif
88
89 using namespace ARDOUR;
90 using namespace std;
91 using namespace PBD;
92
93 MIDI::Port *default_mmc_port = 0;
94 MIDI::Port *default_mtc_port = 0;
95 MIDI::Port *default_midi_port = 0;
96
97 Change ARDOUR::StartChanged = ARDOUR::new_change ();
98 Change ARDOUR::LengthChanged = ARDOUR::new_change ();
99 Change ARDOUR::PositionChanged = ARDOUR::new_change ();
100 Change ARDOUR::NameChanged = ARDOUR::new_change ();
101 Change ARDOUR::BoundsChanged = Change (0); // see init(), below
102
103 sigc::signal<void,std::string> ARDOUR::BootMessage;
104
105 #ifdef HAVE_LIBLO
106 static int
107 setup_osc ()
108 {
109         /* no real cost to creating this object, and it avoids
110            conditionals anywhere that uses it 
111         */
112         
113         osc = new OSC (Config->get_osc_port());
114         
115         if (Config->get_use_osc ()) {
116                 BootMessage (_("Starting OSC"));
117                 return osc->start ();
118         } else {
119                 return 0;
120         }
121 }
122 #endif
123
124 static int 
125 setup_midi ()
126 {
127         if (Config->midi_ports.size() == 0) {
128                 warning << _("no MIDI ports specified: no MMC or MTC control possible") << endmsg;
129                 return 0;
130         }
131
132         BootMessage (_("Configuring MIDI ports"));
133
134         for (std::map<string,XMLNode>::iterator i = Config->midi_ports.begin(); i != Config->midi_ports.end(); ++i) {
135                 MIDI::Manager::instance()->add_port (i->second);
136         }
137
138         MIDI::Port* first;
139         const MIDI::Manager::PortMap& ports = MIDI::Manager::instance()->get_midi_ports();
140
141         if (ports.size() > 1) {
142
143                 first = ports.begin()->second;
144
145                 /* More than one port, so try using specific names for each port */
146
147                 if (Config->get_mmc_port_name() != N_("default")) {
148                         default_mmc_port =  MIDI::Manager::instance()->port (Config->get_mmc_port_name());
149                 } 
150
151                 if (Config->get_mtc_port_name() != N_("default")) {
152                         default_mtc_port =  MIDI::Manager::instance()->port (Config->get_mtc_port_name());
153                 } 
154
155                 if (Config->get_midi_port_name() != N_("default")) {
156                         default_midi_port =  MIDI::Manager::instance()->port (Config->get_midi_port_name());
157                 } 
158                 
159                 /* If that didn't work, just use the first listed port */
160
161                 if (default_mmc_port == 0) {
162                         default_mmc_port = first;
163                 }
164
165                 if (default_mtc_port == 0) {
166                         default_mtc_port = first;
167                 }
168
169                 if (default_midi_port == 0) {
170                         default_midi_port = first;
171                 }
172                 
173         } else if (ports.size() == 1) {
174
175                 first = ports.begin()->second;
176
177                 /* Only one port described, so use it for both MTC and MMC */
178
179                 default_mmc_port = first;
180                 default_mtc_port = default_mmc_port;
181                 default_midi_port = default_mmc_port;
182         }
183
184         if (default_mmc_port == 0) {
185                 warning << string_compose (_("No MMC control (MIDI port \"%1\" not available)"), Config->get_mmc_port_name()) 
186                         << endmsg;
187                 return 0;
188         } 
189
190         if (default_mtc_port == 0) {
191                 warning << string_compose (_("No MTC support (MIDI port \"%1\" not available)"), Config->get_mtc_port_name()) 
192                         << endmsg;
193         }
194
195         if (default_midi_port == 0) {
196                 warning << string_compose (_("No MIDI parameter support (MIDI port \"%1\" not available)"), Config->get_midi_port_name()) 
197                         << endmsg;
198         }
199
200         return 0;
201 }
202
203 void
204 setup_hardware_optimization (bool try_optimization)
205 {
206         bool generic_mix_functions = true;
207
208         if (try_optimization) {
209
210                 FPU fpu;
211
212 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
213                 
214                 if (fpu.has_sse()) {
215
216                         info << "Using SSE optimized routines" << endmsg;
217         
218                         // SSE SET
219                         Session::compute_peak           = x86_sse_compute_peak;
220                         Session::find_peaks             = x86_sse_find_peaks;
221                         Session::apply_gain_to_buffer   = x86_sse_apply_gain_to_buffer;
222                         Session::mix_buffers_with_gain  = x86_sse_mix_buffers_with_gain;
223                         Session::mix_buffers_no_gain    = x86_sse_mix_buffers_no_gain;
224
225                         generic_mix_functions = false;
226
227                 }
228
229 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
230                 long sysVersion = 0;
231
232                 if (noErr != Gestalt(gestaltSystemVersion, &sysVersion))
233                         sysVersion = 0;
234
235                 if (sysVersion >= 0x00001040) { // Tiger at least
236                         Session::compute_peak           = veclib_compute_peak;
237                         Session::find_peaks             = veclib_find_peaks;
238                         Session::apply_gain_to_buffer   = veclib_apply_gain_to_buffer;
239                         Session::mix_buffers_with_gain  = veclib_mix_buffers_with_gain;
240                         Session::mix_buffers_no_gain    = veclib_mix_buffers_no_gain;
241
242                         generic_mix_functions = false;
243
244                         info << "Apple VecLib H/W specific optimizations in use" << endmsg;
245                 }
246 #endif
247
248                 /* consider FPU denormal handling to be "h/w optimization" */
249
250                 setup_fpu ();
251         }
252
253         if (generic_mix_functions) {
254
255                 Session::compute_peak           = compute_peak;
256                 Session::find_peaks             = find_peaks;
257                 Session::apply_gain_to_buffer   = apply_gain_to_buffer;
258                 Session::mix_buffers_with_gain  = mix_buffers_with_gain;
259                 Session::mix_buffers_no_gain    = mix_buffers_no_gain;
260                 
261                 info << "No H/W specific optimizations in use" << endmsg;
262         }
263
264 }
265
266 static void
267 lotsa_files_please ()
268 {
269         struct rlimit rl;
270
271         if (getrlimit (RLIMIT_NOFILE, &rl) == 0) {
272
273                 rl.rlim_cur = rl.rlim_max;
274
275                 if (setrlimit (RLIMIT_NOFILE, &rl) != 0) {
276                         if (rl.rlim_cur == RLIM_INFINITY) {
277                                 error << _("Could not set system open files limit to \"unlimited\"") << endmsg;
278                         } else {
279                                 error << string_compose (_("Could not set system open files limit to %1"), rl.rlim_cur) << endmsg;
280                         }
281                 } else {
282                         if (rl.rlim_cur == RLIM_INFINITY) {
283                                 info << _("Removed open file count limit. Excellent!") << endmsg;
284                         } else {
285                                 info << string_compose (_("Ardour will be limited to %1 open files"), rl.rlim_cur) << endmsg;
286                         }
287                 }
288         } else {
289                 error << string_compose (_("Could not get system open files limit (%1)"), strerror (errno)) << endmsg;
290         }
291 }
292
293 int
294 ARDOUR::init (bool use_vst, bool try_optimization)
295 {
296         extern void setup_enum_writer ();
297
298         (void) bindtextdomain(PACKAGE, LOCALEDIR);
299
300         setup_enum_writer ();
301
302         // allow ardour the absolute maximum number of open files
303         lotsa_files_please ();
304
305         lrdf_init();
306         Library = new AudioLibrary;
307
308         BootMessage (_("Loading configuration"));
309
310         Config = new Configuration;
311
312         if (Config->load_state ()) {
313                 return -1;
314         }
315
316         Config->set_use_vst (use_vst);
317
318         Profile = new RuntimeProfile;
319
320         if (setup_midi ()) {
321                 return -1;
322         }
323     
324 #ifdef HAVE_LIBLO
325         if (setup_osc ()) {
326                 return -1;
327         }
328 #endif
329
330 #ifdef VST_SUPPORT
331         if (Config->get_use_vst() && fst_init ()) {
332                 return -1;
333         }
334 #endif
335
336 #ifdef HAVE_AUDIOUNITS
337         AUPluginInfo::load_cached_info ();
338 #endif
339         
340         /* Make VAMP look in our library ahead of anything else */
341
342         char *p = getenv ("VAMP_PATH");
343         string vamppath = VAMP_DIR;
344         if (p) {
345                 vamppath += ':';
346                 vamppath += p;
347         } 
348         setenv ("VAMP_PATH", vamppath.c_str(), 1);
349
350
351         setup_hardware_optimization (try_optimization);
352
353         SourceFactory::init ();
354         Analyser::init ();
355
356         /* singleton - first object is "it" */
357         new PluginManager ();
358         
359         /* singleton - first object is "it" */
360         new ControlProtocolManager ();
361         ControlProtocolManager::instance().discover_control_protocols (Session::control_protocol_path());
362
363         XMLNode* node;
364         if ((node = Config->control_protocol_state()) != 0) {
365                 ControlProtocolManager::instance().set_state (*node);
366         }
367         
368         BoundsChanged = Change (StartChanged|PositionChanged|LengthChanged);
369
370         return 0;
371 }
372
373 int
374 ARDOUR::cleanup ()
375 {
376         delete Library;
377         lrdf_cleanup ();
378         delete &ControlProtocolManager::instance();
379         return 0;
380 }
381
382
383 microseconds_t
384 ARDOUR::get_microseconds ()
385 {
386         /* XXX need JACK to export its functionality */
387
388         struct timeval now;
389         gettimeofday (&now, 0);
390         return now.tv_sec * 1000000ULL + now.tv_usec;
391 }
392
393 ARDOUR::Change
394 ARDOUR::new_change ()
395 {
396         Change c;
397         static uint32_t change_bit = 1;
398
399         /* catch out-of-range */
400         if (!change_bit)
401         {
402                 fatal << _("programming error: ")
403                         << "change_bit out of range in ARDOUR::new_change()"
404                         << endmsg;
405                 /*NOTREACHED*/
406         }
407
408         c = Change (change_bit);
409         change_bit <<= 1;       // if it shifts too far, change_bit == 0
410
411         return c;
412 }
413
414 string
415 ARDOUR::get_ardour_revision ()
416 {
417         return "$Rev$";
418 }
419
420 string
421 ARDOUR::get_user_ardour_path ()
422 {
423         string path;
424                 
425         path = Glib::get_home_dir();
426
427         if (path.empty()) {
428                 return "/";
429         }
430
431         path += "/.ardour2/";
432
433         /* create it if necessary */
434
435         if (g_mkdir_with_parents (path.c_str (), 0755)) {
436                 throw exception ();
437         }
438
439         return path;
440 }
441
442 string
443 ARDOUR::get_system_data_path ()
444 {
445         string path;
446
447         char *envvar;
448
449         if ((envvar = getenv ("ARDOUR_DATA_PATH")) != 0) {
450                 path = envvar;
451         } else {
452                 path += DATA_DIR;
453                 path += "/ardour2/";
454         }
455         
456         return path;
457 }
458
459 string
460 ARDOUR::get_system_module_path ()
461 {
462         string path;
463         char *envvar;
464
465         if ((envvar = getenv ("ARDOUR_MODULE_PATH")) != 0) {
466                 path = envvar;
467         } else {
468                 path += MODULE_DIR;
469                 path += "/ardour2/";
470         }
471         
472         return path;
473 }
474
475 static string
476 find_file (string name, string dir, string subdir = "")
477 {
478         string path;
479         char* envvar = getenv("ARDOUR_PATH");
480
481         /* 1st attempt: any directory in ARDOUR_PATH */
482         
483         if (envvar != 0) {
484
485                 vector<string> split_path;
486         
487                 split (envvar, split_path, ':');
488                 
489                 for (vector<string>::iterator i = split_path.begin(); i != split_path.end(); ++i) {
490                         path = *i;
491                         path += "/" + name;
492                         if (Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
493                                 // cerr << "Using file " << path << " found in ARDOUR_PATH." << endl;
494                                 return path;
495                         }
496                 }
497         }
498
499         /* 2nd attempt: ~/.ardour/ */
500
501         path = get_user_ardour_path();
502                 
503         if (subdir.length()) {
504                 path = Glib::build_filename (path, subdir);
505         }
506                 
507         path = Glib::build_filename (path, name);
508
509         if (Glib::file_test (path.c_str(), Glib::FILE_TEST_EXISTS)) {
510                 return path;
511         }
512
513         if (dir.length()) {
514                 /* 3rd attempt: dir/... */
515                 
516                 path = dir;
517                 path += "/ardour2/";
518                 
519                 if (subdir.length()) {
520                         path += subdir + "/";
521                 }
522                 
523                 path += name;
524                 
525                 if (access (path.c_str(), R_OK) == 0) {
526                         return path;
527                 }
528         }
529
530         return "";
531 }
532
533 static bool sae_binding_filter (const string& str, void* arg)
534 {
535         /* Not a dotfile, has a prefix before a period, suffix is ".bindings" and contains -sae- */
536         
537         return str[0] != '.' && str.length() > 13 && str.find (".bindings") == (str.length() - 9)
538                 && str.find ("SAE-") != string::npos;
539 }
540
541 static bool binding_filter (const string& str, void* arg)
542 {
543         /* Not a dotfile, has a prefix before a period, suffix is ".bindings" */
544         
545         return str[0] != '.' && str.length() > 9 && str.find (".bindings") == (str.length() - 9);
546 }
547
548 void
549 ARDOUR::find_bindings_files (map<string,string>& files)
550 {
551         PathScanner scanner;
552         vector<string*> *found;
553         string full_path;
554         
555         /* XXX building path, so separators are fixed */
556
557         full_path = get_user_ardour_path ();
558         full_path += ':';
559         full_path = get_system_data_path ();
560
561         if (getenv ("ARDOUR_SAE")) {
562                 found = scanner (full_path, sae_binding_filter, 0, false, true);
563         } else {
564                 found = scanner (full_path, binding_filter, 0, false, true);
565         }
566
567         if (!found) {
568                 return;
569         }
570         
571         for (vector<string*>::iterator x = found->begin(); x != found->end(); ++x) {
572                 string path = *(*x);
573                 pair<string,string> namepath;
574                 namepath.second = path;
575                 path = Glib::path_get_basename (path);
576                 namepath.first = path.substr (0, path.find_first_of ('.'));
577                 
578                 files.insert (namepath);
579                 delete *x;
580         }
581         
582         delete found;
583 }
584
585 string
586 ARDOUR::find_config_file (string name)
587 {
588         const char* envvar;
589
590         if ((envvar = getenv("ARDOUR_CONFIG_PATH")) == 0) {
591                 envvar = CONFIG_DIR;
592         }
593
594         return find_file (name, envvar);
595 }
596
597 string
598 ARDOUR::find_data_file (string name, string subdir)
599 {
600         const char* envvar;
601         if ((envvar = getenv("ARDOUR_DATA_PATH")) == 0) {
602                 envvar = DATA_DIR;
603         }
604
605         return find_file (name, envvar, subdir);
606 }
607
608 ARDOUR::LocaleGuard::LocaleGuard (const char* str)
609 {
610         old = strdup (setlocale (LC_NUMERIC, NULL));
611         if (strcmp (old, str)) {
612                 setlocale (LC_NUMERIC, str);
613         } 
614 }
615
616 ARDOUR::LocaleGuard::~LocaleGuard ()
617 {
618         setlocale (LC_NUMERIC, old);
619         free ((char*)old);
620 }
621
622 void
623 ARDOUR::setup_fpu ()
624 {
625         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
626                 // valgrind doesn't understand this assembler stuff
627                 // September 10th, 2007
628                 return;
629         }
630
631 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
632
633         int MXCSR;
634         FPU fpu;
635
636         /* XXX use real code to determine if the processor supports
637            DenormalsAreZero and FlushToZero
638         */
639         
640         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
641                 return;
642         }
643
644         MXCSR  = _mm_getcsr();
645
646         switch (Config->get_denormal_model()) {
647         case DenormalNone:
648                 MXCSR &= ~(_MM_FLUSH_ZERO_ON|0x8000);
649                 break;
650
651         case DenormalFTZ:
652                 if (fpu.has_flush_to_zero()) {
653                         MXCSR |= _MM_FLUSH_ZERO_ON;
654                 }
655                 break;
656
657         case DenormalDAZ:
658                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
659                 if (fpu.has_denormals_are_zero()) {
660                         MXCSR |= 0x8000;
661                 }
662                 break;
663                 
664         case DenormalFTZDAZ:
665                 if (fpu.has_flush_to_zero()) {
666                         if (fpu.has_denormals_are_zero()) {
667                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x8000;
668                         } else {
669                                 MXCSR |= _MM_FLUSH_ZERO_ON;
670                         }
671                 }
672                 break;
673         }
674
675         _mm_setcsr (MXCSR);
676
677 #endif
678 }
679
680 ARDOUR::OverlapType
681 ARDOUR::coverage (nframes_t sa, nframes_t ea, 
682                   nframes_t sb, nframes_t eb)
683 {
684         /* OverlapType returned reflects how the second (B)
685            range overlaps the first (A).
686
687            The diagrams show various relative placements
688            of A and B for each OverlapType.
689
690            Notes:
691               Internal: the start points cannot coincide
692               External: the start and end points can coincide
693               Start: end points can coincide
694               End: start points can coincide
695
696            XXX Logically, Internal should disallow end
697            point equality.
698         */
699
700         /*
701              |--------------------|   A
702                   |------|            B
703                 |-----------------|   B
704
705
706              "B is internal to A"               
707
708         */
709 #ifdef OLD_COVERAGE
710         if ((sb >= sa) && (eb <= ea)) {
711 #else
712         if ((sb > sa) && (eb <= ea)) {
713 #endif
714                 return OverlapInternal;
715         }
716
717         /*
718              |--------------------|   A
719            ----|                      B
720            -----------------------|   B
721            --|                        B
722            
723              "B overlaps the start of A"
724
725         */
726
727         if ((eb >= sa) && (eb <= ea)) {
728                 return OverlapStart;
729         }
730         /* 
731              |---------------------|  A
732                    |----------------- B
733              |----------------------- B    
734                                    |- B
735
736             "B overlaps the end of A"                              
737
738         */
739         if ((sb >= sa) && (sb <= ea)) {
740                 return OverlapEnd;
741         }
742         /*
743              |--------------------|     A
744            --------------------------  B   
745              |-----------------------  B
746             ----------------------|    B
747              |--------------------|    B
748
749
750            "B overlaps all of A"
751         */
752         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
753                 return OverlapExternal;
754         }
755
756         return OverlapNone;
757 }
758
759 /* not sure where to put these */
760
761 template<class T>
762 std::istream& int_to_type (std::istream& o, T& hf) {
763         int val;
764         o >> val;
765         hf = (T) val;
766         return o;
767 }
768
769 std::istream& operator>>(std::istream& o, HeaderFormat& var) { return int_to_type<HeaderFormat> (o, var); }
770 std::istream& operator>>(std::istream& o, SampleFormat& var) { return int_to_type<SampleFormat> (o, var); }
771 std::istream& operator>>(std::istream& o, AutoConnectOption& var) { return int_to_type<AutoConnectOption> (o, var); }
772 std::istream& operator>>(std::istream& o, MonitorModel& var) { return int_to_type<MonitorModel> (o, var); }
773 std::istream& operator>>(std::istream& o, RemoteModel& var) { return int_to_type<RemoteModel> (o, var); }
774 std::istream& operator>>(std::istream& o, EditMode& var) { return int_to_type<EditMode> (o, var); }
775 std::istream& operator>>(std::istream& o, SoloModel& var) { return int_to_type<SoloModel> (o, var); }
776 std::istream& operator>>(std::istream& o, LayerModel& var) { return int_to_type<LayerModel> (o, var); }
777 std::istream& operator>>(std::istream& o, CrossfadeModel& var) { return int_to_type<CrossfadeModel> (o, var); }
778 std::istream& operator>>(std::istream& o, SlaveSource& var) { return int_to_type<SlaveSource> (o, var); }
779 std::istream& operator>>(std::istream& o, ShuttleBehaviour& var) { return int_to_type<ShuttleBehaviour> (o, var); }
780 std::istream& operator>>(std::istream& o, ShuttleUnits& var) { return int_to_type<ShuttleUnits> (o, var); }
781 std::istream& operator>>(std::istream& o, SmpteFormat& var) { return int_to_type<SmpteFormat> (o, var); }
782 std::istream& operator>>(std::istream& o, DenormalModel& var) { return int_to_type<DenormalModel> (o, var); }
783