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