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