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