Merged with trunk R1283.
[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         if (try_optimization) {
201
202 #if defined (ARCH_X86) && defined (BUILD_SSE_OPTIMIZATIONS)
203         
204                 unsigned int use_sse = 0;
205
206 #ifndef USE_X86_64_ASM
207                 asm volatile (
208                                  "mov $1, %%eax\n"
209                                  "pushl %%ebx\n"
210                                  "cpuid\n"
211                                  "popl %%ebx\n"
212                                  "andl $33554432, %%edx\n"
213                                  "movl %%edx, %0\n"
214                              : "=m" (use_sse)
215                              : 
216                          : "%eax", "%ecx", "%edx", "memory");
217 #else
218
219                 asm volatile (
220                                  "movq $1, %%rax\n"
221                                  "pushq %%rbx\n"
222                                  "cpuid\n"
223                                  "popq %%rbx\n"
224                                  "andq $33554432, %%rdx\n"
225                                  "movq %%rdx, %0\n"
226                              : "=m" (use_sse)
227                              : 
228                          : "%rax", "%rcx", "%rdx", "memory");
229
230 #endif /* USE_X86_64_ASM */
231                 
232                 if (use_sse) {
233                         info << "Using SSE optimized routines" << endmsg;
234         
235                         // SSE SET
236                         Session::compute_peak                   = x86_sse_compute_peak;
237                         Session::apply_gain_to_buffer   = x86_sse_apply_gain_to_buffer;
238                         Session::mix_buffers_with_gain  = x86_sse_mix_buffers_with_gain;
239                         Session::mix_buffers_no_gain    = x86_sse_mix_buffers_no_gain;
240
241                         generic_mix_functions = false;
242
243                 }
244
245 #elif defined (__APPLE__) && defined (BUILD_VECLIB_OPTIMIZATIONS)
246                 long sysVersion = 0;
247
248                 if (noErr != Gestalt(gestaltSystemVersion, &sysVersion))
249                         sysVersion = 0;
250
251                 if (sysVersion >= 0x00001040) { // Tiger at least
252                         Session::compute_peak           = veclib_compute_peak;
253                         Session::apply_gain_to_buffer   = veclib_apply_gain_to_buffer;
254                         Session::mix_buffers_with_gain  = veclib_mix_buffers_with_gain;
255                         Session::mix_buffers_no_gain    = veclib_mix_buffers_no_gain;
256
257                         generic_mix_functions = false;
258
259                         info << "Apple VecLib H/W specific optimizations in use" << endmsg;
260                 }
261 #endif
262         }
263
264         if (generic_mix_functions) {
265
266                 Session::compute_peak                   = compute_peak;
267                 Session::apply_gain_to_buffer   = apply_gain_to_buffer;
268                 Session::mix_buffers_with_gain  = mix_buffers_with_gain;
269                 Session::mix_buffers_no_gain    = mix_buffers_no_gain;
270                 
271                 info << "No H/W specific optimizations in use" << endmsg;
272         }
273 }
274
275 int
276 ARDOUR::init (ARDOUR::AudioEngine& engine, bool use_vst, bool try_optimization)
277 {
278         extern void setup_enum_writer ();
279
280         (void) bindtextdomain(PACKAGE, LOCALEDIR);
281
282         PBD::ID::init ();
283         
284         setup_enum_writer ();
285
286         lrdf_init();
287         Library = new AudioLibrary;
288
289         Config = new Configuration;
290
291         if (Config->load_state ()) {
292                 return -1;
293         }
294
295         Config->set_use_vst (use_vst);
296
297         if (setup_midi (engine)) {
298                 return -1;
299         }
300     
301 #ifdef HAVE_LIBLO
302         if (setup_osc ()) {
303                 return -1;
304         }
305 #endif
306
307 #ifdef VST_SUPPORT
308         if (Config->get_use_vst() && fst_init ()) {
309                 return -1;
310         }
311 #endif
312
313         setup_hardware_optimization (try_optimization);
314
315         /* singleton - first object is "it" */
316         new PluginManager ();
317         
318         /* singleton - first object is "it" */
319         new ControlProtocolManager ();
320         ControlProtocolManager::instance().discover_control_protocols (Session::control_protocol_path());
321
322         XMLNode* node;
323         if ((node = Config->control_protocol_state()) != 0) {
324                 ControlProtocolManager::instance().set_state (*node);
325         }
326         
327         BoundsChanged = Change (StartChanged|PositionChanged|LengthChanged);
328
329         return 0;
330 }
331
332 int
333 ARDOUR::cleanup ()
334 {
335         delete Library;
336         lrdf_cleanup ();
337         delete &ControlProtocolManager::instance();
338         return 0;
339 }
340
341
342 microseconds_t
343 ARDOUR::get_microseconds ()
344 {
345         /* XXX need JACK to export its functionality */
346
347         struct timeval now;
348         gettimeofday (&now, 0);
349         return now.tv_sec * 1000000ULL + now.tv_usec;
350 }
351
352 ARDOUR::Change
353 ARDOUR::new_change ()
354 {
355         Change c;
356         static uint32_t change_bit = 1;
357
358         /* catch out-of-range */
359         if (!change_bit)
360         {
361                 fatal << _("programming error: ")
362                         << "change_bit out of range in ARDOUR::new_change()"
363                         << endmsg;
364                 /*NOTREACHED*/
365         }
366
367         c = Change (change_bit);
368         change_bit <<= 1;       // if it shifts too far, change_bit == 0
369
370         return c;
371 }
372
373 string
374 ARDOUR::get_ardour_revision ()
375 {
376         return "$Rev$";
377 }
378
379 string
380 ARDOUR::get_user_ardour_path ()
381 {
382         string path;
383         char* envvar;
384         
385         if ((envvar = getenv ("HOME")) == 0 || strlen (envvar) == 0) {
386                 return "/";
387         }
388                 
389         path = envvar;
390         path += "/.ardour2/";
391
392         /* create it if necessary */
393
394         if (g_mkdir_with_parents (path.c_str (), 0755)) {
395                 throw exception ();
396         }
397
398         return path;
399 }
400
401 string
402 ARDOUR::get_system_data_path ()
403 {
404         string path;
405
406         char *envvar;
407
408         if ((envvar = getenv ("ARDOUR_DATA_PATH")) != 0) {
409                 path = envvar;
410         } else {
411                 path += DATA_DIR;
412                 path += "/ardour2/";
413         }
414         
415         return path;
416 }
417
418 string
419 ARDOUR::get_system_module_path ()
420 {
421         string path;
422         char *envvar;
423
424         if ((envvar = getenv ("ARDOUR_MODULE_PATH")) != 0) {
425                 path = envvar;
426         } else {
427                 path += MODULE_DIR;
428                 path += "/ardour2/";
429         }
430         
431         return path;
432 }
433
434 static string
435 find_file (string name, string dir, string subdir = "")
436 {
437         string path;
438         char* envvar = getenv("ARDOUR_PATH");
439
440         /* 1st attempt: any directory in ARDOUR_PATH */
441         
442         if (envvar != 0) {
443
444                 vector<string> split_path;
445         
446                 split (envvar, split_path, ':');
447                 
448                 for (vector<string>::iterator i = split_path.begin(); i != split_path.end(); ++i) {
449                         path = *i;
450                         path += "/" + name;
451                         if (access (path.c_str(), R_OK) == 0) {
452                                 // cerr << "Using file " << path << " found in ARDOUR_PATH." << endl;
453                                 return path;
454                         }
455                 }
456         }
457
458         /* 2nd attempt: ~/.ardour/ */
459
460         path = get_user_ardour_path();
461                 
462         if (subdir.length()) {
463                 path += subdir + "/";
464         }
465                 
466         path += name;
467         if (access (path.c_str(), R_OK) == 0) {
468                 return path;
469         }
470
471         /* 3rd attempt: dir/... */
472         
473         path = dir;
474         path += "/ardour2/";
475         
476         if (subdir.length()) {
477                 path += subdir + "/";
478         }
479         
480         path += name;
481         
482         if (access (path.c_str(), R_OK) == 0) {
483                 return path;
484         }
485
486         return "";
487 }
488
489 string
490 ARDOUR::find_config_file (string name)
491 {
492         char* envvar;
493
494         if ((envvar = getenv("ARDOUR_CONFIG_PATH")) == 0) {
495                 envvar = CONFIG_DIR;
496         }
497
498         return find_file (name, envvar);
499 }
500
501 string
502 ARDOUR::find_data_file (string name, string subdir)
503 {
504         char* envvar;
505         if ((envvar = getenv("ARDOUR_DATA_PATH")) == 0) {
506                 envvar = DATA_DIR;
507         }
508
509         return find_file (name, envvar, subdir);
510 }
511
512 ARDOUR::LocaleGuard::LocaleGuard (const char* str)
513 {
514         old = strdup (setlocale (LC_NUMERIC, NULL));
515         if (strcmp (old, str)) {
516                 setlocale (LC_NUMERIC, str);
517         } 
518 }
519
520 ARDOUR::LocaleGuard::~LocaleGuard ()
521 {
522         setlocale (LC_NUMERIC, old);
523         free ((char*)old);
524 }
525
526 ARDOUR::OverlapType
527 ARDOUR::coverage (nframes_t sa, nframes_t ea, 
528                   nframes_t sb, nframes_t eb)
529 {
530         /* OverlapType returned reflects how the second (B)
531            range overlaps the first (A).
532
533            The diagrams show various relative placements
534            of A and B for each OverlapType.
535
536            Notes:
537               Internal: the start points cannot coincide
538               External: the start and end points can coincide
539               Start: end points can coincide
540               End: start points can coincide
541
542            XXX Logically, Internal should disallow end
543            point equality.
544         */
545
546         /*
547              |--------------------|   A
548                   |------|            B
549                 |-----------------|   B
550
551
552              "B is internal to A"               
553
554         */
555 #ifdef OLD_COVERAGE
556         if ((sb >= sa) && (eb <= ea)) {
557 #else
558         if ((sb > sa) && (eb <= ea)) {
559 #endif
560                 return OverlapInternal;
561         }
562
563         /*
564              |--------------------|   A
565            ----|                      B
566            -----------------------|   B
567            --|                        B
568            
569              "B overlaps the start of A"
570
571         */
572
573         if ((eb >= sa) && (eb <= ea)) {
574                 return OverlapStart;
575         }
576         /* 
577              |---------------------|  A
578                    |----------------- B
579              |----------------------- B    
580                                    |- B
581
582             "B overlaps the end of A"                              
583
584         */
585         if ((sb >= sa) && (sb <= ea)) {
586                 return OverlapEnd;
587         }
588         /*
589              |--------------------|     A
590            --------------------------  B   
591              |-----------------------  B
592             ----------------------|    B
593              |--------------------|    B
594
595
596            "B overlaps all of A"
597         */
598         if ((sa >= sb) && (sa <= eb) && (ea <= eb)) {
599                 return OverlapExternal;
600         }
601
602         return OverlapNone;
603 }
604
605 /* not sure where to put these */
606
607 template<class T>
608 std::istream& int_to_type (std::istream& o, T& hf) {
609         int val;
610         o >> val;
611         hf = (T) val;
612         return o;
613 }
614
615 std::istream& operator>>(std::istream& o, HeaderFormat& var) { return int_to_type<HeaderFormat> (o, var); }
616 std::istream& operator>>(std::istream& o, SampleFormat& var) { return int_to_type<SampleFormat> (o, var); }
617 std::istream& operator>>(std::istream& o, AutoConnectOption& var) { return int_to_type<AutoConnectOption> (o, var); }
618 std::istream& operator>>(std::istream& o, MonitorModel& var) { return int_to_type<MonitorModel> (o, var); }
619 std::istream& operator>>(std::istream& o, EditMode& var) { return int_to_type<EditMode> (o, var); }
620 std::istream& operator>>(std::istream& o, SoloModel& var) { return int_to_type<SoloModel> (o, var); }
621 std::istream& operator>>(std::istream& o, LayerModel& var) { return int_to_type<LayerModel> (o, var); }
622 std::istream& operator>>(std::istream& o, CrossfadeModel& var) { return int_to_type<CrossfadeModel> (o, var); }
623 std::istream& operator>>(std::istream& o, SlaveSource& var) { return int_to_type<SlaveSource> (o, var); }
624 std::istream& operator>>(std::istream& o, ShuttleBehaviour& var) { return int_to_type<ShuttleBehaviour> (o, var); }
625 std::istream& operator>>(std::istream& o, ShuttleUnits& var) { return int_to_type<ShuttleUnits> (o, var); }
626 std::istream& operator>>(std::istream& o, SmpteFormat& var) { return int_to_type<SmpteFormat> (o, var); }
627