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