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