Merge with 2.0-ongoing R2988
[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 #include <cstdio> // Needed so that libraptor (included in lrdf) won't complain
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <locale.h>
25
26 #ifdef VST_SUPPORT
27 #include <fst.h>
28 #endif
29
30 #ifdef __SSE__
31 #include <xmmintrin.h>
32 #endif
33
34 #include <lrdf.h>
35
36 #include <pbd/error.h>
37 #include <pbd/id.h>
38 #include <pbd/strsplit.h>
39 #include <pbd/fpu.h>
40
41 #include <midi++/port.h>
42 #include <midi++/manager.h>
43 #include <midi++/mmc.h>
44
45 #include <ardour/ardour.h>
46 #include <ardour/analyser.h>
47 #include <ardour/audio_library.h>
48 #include <ardour/configuration.h>
49 #include <ardour/profile.h>
50 #include <ardour/plugin_manager.h>
51 #include <ardour/audiosource.h>
52 #include <ardour/utils.h>
53 #include <ardour/session.h>
54 #include <ardour/source_factory.h>
55 #include <ardour/control_protocol_manager.h>
56 #include <ardour/audioengine.h>
57
58 #ifdef HAVE_LIBLO
59 #include <ardour/osc.h>
60 #endif
61
62 #include <ardour/mix.h>
63 #include <ardour/runtime_functions.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 compute_peak_t          ARDOUR::compute_peak = 0;
94 find_peaks_t            ARDOUR::find_peaks = 0;
95 apply_gain_to_buffer_t  ARDOUR::apply_gain_to_buffer = 0;
96 mix_buffers_with_gain_t ARDOUR::mix_buffers_with_gain = 0;
97 mix_buffers_no_gain_t   ARDOUR::mix_buffers_no_gain = 0;
98
99 #ifdef HAVE_LIBLO
100 static int
101 setup_osc ()
102 {
103         /* no real cost to creating this object, and it avoids
104            conditionals anywhere that uses it 
105         */
106         
107         osc = new OSC (Config->get_osc_port());
108         
109         if (Config->get_use_osc ()) {
110                 return osc->start ();
111         } else {
112                 return 0;
113         }
114 }
115 #endif
116
117 int 
118 setup_midi ()
119 {
120         if (Config->midi_ports.size() == 0) {
121                 warning << _("no MIDI ports specified: no MMC or MTC control possible") << endmsg;
122                 return 0;
123         }
124
125         for (std::map<string,XMLNode>::iterator i = Config->midi_ports.begin(); i != Config->midi_ports.end(); ++i) {
126                 MIDI::Manager::instance()->add_port (i->second);
127         }
128
129         MIDI::Port* first;
130         const MIDI::Manager::PortMap& ports = MIDI::Manager::instance()->get_midi_ports();
131
132         if (ports.size() > 1) {
133
134                 first = ports.begin()->second;
135
136                 /* More than one port, so try using specific names for each port */
137
138                 if (Config->get_mmc_port_name() != N_("default")) {
139                         default_mmc_port =  MIDI::Manager::instance()->port (Config->get_mmc_port_name());
140                 } 
141
142                 if (Config->get_mtc_port_name() != N_("default")) {
143                         default_mtc_port =  MIDI::Manager::instance()->port (Config->get_mtc_port_name());
144                 } 
145
146                 if (Config->get_midi_port_name() != N_("default")) {
147                         default_midi_port =  MIDI::Manager::instance()->port (Config->get_midi_port_name());
148                 } 
149                 
150                 /* If that didn't work, just use the first listed port */
151
152                 if (default_mmc_port == 0) {
153                         default_mmc_port = first;
154                 }
155
156                 if (default_mtc_port == 0) {
157                         default_mtc_port = first;
158                 }
159
160                 if (default_midi_port == 0) {
161                         default_midi_port = first;
162                 }
163                 
164         } else if (ports.size() == 1) {
165
166                 first = ports.begin()->second;
167
168                 /* Only one port described, so use it for both MTC and MMC */
169
170                 default_mmc_port = first;
171                 default_mtc_port = default_mmc_port;
172                 default_midi_port = default_mmc_port;
173         }
174
175         if (default_mmc_port == 0) {
176                 warning << string_compose (_("No MMC control (MIDI port \"%1\" not available)"), Config->get_mmc_port_name()) 
177                         << endmsg;
178                 return 0;
179         } 
180
181         if (default_mtc_port == 0) {
182                 warning << string_compose (_("No MTC support (MIDI port \"%1\" not available)"), Config->get_mtc_port_name()) 
183                         << endmsg;
184         }
185
186         if (default_midi_port == 0) {
187                 warning << string_compose (_("No MIDI parameter support (MIDI port \"%1\" not available)"), Config->get_midi_port_name()) 
188                         << endmsg;
189         }
190
191         return 0;
192 }
193
194 void
195 setup_hardware_optimization (bool try_optimization)
196 {
197         bool generic_mix_functions = true;
198
199         if (try_optimization) {
200
201                 FPU fpu;
202
203 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
204
205                 if (fpu.has_sse()) {
206
207                         info << "Using SSE optimized routines" << endmsg;
208
209                         // SSE SET
210                         compute_peak          = x86_sse_compute_peak;
211                         find_peaks            = x86_sse_find_peaks;
212                         apply_gain_to_buffer  = x86_sse_apply_gain_to_buffer;
213                         mix_buffers_with_gain = x86_sse_mix_buffers_with_gain;
214                         mix_buffers_no_gain   = x86_sse_mix_buffers_no_gain;
215
216                         generic_mix_functions = false;
217
218                 }
219
220 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
221                 long sysVersion = 0;
222
223                 if (noErr != Gestalt(gestaltSystemVersion, &sysVersion))
224                         sysVersion = 0;
225
226                 if (sysVersion >= 0x00001040) { // Tiger at least
227                         compute_peak           = veclib_compute_peak;
228                         find_peaks             = veclib_find_peaks;
229                         apply_gain_to_buffer   = veclib_apply_gain_to_buffer;
230                         mix_buffers_with_gain  = veclib_mix_buffers_with_gain;
231                         mix_buffers_no_gain    = veclib_mix_buffers_no_gain;
232
233                         generic_mix_functions = false;
234
235                         info << "Apple VecLib H/W specific optimizations in use" << endmsg;
236                 }
237 #endif
238
239                 /* consider FPU denormal handling to be "h/w optimization" */
240
241                 setup_fpu ();
242         }
243
244         if (generic_mix_functions) {
245
246                 compute_peak          = default_compute_peak;
247                 find_peaks            = default_find_peaks;
248                 apply_gain_to_buffer  = default_apply_gain_to_buffer;
249                 mix_buffers_with_gain = default_mix_buffers_with_gain;
250                 mix_buffers_no_gain   = default_mix_buffers_no_gain;
251
252                 info << "No H/W specific optimizations in use" << endmsg;
253         }
254 }
255
256 int
257 ARDOUR::init (bool use_vst, bool try_optimization)
258 {
259         extern void setup_enum_writer ();
260
261         (void) bindtextdomain(PACKAGE, LOCALEDIR);
262
263         setup_enum_writer ();
264
265         lrdf_init();
266         Library = new AudioLibrary;
267
268         Config = new Configuration;
269
270         if (Config->load_state ()) {
271                 return -1;
272         }
273
274         Config->set_use_vst (use_vst);
275
276         Profile = new RuntimeProfile;
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 ();
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 ARDOUR::LocaleGuard::LocaleGuard (const char* str)
371 {
372         old = strdup (setlocale (LC_NUMERIC, NULL));
373         if (strcmp (old, str)) {
374                 setlocale (LC_NUMERIC, str);
375         } 
376 }
377
378 ARDOUR::LocaleGuard::~LocaleGuard ()
379 {
380         setlocale (LC_NUMERIC, old);
381         free ((char*)old);
382 }
383
384 void
385 ARDOUR::setup_fpu ()
386 {
387
388         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
389                 // valgrind doesn't understand this assembler stuff
390                 // September 10th, 2007
391                 return;
392         }
393
394 #if defined(ARCH_X86) && defined(USE_XMMINTRIN)
395
396         int MXCSR;
397         FPU fpu;
398
399         /* XXX use real code to determine if the processor supports
400            DenormalsAreZero and FlushToZero
401         */
402         
403         if (!fpu.has_flush_to_zero() && !fpu.has_denormals_are_zero()) {
404                 return;
405         }
406
407         MXCSR  = _mm_getcsr();
408
409         switch (Config->get_denormal_model()) {
410         case DenormalNone:
411                 MXCSR &= ~(_MM_FLUSH_ZERO_ON|0x8000);
412                 break;
413
414         case DenormalFTZ:
415                 if (fpu.has_flush_to_zero()) {
416                         MXCSR |= _MM_FLUSH_ZERO_ON;
417                 }
418                 break;
419
420         case DenormalDAZ:
421                 MXCSR &= ~_MM_FLUSH_ZERO_ON;
422                 if (fpu.has_denormals_are_zero()) {
423                         MXCSR |= 0x8000;
424                 }
425                 break;
426                 
427         case DenormalFTZDAZ:
428                 if (fpu.has_flush_to_zero()) {
429                         if (fpu.has_denormals_are_zero()) {
430                                 MXCSR |= _MM_FLUSH_ZERO_ON | 0x8000;
431                         } else {
432                                 MXCSR |= _MM_FLUSH_ZERO_ON;
433                         }
434                 }
435                 break;
436         }
437
438         _mm_setcsr (MXCSR);
439
440 #endif
441 }
442
443 ARDOUR::OverlapType
444 ARDOUR::coverage (nframes_t sa, nframes_t ea, 
445                   nframes_t sb, nframes_t eb)
446 {
447         /* OverlapType returned reflects how the second (B)
448            range overlaps the first (A).
449
450            The diagrams show various relative placements
451            of A and B for each OverlapType.
452
453            Notes:
454               Internal: the start points cannot coincide
455               External: the start and end points can coincide
456               Start: end points can coincide
457               End: start points can coincide
458
459            XXX Logically, Internal should disallow end
460            point equality.
461         */
462
463         /*
464              |--------------------|   A
465                   |------|            B
466                 |-----------------|   B
467
468
469              "B is internal to A"               
470
471         */
472 #ifdef OLD_COVERAGE
473         if ((sb >= sa) && (eb <= ea)) {
474 #else
475         if ((sb > sa) && (eb <= ea)) {
476 #endif
477                 return OverlapInternal;
478         }
479
480         /*
481              |--------------------|   A
482            ----|                      B
483            -----------------------|   B
484            --|                        B
485            
486              "B overlaps the start of A"
487
488         */
489
490         if ((eb >= sa) && (eb <= ea)) {
491                 return OverlapStart;
492         }
493         /* 
494              |---------------------|  A
495                    |----------------- B
496              |----------------------- B    
497                                    |- B
498
499             "B overlaps the end of A"                              
500
501         */
502         if ((sb > sa) && (sb <= ea)) {
503                 return OverlapEnd;
504         }
505         /*
506              |--------------------|     A
507            --------------------------  B   
508              |-----------------------  B
509             ----------------------|    B
510              |--------------------|    B
511
512
513            "B overlaps all of A"
514         */
515         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
516                 return OverlapExternal;
517         }
518
519         return OverlapNone;
520 }
521
522 /* not sure where to put these */
523
524 template<class T>
525 std::istream& int_to_type (std::istream& o, T& hf) {
526         int val;
527         o >> val;
528         hf = (T) val;
529         return o;
530 }
531
532 std::istream& operator>>(std::istream& o, HeaderFormat& var) { return int_to_type<HeaderFormat> (o, var); }
533 std::istream& operator>>(std::istream& o, SampleFormat& var) { return int_to_type<SampleFormat> (o, var); }
534 std::istream& operator>>(std::istream& o, AutoConnectOption& var) { return int_to_type<AutoConnectOption> (o, var); }
535 std::istream& operator>>(std::istream& o, MonitorModel& var) { return int_to_type<MonitorModel> (o, var); }
536 std::istream& operator>>(std::istream& o, RemoteModel& var) { return int_to_type<RemoteModel> (o, var); }
537 std::istream& operator>>(std::istream& o, EditMode& var) { return int_to_type<EditMode> (o, var); }
538 std::istream& operator>>(std::istream& o, SoloModel& var) { return int_to_type<SoloModel> (o, var); }
539 std::istream& operator>>(std::istream& o, LayerModel& var) { return int_to_type<LayerModel> (o, var); }
540 std::istream& operator>>(std::istream& o, CrossfadeModel& var) { return int_to_type<CrossfadeModel> (o, var); }
541 std::istream& operator>>(std::istream& o, SlaveSource& var) { return int_to_type<SlaveSource> (o, var); }
542 std::istream& operator>>(std::istream& o, ShuttleBehaviour& var) { return int_to_type<ShuttleBehaviour> (o, var); }
543 std::istream& operator>>(std::istream& o, ShuttleUnits& var) { return int_to_type<ShuttleUnits> (o, var); }
544 std::istream& operator>>(std::istream& o, SmpteFormat& var) { return int_to_type<SmpteFormat> (o, var); }
545 std::istream& operator>>(std::istream& o, DenormalModel& var) { return int_to_type<DenormalModel> (o, var); }
546