Include windows.h on windows build for LARGE_INTEGER
[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 int
248 ARDOUR::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         if (old_version == 3) {
254         
255                 old_name = Glib::build_filename (old_dir, "recent");
256                 new_name = Glib::build_filename (new_dir, "recent");
257
258                 copy_file (old_name, new_name);
259
260                 /* can only copy ardour.rc - UI config is not compatible */
261
262                 old_name = Glib::build_filename (old_dir, "ardour.rc");
263                 new_name = Glib::build_filename (new_dir, "config");
264
265                 copy_file (old_name, new_name);
266
267                 /* copy templates and route templates */
268
269                 old_name = Glib::build_filename (old_dir, "templates");
270                 new_name = Glib::build_filename (new_dir, "templates");
271
272                 copy_recurse (old_name, new_name);
273
274                 old_name = Glib::build_filename (old_dir, "route_templates");
275                 new_name = Glib::build_filename (new_dir, "route_templates");
276
277                 copy_recurse (old_name, new_name);
278
279                 /* presets */
280
281                 old_name = Glib::build_filename (old_dir, "presets");
282                 new_name = Glib::build_filename (new_dir, "presets");
283                 
284                 copy_recurse (old_name, new_name);
285
286                 /* presets */
287
288                 old_name = Glib::build_filename (old_dir, "plugin_statuses");
289                 new_name = Glib::build_filename (new_dir, "plugin_statuses");
290
291                 copy_file (old_name, new_name);
292                 
293                 /* export formats */
294
295                 old_name = Glib::build_filename (old_dir, export_formats_dir_name);
296                 new_name = Glib::build_filename (new_dir, export_formats_dir_name);
297                 
298                 vector<string> export_formats;
299                 g_mkdir_with_parents (Glib::build_filename (new_dir, export_formats_dir_name).c_str(), 0755);
300                 find_files_matching_pattern (export_formats, old_name, "*.format");
301                 for (vector<string>::iterator i = export_formats.begin(); i != export_formats.end(); ++i) {
302                         std::string from = *i;
303                         std::string to = Glib::build_filename (new_name, Glib::path_get_basename (*i));
304                         copy_file (from, to);
305                 }
306         }
307
308         return 0;
309 }
310
311 static void
312 maybe_copy_old_configuration_files ()
313 {
314         int version = atoi (X_(PROGRAM_VERSION));
315
316         if (version <= 1) {
317                 return;
318         }
319
320         version--;
321
322         string old_config_dir = user_config_directory (version);
323
324         if (Glib::file_test (old_config_dir, Glib::FILE_TEST_IS_DIR)) {
325                 string current_config_dir = user_config_directory ();
326                 boost::optional<bool> r = CopyConfigurationFiles (old_config_dir, current_config_dir, version); /* EMIT SIGNAL */
327                 if (r) {
328                         if (r.get()) {
329                                 copy_configuration_files (old_config_dir, current_config_dir, version);
330                         }
331                 }
332         }
333 }
334
335 bool
336 ARDOUR::init (bool use_windows_vst, bool try_optimization, const char* localedir)
337 {
338         if (libardour_initialized) {
339                 return true;
340         }
341
342         if (!PBD::init()) return false;
343
344 #ifdef ENABLE_NLS
345         (void) bindtextdomain(PACKAGE, localedir);
346         (void) bind_textdomain_codeset (PACKAGE, "UTF-8");
347 #endif
348
349         SessionEvent::init_event_pool ();
350
351         Operations::make_operations_quarks ();
352         SessionObject::make_property_quarks ();
353         Region::make_property_quarks ();
354         MidiRegion::make_property_quarks ();
355         AudioRegion::make_property_quarks ();
356         RouteGroup::make_property_quarks ();
357         Playlist::make_property_quarks ();
358         AudioPlaylist::make_property_quarks ();
359
360         /* this is a useful ready to use PropertyChange that many
361            things need to check. This avoids having to compose
362            it every time we want to check for any of the relevant
363            property changes.
364         */
365
366         bounds_change.add (ARDOUR::Properties::start);
367         bounds_change.add (ARDOUR::Properties::position);
368         bounds_change.add (ARDOUR::Properties::length);
369
370         /* provide a state version for the few cases that need it and are not
371            driven by reading state from disk (e.g. undo/redo)
372         */
373
374         Stateful::current_state_version = CURRENT_SESSION_FILE_VERSION;
375
376         ARDOUR::setup_enum_writer ();
377
378         // allow ardour the absolute maximum number of open files
379         lotsa_files_please ();
380
381         maybe_copy_old_configuration_files ();
382         
383 #ifdef HAVE_LRDF
384         lrdf_init();
385 #endif
386         Library = new AudioLibrary;
387
388         BootMessage (_("Loading configuration"));
389
390         Config = new RCConfiguration;
391
392         if (Config->load_state ()) {
393                 return false;
394         }
395
396         Config->set_use_windows_vst (use_windows_vst);
397 #ifdef LXVST_SUPPORT
398         Config->set_use_lxvst(true);
399 #endif
400
401         Profile = new RuntimeProfile;
402
403
404 #ifdef WINDOWS_VST_SUPPORT
405         if (Config->get_use_windows_vst() && fst_init (0)) {
406                 return false;
407         }
408 #endif
409
410 #ifdef LXVST_SUPPORT
411         if (Config->get_use_lxvst() && vstfx_init (0)) {
412                 return false;
413         }
414 #endif
415
416 #ifdef AUDIOUNIT_SUPPORT
417         AUPluginInfo::load_cached_info ();
418 #endif
419
420         setup_hardware_optimization (try_optimization);
421
422         SourceFactory::init ();
423         Analyser::init ();
424
425         /* singletons - first object is "it" */
426         (void) PluginManager::instance();
427 #ifdef LV2_SUPPORT
428         (void) URIMap::instance();
429 #endif
430         (void) EventTypeMap::instance();
431
432         ProcessThread::init ();
433         /* the + 4 is a bit of a handwave. i don't actually know
434            how many more per-thread buffer sets we need above
435            the h/w concurrency, but its definitely > 1 more.
436         */
437         BufferManager::init (hardware_concurrency() + 4); 
438
439         PannerManager::instance().discover_panners();
440
441         ARDOUR::AudioEngine::create ();
442
443         libardour_initialized = true;
444
445         return true;
446 }
447
448 void
449 ARDOUR::init_post_engine ()
450 {
451         ControlProtocolManager::instance().discover_control_protocols ();
452
453         XMLNode* node;
454         if ((node = Config->control_protocol_state()) != 0) {
455                 ControlProtocolManager::instance().set_state (*node, Stateful::loading_state_version);
456         }
457
458         /* find plugins */
459
460         ARDOUR::PluginManager::instance().refresh (!Config->get_discover_vst_on_start());
461 }
462
463 void
464 ARDOUR::cleanup () 
465 {
466         if (!libardour_initialized) {
467                 return;
468         }
469
470         ARDOUR::AudioEngine::destroy ();
471
472         delete Library;
473 #ifdef HAVE_LRDF
474         lrdf_cleanup ();
475 #endif
476         delete &ControlProtocolManager::instance();
477 #ifdef WINDOWS_VST_SUPPORT
478         fst_exit ();
479 #endif
480
481 #ifdef LXVST_SUPPORT
482         vstfx_exit();
483 #endif
484         delete &PluginManager::instance();
485         delete Config;
486         PBD::cleanup ();
487
488         return;
489 }
490
491 void
492 ARDOUR::find_bindings_files (map<string,string>& files)
493 {
494         vector<std::string> found;
495         Searchpath spath = ardour_config_search_path();
496
497         if (getenv ("ARDOUR_SAE")) {
498                 find_files_matching_pattern (found, spath, "*SAE-*.bindings");
499         } else {
500                 find_files_matching_pattern (found, spath, "*.bindings");
501         }
502
503         if (found.empty()) {
504                 return;
505         }
506
507         for (vector<std::string>::iterator x = found.begin(); x != found.end(); ++x) {
508                 std::string path(*x);
509                 pair<string,string> namepath;
510                 namepath.second = path;
511                 namepath.first = PBD::basename_nosuffix (path);
512                 files.insert (namepath);
513         }
514 }
515
516 bool
517 ARDOUR::no_auto_connect()
518 {
519         return getenv ("ARDOUR_NO_AUTOCONNECT") != 0;
520 }
521
522 void
523 ARDOUR::setup_fpu ()
524 {
525
526         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
527                 // valgrind doesn't understand this assembler stuff
528                 // September 10th, 2007
529                 return;
530         }
531
532 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
533
534         int MXCSR;
535         FPU fpu;
536
537         /* XXX use real code to determine if the processor supports
538            DenormalsAreZero and FlushToZero
539         */
540
541         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
542                 return;
543         }
544
545         MXCSR  = _mm_getcsr();
546
547 #ifdef DEBUG_DENORMAL_EXCEPTION
548         /* This will raise a FP exception if a denormal is detected */
549         MXCSR &= ~_MM_MASK_DENORM;
550 #endif  
551
552         switch (Config->get_denormal_model()) {
553         case DenormalNone:
554                 MXCSR &= ~(_MM_FLUSH_ZERO_ON | 0x40);
555                 break;
556
557         case DenormalFTZ:
558                 if (fpu.has_flush_to_zero()) {
559                         MXCSR |= _MM_FLUSH_ZERO_ON;
560                 }
561                 break;
562
563         case DenormalDAZ:
564                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
565                 if (fpu.has_denormals_are_zero()) {
566                         MXCSR |= 0x40;
567                 }
568                 break;
569
570         case DenormalFTZDAZ:
571                 if (fpu.has_flush_to_zero()) {
572                         if (fpu.has_denormals_are_zero()) {
573                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x40;
574                         } else {
575                                 MXCSR |= _MM_FLUSH_ZERO_ON;
576                         }
577                 }
578                 break;
579         }
580
581         _mm_setcsr (MXCSR);
582
583 #endif
584 }
585
586 /* this can be changed to modify the translation behaviour for
587    cases where the user has never expressed a preference.
588 */
589 static const bool translate_by_default = true;
590
591 string
592 ARDOUR::translation_enable_path ()
593 {
594         return Glib::build_filename (user_config_directory(), ".translate");
595 }
596
597 bool
598 ARDOUR::translations_are_enabled ()
599 {
600         int fd = ::open (ARDOUR::translation_enable_path().c_str(), O_RDONLY);
601
602         if (fd < 0) {
603                 return translate_by_default;
604         }
605
606         char c;
607         bool ret = false;
608
609         if (::read (fd, &c, 1) == 1 && c == '1') {
610                 ret = true;
611         }
612
613         ::close (fd);
614
615         return ret;
616 }
617
618 bool
619 ARDOUR::set_translations_enabled (bool yn)
620 {
621         string i18n_enabler = ARDOUR::translation_enable_path();
622         int fd = ::open (i18n_enabler.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
623
624         if (fd < 0) {
625                 return false;
626         }
627         
628         char c;
629         
630         if (yn) {
631                 c = '1';
632         } else {
633                 c = '0';
634         }
635         
636         (void) ::write (fd, &c, 1);
637         (void) ::close (fd);
638
639         return true;
640 }
641
642
643 vector<SyncSource>
644 ARDOUR::get_available_sync_options ()
645 {
646         vector<SyncSource> ret;
647
648         boost::shared_ptr<AudioBackend> backend = AudioEngine::instance()->current_backend();
649         if (backend && backend->name() == "JACK") {
650                 ret.push_back (Engine);
651         }
652
653         ret.push_back (MTC);
654         ret.push_back (MIDIClock);
655         ret.push_back (LTC);
656
657         return ret;
658 }
659
660 /** Return a monotonic value for the number of microseconds that have elapsed
661  * since an arbitrary zero origin.
662  */
663
664 #ifdef __MACH__
665 /* Thanks Apple for not implementing this basic SUSv2, POSIX.1-2001 function
666  */
667 #include <mach/mach_time.h>
668 #define CLOCK_REALTIME 0
669 #define CLOCK_MONOTONIC 0
670 int 
671 clock_gettime (int /*clk_id*/, struct timespec *t)
672 {
673         static bool initialized = false;
674         static mach_timebase_info_data_t timebase;
675         if (!initialized) {
676                 mach_timebase_info(&timebase);
677                 initialized = true;
678         }
679         uint64_t time;
680         time = mach_absolute_time();
681         double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);
682         double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);
683         t->tv_sec = seconds;
684         t->tv_nsec = nseconds;
685         return 0;
686 }
687 #endif
688  
689 microseconds_t
690 ARDOUR::get_microseconds ()
691 {
692 #ifdef PLATFORM_WINDOWS
693         microseconds_t ret = 0;
694         LARGE_INTEGER freq, time;
695
696         if (QueryPerformanceFrequency(&freq))
697                 if (QueryPerformanceCounter(&time))
698                         ret = (microseconds_t)((time.QuadPart * 1000000) / freq.QuadPart);
699
700         return ret;
701 #else
702         struct timespec ts;
703         if (clock_gettime (CLOCK_MONOTONIC, &ts) != 0) {
704                 /* EEEK! */
705                 return 0;
706         }
707         return (microseconds_t) ts.tv_sec * 1000000 + (ts.tv_nsec/1000);
708 #endif
709 }
710
711 /** Return the number of bits per sample for a given sample format.
712  *
713  * This is closely related to sndfile_data_width() but does NOT
714  * return a "magic" value to differentiate between 32 bit integer
715  * and 32 bit floating point values.
716  */
717
718 int
719 ARDOUR::format_data_width (ARDOUR::SampleFormat format)
720 {
721
722
723
724         switch (format) {
725         case ARDOUR::FormatInt16:
726                 return 16;
727         case ARDOUR::FormatInt24:
728                 return 24;
729         default:
730                 return 32;
731         }
732 }