improve debug output
[ardour.git] / libs / ardour / globals.cc
1 /*
2  * Copyright (C) 2005-2019 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2005 Taybin Rutkin <taybin@taybin.com>
4  * Copyright (C) 2006-2008 Doug McLain <doug@nostar.net>
5  * Copyright (C) 2006-2015 David Robillard <d@drobilla.net>
6  * Copyright (C) 2006-2017 Tim Mayberry <mojofunk@gmail.com>
7  * Copyright (C) 2006 Sampo Savolainen <v2@iki.fi>
8  * Copyright (C) 2009-2012 Carl Hetherington <carl@carlh.net>
9  * Copyright (C) 2012-2019 Robin Gareus <robin@gareus.org>
10  * Copyright (C) 2013-2015 John Emmas <john@creativepost.co.uk>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  */
26
27 #ifdef WAF_BUILD
28 #include "libardour-config.h"
29 #endif
30
31 #ifdef interface
32 #undef interface
33 #endif
34
35 #include <cstdio> // Needed so that libraptor (included in lrdf) won't complain
36 #include <cstdlib>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/time.h>
40 #ifndef PLATFORM_WINDOWS
41 #include <sys/resource.h>
42 #endif
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <errno.h>
46 #include <time.h>
47
48 #include <glib.h>
49 #include "pbd/gstdio_compat.h"
50
51 #ifdef PLATFORM_WINDOWS
52 #include <stdio.h> // for _setmaxstdio
53 #include <windows.h> // for LARGE_INTEGER
54 #endif
55
56 #ifdef HAVE_FFTW35F
57 #include <fftw3.h>
58 #endif
59
60 #ifdef WINDOWS_VST_SUPPORT
61 #include <fst.h>
62 #endif
63
64 #ifdef LXVST_SUPPORT
65 #include "ardour/linux_vst_support.h"
66 #endif
67
68 #ifdef AUDIOUNIT_SUPPORT
69 #include "ardour/audio_unit.h"
70 #endif
71
72 #if defined(__SSE__) || defined(USE_XMMINTRIN)
73 #include <xmmintrin.h>
74 #endif
75
76 #ifdef check
77 #undef check /* stupid Apple and their un-namespaced, generic Carbon macros */
78 #endif
79
80 #include <glibmm/fileutils.h>
81 #include <glibmm/miscutils.h>
82
83 #ifdef HAVE_LRDF
84 #include <lrdf.h>
85 #endif
86
87 #include "pbd/cpus.h"
88 #include "pbd/error.h"
89 #include "pbd/id.h"
90 #include "pbd/pbd.h"
91 #include "pbd/strsplit.h"
92 #include "pbd/fpu.h"
93 #include "pbd/file_utils.h"
94 #include "pbd/enumwriter.h"
95
96 #include "midi++/port.h"
97 #include "midi++/mmc.h"
98
99 #include "LuaBridge/LuaBridge.h"
100
101 #include "ardour/analyser.h"
102 #include "ardour/audio_library.h"
103 #include "ardour/audio_backend.h"
104 #include "ardour/audioengine.h"
105 #include "ardour/audioplaylist.h"
106 #include "ardour/audioregion.h"
107 #include "ardour/buffer_manager.h"
108 #include "ardour/control_protocol_manager.h"
109 #include "ardour/directory_names.h"
110 #include "ardour/event_type_map.h"
111 #include "ardour/filesystem_paths.h"
112 #include "ardour/midi_region.h"
113 #include "ardour/midi_ui.h"
114 #include "ardour/midiport_manager.h"
115 #include "ardour/mix.h"
116 #include "ardour/operations.h"
117 #include "ardour/panner_manager.h"
118 #include "ardour/plugin_manager.h"
119 #include "ardour/presentation_info.h"
120 #include "ardour/process_thread.h"
121 #include "ardour/profile.h"
122 #include "ardour/rc_configuration.h"
123 #include "ardour/region.h"
124 #include "ardour/route_group.h"
125 #include "ardour/runtime_functions.h"
126 #include "ardour/session_event.h"
127 #include "ardour/source_factory.h"
128 #include "ardour/transport_fsm.h"
129 #include "ardour/transport_master_manager.h"
130 #ifdef LV2_SUPPORT
131 #include "ardour/uri_map.h"
132 #endif
133 #include "audiographer/routines.h"
134
135 #if defined (__APPLE__)
136 #include <CoreFoundation/CoreFoundation.h>
137 #endif
138
139 #include "pbd/i18n.h"
140
141 ARDOUR::RCConfiguration* ARDOUR::Config = 0;
142 ARDOUR::RuntimeProfile* ARDOUR::Profile = 0;
143 ARDOUR::AudioLibrary* ARDOUR::Library = 0;
144
145 using namespace ARDOUR;
146 using namespace std;
147 using namespace PBD;
148
149 bool libardour_initialized = false;
150
151 compute_peak_t          ARDOUR::compute_peak = 0;
152 find_peaks_t            ARDOUR::find_peaks = 0;
153 apply_gain_to_buffer_t  ARDOUR::apply_gain_to_buffer = 0;
154 mix_buffers_with_gain_t ARDOUR::mix_buffers_with_gain = 0;
155 mix_buffers_no_gain_t   ARDOUR::mix_buffers_no_gain = 0;
156 copy_vector_t           ARDOUR::copy_vector = 0;
157
158 PBD::Signal1<void,std::string> ARDOUR::BootMessage;
159 PBD::Signal3<void,std::string,std::string,bool> ARDOUR::PluginScanMessage;
160 PBD::Signal1<void,int> ARDOUR::PluginScanTimeout;
161 PBD::Signal0<void> ARDOUR::GUIIdle;
162 PBD::Signal3<bool,std::string,std::string,int> ARDOUR::CopyConfigurationFiles;
163
164 std::map<std::string, bool> ARDOUR::reserved_io_names;
165
166 static bool have_old_configuration_files = false;
167 static bool running_from_gui = false;
168
169 namespace ARDOUR {
170 extern void setup_enum_writer ();
171 }
172
173 /* this is useful for quite a few things that want to check
174    if any bounds-related property has changed
175 */
176 PBD::PropertyChange ARDOUR::bounds_change;
177
178 static PBD::ScopedConnection engine_startup_connection;
179
180 void
181 setup_hardware_optimization (bool try_optimization)
182 {
183         bool generic_mix_functions = true;
184
185         if (try_optimization) {
186
187                 FPU* fpu = FPU::instance();
188
189 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
190
191 #ifdef PLATFORM_WINDOWS
192                 /* We have AVX-optimized code for Windows */
193                 if (fpu->has_avx())
194 #else
195                 /* AVX code doesn't compile on Linux yet */
196                 if (false)
197 #endif
198                 {
199                         info << "Using AVX optimized routines" << endmsg;
200
201                         // AVX SET
202                         compute_peak          = x86_sse_avx_compute_peak;
203                         find_peaks            = x86_sse_avx_find_peaks;
204                         apply_gain_to_buffer  = x86_sse_avx_apply_gain_to_buffer;
205                         mix_buffers_with_gain = x86_sse_avx_mix_buffers_with_gain;
206                         mix_buffers_no_gain   = x86_sse_avx_mix_buffers_no_gain;
207                         copy_vector           = x86_sse_avx_copy_vector;
208
209                         generic_mix_functions = false;
210
211                 } else 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                         copy_vector           = default_copy_vector;
222
223                         generic_mix_functions = false;
224
225                 }
226
227 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
228
229                 if (floor (kCFCoreFoundationVersionNumber) > kCFCoreFoundationVersionNumber10_4) { /* at least Tiger */
230                         compute_peak           = veclib_compute_peak;
231                         find_peaks             = veclib_find_peaks;
232                         apply_gain_to_buffer   = veclib_apply_gain_to_buffer;
233                         mix_buffers_with_gain  = veclib_mix_buffers_with_gain;
234                         mix_buffers_no_gain    = veclib_mix_buffers_no_gain;
235                         copy_vector            = default_copy_vector;
236
237                         generic_mix_functions = false;
238
239                         info << "Apple VecLib H/W specific optimizations in use" << endmsg;
240                 }
241 #endif
242
243                 /* consider FPU denormal handling to be "h/w optimization" */
244
245                 setup_fpu ();
246         }
247
248         if (generic_mix_functions) {
249
250                 compute_peak          = default_compute_peak;
251                 find_peaks            = default_find_peaks;
252                 apply_gain_to_buffer  = default_apply_gain_to_buffer;
253                 mix_buffers_with_gain = default_mix_buffers_with_gain;
254                 mix_buffers_no_gain   = default_mix_buffers_no_gain;
255                 copy_vector           = default_copy_vector;
256
257                 info << "No H/W specific optimizations in use" << endmsg;
258         }
259
260         AudioGrapher::Routines::override_compute_peak (compute_peak);
261         AudioGrapher::Routines::override_apply_gain_to_buffer (apply_gain_to_buffer);
262 }
263
264 static void
265 lotsa_files_please ()
266 {
267 #ifndef PLATFORM_WINDOWS
268         struct rlimit rl;
269
270         if (getrlimit (RLIMIT_NOFILE, &rl) == 0) {
271
272 #ifdef __APPLE__
273                 /* See the COMPATIBILITY note on the Apple setrlimit() man page */
274                 rl.rlim_cur = min ((rlim_t) OPEN_MAX, rl.rlim_max);
275 #else
276                 rl.rlim_cur = rl.rlim_max;
277 #endif
278
279                 if (setrlimit (RLIMIT_NOFILE, &rl) != 0) {
280                         if (rl.rlim_cur == RLIM_INFINITY) {
281                                 error << _("Could not set system open files limit to \"unlimited\"") << endmsg;
282                         } else {
283                                 error << string_compose (_("Could not set system open files limit to %1"), rl.rlim_cur) << endmsg;
284                         }
285                 } else {
286                         if (rl.rlim_cur != RLIM_INFINITY) {
287                                 info << string_compose (_("Your system is configured to limit %1 to %2 open files"), PROGRAM_NAME, rl.rlim_cur) << endmsg;
288                         }
289                 }
290         } else {
291                 error << string_compose (_("Could not get system open files limit (%1)"), strerror (errno)) << endmsg;
292         }
293 #else
294         /* this only affects stdio. 2048 is the maxium possible (512 the default).
295          *
296          * If we want more, we'll have to replaces the POSIX I/O interfaces with
297          * Win32 API calls (CreateFile, WriteFile, etc) which allows for 16K.
298          *
299          * see http://stackoverflow.com/questions/870173/is-there-a-limit-on-number-of-open-files-in-windows
300          * and http://bugs.mysql.com/bug.php?id=24509
301          */
302         int newmax = _setmaxstdio (2048);
303         if (newmax > 0) {
304                 info << string_compose (_("Your system is configured to limit %1 to %2 open files"), PROGRAM_NAME, newmax) << endmsg;
305         } else {
306                 error << string_compose (_("Could not set system open files limit. Current limit is %1 open files"), _getmaxstdio())  << endmsg;
307         }
308 #endif
309 }
310
311 static int
312 copy_configuration_files (string const & old_dir, string const & new_dir, int old_version)
313 {
314         string old_name;
315         string new_name;
316
317         /* ensure target directory exists */
318
319         if (g_mkdir_with_parents (new_dir.c_str(), 0755)) {
320                 return -1;
321         }
322
323         if (old_version >= 3) {
324
325                 old_name = Glib::build_filename (old_dir, X_("recent"));
326                 new_name = Glib::build_filename (new_dir, X_("recent"));
327
328                 copy_file (old_name, new_name);
329
330                 old_name = Glib::build_filename (old_dir, X_("sfdb"));
331                 new_name = Glib::build_filename (new_dir, X_("sfdb"));
332
333                 copy_file (old_name, new_name);
334
335                 /* can only copy ardour.rc/config - UI config is not compatible */
336
337                 /* users who have been using git/nightlies since the last
338                  * release of 3.5 will have $CONFIG/config rather than
339                  * $CONFIG/ardour.rc. Pick up the newer "old" config file,
340                  * to avoid confusion.
341                  */
342
343                 string old_name = Glib::build_filename (old_dir, X_("config"));
344
345                 if (!Glib::file_test (old_name, Glib::FILE_TEST_EXISTS)) {
346                         old_name = Glib::build_filename (old_dir, X_("ardour.rc"));
347                 }
348
349                 new_name = Glib::build_filename (new_dir, X_("config"));
350
351                 copy_file (old_name, new_name);
352
353                 /* copy templates and route templates */
354
355                 old_name = Glib::build_filename (old_dir, X_("templates"));
356                 new_name = Glib::build_filename (new_dir, X_("templates"));
357
358                 copy_recurse (old_name, new_name);
359
360                 old_name = Glib::build_filename (old_dir, X_("route_templates"));
361                 new_name = Glib::build_filename (new_dir, X_("route_templates"));
362
363                 copy_recurse (old_name, new_name);
364
365                 /* presets */
366
367                 old_name = Glib::build_filename (old_dir, X_("presets"));
368                 new_name = Glib::build_filename (new_dir, X_("presets"));
369
370                 copy_recurse (old_name, new_name);
371
372                 /* plugin status */
373                 g_mkdir_with_parents (Glib::build_filename (new_dir, plugin_metadata_dir_name).c_str(), 0755);
374
375                 old_name = Glib::build_filename (old_dir, X_("plugin_statuses")); /* until 6.0 */
376                 new_name = Glib::build_filename (new_dir, plugin_metadata_dir_name, X_("plugin_statuses"));
377                 copy_file (old_name, new_name); /* can fail silently */
378
379                 old_name = Glib::build_filename (old_dir, plugin_metadata_dir_name, X_("plugin_statuses"));
380                 copy_file (old_name, new_name);
381
382                 /* plugin tags */
383
384                 old_name = Glib::build_filename (old_dir, plugin_metadata_dir_name, X_("plugin_tags"));
385                 new_name = Glib::build_filename (new_dir, plugin_metadata_dir_name, X_("plugin_tags"));
386
387                 copy_file (old_name, new_name);
388
389                 /* export formats */
390
391                 old_name = Glib::build_filename (old_dir, export_formats_dir_name);
392                 new_name = Glib::build_filename (new_dir, export_formats_dir_name);
393
394                 vector<string> export_formats;
395                 g_mkdir_with_parents (Glib::build_filename (new_dir, export_formats_dir_name).c_str(), 0755);
396                 find_files_matching_pattern (export_formats, old_name, X_("*.format"));
397                 for (vector<string>::iterator i = export_formats.begin(); i != export_formats.end(); ++i) {
398                         std::string from = *i;
399                         std::string to = Glib::build_filename (new_name, Glib::path_get_basename (*i));
400                         copy_file (from, to);
401                 }
402         }
403
404         return 0;
405 }
406
407 void
408 ARDOUR::check_for_old_configuration_files ()
409 {
410         int current_version = atoi (X_(PROGRAM_VERSION));
411
412         if (current_version <= 1) {
413                 return;
414         }
415
416         int old_version = current_version - 1;
417
418         string old_config_dir = user_config_directory (old_version);
419         /* pass in the current version explicitly to avoid creation */
420         string current_config_dir = user_config_directory (current_version);
421
422         if (!Glib::file_test (current_config_dir, Glib::FILE_TEST_IS_DIR)) {
423                 if (Glib::file_test (old_config_dir, Glib::FILE_TEST_IS_DIR)) {
424                         have_old_configuration_files = true;
425                 }
426         }
427 }
428
429 int
430 ARDOUR::handle_old_configuration_files (boost::function<bool (std::string const&, std::string const&, int)> ui_handler)
431 {
432         if (have_old_configuration_files) {
433                 int current_version = atoi (X_(PROGRAM_VERSION));
434                 assert (current_version > 1); // established in check_for_old_configuration_files ()
435                 int old_version = current_version - 1;
436                 string old_config_dir = user_config_directory (old_version);
437                 string current_config_dir = user_config_directory (current_version);
438
439                 if (ui_handler (old_config_dir, current_config_dir, old_version)) {
440                         copy_configuration_files (old_config_dir, current_config_dir, old_version);
441                         return 1;
442                 }
443         }
444         return 0;
445 }
446
447 bool
448 ARDOUR::init (bool use_windows_vst, bool try_optimization, const char* localedir, bool with_gui)
449 {
450         if (libardour_initialized) {
451                 return true;
452         }
453
454         running_from_gui = with_gui;
455
456 #ifndef NDEBUG
457         if (getenv("ARDOUR_LUA_METATABLES")) {
458                 luabridge::Security::setHideMetatables (false);
459         }
460 #endif
461
462 #ifdef HAVE_FFTW35F
463         fftwf_make_planner_thread_safe ();
464 #endif
465
466         if (!PBD::init()) return false;
467
468 #if ENABLE_NLS
469         (void) bindtextdomain(PACKAGE, localedir);
470         (void) bind_textdomain_codeset (PACKAGE, "UTF-8");
471 #endif
472
473         SessionEvent::init_event_pool ();
474         TransportFSM::Event::init_pool ();
475
476         Operations::make_operations_quarks ();
477         SessionObject::make_property_quarks ();
478         Region::make_property_quarks ();
479         MidiRegion::make_property_quarks ();
480         AudioRegion::make_property_quarks ();
481         RouteGroup::make_property_quarks ();
482         Playlist::make_property_quarks ();
483         AudioPlaylist::make_property_quarks ();
484         PresentationInfo::make_property_quarks ();
485         TransportMaster::make_property_quarks ();
486
487         /* this is a useful ready to use PropertyChange that many
488            things need to check. This avoids having to compose
489            it every time we want to check for any of the relevant
490            property changes.
491         */
492
493         bounds_change.add (ARDOUR::Properties::start);
494         bounds_change.add (ARDOUR::Properties::position);
495         bounds_change.add (ARDOUR::Properties::length);
496
497         /* provide a state version for the few cases that need it and are not
498            driven by reading state from disk (e.g. undo/redo)
499         */
500
501         Stateful::current_state_version = CURRENT_SESSION_FILE_VERSION;
502
503         ARDOUR::setup_enum_writer ();
504
505         // allow ardour the absolute maximum number of open files
506         lotsa_files_please ();
507
508 #ifdef HAVE_LRDF
509         lrdf_init();
510 #endif
511         Library = new AudioLibrary;
512
513         BootMessage (_("Loading configuration"));
514
515         Config = new RCConfiguration;
516
517         if (Config->load_state ()) {
518                 return false;
519         }
520
521         Config->set_use_windows_vst (use_windows_vst);
522 #ifdef LXVST_SUPPORT
523         Config->set_use_lxvst(true);
524 #endif
525
526         Profile = new RuntimeProfile;
527
528
529 #ifdef WINDOWS_VST_SUPPORT
530         if (Config->get_use_windows_vst() && fst_init (0)) {
531                 return false;
532         }
533 #endif
534
535 #ifdef LXVST_SUPPORT
536         if (Config->get_use_lxvst() && vstfx_init (0)) {
537                 return false;
538         }
539 #endif
540
541 #ifdef AUDIOUNIT_SUPPORT
542         AUPluginInfo::load_cached_info ();
543 #endif
544
545         setup_hardware_optimization (try_optimization);
546
547         SourceFactory::init ();
548         Analyser::init ();
549
550         /* singletons - first object is "it" */
551         (void) PluginManager::instance();
552 #ifdef LV2_SUPPORT
553         (void) URIMap::instance();
554 #endif
555         (void) EventTypeMap::instance();
556
557         ControlProtocolManager::instance().discover_control_protocols ();
558
559         /* for each control protocol, check for a request buffer factory method
560            and if it exists, store it in the EventLoop list of such
561            methods. This allows the relevant threads to register themselves
562            with EventLoops so that signal emission can be RT-safe.
563         */
564
565         ControlProtocolManager::instance().register_request_buffer_factories ();
566         /* it would be nice if this could auto-register itself in the
567            constructor, since MidiControlUI is a singleton, but it can't be
568            created until after the engine is running. Therefore we have to
569            explicitly register it here.
570         */
571         EventLoop::register_request_buffer_factory (X_("midiUI"), MidiControlUI::request_factory);
572
573         /* the + 4 is a bit of a handwave. i don't actually know
574            how many more per-thread buffer sets we need above
575            the h/w concurrency, but its definitely > 1 more.
576         */
577         BufferManager::init (hardware_concurrency() + 4);
578
579         PannerManager::instance().discover_panners();
580
581         ARDOUR::AudioEngine::create ();
582         TransportMasterManager::create ();
583
584         /* it is unfortunate that we need to include reserved names here that
585            refer to control surfaces. But there's no way to ensure a complete
586            lack of collisions without doing this, since the control surface
587            support may not even be active. Without adding an API to control
588            surface support that would list their port names, we do have to
589            list them here.
590
591            We also need to know if the given I/O is an actual route.
592            For routes (e.g. "master"), bus creation needs to be allowed the first time,
593            while for pure I/O (e.g. "Click") track/bus creation must always fail.
594         */
595
596         reserved_io_names[_("Monitor")] = true;
597         reserved_io_names[_("Master")] = true;
598         reserved_io_names["auditioner"] = true; // auditioner.cc  Track (s, "auditioner",...)
599         reserved_io_names[_("Virtual Keyboard")] = false;
600
601         /* pure I/O */
602         reserved_io_names[X_("Click")] = false; // session.cc ClickIO (*this, X_("Click")
603         reserved_io_names[_("Control")] = false;
604         reserved_io_names[_("Mackie")] = false;
605         reserved_io_names[_("FaderPort Recv")] = false;
606         reserved_io_names[_("FaderPort Send")] = false;
607         reserved_io_names[_("FaderPort2 Recv")] = false;
608         reserved_io_names[_("FaderPort2 Send")] = false;
609         reserved_io_names[_("FaderPort8 Recv")] = false;
610         reserved_io_names[_("FaderPort8 Send")] = false;
611         reserved_io_names[_("FaderPort16 Recv")] = false;
612         reserved_io_names[_("FaderPort16 Send")] = false;
613
614         libardour_initialized = true;
615
616         return true;
617 }
618
619 void
620 ARDOUR::init_post_engine (uint32_t start_cnt)
621 {
622         XMLNode* node;
623
624         if (start_cnt == 0) {
625
626                 if (!running_from_gui) {
627
628                         /* find plugins, but only using the existing cache (i.e. do
629                          * not discover new ones. GUIs are responsible for
630                          * invoking this themselves after the engine is
631                          * started, with whatever options they want.
632                          */
633
634                         ARDOUR::PluginManager::instance().refresh (true);
635                 }
636
637                 if ((node = Config->control_protocol_state()) != 0) {
638                         ControlProtocolManager::instance().set_state (*node, 0 /* here: global-config state */);
639                 }
640         }
641
642         if (start_cnt > 0) {
643                 TransportMasterManager::instance().restart ();
644         }
645 }
646
647 void
648 ARDOUR::cleanup ()
649 {
650         if (!libardour_initialized) {
651                 return;
652         }
653
654         engine_startup_connection.disconnect ();
655
656         delete &ControlProtocolManager::instance();
657         ARDOUR::AudioEngine::destroy ();
658
659         delete Library;
660 #ifdef HAVE_LRDF
661         lrdf_cleanup ();
662 #endif
663 #ifdef WINDOWS_VST_SUPPORT
664         fst_exit ();
665 #endif
666
667 #ifdef LXVST_SUPPORT
668         vstfx_exit();
669 #endif
670         delete &PluginManager::instance();
671         delete Config;
672         PBD::cleanup ();
673
674         return;
675 }
676
677 bool
678 ARDOUR::no_auto_connect()
679 {
680         return getenv ("ARDOUR_NO_AUTOCONNECT") != 0;
681 }
682
683 void
684 ARDOUR::setup_fpu ()
685 {
686         FPU* fpu = FPU::instance ();
687
688         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
689                 // valgrind doesn't understand this assembler stuff
690                 // September 10th, 2007
691                 return;
692         }
693
694 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
695         /* see also https://carlh.net/plugins/denormals.php */
696
697         unsigned int MXCSR;
698
699         if (!fpu->has_flush_to_zero() && !fpu->has_denormals_are_zero()) {
700                 return;
701         }
702
703         MXCSR  = _mm_getcsr();
704
705 #ifdef DEBUG_DENORMAL_EXCEPTION
706         /* This will raise a FP exception if a denormal is detected */
707         MXCSR &= ~_MM_MASK_DENORM;
708 #endif
709
710         switch (Config->get_denormal_model()) {
711         case DenormalNone:
712                 MXCSR &= ~(_MM_FLUSH_ZERO_ON | 0x40);
713                 break;
714
715         case DenormalFTZ:
716                 if (fpu->has_flush_to_zero()) {
717                         MXCSR |= _MM_FLUSH_ZERO_ON;
718                 }
719                 break;
720
721         case DenormalDAZ:
722                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
723                 if (fpu->has_denormals_are_zero()) {
724                         MXCSR |= 0x40;
725                 }
726                 break;
727
728         case DenormalFTZDAZ:
729                 if (fpu->has_flush_to_zero()) {
730                         if (fpu->has_denormals_are_zero()) {
731                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x40;
732                         } else {
733                                 MXCSR |= _MM_FLUSH_ZERO_ON;
734                         }
735                 }
736                 break;
737         }
738
739         _mm_setcsr (MXCSR);
740
741 #elif defined(__aarch64__)
742         /* http://infocenter.arm.com/help/topic/com.arm.doc.ddi0488d/CIHCACFF.html
743          * bit 24: flush-to-zero */
744         if (Config->get_denormal_model() != DenormalNone) {
745                 uint64_t cw;
746                 __asm__ __volatile__ (
747                                 "mrs    %0, fpcr           \n"
748                                 "orr    %0, %0, #0x1000000 \n"
749                                 "msr    fpcr, %0           \n"
750                                 "isb                       \n"
751                                 : "=r"(cw) :: "memory");
752         }
753
754 #elif defined(__arm__)
755         /* http://infocenter.arm.com/help/topic/com.arm.doc.dui0068b/BCFHFBGA.html
756          * bit 24: flush-to-zero */
757         if (Config->get_denormal_model() != DenormalNone) {
758                 uint32_t cw;
759                 __asm__ __volatile__ (
760                                 "vmrs   %0, fpscr          \n"
761                                 "orr    %0, %0, #0x1000000 \n"
762                                 "vmsr   fpscr, %0          \n"
763                                 : "=r"(cw) :: "memory");
764         }
765
766 #endif
767 }
768
769 /* this can be changed to modify the translation behaviour for
770    cases where the user has never expressed a preference.
771 */
772 static const bool translate_by_default = true;
773
774 string
775 ARDOUR::translation_enable_path ()
776 {
777         return Glib::build_filename (user_config_directory(), ".translate");
778 }
779
780 bool
781 ARDOUR::translations_are_enabled ()
782 {
783         int fd = g_open (ARDOUR::translation_enable_path().c_str(), O_RDONLY, 0444);
784
785         if (fd < 0) {
786                 return translate_by_default;
787         }
788
789         char c;
790         bool ret = false;
791
792         if (::read (fd, &c, 1) == 1 && c == '1') {
793                 ret = true;
794         }
795
796         ::close (fd);
797
798         return ret;
799 }
800
801 bool
802 ARDOUR::set_translations_enabled (bool yn)
803 {
804         string i18n_enabler = ARDOUR::translation_enable_path();
805         int fd = g_open (i18n_enabler.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
806
807         if (fd < 0) {
808                 return false;
809         }
810
811         char c;
812
813         if (yn) {
814                 c = '1';
815         } else {
816                 c = '0';
817         }
818
819         (void) ::write (fd, &c, 1);
820         (void) ::close (fd);
821
822         Config->ParameterChanged ("enable-translation");
823         return true;
824 }
825
826
827 vector<SyncSource>
828 ARDOUR::get_available_sync_options ()
829 {
830         vector<SyncSource> ret;
831
832         boost::shared_ptr<AudioBackend> backend = AudioEngine::instance()->current_backend();
833         if (backend && backend->name() == "JACK") {
834                 ret.push_back (Engine);
835         }
836
837         ret.push_back (MTC);
838         ret.push_back (MIDIClock);
839         ret.push_back (LTC);
840
841         return ret;
842 }
843
844 /** Return a monotonic value for the number of microseconds that have elapsed
845  * since an arbitrary zero origin.
846  */
847
848 #ifdef __MACH__
849 /* Thanks Apple for not implementing this basic SUSv2, POSIX.1-2001 function
850  */
851 #include <mach/mach_time.h>
852 #define CLOCK_REALTIME 0
853 #define CLOCK_MONOTONIC 0
854 int
855 clock_gettime (int /*clk_id*/, struct timespec *t)
856 {
857         static bool initialized = false;
858         static mach_timebase_info_data_t timebase;
859         if (!initialized) {
860                 mach_timebase_info(&timebase);
861                 initialized = true;
862         }
863         uint64_t time;
864         time = mach_absolute_time();
865         double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);
866         double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);
867         t->tv_sec = seconds;
868         t->tv_nsec = nseconds;
869         return 0;
870 }
871 #endif
872
873 microseconds_t
874 ARDOUR::get_microseconds ()
875 {
876 #ifdef PLATFORM_WINDOWS
877         microseconds_t ret = 0;
878         LARGE_INTEGER freq, time;
879
880         if (QueryPerformanceFrequency(&freq))
881                 if (QueryPerformanceCounter(&time))
882                         ret = (microseconds_t)((time.QuadPart * 1000000) / freq.QuadPart);
883
884         return ret;
885 #else
886         struct timespec ts;
887         if (clock_gettime (CLOCK_MONOTONIC, &ts) != 0) {
888                 /* EEEK! */
889                 return 0;
890         }
891         return (microseconds_t) ts.tv_sec * 1000000 + (ts.tv_nsec/1000);
892 #endif
893 }
894
895 /** Return the number of bits per sample for a given sample format.
896  *
897  * This is closely related to sndfile_data_width() but does NOT
898  * return a "magic" value to differentiate between 32 bit integer
899  * and 32 bit floating point values.
900  */
901
902 int
903 ARDOUR::format_data_width (ARDOUR::SampleFormat format)
904 {
905
906
907
908         switch (format) {
909         case ARDOUR::FormatInt16:
910                 return 16;
911         case ARDOUR::FormatInt24:
912                 return 24;
913         default:
914                 return 32;
915         }
916 }