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