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