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