alter config file copying infrastructure so it can be used at a suitable time in...
[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 #ifdef PLATFORM_WINDOWS
41 #include <windows.h> // for LARGE_INTEGER
42 #endif
43
44 #ifdef WINDOWS_VST_SUPPORT
45 #include <fst.h>
46 #endif
47
48 #ifdef LXVST_SUPPORT
49 #include "ardour/linux_vst_support.h"
50 #endif
51
52 #ifdef AUDIOUNIT_SUPPORT
53 #include "ardour/audio_unit.h"
54 #endif
55
56 #if defined(__SSE__) || defined(USE_XMMINTRIN)
57 #include <xmmintrin.h>
58 #endif
59
60 #ifdef check
61 #undef check /* stupid Apple and their un-namespaced, generic Carbon macros */
62 #endif 
63
64 #include <glibmm/fileutils.h>
65 #include <glibmm/miscutils.h>
66
67 #ifdef HAVE_LRDF
68 #include <lrdf.h>
69 #endif
70
71 #include "pbd/cpus.h"
72 #include "pbd/error.h"
73 #include "pbd/id.h"
74 #include "pbd/pbd.h"
75 #include "pbd/strsplit.h"
76 #include "pbd/fpu.h"
77 #include "pbd/file_utils.h"
78 #include "pbd/enumwriter.h"
79 #include "pbd/basename.h"
80
81 #include "midi++/port.h"
82 #include "midi++/mmc.h"
83
84 #include "ardour/analyser.h"
85 #include "ardour/audio_library.h"
86 #include "ardour/audio_backend.h"
87 #include "ardour/audioengine.h"
88 #include "ardour/audioplaylist.h"
89 #include "ardour/audioregion.h"
90 #include "ardour/buffer_manager.h"
91 #include "ardour/control_protocol_manager.h"
92 #include "ardour/directory_names.h"
93 #include "ardour/event_type_map.h"
94 #include "ardour/filesystem_paths.h"
95 #include "ardour/midi_region.h"
96 #include "ardour/midiport_manager.h"
97 #include "ardour/mix.h"
98 #include "ardour/operations.h"
99 #include "ardour/panner_manager.h"
100 #include "ardour/plugin_manager.h"
101 #include "ardour/process_thread.h"
102 #include "ardour/profile.h"
103 #include "ardour/rc_configuration.h"
104 #include "ardour/region.h"
105 #include "ardour/route_group.h"
106 #include "ardour/runtime_functions.h"
107 #include "ardour/session_event.h"
108 #include "ardour/source_factory.h"
109 #include "ardour/uri_map.h"
110
111 #include "audiographer/routines.h"
112
113 #if defined (__APPLE__)
114        #include <Carbon/Carbon.h> // For Gestalt
115 #endif
116
117 #include "i18n.h"
118
119 ARDOUR::RCConfiguration* ARDOUR::Config = 0;
120 ARDOUR::RuntimeProfile* ARDOUR::Profile = 0;
121 ARDOUR::AudioLibrary* ARDOUR::Library = 0;
122
123 using namespace ARDOUR;
124 using namespace std;
125 using namespace PBD;
126
127 bool libardour_initialized = false;
128
129 compute_peak_t          ARDOUR::compute_peak = 0;
130 find_peaks_t            ARDOUR::find_peaks = 0;
131 apply_gain_to_buffer_t  ARDOUR::apply_gain_to_buffer = 0;
132 mix_buffers_with_gain_t ARDOUR::mix_buffers_with_gain = 0;
133 mix_buffers_no_gain_t   ARDOUR::mix_buffers_no_gain = 0;
134
135 PBD::Signal1<void,std::string> ARDOUR::BootMessage;
136 PBD::Signal3<void,std::string,std::string,bool> ARDOUR::PluginScanMessage;
137 PBD::Signal1<void,int> ARDOUR::PluginScanTimeout;
138 PBD::Signal0<void> ARDOUR::GUIIdle;
139 PBD::Signal3<bool,std::string,std::string,int> ARDOUR::CopyConfigurationFiles;
140
141 namespace ARDOUR {
142 extern void setup_enum_writer ();
143 }
144
145 /* this is useful for quite a few things that want to check
146    if any bounds-related property has changed
147 */
148 PBD::PropertyChange ARDOUR::bounds_change;
149
150 void
151 setup_hardware_optimization (bool try_optimization)
152 {
153         bool generic_mix_functions = true;
154
155         if (try_optimization) {
156
157                 FPU fpu;
158
159 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
160
161                 if (fpu.has_sse()) {
162
163                         info << "Using SSE optimized routines" << endmsg;
164
165                         // SSE SET
166                         compute_peak          = x86_sse_compute_peak;
167                         find_peaks            = x86_sse_find_peaks;
168                         apply_gain_to_buffer  = x86_sse_apply_gain_to_buffer;
169                         mix_buffers_with_gain = x86_sse_mix_buffers_with_gain;
170                         mix_buffers_no_gain   = x86_sse_mix_buffers_no_gain;
171
172                         generic_mix_functions = false;
173
174                 }
175
176 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
177                 SInt32 sysVersion = 0;
178
179                 if (noErr != Gestalt(gestaltSystemVersion, &sysVersion))
180                         sysVersion = 0;
181
182                 if (sysVersion >= 0x00001040) { // Tiger at least
183                         compute_peak           = veclib_compute_peak;
184                         find_peaks             = veclib_find_peaks;
185                         apply_gain_to_buffer   = veclib_apply_gain_to_buffer;
186                         mix_buffers_with_gain  = veclib_mix_buffers_with_gain;
187                         mix_buffers_no_gain    = veclib_mix_buffers_no_gain;
188
189                         generic_mix_functions = false;
190
191                         info << "Apple VecLib H/W specific optimizations in use" << endmsg;
192                 }
193 #endif
194
195                 /* consider FPU denormal handling to be "h/w optimization" */
196
197                 setup_fpu ();
198         }
199
200         if (generic_mix_functions) {
201
202                 compute_peak          = default_compute_peak;
203                 find_peaks            = default_find_peaks;
204                 apply_gain_to_buffer  = default_apply_gain_to_buffer;
205                 mix_buffers_with_gain = default_mix_buffers_with_gain;
206                 mix_buffers_no_gain   = default_mix_buffers_no_gain;
207
208                 info << "No H/W specific optimizations in use" << endmsg;
209         }
210
211         AudioGrapher::Routines::override_compute_peak (compute_peak);
212         AudioGrapher::Routines::override_apply_gain_to_buffer (apply_gain_to_buffer);
213 }
214
215 static void
216 lotsa_files_please ()
217 {
218 #ifndef PLATFORM_WINDOWS
219         struct rlimit rl;
220
221         if (getrlimit (RLIMIT_NOFILE, &rl) == 0) {
222
223 #ifdef __APPLE__
224                 /* See the COMPATIBILITY note on the Apple setrlimit() man page */
225                 rl.rlim_cur = min ((rlim_t) OPEN_MAX, rl.rlim_max);
226 #else
227                 rl.rlim_cur = rl.rlim_max;
228 #endif
229
230                 if (setrlimit (RLIMIT_NOFILE, &rl) != 0) {
231                         if (rl.rlim_cur == RLIM_INFINITY) {
232                                 error << _("Could not set system open files limit to \"unlimited\"") << endmsg;
233                         } else {
234                                 error << string_compose (_("Could not set system open files limit to %1"), rl.rlim_cur) << endmsg;
235                         }
236                 } else {
237                         if (rl.rlim_cur != RLIM_INFINITY) {
238                                 info << string_compose (_("Your system is configured to limit %1 to only %2 open files"), PROGRAM_NAME, rl.rlim_cur) << endmsg;
239                         }
240                 }
241         } else {
242                 error << string_compose (_("Could not get system open files limit (%1)"), strerror (errno)) << endmsg;
243         }
244 #endif
245 }
246
247 static int
248 copy_configuration_files (string const & old_dir, string const & new_dir, int old_version)
249 {
250         string old_name;
251         string new_name;
252
253         /* ensure target directory exists */
254
255         if (g_mkdir_with_parents (new_dir.c_str(), 0755)) {
256                 return -1;
257         }
258         
259         if (old_version == 3) {
260         
261                 old_name = Glib::build_filename (old_dir, X_("recent"));
262                 new_name = Glib::build_filename (new_dir, X_("recent"));
263
264                 copy_file (old_name, new_name);
265
266                 /* can only copy ardour.rc - UI config is not compatible */
267
268                 old_name = Glib::build_filename (old_dir, X_("ardour.rc"));
269                 new_name = Glib::build_filename (new_dir, X_("config"));
270
271                 copy_file (old_name, new_name);
272
273                 /* copy templates and route templates */
274
275                 old_name = Glib::build_filename (old_dir, X_("templates"));
276                 new_name = Glib::build_filename (new_dir, X_("templates"));
277
278                 copy_recurse (old_name, new_name);
279
280                 old_name = Glib::build_filename (old_dir, X_("route_templates"));
281                 new_name = Glib::build_filename (new_dir, X_("route_templates"));
282
283                 copy_recurse (old_name, new_name);
284
285                 /* presets */
286
287                 old_name = Glib::build_filename (old_dir, X_("presets"));
288                 new_name = Glib::build_filename (new_dir, X_("presets"));
289                 
290                 copy_recurse (old_name, new_name);
291
292                 /* presets */
293
294                 old_name = Glib::build_filename (old_dir, X_("plugin_statuses"));
295                 new_name = Glib::build_filename (new_dir, X_("plugin_statuses"));
296
297                 copy_file (old_name, new_name);
298                 
299                 /* export formats */
300
301                 old_name = Glib::build_filename (old_dir, export_formats_dir_name);
302                 new_name = Glib::build_filename (new_dir, export_formats_dir_name);
303                 
304                 vector<string> export_formats;
305                 g_mkdir_with_parents (Glib::build_filename (new_dir, export_formats_dir_name).c_str(), 0755);
306                 find_files_matching_pattern (export_formats, old_name, X_("*.format"));
307                 for (vector<string>::iterator i = export_formats.begin(); i != export_formats.end(); ++i) {
308                         std::string from = *i;
309                         std::string to = Glib::build_filename (new_name, Glib::path_get_basename (*i));
310                         copy_file (from, to);
311                 }
312         }
313
314         return 0;
315 }
316
317 int
318 ARDOUR::check_for_old_configuration_files (boost::function<bool (std::string const&, std::string const&, int)> ui_handler)
319 {
320         int current_version = atoi (X_(PROGRAM_VERSION));
321         
322         if (current_version <= 1) {
323                 return 0;
324         }
325
326         int old_version = current_version - 1;
327
328         string old_config_dir = user_config_directory (old_version);
329         /* pass in the current version explicitly to avoid creation */
330         string current_config_dir = user_config_directory (current_version); 
331
332         if (!Glib::file_test (current_config_dir, Glib::FILE_TEST_IS_DIR)) {
333                 if (Glib::file_test (old_config_dir, Glib::FILE_TEST_IS_DIR)) {
334                         
335                         if (ui_handler (old_config_dir, current_config_dir, old_version)) {
336                                 copy_configuration_files (old_config_dir, current_config_dir, old_version);
337                                 return 1;
338                         }
339                 }
340         }
341
342         return 0;
343 }
344
345 bool
346 ARDOUR::init (bool use_windows_vst, bool try_optimization, const char* localedir)
347 {
348         if (libardour_initialized) {
349                 return true;
350         }
351
352         if (!PBD::init()) return false;
353
354 #ifdef ENABLE_NLS
355         (void) bindtextdomain(PACKAGE, localedir);
356         (void) bind_textdomain_codeset (PACKAGE, "UTF-8");
357 #endif
358
359         SessionEvent::init_event_pool ();
360
361         Operations::make_operations_quarks ();
362         SessionObject::make_property_quarks ();
363         Region::make_property_quarks ();
364         MidiRegion::make_property_quarks ();
365         AudioRegion::make_property_quarks ();
366         RouteGroup::make_property_quarks ();
367         Playlist::make_property_quarks ();
368         AudioPlaylist::make_property_quarks ();
369
370         /* this is a useful ready to use PropertyChange that many
371            things need to check. This avoids having to compose
372            it every time we want to check for any of the relevant
373            property changes.
374         */
375
376         bounds_change.add (ARDOUR::Properties::start);
377         bounds_change.add (ARDOUR::Properties::position);
378         bounds_change.add (ARDOUR::Properties::length);
379
380         /* provide a state version for the few cases that need it and are not
381            driven by reading state from disk (e.g. undo/redo)
382         */
383
384         Stateful::current_state_version = CURRENT_SESSION_FILE_VERSION;
385
386         ARDOUR::setup_enum_writer ();
387
388         // allow ardour the absolute maximum number of open files
389         lotsa_files_please ();
390
391 #ifdef HAVE_LRDF
392         lrdf_init();
393 #endif
394         Library = new AudioLibrary;
395
396         BootMessage (_("Loading configuration"));
397
398         Config = new RCConfiguration;
399
400         if (Config->load_state ()) {
401                 return false;
402         }
403
404         Config->set_use_windows_vst (use_windows_vst);
405 #ifdef LXVST_SUPPORT
406         Config->set_use_lxvst(true);
407 #endif
408
409         Profile = new RuntimeProfile;
410
411
412 #ifdef WINDOWS_VST_SUPPORT
413         if (Config->get_use_windows_vst() && fst_init (0)) {
414                 return false;
415         }
416 #endif
417
418 #ifdef LXVST_SUPPORT
419         if (Config->get_use_lxvst() && vstfx_init (0)) {
420                 return false;
421         }
422 #endif
423
424 #ifdef AUDIOUNIT_SUPPORT
425         AUPluginInfo::load_cached_info ();
426 #endif
427
428         setup_hardware_optimization (try_optimization);
429
430         SourceFactory::init ();
431         Analyser::init ();
432
433         /* singletons - first object is "it" */
434         (void) PluginManager::instance();
435 #ifdef LV2_SUPPORT
436         (void) URIMap::instance();
437 #endif
438         (void) EventTypeMap::instance();
439
440         ProcessThread::init ();
441         /* the + 4 is a bit of a handwave. i don't actually know
442            how many more per-thread buffer sets we need above
443            the h/w concurrency, but its definitely > 1 more.
444         */
445         BufferManager::init (hardware_concurrency() + 4); 
446
447         PannerManager::instance().discover_panners();
448
449         ARDOUR::AudioEngine::create ();
450
451         libardour_initialized = true;
452
453         return true;
454 }
455
456 void
457 ARDOUR::init_post_engine ()
458 {
459         ControlProtocolManager::instance().discover_control_protocols ();
460
461         XMLNode* node;
462         if ((node = Config->control_protocol_state()) != 0) {
463                 ControlProtocolManager::instance().set_state (*node, Stateful::loading_state_version);
464         }
465
466         /* find plugins */
467
468         ARDOUR::PluginManager::instance().refresh (!Config->get_discover_vst_on_start());
469 }
470
471 void
472 ARDOUR::cleanup () 
473 {
474         if (!libardour_initialized) {
475                 return;
476         }
477
478         ARDOUR::AudioEngine::destroy ();
479
480         delete Library;
481 #ifdef HAVE_LRDF
482         lrdf_cleanup ();
483 #endif
484         delete &ControlProtocolManager::instance();
485 #ifdef WINDOWS_VST_SUPPORT
486         fst_exit ();
487 #endif
488
489 #ifdef LXVST_SUPPORT
490         vstfx_exit();
491 #endif
492         delete &PluginManager::instance();
493         delete Config;
494         PBD::cleanup ();
495
496         return;
497 }
498
499 void
500 ARDOUR::find_bindings_files (map<string,string>& files)
501 {
502         vector<std::string> found;
503         Searchpath spath = ardour_config_search_path();
504
505         if (getenv ("ARDOUR_SAE")) {
506                 find_files_matching_pattern (found, spath, "*SAE-*.bindings");
507         } else {
508                 find_files_matching_pattern (found, spath, "*.bindings");
509         }
510
511         if (found.empty()) {
512                 return;
513         }
514
515         for (vector<std::string>::iterator x = found.begin(); x != found.end(); ++x) {
516                 std::string path(*x);
517                 pair<string,string> namepath;
518                 namepath.second = path;
519                 namepath.first = PBD::basename_nosuffix (path);
520                 files.insert (namepath);
521         }
522 }
523
524 bool
525 ARDOUR::no_auto_connect()
526 {
527         return getenv ("ARDOUR_NO_AUTOCONNECT") != 0;
528 }
529
530 void
531 ARDOUR::setup_fpu ()
532 {
533
534         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
535                 // valgrind doesn't understand this assembler stuff
536                 // September 10th, 2007
537                 return;
538         }
539
540 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
541
542         int MXCSR;
543         FPU fpu;
544
545         /* XXX use real code to determine if the processor supports
546            DenormalsAreZero and FlushToZero
547         */
548
549         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
550                 return;
551         }
552
553         MXCSR  = _mm_getcsr();
554
555 #ifdef DEBUG_DENORMAL_EXCEPTION
556         /* This will raise a FP exception if a denormal is detected */
557         MXCSR &= ~_MM_MASK_DENORM;
558 #endif  
559
560         switch (Config->get_denormal_model()) {
561         case DenormalNone:
562                 MXCSR &= ~(_MM_FLUSH_ZERO_ON | 0x40);
563                 break;
564
565         case DenormalFTZ:
566                 if (fpu.has_flush_to_zero()) {
567                         MXCSR |= _MM_FLUSH_ZERO_ON;
568                 }
569                 break;
570
571         case DenormalDAZ:
572                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
573                 if (fpu.has_denormals_are_zero()) {
574                         MXCSR |= 0x40;
575                 }
576                 break;
577
578         case DenormalFTZDAZ:
579                 if (fpu.has_flush_to_zero()) {
580                         if (fpu.has_denormals_are_zero()) {
581                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x40;
582                         } else {
583                                 MXCSR |= _MM_FLUSH_ZERO_ON;
584                         }
585                 }
586                 break;
587         }
588
589         _mm_setcsr (MXCSR);
590
591 #endif
592 }
593
594 /* this can be changed to modify the translation behaviour for
595    cases where the user has never expressed a preference.
596 */
597 static const bool translate_by_default = true;
598
599 string
600 ARDOUR::translation_enable_path ()
601 {
602         return Glib::build_filename (user_config_directory(), ".translate");
603 }
604
605 bool
606 ARDOUR::translations_are_enabled ()
607 {
608         int fd = ::open (ARDOUR::translation_enable_path().c_str(), O_RDONLY);
609
610         if (fd < 0) {
611                 return translate_by_default;
612         }
613
614         char c;
615         bool ret = false;
616
617         if (::read (fd, &c, 1) == 1 && c == '1') {
618                 ret = true;
619         }
620
621         ::close (fd);
622
623         return ret;
624 }
625
626 bool
627 ARDOUR::set_translations_enabled (bool yn)
628 {
629         string i18n_enabler = ARDOUR::translation_enable_path();
630         int fd = ::open (i18n_enabler.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
631
632         if (fd < 0) {
633                 return false;
634         }
635         
636         char c;
637         
638         if (yn) {
639                 c = '1';
640         } else {
641                 c = '0';
642         }
643         
644         (void) ::write (fd, &c, 1);
645         (void) ::close (fd);
646
647         return true;
648 }
649
650
651 vector<SyncSource>
652 ARDOUR::get_available_sync_options ()
653 {
654         vector<SyncSource> ret;
655
656         boost::shared_ptr<AudioBackend> backend = AudioEngine::instance()->current_backend();
657         if (backend && backend->name() == "JACK") {
658                 ret.push_back (Engine);
659         }
660
661         ret.push_back (MTC);
662         ret.push_back (MIDIClock);
663         ret.push_back (LTC);
664
665         return ret;
666 }
667
668 /** Return a monotonic value for the number of microseconds that have elapsed
669  * since an arbitrary zero origin.
670  */
671
672 #ifdef __MACH__
673 /* Thanks Apple for not implementing this basic SUSv2, POSIX.1-2001 function
674  */
675 #include <mach/mach_time.h>
676 #define CLOCK_REALTIME 0
677 #define CLOCK_MONOTONIC 0
678 int 
679 clock_gettime (int /*clk_id*/, struct timespec *t)
680 {
681         static bool initialized = false;
682         static mach_timebase_info_data_t timebase;
683         if (!initialized) {
684                 mach_timebase_info(&timebase);
685                 initialized = true;
686         }
687         uint64_t time;
688         time = mach_absolute_time();
689         double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);
690         double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);
691         t->tv_sec = seconds;
692         t->tv_nsec = nseconds;
693         return 0;
694 }
695 #endif
696  
697 microseconds_t
698 ARDOUR::get_microseconds ()
699 {
700 #ifdef PLATFORM_WINDOWS
701         microseconds_t ret = 0;
702         LARGE_INTEGER freq, time;
703
704         if (QueryPerformanceFrequency(&freq))
705                 if (QueryPerformanceCounter(&time))
706                         ret = (microseconds_t)((time.QuadPart * 1000000) / freq.QuadPart);
707
708         return ret;
709 #else
710         struct timespec ts;
711         if (clock_gettime (CLOCK_MONOTONIC, &ts) != 0) {
712                 /* EEEK! */
713                 return 0;
714         }
715         return (microseconds_t) ts.tv_sec * 1000000 + (ts.tv_nsec/1000);
716 #endif
717 }
718
719 /** Return the number of bits per sample for a given sample format.
720  *
721  * This is closely related to sndfile_data_width() but does NOT
722  * return a "magic" value to differentiate between 32 bit integer
723  * and 32 bit floating point values.
724  */
725
726 int
727 ARDOUR::format_data_width (ARDOUR::SampleFormat format)
728 {
729
730
731
732         switch (format) {
733         case ARDOUR::FormatInt16:
734                 return 16;
735         case ARDOUR::FormatInt24:
736                 return 24;
737         default:
738                 return 32;
739         }
740 }