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