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