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