provide support for playhead-to-next/previous-region-boundary actions, and bindings...
[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
20 #include <cstdio> // Needed so that libraptor (included in lrdf) won't complain
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <locale.h>
26
27 #ifdef VST_SUPPORT
28 #include <fst.h>
29 #endif
30
31 #ifdef __SSE__
32 #include <xmmintrin.h>
33 #endif
34
35 #include <glibmm/fileutils.h>
36
37 #include <lrdf.h>
38
39 #include <pbd/error.h>
40 #include <pbd/id.h>
41 #include <pbd/strsplit.h>
42 #include <pbd/fpu.h>
43
44 #include <midi++/port.h>
45 #include <midi++/manager.h>
46 #include <midi++/mmc.h>
47
48 #include <ardour/ardour.h>
49 #include <ardour/audio_library.h>
50 #include <ardour/configuration.h>
51 #include <ardour/profile.h>
52 #include <ardour/plugin_manager.h>
53 #include <ardour/audiosource.h>
54 #include <ardour/utils.h>
55 #include <ardour/session.h>
56 #include <ardour/source_factory.h>
57 #include <ardour/control_protocol_manager.h>
58
59 #ifdef HAVE_LIBLO
60 #include <ardour/osc.h>
61 #endif
62
63 #include <ardour/mix.h>
64
65 #if defined (__APPLE__)
66        #include <Carbon/Carbon.h> // For Gestalt
67 #endif
68        
69 #include "i18n.h"
70
71 ARDOUR::Configuration* ARDOUR::Config = 0;
72 ARDOUR::RuntimeProfile* ARDOUR::Profile = 0;
73 ARDOUR::AudioLibrary* ARDOUR::Library = 0;
74
75 #ifdef HAVE_LIBLO
76 ARDOUR::OSC* ARDOUR::osc = 0;
77 #endif
78
79 using namespace ARDOUR;
80 using namespace std;
81 using namespace PBD;
82
83 MIDI::Port *default_mmc_port = 0;
84 MIDI::Port *default_mtc_port = 0;
85 MIDI::Port *default_midi_port = 0;
86
87 Change ARDOUR::StartChanged = ARDOUR::new_change ();
88 Change ARDOUR::LengthChanged = ARDOUR::new_change ();
89 Change ARDOUR::PositionChanged = ARDOUR::new_change ();
90 Change ARDOUR::NameChanged = ARDOUR::new_change ();
91 Change ARDOUR::BoundsChanged = Change (0); // see init(), below
92
93 #ifdef HAVE_LIBLO
94 static int
95 setup_osc ()
96 {
97         /* no real cost to creating this object, and it avoids
98            conditionals anywhere that uses it 
99         */
100         
101         osc = new OSC (Config->get_osc_port());
102         
103         if (Config->get_use_osc ()) {
104                 return osc->start ();
105         } else {
106                 return 0;
107         }
108 }
109 #endif
110
111 static int 
112 setup_midi ()
113 {
114         if (Config->midi_ports.size() == 0) {
115                 warning << _("no MIDI ports specified: no MMC or MTC control possible") << endmsg;
116                 return 0;
117         }
118
119         for (std::map<string,XMLNode>::iterator i = Config->midi_ports.begin(); i != Config->midi_ports.end(); ++i) {
120                 MIDI::Manager::instance()->add_port (i->second);
121         }
122
123         MIDI::Port* first;
124         const MIDI::Manager::PortMap& ports = MIDI::Manager::instance()->get_midi_ports();
125
126         if (ports.size() > 1) {
127
128                 first = ports.begin()->second;
129
130                 /* More than one port, so try using specific names for each port */
131
132                 if (Config->get_mmc_port_name() != N_("default")) {
133                         default_mmc_port =  MIDI::Manager::instance()->port (Config->get_mmc_port_name());
134                 } 
135
136                 if (Config->get_mtc_port_name() != N_("default")) {
137                         default_mtc_port =  MIDI::Manager::instance()->port (Config->get_mtc_port_name());
138                 } 
139
140                 if (Config->get_midi_port_name() != N_("default")) {
141                         default_midi_port =  MIDI::Manager::instance()->port (Config->get_midi_port_name());
142                 } 
143                 
144                 /* If that didn't work, just use the first listed port */
145
146                 if (default_mmc_port == 0) {
147                         default_mmc_port = first;
148                 }
149
150                 if (default_mtc_port == 0) {
151                         default_mtc_port = first;
152                 }
153
154                 if (default_midi_port == 0) {
155                         default_midi_port = first;
156                 }
157                 
158         } else if (ports.size() == 1) {
159
160                 first = ports.begin()->second;
161
162                 /* Only one port described, so use it for both MTC and MMC */
163
164                 default_mmc_port = first;
165                 default_mtc_port = default_mmc_port;
166                 default_midi_port = default_mmc_port;
167         }
168
169         if (default_mmc_port == 0) {
170                 warning << string_compose (_("No MMC control (MIDI port \"%1\" not available)"), Config->get_mmc_port_name()) 
171                         << endmsg;
172                 return 0;
173         } 
174
175         if (default_mtc_port == 0) {
176                 warning << string_compose (_("No MTC support (MIDI port \"%1\" not available)"), Config->get_mtc_port_name()) 
177                         << endmsg;
178         }
179
180         if (default_midi_port == 0) {
181                 warning << string_compose (_("No MIDI parameter support (MIDI port \"%1\" not available)"), Config->get_midi_port_name()) 
182                         << endmsg;
183         }
184
185         return 0;
186 }
187
188 void
189 setup_hardware_optimization (bool try_optimization)
190 {
191         bool generic_mix_functions = true;
192
193         if (try_optimization) {
194
195                 FPU fpu;
196
197 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
198                 
199                 if (fpu.has_sse()) {
200
201                         info << "Using SSE optimized routines" << endmsg;
202         
203                         // SSE SET
204                         Session::compute_peak           = x86_sse_compute_peak;
205                         Session::find_peaks             = x86_sse_find_peaks;
206                         Session::apply_gain_to_buffer   = x86_sse_apply_gain_to_buffer;
207                         Session::mix_buffers_with_gain  = x86_sse_mix_buffers_with_gain;
208                         Session::mix_buffers_no_gain    = x86_sse_mix_buffers_no_gain;
209
210                         generic_mix_functions = false;
211
212                 }
213
214 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
215                 long sysVersion = 0;
216
217                 if (noErr != Gestalt(gestaltSystemVersion, &sysVersion))
218                         sysVersion = 0;
219
220                 if (sysVersion >= 0x00001040) { // Tiger at least
221                         Session::compute_peak           = veclib_compute_peak;
222                         Session::find_peaks             = veclib_find_peaks;
223                         Session::apply_gain_to_buffer   = veclib_apply_gain_to_buffer;
224                         Session::mix_buffers_with_gain  = veclib_mix_buffers_with_gain;
225                         Session::mix_buffers_no_gain    = veclib_mix_buffers_no_gain;
226
227                         generic_mix_functions = false;
228
229                         info << "Apple VecLib H/W specific optimizations in use" << endmsg;
230                 }
231 #endif
232
233                 /* consider FPU denormal handling to be "h/w optimization" */
234
235                 setup_fpu ();
236         }
237
238         if (generic_mix_functions) {
239
240                 Session::compute_peak           = compute_peak;
241                 Session::find_peaks             = find_peaks;
242                 Session::apply_gain_to_buffer   = apply_gain_to_buffer;
243                 Session::mix_buffers_with_gain  = mix_buffers_with_gain;
244                 Session::mix_buffers_no_gain    = mix_buffers_no_gain;
245                 
246                 info << "No H/W specific optimizations in use" << endmsg;
247         }
248
249 }
250
251 int
252 ARDOUR::init (bool use_vst, bool try_optimization)
253 {
254         extern void setup_enum_writer ();
255
256         (void) bindtextdomain(PACKAGE, LOCALEDIR);
257
258         setup_enum_writer ();
259
260         lrdf_init();
261         Library = new AudioLibrary;
262
263         Config = new Configuration;
264
265         if (Config->load_state ()) {
266                 return -1;
267         }
268
269         Config->set_use_vst (use_vst);
270
271         Profile = new RuntimeProfile;
272
273         if (setup_midi ()) {
274                 return -1;
275         }
276     
277 #ifdef HAVE_LIBLO
278         if (setup_osc ()) {
279                 return -1;
280         }
281 #endif
282
283 #ifdef VST_SUPPORT
284         if (Config->get_use_vst() && fst_init ()) {
285                 return -1;
286         }
287 #endif
288
289         setup_hardware_optimization (try_optimization);
290
291         SourceFactory::init ();
292
293         /* singleton - first object is "it" */
294         new PluginManager ();
295         
296         /* singleton - first object is "it" */
297         new ControlProtocolManager ();
298         ControlProtocolManager::instance().discover_control_protocols (Session::control_protocol_path());
299
300         XMLNode* node;
301         if ((node = Config->control_protocol_state()) != 0) {
302                 ControlProtocolManager::instance().set_state (*node);
303         }
304         
305         BoundsChanged = Change (StartChanged|PositionChanged|LengthChanged);
306
307         return 0;
308 }
309
310 int
311 ARDOUR::cleanup ()
312 {
313         delete Library;
314         lrdf_cleanup ();
315         delete &ControlProtocolManager::instance();
316         return 0;
317 }
318
319
320 microseconds_t
321 ARDOUR::get_microseconds ()
322 {
323         /* XXX need JACK to export its functionality */
324
325         struct timeval now;
326         gettimeofday (&now, 0);
327         return now.tv_sec * 1000000ULL + now.tv_usec;
328 }
329
330 ARDOUR::Change
331 ARDOUR::new_change ()
332 {
333         Change c;
334         static uint32_t change_bit = 1;
335
336         /* catch out-of-range */
337         if (!change_bit)
338         {
339                 fatal << _("programming error: ")
340                         << "change_bit out of range in ARDOUR::new_change()"
341                         << endmsg;
342                 /*NOTREACHED*/
343         }
344
345         c = Change (change_bit);
346         change_bit <<= 1;       // if it shifts too far, change_bit == 0
347
348         return c;
349 }
350
351 string
352 ARDOUR::get_ardour_revision ()
353 {
354         return "$Rev$";
355 }
356
357 string
358 ARDOUR::get_user_ardour_path ()
359 {
360         string path;
361         char* envvar;
362         
363         if ((envvar = getenv ("HOME")) == 0 || strlen (envvar) == 0) {
364                 return "/";
365         }
366                 
367         path = envvar;
368         path += "/.ardour2/";
369
370         /* create it if necessary */
371
372         if (g_mkdir_with_parents (path.c_str (), 0755)) {
373                 throw exception ();
374         }
375
376         return path;
377 }
378
379 string
380 ARDOUR::get_system_data_path ()
381 {
382         string path;
383
384         char *envvar;
385
386         if ((envvar = getenv ("ARDOUR_DATA_PATH")) != 0) {
387                 path = envvar;
388         } else {
389                 path += DATA_DIR;
390                 path += "/ardour2/";
391         }
392         
393         return path;
394 }
395
396 string
397 ARDOUR::get_system_module_path ()
398 {
399         string path;
400         char *envvar;
401
402         if ((envvar = getenv ("ARDOUR_MODULE_PATH")) != 0) {
403                 path = envvar;
404         } else {
405                 path += MODULE_DIR;
406                 path += "/ardour2/";
407         }
408         
409         return path;
410 }
411
412 static string
413 find_file (string name, string dir, string subdir = "")
414 {
415         string path;
416         char* envvar = getenv("ARDOUR_PATH");
417
418         /* 1st attempt: any directory in ARDOUR_PATH */
419         
420         if (envvar != 0) {
421
422                 vector<string> split_path;
423         
424                 split (envvar, split_path, ':');
425                 
426                 for (vector<string>::iterator i = split_path.begin(); i != split_path.end(); ++i) {
427                         path = *i;
428                         path += "/" + name;
429                         if (Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
430                                 // cerr << "Using file " << path << " found in ARDOUR_PATH." << endl;
431                                 return path;
432                         }
433                 }
434         }
435
436         /* 2nd attempt: ~/.ardour/ */
437
438         path = get_user_ardour_path();
439                 
440         if (subdir.length()) {
441                 path += subdir + "/";
442         }
443                 
444         path += name;
445         if (access (path.c_str(), R_OK) == 0) {
446                 return path;
447         }
448
449         /* 3rd attempt: dir/... */
450         
451         path = dir;
452         path += "/ardour2/";
453         
454         if (subdir.length()) {
455                 path += subdir + "/";
456         }
457         
458         path += name;
459         
460         if (access (path.c_str(), R_OK) == 0) {
461                 return path;
462         }
463
464         return "";
465 }
466
467 string
468 ARDOUR::find_config_file (string name)
469 {
470         char* envvar;
471
472         if ((envvar = getenv("ARDOUR_CONFIG_PATH")) == 0) {
473                 envvar = CONFIG_DIR;
474         }
475
476         return find_file (name, envvar);
477 }
478
479 string
480 ARDOUR::find_data_file (string name, string subdir)
481 {
482         char* envvar;
483         if ((envvar = getenv("ARDOUR_DATA_PATH")) == 0) {
484                 envvar = DATA_DIR;
485         }
486
487         return find_file (name, envvar, subdir);
488 }
489
490 ARDOUR::LocaleGuard::LocaleGuard (const char* str)
491 {
492         old = strdup (setlocale (LC_NUMERIC, NULL));
493         if (strcmp (old, str)) {
494                 setlocale (LC_NUMERIC, str);
495         } 
496 }
497
498 ARDOUR::LocaleGuard::~LocaleGuard ()
499 {
500         setlocale (LC_NUMERIC, old);
501         free ((char*)old);
502 }
503
504 void
505 ARDOUR::setup_fpu ()
506 {
507         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
508                 // valgrind doesn't understand this assembler stuff
509                 // September 10th, 2007
510                 return;
511         }
512
513 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
514
515         int MXCSR;
516         FPU fpu;
517
518         /* XXX use real code to determine if the processor supports
519            DenormalsAreZero and FlushToZero
520         */
521         
522         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
523                 return;
524         }
525
526         MXCSR  = _mm_getcsr();
527
528         switch (Config->get_denormal_model()) {
529         case DenormalNone:
530                 MXCSR &= ~(_MM_FLUSH_ZERO_ON|0x8000);
531                 break;
532
533         case DenormalFTZ:
534                 if (fpu.has_flush_to_zero()) {
535                         MXCSR |= _MM_FLUSH_ZERO_ON;
536                 }
537                 break;
538
539         case DenormalDAZ:
540                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
541                 if (fpu.has_denormals_are_zero()) {
542                         MXCSR |= 0x8000;
543                 }
544                 break;
545                 
546         case DenormalFTZDAZ:
547                 if (fpu.has_flush_to_zero()) {
548                         if (fpu.has_denormals_are_zero()) {
549                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x8000;
550                         } else {
551                                 MXCSR |= _MM_FLUSH_ZERO_ON;
552                         }
553                 }
554                 break;
555         }
556
557         _mm_setcsr (MXCSR);
558
559 #endif
560 }
561
562 ARDOUR::OverlapType
563 ARDOUR::coverage (nframes_t sa, nframes_t ea, 
564                   nframes_t sb, nframes_t eb)
565 {
566         /* OverlapType returned reflects how the second (B)
567            range overlaps the first (A).
568
569            The diagrams show various relative placements
570            of A and B for each OverlapType.
571
572            Notes:
573               Internal: the start points cannot coincide
574               External: the start and end points can coincide
575               Start: end points can coincide
576               End: start points can coincide
577
578            XXX Logically, Internal should disallow end
579            point equality.
580         */
581
582         /*
583              |--------------------|   A
584                   |------|            B
585                 |-----------------|   B
586
587
588              "B is internal to A"               
589
590         */
591 #ifdef OLD_COVERAGE
592         if ((sb >= sa) && (eb <= ea)) {
593 #else
594         if ((sb > sa) && (eb <= ea)) {
595 #endif
596                 return OverlapInternal;
597         }
598
599         /*
600              |--------------------|   A
601            ----|                      B
602            -----------------------|   B
603            --|                        B
604            
605              "B overlaps the start of A"
606
607         */
608
609         if ((eb >= sa) && (eb <= ea)) {
610                 return OverlapStart;
611         }
612         /* 
613              |---------------------|  A
614                    |----------------- B
615              |----------------------- B    
616                                    |- B
617
618             "B overlaps the end of A"                              
619
620         */
621         if ((sb >= sa) && (sb <= ea)) {
622                 return OverlapEnd;
623         }
624         /*
625              |--------------------|     A
626            --------------------------  B   
627              |-----------------------  B
628             ----------------------|    B
629              |--------------------|    B
630
631
632            "B overlaps all of A"
633         */
634         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
635                 return OverlapExternal;
636         }
637
638         return OverlapNone;
639 }
640
641 /* not sure where to put these */
642
643 template<class T>
644 std::istream& int_to_type (std::istream& o, T& hf) {
645         int val;
646         o >> val;
647         hf = (T) val;
648         return o;
649 }
650
651 std::istream& operator>>(std::istream& o, HeaderFormat& var) { return int_to_type<HeaderFormat> (o, var); }
652 std::istream& operator>>(std::istream& o, SampleFormat& var) { return int_to_type<SampleFormat> (o, var); }
653 std::istream& operator>>(std::istream& o, AutoConnectOption& var) { return int_to_type<AutoConnectOption> (o, var); }
654 std::istream& operator>>(std::istream& o, MonitorModel& var) { return int_to_type<MonitorModel> (o, var); }
655 std::istream& operator>>(std::istream& o, RemoteModel& var) { return int_to_type<RemoteModel> (o, var); }
656 std::istream& operator>>(std::istream& o, EditMode& var) { return int_to_type<EditMode> (o, var); }
657 std::istream& operator>>(std::istream& o, SoloModel& var) { return int_to_type<SoloModel> (o, var); }
658 std::istream& operator>>(std::istream& o, LayerModel& var) { return int_to_type<LayerModel> (o, var); }
659 std::istream& operator>>(std::istream& o, CrossfadeModel& var) { return int_to_type<CrossfadeModel> (o, var); }
660 std::istream& operator>>(std::istream& o, SlaveSource& var) { return int_to_type<SlaveSource> (o, var); }
661 std::istream& operator>>(std::istream& o, ShuttleBehaviour& var) { return int_to_type<ShuttleBehaviour> (o, var); }
662 std::istream& operator>>(std::istream& o, ShuttleUnits& var) { return int_to_type<ShuttleUnits> (o, var); }
663 std::istream& operator>>(std::istream& o, SmpteFormat& var) { return int_to_type<SmpteFormat> (o, var); }
664 std::istream& operator>>(std::istream& o, DenormalModel& var) { return int_to_type<DenormalModel> (o, var); }
665