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