add new sigc++2 directory
[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 void
416 ARDOUR::find_bindings_files (map<string,string>& files)
417 {
418         vector<sys::path> found;
419
420         SearchPath spath = ardour_search_path() + user_config_directory() + system_config_search_path();
421
422         if (getenv ("ARDOUR_SAE")) {
423                 Glib::PatternSpec pattern("*SAE-*.bindings");
424                 find_matching_files_in_search_path (spath, pattern, found);
425         } else {
426                 Glib::PatternSpec pattern("*.bindings");
427                 find_matching_files_in_search_path (spath, pattern, found);
428         }
429
430         if (found.empty()) {
431                 return;
432         }
433         
434         for (vector<sys::path>::iterator x = found.begin(); x != found.end(); ++x) {
435                 sys::path path = *x;
436                 pair<string,string> namepath;
437                 namepath.second = path.to_string();
438                 namepath.first = path.leaf().substr (0, path.leaf().find_first_of ('.'));
439                 files.insert (namepath);
440         }
441 }
442
443 ARDOUR::LocaleGuard::LocaleGuard (const char* str)
444 {
445         old = strdup (setlocale (LC_NUMERIC, NULL));
446         if (strcmp (old, str)) {
447                 setlocale (LC_NUMERIC, str);
448         } 
449 }
450
451 ARDOUR::LocaleGuard::~LocaleGuard ()
452 {
453         setlocale (LC_NUMERIC, old);
454         free ((char*)old);
455 }
456
457 void
458 ARDOUR::setup_fpu ()
459 {
460
461         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
462                 // valgrind doesn't understand this assembler stuff
463                 // September 10th, 2007
464                 return;
465         }
466
467 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
468
469         int MXCSR;
470         FPU fpu;
471
472         /* XXX use real code to determine if the processor supports
473            DenormalsAreZero and FlushToZero
474         */
475         
476         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
477                 return;
478         }
479
480         MXCSR  = _mm_getcsr();
481
482         switch (Config->get_denormal_model()) {
483         case DenormalNone:
484                 MXCSR &= ~(_MM_FLUSH_ZERO_ON|0x8000);
485                 break;
486
487         case DenormalFTZ:
488                 if (fpu.has_flush_to_zero()) {
489                         MXCSR |= _MM_FLUSH_ZERO_ON;
490                 }
491                 break;
492
493         case DenormalDAZ:
494                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
495                 if (fpu.has_denormals_are_zero()) {
496                         MXCSR |= 0x8000;
497                 }
498                 break;
499                 
500         case DenormalFTZDAZ:
501                 if (fpu.has_flush_to_zero()) {
502                         if (fpu.has_denormals_are_zero()) {
503                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x8000;
504                         } else {
505                                 MXCSR |= _MM_FLUSH_ZERO_ON;
506                         }
507                 }
508                 break;
509         }
510
511         _mm_setcsr (MXCSR);
512
513 #endif
514 }
515
516 ARDOUR::OverlapType
517 ARDOUR::coverage (nframes_t sa, nframes_t ea, 
518                   nframes_t sb, nframes_t eb)
519 {
520         /* OverlapType returned reflects how the second (B)
521            range overlaps the first (A).
522
523            The diagrams show various relative placements
524            of A and B for each OverlapType.
525
526            Notes:
527               Internal: the start points cannot coincide
528               External: the start and end points can coincide
529               Start: end points can coincide
530               End: start points can coincide
531
532            XXX Logically, Internal should disallow end
533            point equality.
534         */
535
536         /*
537              |--------------------|   A
538                   |------|            B
539                 |-----------------|   B
540
541
542              "B is internal to A"               
543
544         */
545 #ifdef OLD_COVERAGE
546         if ((sb >= sa) && (eb <= ea)) {
547 #else
548         if ((sb > sa) && (eb <= ea)) {
549 #endif
550                 return OverlapInternal;
551         }
552
553         /*
554              |--------------------|   A
555            ----|                      B
556            -----------------------|   B
557            --|                        B
558            
559              "B overlaps the start of A"
560
561         */
562
563         if ((eb >= sa) && (eb <= ea)) {
564                 return OverlapStart;
565         }
566         /* 
567              |---------------------|  A
568                    |----------------- B
569              |----------------------- B    
570                                    |- B
571
572             "B overlaps the end of A"                              
573
574         */
575         if ((sb > sa) && (sb <= ea)) {
576                 return OverlapEnd;
577         }
578         /*
579              |--------------------|     A
580            --------------------------  B   
581              |-----------------------  B
582             ----------------------|    B
583              |--------------------|    B
584
585
586            "B overlaps all of A"
587         */
588         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
589                 return OverlapExternal;
590         }
591
592         return OverlapNone;
593 }
594
595 /* not sure where to put these */
596
597 template<class T>
598 std::istream& int_to_type (std::istream& o, T& hf) {
599         int val;
600         o >> val;
601         hf = (T) val;
602         return o;
603 }
604
605 std::istream& operator>>(std::istream& o, HeaderFormat& var) { return int_to_type<HeaderFormat> (o, var); }
606 std::istream& operator>>(std::istream& o, SampleFormat& var) { return int_to_type<SampleFormat> (o, var); }
607 std::istream& operator>>(std::istream& o, AutoConnectOption& var) { return int_to_type<AutoConnectOption> (o, var); }
608 std::istream& operator>>(std::istream& o, MonitorModel& var) { return int_to_type<MonitorModel> (o, var); }
609 std::istream& operator>>(std::istream& o, RemoteModel& var) { return int_to_type<RemoteModel> (o, var); }
610 std::istream& operator>>(std::istream& o, EditMode& var) { return int_to_type<EditMode> (o, var); }
611 std::istream& operator>>(std::istream& o, SoloModel& var) { return int_to_type<SoloModel> (o, var); }
612 std::istream& operator>>(std::istream& o, LayerModel& var) { return int_to_type<LayerModel> (o, var); }
613 std::istream& operator>>(std::istream& o, CrossfadeModel& var) { return int_to_type<CrossfadeModel> (o, var); }
614 std::istream& operator>>(std::istream& o, SlaveSource& var) { return int_to_type<SlaveSource> (o, var); }
615 std::istream& operator>>(std::istream& o, ShuttleBehaviour& var) { return int_to_type<ShuttleBehaviour> (o, var); }
616 std::istream& operator>>(std::istream& o, ShuttleUnits& var) { return int_to_type<ShuttleUnits> (o, var); }
617 std::istream& operator>>(std::istream& o, SmpteFormat& var) { return int_to_type<SmpteFormat> (o, var); }
618 std::istream& operator>>(std::istream& o, DenormalModel& var) { return int_to_type<DenormalModel> (o, var); }
619