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