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