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