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