remove offset from process callback tree. some breakage may have occured. yes, really.
[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 (0)) {
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 #ifdef VST_SUPPORT
367         fst_exit ();
368 #endif
369         return 0;
370 }
371
372
373 microseconds_t
374 ARDOUR::get_microseconds ()
375 {
376         return (microseconds_t) jack_get_time ();
377 }
378
379 ARDOUR::Change
380 ARDOUR::new_change ()
381 {
382         Change c;
383         static uint32_t change_bit = 1;
384
385         /* catch out-of-range */
386         if (!change_bit)
387         {
388                 fatal << _("programming error: ")
389                         << "change_bit out of range in ARDOUR::new_change()"
390                         << endmsg;
391                 /*NOTREACHED*/
392         }
393
394         c = Change (change_bit);
395         change_bit <<= 1;       // if it shifts too far, change_bit == 0
396
397         return c;
398 }
399
400 string
401 ARDOUR::get_ardour_revision ()
402 {
403         return "$Rev$";
404 }
405
406 void
407 ARDOUR::find_bindings_files (map<string,string>& files)
408 {
409         vector<sys::path> found;
410         SearchPath spath = ardour_search_path() + user_config_directory() + system_config_search_path();
411
412         if (getenv ("ARDOUR_SAE")) {
413                 Glib::PatternSpec pattern("*SAE-*.bindings");
414                 find_matching_files_in_search_path (spath, pattern, found);
415         } else {
416                 Glib::PatternSpec pattern("*.bindings");
417                 find_matching_files_in_search_path (spath, pattern, found);
418         }
419
420         if (found.empty()) {
421                 return;
422         }
423
424         for (vector<sys::path>::iterator x = found.begin(); x != found.end(); ++x) {
425                 sys::path path = *x;
426                 pair<string,string> namepath;
427                 namepath.second = path.to_string();
428                 namepath.first = path.leaf().substr (0, path.leaf().find_first_of ('.'));
429                 files.insert (namepath);
430         }
431 }
432
433 ARDOUR::LocaleGuard::LocaleGuard (const char* str)
434 {
435         old = strdup (setlocale (LC_NUMERIC, NULL));
436         if (strcmp (old, str)) {
437                 setlocale (LC_NUMERIC, str);
438         }
439 }
440
441 ARDOUR::LocaleGuard::~LocaleGuard ()
442 {
443         setlocale (LC_NUMERIC, old);
444         free ((char*)old);
445 }
446
447 void
448 ARDOUR::setup_fpu ()
449 {
450
451         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
452                 // valgrind doesn't understand this assembler stuff
453                 // September 10th, 2007
454                 return;
455         }
456
457 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
458
459         int MXCSR;
460         FPU fpu;
461
462         /* XXX use real code to determine if the processor supports
463            DenormalsAreZero and FlushToZero
464         */
465
466         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
467                 return;
468         }
469
470         MXCSR  = _mm_getcsr();
471
472         switch (Config->get_denormal_model()) {
473         case DenormalNone:
474                 MXCSR &= ~(_MM_FLUSH_ZERO_ON|0x8000);
475                 break;
476
477         case DenormalFTZ:
478                 if (fpu.has_flush_to_zero()) {
479                         MXCSR |= _MM_FLUSH_ZERO_ON;
480                 }
481                 break;
482
483         case DenormalDAZ:
484                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
485                 if (fpu.has_denormals_are_zero()) {
486                         MXCSR |= 0x8000;
487                 }
488                 break;
489
490         case DenormalFTZDAZ:
491                 if (fpu.has_flush_to_zero()) {
492                         if (fpu.has_denormals_are_zero()) {
493                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x8000;
494                         } else {
495                                 MXCSR |= _MM_FLUSH_ZERO_ON;
496                         }
497                 }
498                 break;
499         }
500
501         _mm_setcsr (MXCSR);
502
503 #endif
504 }
505
506 ARDOUR::OverlapType
507 ARDOUR::coverage (nframes_t sa, nframes_t ea,
508                   nframes_t sb, nframes_t eb)
509 {
510         /* OverlapType returned reflects how the second (B)
511            range overlaps the first (A).
512
513            The diagrams show various relative placements
514            of A and B for each OverlapType.
515
516            Notes:
517               Internal: the start points cannot coincide
518               External: the start and end points can coincide
519               Start: end points can coincide
520               End: start points can coincide
521
522            XXX Logically, Internal should disallow end
523            point equality.
524         */
525
526         /*
527              |--------------------|   A
528                   |------|            B
529                 |-----------------|   B
530
531
532              "B is internal to A"
533
534         */
535 #ifdef OLD_COVERAGE
536         if ((sb >= sa) && (eb <= ea)) {
537 #else
538         if ((sb > sa) && (eb <= ea)) {
539 #endif
540                 return OverlapInternal;
541         }
542
543         /*
544              |--------------------|   A
545            ----|                      B
546            -----------------------|   B
547            --|                        B
548
549              "B overlaps the start of A"
550
551         */
552
553         if ((eb >= sa) && (eb <= ea)) {
554                 return OverlapStart;
555         }
556         /*
557              |---------------------|  A
558                    |----------------- B
559              |----------------------- B
560                                    |- B
561
562             "B overlaps the end of A"
563
564         */
565         if ((sb > sa) && (sb <= ea)) {
566                 return OverlapEnd;
567         }
568         /*
569              |--------------------|     A
570            --------------------------  B
571              |-----------------------  B
572             ----------------------|    B
573              |--------------------|    B
574
575
576            "B overlaps all of A"
577         */
578         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
579                 return OverlapExternal;
580         }
581
582         return OverlapNone;
583 }
584
585 /* not sure where to put these */
586
587 template<class T>
588 std::istream& int_to_type (std::istream& o, T& hf) {
589         int val;
590         o >> val;
591         hf = (T) val;
592         return o;
593 }
594
595 std::istream& operator>>(std::istream& o, HeaderFormat& var) { return int_to_type<HeaderFormat> (o, var); }
596 std::istream& operator>>(std::istream& o, SampleFormat& var) { return int_to_type<SampleFormat> (o, var); }
597 std::istream& operator>>(std::istream& o, AutoConnectOption& var) { return int_to_type<AutoConnectOption> (o, var); }
598 std::istream& operator>>(std::istream& o, MonitorModel& var) { return int_to_type<MonitorModel> (o, var); }
599 std::istream& operator>>(std::istream& o, RemoteModel& var) { return int_to_type<RemoteModel> (o, var); }
600 std::istream& operator>>(std::istream& o, EditMode& var) { return int_to_type<EditMode> (o, var); }
601 std::istream& operator>>(std::istream& o, SoloModel& var) { return int_to_type<SoloModel> (o, var); }
602 std::istream& operator>>(std::istream& o, LayerModel& var) { return int_to_type<LayerModel> (o, var); }
603 std::istream& operator>>(std::istream& o, CrossfadeModel& var) { return int_to_type<CrossfadeModel> (o, var); }
604 std::istream& operator>>(std::istream& o, SlaveSource& var) { return int_to_type<SlaveSource> (o, var); }
605 std::istream& operator>>(std::istream& o, ShuttleBehaviour& var) { return int_to_type<ShuttleBehaviour> (o, var); }
606 std::istream& operator>>(std::istream& o, ShuttleUnits& var) { return int_to_type<ShuttleUnits> (o, var); }
607 std::istream& operator>>(std::istream& o, SmpteFormat& var) { return int_to_type<SmpteFormat> (o, var); }
608 std::istream& operator>>(std::istream& o, DenormalModel& var) { return int_to_type<DenormalModel> (o, var); }
609