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