90% done with external sync design changes (GUI now has toggle switch for ext/int...
[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/source_factory.h"
76 #include "ardour/utils.h"
77
78 #if defined (__APPLE__)
79        #include <Carbon/Carbon.h> // For Gestalt
80 #endif
81
82 #include "i18n.h"
83
84 ARDOUR::RCConfiguration* ARDOUR::Config = 0;
85 ARDOUR::RuntimeProfile* ARDOUR::Profile = 0;
86 ARDOUR::AudioLibrary* ARDOUR::Library = 0;
87
88 using namespace ARDOUR;
89 using namespace std;
90 using namespace PBD;
91
92 uint64_t ARDOUR::debug_bits = 0x0;
93
94 MIDI::Port *ARDOUR::default_mmc_port = 0;
95 MIDI::Port *ARDOUR::default_mtc_port = 0;
96 MIDI::Port *ARDOUR::default_midi_port = 0;
97 MIDI::Port *ARDOUR::default_midi_clock_port = 0;
98
99 Change ARDOUR::StartChanged = ARDOUR::new_change ();
100 Change ARDOUR::LengthChanged = ARDOUR::new_change ();
101 Change ARDOUR::PositionChanged = ARDOUR::new_change ();
102 Change ARDOUR::NameChanged = ARDOUR::new_change ();
103 Change ARDOUR::BoundsChanged = Change (0); // see init(), below
104
105 compute_peak_t          ARDOUR::compute_peak = 0;
106 find_peaks_t            ARDOUR::find_peaks = 0;
107 apply_gain_to_buffer_t  ARDOUR::apply_gain_to_buffer = 0;
108 mix_buffers_with_gain_t ARDOUR::mix_buffers_with_gain = 0;
109 mix_buffers_no_gain_t   ARDOUR::mix_buffers_no_gain = 0;
110
111 sigc::signal<void,std::string> ARDOUR::BootMessage;
112
113 void
114 ARDOUR::debug_print (const char* prefix, std::string str)
115 {
116         cerr << prefix << ": " << str;
117 }
118
119 void
120 ARDOUR::set_debug_bits (uint64_t bits)
121 {
122         debug_bits = bits;
123 }
124
125 int
126 ARDOUR::setup_midi ()
127 {
128         if (Config->midi_ports.size() == 0) {
129                 return 0;
130         }
131
132         BootMessage (_("Configuring MIDI ports"));
133
134         for (std::map<string,XMLNode>::iterator i = Config->midi_ports.begin(); i != Config->midi_ports.end(); ++i) {
135                 MIDI::Manager::instance()->add_port (i->second);
136         }
137
138         MIDI::Port* first;
139         const MIDI::Manager::PortMap& ports = MIDI::Manager::instance()->get_midi_ports();
140
141
142         if (ports.size() > 1) {
143
144                 first = ports.begin()->second;
145
146                 /* More than one port, so try using specific names for each port */
147
148                 default_mmc_port =  MIDI::Manager::instance()->port (Config->get_mmc_port_name());
149                 default_mtc_port =  MIDI::Manager::instance()->port (Config->get_mtc_port_name());
150                 default_midi_port =  MIDI::Manager::instance()->port (Config->get_midi_port_name());
151                 default_midi_clock_port =  MIDI::Manager::instance()->port (Config->get_midi_clock_port_name());
152
153                 /* If that didn't work, just use the first listed port */
154
155                 if (default_mmc_port == 0) {
156                         default_mmc_port = first;
157                 }
158
159                 if (default_mtc_port == 0) {
160                         default_mtc_port = first;
161                 }
162
163                 if (default_midi_port == 0) {
164                         default_midi_port = first;
165                 }
166
167                 if (default_midi_clock_port == 0) {
168                         default_midi_clock_port = first;
169                 }
170
171         } else if (ports.size() == 1) {
172
173                 first = ports.begin()->second;
174
175                 /* Only one port described, so use it for both MTC and MMC */
176
177                 default_mmc_port = first;
178                 default_mtc_port = default_mmc_port;
179                 default_midi_port = default_mmc_port;
180                 default_midi_clock_port = default_mmc_port;
181         }
182
183         if (default_mmc_port == 0) {
184                 warning << string_compose (_("No MMC control (MIDI port \"%1\" not available)"), Config->get_mmc_port_name())
185                         << endmsg;
186         }
187
188
189         if (default_mtc_port == 0) {
190                 warning << string_compose (_("No MTC support (MIDI port \"%1\" not available)"), Config->get_mtc_port_name())
191                         << endmsg;
192         }
193
194         if (default_midi_port == 0) {
195                 warning << string_compose (_("No MIDI parameter support (MIDI port \"%1\" not available)"), Config->get_midi_port_name())
196                         << endmsg;
197         }
198
199         if (default_midi_clock_port == 0) {
200                 warning << string_compose (_("No MIDI Clock support (MIDI port \"%1\" not available)"), Config->get_midi_clock_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         if (!Glib::thread_supported())
300                 Glib::thread_init();
301
302         PBD::ID::init ();
303
304         extern void setup_enum_writer ();
305
306         (void) bindtextdomain(PACKAGE, LOCALEDIR);
307
308         /* provide a state version for the few cases that need it and are not
309            driven by reading state from disk (e.g. undo/redo)
310         */
311
312         Stateful::current_state_version = CURRENT_SESSION_FILE_VERSION;
313
314         setup_enum_writer ();
315
316         // allow ardour the absolute maximum number of open files
317         lotsa_files_please ();
318
319         lrdf_init();
320         Library = new AudioLibrary;
321
322         BootMessage (_("Loading configuration"));
323
324         Config = new RCConfiguration;
325
326         if (Config->load_state ()) {
327                 return -1;
328         }
329
330         
331         Config->set_use_vst (use_vst);
332
333         cerr << "After config loaded, MTC port name = " << Config->get_mtc_port_name() << endl;
334
335         Profile = new RuntimeProfile;
336
337
338 #ifdef VST_SUPPORT
339         if (Config->get_use_vst() && fst_init (0)) {
340                 return -1;
341         }
342 #endif
343
344 #ifdef HAVE_AUDIOUNITS
345         AUPluginInfo::load_cached_info ();
346 #endif
347
348         /* Make VAMP look in our library ahead of anything else */
349
350         char *p = getenv ("VAMP_PATH");
351         string vamppath = VAMP_DIR;
352         if (p) {
353                 vamppath += ':';
354                 vamppath += p;
355         }
356         setenv ("VAMP_PATH", vamppath.c_str(), 1);
357
358
359         setup_hardware_optimization (try_optimization);
360
361         SourceFactory::init ();
362         Analyser::init ();
363
364         /* singleton - first object is "it" */
365         new PluginManager ();
366
367         BoundsChanged = Change (StartChanged|PositionChanged|LengthChanged);
368
369         return 0;
370 }
371
372 void
373 ARDOUR::init_post_engine ()
374 {
375         ControlProtocolManager::instance().discover_control_protocols ();
376
377         XMLNode* node;
378         if ((node = Config->control_protocol_state()) != 0) {
379                 ControlProtocolManager::instance().set_state (*node, Stateful::loading_state_version);
380         }
381 }
382
383 int
384 ARDOUR::cleanup ()
385 {
386         delete Library;
387         lrdf_cleanup ();
388         delete &ControlProtocolManager::instance();
389 #ifdef VST_SUPPORT
390         fst_exit ();
391 #endif
392         return 0;
393 }
394
395 ARDOUR::Change
396 ARDOUR::new_change ()
397 {
398         Change c;
399         static uint32_t change_bit = 1;
400
401         /* catch out-of-range */
402         if (!change_bit)
403         {
404                 fatal << _("programming error: ")
405                         << "change_bit out of range in ARDOUR::new_change()"
406                         << endmsg;
407                 /*NOTREACHED*/
408         }
409
410         c = Change (change_bit);
411         change_bit <<= 1;       // if it shifts too far, change_bit == 0
412
413         return c;
414 }
415
416 string
417 ARDOUR::get_ardour_revision ()
418 {
419         return "$Rev$";
420 }
421
422 void
423 ARDOUR::find_bindings_files (map<string,string>& files)
424 {
425         vector<sys::path> found;
426         SearchPath spath = ardour_search_path() + user_config_directory() + system_config_search_path();
427
428         if (getenv ("ARDOUR_SAE")) {
429                 Glib::PatternSpec pattern("*SAE-*.bindings");
430                 find_matching_files_in_search_path (spath, pattern, found);
431         } else {
432                 Glib::PatternSpec pattern("*.bindings");
433                 find_matching_files_in_search_path (spath, pattern, found);
434         }
435
436         if (found.empty()) {
437                 return;
438         }
439
440         for (vector<sys::path>::iterator x = found.begin(); x != found.end(); ++x) {
441                 sys::path path = *x;
442                 pair<string,string> namepath;
443                 namepath.second = path.to_string();
444                 namepath.first = path.leaf().substr (0, path.leaf().find_first_of ('.'));
445                 files.insert (namepath);
446         }
447 }
448
449 bool
450 ARDOUR::no_auto_connect()
451 {
452         return getenv ("ARDOUR_NO_AUTOCONNECT") != 0;
453 }
454
455 void
456 ARDOUR::setup_fpu ()
457 {
458
459         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
460                 // valgrind doesn't understand this assembler stuff
461                 // September 10th, 2007
462                 return;
463         }
464
465 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
466
467         int MXCSR;
468         FPU fpu;
469
470         /* XXX use real code to determine if the processor supports
471            DenormalsAreZero and FlushToZero
472         */
473
474         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
475                 return;
476         }
477
478         MXCSR  = _mm_getcsr();
479
480         switch (Config->get_denormal_model()) {
481         case DenormalNone:
482                 MXCSR &= ~(_MM_FLUSH_ZERO_ON|0x8000);
483                 break;
484
485         case DenormalFTZ:
486                 if (fpu.has_flush_to_zero()) {
487                         MXCSR |= _MM_FLUSH_ZERO_ON;
488                 }
489                 break;
490
491         case DenormalDAZ:
492                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
493                 if (fpu.has_denormals_are_zero()) {
494                         MXCSR |= 0x8000;
495                 }
496                 break;
497
498         case DenormalFTZDAZ:
499                 if (fpu.has_flush_to_zero()) {
500                         if (fpu.has_denormals_are_zero()) {
501                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x8000;
502                         } else {
503                                 MXCSR |= _MM_FLUSH_ZERO_ON;
504                         }
505                 }
506                 break;
507         }
508
509         _mm_setcsr (MXCSR);
510
511 #endif
512 }
513
514 ARDOUR::OverlapType
515 ARDOUR::coverage (nframes_t sa, nframes_t ea,
516                   nframes_t sb, nframes_t eb)
517 {
518         /* OverlapType returned reflects how the second (B)
519            range overlaps the first (A).
520
521            The diagrams show various relative placements
522            of A and B for each OverlapType.
523
524            Notes:
525               Internal: the start points cannot coincide
526               External: the start and end points can coincide
527               Start: end points can coincide
528               End: start points can coincide
529
530            XXX Logically, Internal should disallow end
531            point equality.
532         */
533
534         /*
535              |--------------------|   A
536                   |------|            B
537                 |-----------------|   B
538
539
540              "B is internal to A"
541
542         */
543 #ifdef OLD_COVERAGE
544         if ((sb >= sa) && (eb <= ea)) {
545 #else
546         if ((sb > sa) && (eb <= ea)) {
547 #endif
548                 return OverlapInternal;
549         }
550
551         /*
552              |--------------------|   A
553            ----|                      B
554            -----------------------|   B
555            --|                        B
556
557              "B overlaps the start of A"
558
559         */
560
561         if ((eb >= sa) && (eb <= ea)) {
562                 return OverlapStart;
563         }
564         /*
565              |---------------------|  A
566                    |----------------- B
567              |----------------------- B
568                                    |- B
569
570             "B overlaps the end of A"
571
572         */
573         if ((sb > sa) && (sb <= ea)) {
574                 return OverlapEnd;
575         }
576         /*
577              |--------------------|     A
578            --------------------------  B
579              |-----------------------  B
580             ----------------------|    B
581              |--------------------|    B
582
583
584            "B overlaps all of A"
585         */
586         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
587                 return OverlapExternal;
588         }
589
590         return OverlapNone;
591 }
592