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