2 Copyright (C) 2000 Paul Davis
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.
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.
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.
20 #include "libardour-config.h"
27 #include <cstdio> // Needed so that libraptor (included in lrdf) won't complain
30 #include <sys/types.h>
32 #ifndef PLATFORM_WINDOWS
33 #include <sys/resource.h>
41 #include "pbd/gstdio_compat.h"
43 #ifdef PLATFORM_WINDOWS
44 #include <stdio.h> // for _setmaxstdio
45 #include <windows.h> // for LARGE_INTEGER
48 #ifdef WINDOWS_VST_SUPPORT
53 #include "ardour/linux_vst_support.h"
56 #ifdef AUDIOUNIT_SUPPORT
57 #include "ardour/audio_unit.h"
60 #if defined(__SSE__) || defined(USE_XMMINTRIN)
61 #include <xmmintrin.h>
65 #undef check /* stupid Apple and their un-namespaced, generic Carbon macros */
68 #include <glibmm/fileutils.h>
69 #include <glibmm/miscutils.h>
76 #include "pbd/error.h"
79 #include "pbd/strsplit.h"
81 #include "pbd/file_utils.h"
82 #include "pbd/enumwriter.h"
83 #include "pbd/basename.h"
85 #include "midi++/port.h"
86 #include "midi++/mmc.h"
88 #include "ardour/analyser.h"
89 #include "ardour/audio_library.h"
90 #include "ardour/audio_backend.h"
91 #include "ardour/audioengine.h"
92 #include "ardour/audioplaylist.h"
93 #include "ardour/audioregion.h"
94 #include "ardour/buffer_manager.h"
95 #include "ardour/control_protocol_manager.h"
96 #include "ardour/directory_names.h"
97 #include "ardour/event_type_map.h"
98 #include "ardour/filesystem_paths.h"
99 #include "ardour/midi_region.h"
100 #include "ardour/midi_ui.h"
101 #include "ardour/midiport_manager.h"
102 #include "ardour/mix.h"
103 #include "ardour/operations.h"
104 #include "ardour/panner_manager.h"
105 #include "ardour/plugin_manager.h"
106 #include "ardour/process_thread.h"
107 #include "ardour/profile.h"
108 #include "ardour/rc_configuration.h"
109 #include "ardour/region.h"
110 #include "ardour/route_group.h"
111 #include "ardour/runtime_functions.h"
112 #include "ardour/session_event.h"
113 #include "ardour/source_factory.h"
114 #include "ardour/uri_map.h"
116 #include "audiographer/routines.h"
118 #if defined (__APPLE__)
119 #include <Carbon/Carbon.h> // For Gestalt
124 ARDOUR::RCConfiguration* ARDOUR::Config = 0;
125 ARDOUR::RuntimeProfile* ARDOUR::Profile = 0;
126 ARDOUR::AudioLibrary* ARDOUR::Library = 0;
128 using namespace ARDOUR;
132 bool libardour_initialized = false;
134 compute_peak_t ARDOUR::compute_peak = 0;
135 find_peaks_t ARDOUR::find_peaks = 0;
136 apply_gain_to_buffer_t ARDOUR::apply_gain_to_buffer = 0;
137 mix_buffers_with_gain_t ARDOUR::mix_buffers_with_gain = 0;
138 mix_buffers_no_gain_t ARDOUR::mix_buffers_no_gain = 0;
139 copy_vector_t ARDOUR::copy_vector = 0;
141 PBD::Signal1<void,std::string> ARDOUR::BootMessage;
142 PBD::Signal3<void,std::string,std::string,bool> ARDOUR::PluginScanMessage;
143 PBD::Signal1<void,int> ARDOUR::PluginScanTimeout;
144 PBD::Signal0<void> ARDOUR::GUIIdle;
145 PBD::Signal3<bool,std::string,std::string,int> ARDOUR::CopyConfigurationFiles;
147 std::vector<std::string> ARDOUR::reserved_io_names;
149 static bool have_old_configuration_files = false;
152 extern void setup_enum_writer ();
155 /* this is useful for quite a few things that want to check
156 if any bounds-related property has changed
158 PBD::PropertyChange ARDOUR::bounds_change;
161 setup_hardware_optimization (bool try_optimization)
163 bool generic_mix_functions = true;
165 if (try_optimization) {
167 FPU* fpu = FPU::instance();
169 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
171 #ifdef PLATFORM_WINDOWS
172 /* We have AVX-optimized code for Windows */
174 if (fpu->has_avx()) {
176 /* AVX code doesn't compile on Linux yet */
180 info << "Using AVX optimized routines" << endmsg;
183 compute_peak = x86_sse_avx_compute_peak;
184 find_peaks = x86_sse_avx_find_peaks;
185 apply_gain_to_buffer = x86_sse_avx_apply_gain_to_buffer;
186 mix_buffers_with_gain = x86_sse_avx_mix_buffers_with_gain;
187 mix_buffers_no_gain = x86_sse_avx_mix_buffers_no_gain;
188 copy_vector = x86_sse_avx_copy_vector;
190 generic_mix_functions = false;
192 } else if (fpu->has_sse()) {
194 info << "Using SSE optimized routines" << endmsg;
197 compute_peak = x86_sse_compute_peak;
198 find_peaks = x86_sse_find_peaks;
199 apply_gain_to_buffer = x86_sse_apply_gain_to_buffer;
200 mix_buffers_with_gain = x86_sse_mix_buffers_with_gain;
201 mix_buffers_no_gain = x86_sse_mix_buffers_no_gain;
202 copy_vector = default_copy_vector;
204 generic_mix_functions = false;
208 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
209 SInt32 sysVersion = 0;
211 if (noErr != Gestalt(gestaltSystemVersion, &sysVersion))
214 if (sysVersion >= 0x00001040) { // Tiger at least
215 compute_peak = veclib_compute_peak;
216 find_peaks = veclib_find_peaks;
217 apply_gain_to_buffer = veclib_apply_gain_to_buffer;
218 mix_buffers_with_gain = veclib_mix_buffers_with_gain;
219 mix_buffers_no_gain = veclib_mix_buffers_no_gain;
220 copy_vector = default_copy_vector;
222 generic_mix_functions = false;
224 info << "Apple VecLib H/W specific optimizations in use" << endmsg;
228 /* consider FPU denormal handling to be "h/w optimization" */
233 if (generic_mix_functions) {
235 compute_peak = default_compute_peak;
236 find_peaks = default_find_peaks;
237 apply_gain_to_buffer = default_apply_gain_to_buffer;
238 mix_buffers_with_gain = default_mix_buffers_with_gain;
239 mix_buffers_no_gain = default_mix_buffers_no_gain;
240 copy_vector = default_copy_vector;
242 info << "No H/W specific optimizations in use" << endmsg;
245 AudioGrapher::Routines::override_compute_peak (compute_peak);
246 AudioGrapher::Routines::override_apply_gain_to_buffer (apply_gain_to_buffer);
250 lotsa_files_please ()
252 #ifndef PLATFORM_WINDOWS
255 if (getrlimit (RLIMIT_NOFILE, &rl) == 0) {
258 /* See the COMPATIBILITY note on the Apple setrlimit() man page */
259 rl.rlim_cur = min ((rlim_t) OPEN_MAX, rl.rlim_max);
261 rl.rlim_cur = rl.rlim_max;
264 if (setrlimit (RLIMIT_NOFILE, &rl) != 0) {
265 if (rl.rlim_cur == RLIM_INFINITY) {
266 error << _("Could not set system open files limit to \"unlimited\"") << endmsg;
268 error << string_compose (_("Could not set system open files limit to %1"), rl.rlim_cur) << endmsg;
271 if (rl.rlim_cur != RLIM_INFINITY) {
272 info << string_compose (_("Your system is configured to limit %1 to only %2 open files"), PROGRAM_NAME, rl.rlim_cur) << endmsg;
276 error << string_compose (_("Could not get system open files limit (%1)"), strerror (errno)) << endmsg;
279 /* this only affects stdio. 2048 is the maxium possible (512 the default).
281 * If we want more, we'll have to replaces the POSIX I/O interfaces with
282 * Win32 API calls (CreateFile, WriteFile, etc) which allows for 16K.
284 * see http://stackoverflow.com/questions/870173/is-there-a-limit-on-number-of-open-files-in-windows
285 * and http://bugs.mysql.com/bug.php?id=24509
287 int newmax = _setmaxstdio (2048);
289 info << string_compose (_("Your system is configured to limit %1 to only %2 open files"), PROGRAM_NAME, newmax) << endmsg;
291 error << string_compose (_("Could not set system open files limit. Current limit is %1 open files"), _getmaxstdio) << endmsg;
297 copy_configuration_files (string const & old_dir, string const & new_dir, int old_version)
302 /* ensure target directory exists */
304 if (g_mkdir_with_parents (new_dir.c_str(), 0755)) {
308 if (old_version == 3) {
310 old_name = Glib::build_filename (old_dir, X_("recent"));
311 new_name = Glib::build_filename (new_dir, X_("recent"));
313 copy_file (old_name, new_name);
315 old_name = Glib::build_filename (old_dir, X_("sfdb"));
316 new_name = Glib::build_filename (new_dir, X_("sfdb"));
318 copy_file (old_name, new_name);
320 /* can only copy ardour.rc/config - UI config is not compatible */
322 /* users who have been using git/nightlies since the last
323 * release of 3.5 will have $CONFIG/config rather than
324 * $CONFIG/ardour.rc. Pick up the newer "old" config file,
325 * to avoid confusion.
328 string old_name = Glib::build_filename (old_dir, X_("config"));
330 if (!Glib::file_test (old_name, Glib::FILE_TEST_EXISTS)) {
331 old_name = Glib::build_filename (old_dir, X_("ardour.rc"));
334 new_name = Glib::build_filename (new_dir, X_("config"));
336 copy_file (old_name, new_name);
338 /* copy templates and route templates */
340 old_name = Glib::build_filename (old_dir, X_("templates"));
341 new_name = Glib::build_filename (new_dir, X_("templates"));
343 copy_recurse (old_name, new_name);
345 old_name = Glib::build_filename (old_dir, X_("route_templates"));
346 new_name = Glib::build_filename (new_dir, X_("route_templates"));
348 copy_recurse (old_name, new_name);
352 old_name = Glib::build_filename (old_dir, X_("presets"));
353 new_name = Glib::build_filename (new_dir, X_("presets"));
355 copy_recurse (old_name, new_name);
359 old_name = Glib::build_filename (old_dir, X_("plugin_statuses"));
360 new_name = Glib::build_filename (new_dir, X_("plugin_statuses"));
362 copy_file (old_name, new_name);
366 old_name = Glib::build_filename (old_dir, export_formats_dir_name);
367 new_name = Glib::build_filename (new_dir, export_formats_dir_name);
369 vector<string> export_formats;
370 g_mkdir_with_parents (Glib::build_filename (new_dir, export_formats_dir_name).c_str(), 0755);
371 find_files_matching_pattern (export_formats, old_name, X_("*.format"));
372 for (vector<string>::iterator i = export_formats.begin(); i != export_formats.end(); ++i) {
373 std::string from = *i;
374 std::string to = Glib::build_filename (new_name, Glib::path_get_basename (*i));
375 copy_file (from, to);
383 ARDOUR::check_for_old_configuration_files ()
385 int current_version = atoi (X_(PROGRAM_VERSION));
387 if (current_version <= 1) {
391 int old_version = current_version - 1;
393 string old_config_dir = user_config_directory (old_version);
394 /* pass in the current version explicitly to avoid creation */
395 string current_config_dir = user_config_directory (current_version);
397 if (!Glib::file_test (current_config_dir, Glib::FILE_TEST_IS_DIR)) {
398 if (Glib::file_test (old_config_dir, Glib::FILE_TEST_IS_DIR)) {
399 have_old_configuration_files = true;
405 ARDOUR::handle_old_configuration_files (boost::function<bool (std::string const&, std::string const&, int)> ui_handler)
407 if (have_old_configuration_files) {
408 int current_version = atoi (X_(PROGRAM_VERSION));
409 assert (current_version > 1); // established in check_for_old_configuration_files ()
410 int old_version = current_version - 1;
411 string old_config_dir = user_config_directory (old_version);
412 string current_config_dir = user_config_directory (current_version);
414 if (ui_handler (old_config_dir, current_config_dir, old_version)) {
415 copy_configuration_files (old_config_dir, current_config_dir, old_version);
423 ARDOUR::init (bool use_windows_vst, bool try_optimization, const char* localedir)
425 if (libardour_initialized) {
429 if (!PBD::init()) return false;
432 (void) bindtextdomain(PACKAGE, localedir);
433 (void) bind_textdomain_codeset (PACKAGE, "UTF-8");
436 SessionEvent::init_event_pool ();
438 Operations::make_operations_quarks ();
439 SessionObject::make_property_quarks ();
440 Region::make_property_quarks ();
441 MidiRegion::make_property_quarks ();
442 AudioRegion::make_property_quarks ();
443 RouteGroup::make_property_quarks ();
444 Playlist::make_property_quarks ();
445 AudioPlaylist::make_property_quarks ();
447 /* this is a useful ready to use PropertyChange that many
448 things need to check. This avoids having to compose
449 it every time we want to check for any of the relevant
453 bounds_change.add (ARDOUR::Properties::start);
454 bounds_change.add (ARDOUR::Properties::position);
455 bounds_change.add (ARDOUR::Properties::length);
457 /* provide a state version for the few cases that need it and are not
458 driven by reading state from disk (e.g. undo/redo)
461 Stateful::current_state_version = CURRENT_SESSION_FILE_VERSION;
463 ARDOUR::setup_enum_writer ();
465 // allow ardour the absolute maximum number of open files
466 lotsa_files_please ();
471 Library = new AudioLibrary;
473 BootMessage (_("Loading configuration"));
475 Config = new RCConfiguration;
477 if (Config->load_state ()) {
481 Config->set_use_windows_vst (use_windows_vst);
483 Config->set_use_lxvst(true);
486 Profile = new RuntimeProfile;
489 #ifdef WINDOWS_VST_SUPPORT
490 if (Config->get_use_windows_vst() && fst_init (0)) {
496 if (Config->get_use_lxvst() && vstfx_init (0)) {
501 #ifdef AUDIOUNIT_SUPPORT
502 AUPluginInfo::load_cached_info ();
505 setup_hardware_optimization (try_optimization);
507 SourceFactory::init ();
510 /* singletons - first object is "it" */
511 (void) PluginManager::instance();
513 (void) URIMap::instance();
515 (void) EventTypeMap::instance();
517 ControlProtocolManager::instance().discover_control_protocols ();
519 /* for each control protocol, check for a request buffer factory method
520 and if it exists, store it in the EventLoop list of such
521 methods. This allows the relevant threads to register themselves
522 with EventLoops so that signal emission can be RT-safe.
525 ControlProtocolManager::instance().register_request_buffer_factories ();
526 /* it would be nice if this could auto-register itself in the
527 constructor, since MidiControlUI is a singleton, but it can't be
528 created until after the engine is running. Therefore we have to
529 explicitly register it here.
531 EventLoop::register_request_buffer_factory (X_("midiUI"), MidiControlUI::request_factory);
533 ProcessThread::init ();
534 /* the + 4 is a bit of a handwave. i don't actually know
535 how many more per-thread buffer sets we need above
536 the h/w concurrency, but its definitely > 1 more.
538 BufferManager::init (hardware_concurrency() + 4);
540 PannerManager::instance().discover_panners();
542 ARDOUR::AudioEngine::create ();
544 /* it is unfortunate that we need to include reserved names here that
545 refer to control surfaces. But there's no way to ensure a complete
546 lack of collisions without doing this, since the control surface
547 support may not even be active. Without adding an API to control
548 surface support that would list their port names, we do have to
552 char const * const reserved[] = {
561 for (int n = 0; reserved[n]; ++n) {
562 reserved_io_names.push_back (reserved[n]);
565 libardour_initialized = true;
571 ARDOUR::init_post_engine ()
574 if ((node = Config->control_protocol_state()) != 0) {
575 ControlProtocolManager::instance().set_state (*node, Stateful::loading_state_version);
580 ARDOUR::PluginManager::instance().refresh (!Config->get_discover_vst_on_start());
586 if (!libardour_initialized) {
590 ARDOUR::AudioEngine::destroy ();
596 delete &ControlProtocolManager::instance();
597 #ifdef WINDOWS_VST_SUPPORT
604 delete &PluginManager::instance();
612 ARDOUR::find_bindings_files (map<string,string>& files)
614 vector<std::string> found;
615 Searchpath spath = ardour_config_search_path();
617 if (getenv ("ARDOUR_SAE")) {
618 find_files_matching_pattern (found, spath, "*SAE-*.bindings");
620 find_files_matching_pattern (found, spath, "*.bindings");
627 for (vector<std::string>::iterator x = found.begin(); x != found.end(); ++x) {
628 std::string path(*x);
629 pair<string,string> namepath;
630 namepath.second = path;
631 namepath.first = PBD::basename_nosuffix (path);
632 files.insert (namepath);
637 ARDOUR::no_auto_connect()
639 return getenv ("ARDOUR_NO_AUTOCONNECT") != 0;
645 FPU* fpu = FPU::instance ();
647 if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
648 // valgrind doesn't understand this assembler stuff
649 // September 10th, 2007
653 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
657 if (!fpu->has_flush_to_zero() && !fpu->has_denormals_are_zero()) {
661 MXCSR = _mm_getcsr();
663 #ifdef DEBUG_DENORMAL_EXCEPTION
664 /* This will raise a FP exception if a denormal is detected */
665 MXCSR &= ~_MM_MASK_DENORM;
668 switch (Config->get_denormal_model()) {
670 MXCSR &= ~(_MM_FLUSH_ZERO_ON | 0x40);
674 if (fpu->has_flush_to_zero()) {
675 MXCSR |= _MM_FLUSH_ZERO_ON;
680 MXCSR &= ~_MM_FLUSH_ZERO_ON;
681 if (fpu->has_denormals_are_zero()) {
687 if (fpu->has_flush_to_zero()) {
688 if (fpu->has_denormals_are_zero()) {
689 MXCSR |= _MM_FLUSH_ZERO_ON | 0x40;
691 MXCSR |= _MM_FLUSH_ZERO_ON;
702 /* this can be changed to modify the translation behaviour for
703 cases where the user has never expressed a preference.
705 static const bool translate_by_default = true;
708 ARDOUR::translation_enable_path ()
710 return Glib::build_filename (user_config_directory(), ".translate");
714 ARDOUR::translations_are_enabled ()
716 int fd = g_open (ARDOUR::translation_enable_path().c_str(), O_RDONLY, 0444);
719 return translate_by_default;
725 if (::read (fd, &c, 1) == 1 && c == '1') {
735 ARDOUR::set_translations_enabled (bool yn)
737 string i18n_enabler = ARDOUR::translation_enable_path();
738 int fd = g_open (i18n_enabler.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
752 (void) ::write (fd, &c, 1);
760 ARDOUR::get_available_sync_options ()
762 vector<SyncSource> ret;
764 boost::shared_ptr<AudioBackend> backend = AudioEngine::instance()->current_backend();
765 if (backend && backend->name() == "JACK") {
766 ret.push_back (Engine);
770 ret.push_back (MIDIClock);
776 /** Return a monotonic value for the number of microseconds that have elapsed
777 * since an arbitrary zero origin.
781 /* Thanks Apple for not implementing this basic SUSv2, POSIX.1-2001 function
783 #include <mach/mach_time.h>
784 #define CLOCK_REALTIME 0
785 #define CLOCK_MONOTONIC 0
787 clock_gettime (int /*clk_id*/, struct timespec *t)
789 static bool initialized = false;
790 static mach_timebase_info_data_t timebase;
792 mach_timebase_info(&timebase);
796 time = mach_absolute_time();
797 double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);
798 double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);
800 t->tv_nsec = nseconds;
806 ARDOUR::get_microseconds ()
808 #ifdef PLATFORM_WINDOWS
809 microseconds_t ret = 0;
810 LARGE_INTEGER freq, time;
812 if (QueryPerformanceFrequency(&freq))
813 if (QueryPerformanceCounter(&time))
814 ret = (microseconds_t)((time.QuadPart * 1000000) / freq.QuadPart);
819 if (clock_gettime (CLOCK_MONOTONIC, &ts) != 0) {
823 return (microseconds_t) ts.tv_sec * 1000000 + (ts.tv_nsec/1000);
827 /** Return the number of bits per sample for a given sample format.
829 * This is closely related to sndfile_data_width() but does NOT
830 * return a "magic" value to differentiate between 32 bit integer
831 * and 32 bit floating point values.
835 ARDOUR::format_data_width (ARDOUR::SampleFormat format)
841 case ARDOUR::FormatInt16:
843 case ARDOUR::FormatInt24: