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