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