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