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