skeleton framework for LTC-slave
[ardour.git] / libs / ardour / utils.cc
1 /*
2     Copyright (C) 2000-2003 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
20 #ifdef WAF_BUILD
21 #include "libardour-config.h"
22 #endif
23
24 #include <stdint.h>
25
26 #include <cstdio> /* for sprintf */
27 #include <cstring>
28 #include <climits>
29 #include <cstdlib>
30 #include <cmath>
31 #include <cctype>
32 #include <cstring>
33 #include <cerrno>
34 #include <iostream>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <fcntl.h>
39 #include <dirent.h>
40 #include <errno.h>
41 #include <regex.h>
42
43 #include <glibmm/miscutils.h>
44 #include <glibmm/fileutils.h>
45
46 #include "pbd/cpus.h"
47 #include "pbd/error.h"
48 #include "pbd/stacktrace.h"
49 #include "pbd/xml++.h"
50 #include "pbd/basename.h"
51 #include "pbd/strsplit.h"
52 #include "pbd/replace_all.h"
53
54 #include "ardour/utils.h"
55 #include "ardour/rc_configuration.h"
56
57 #include "i18n.h"
58
59 using namespace ARDOUR;
60 using namespace std;
61 using namespace PBD;
62
63 string
64 legalize_for_path (const string& str)
65 {
66         string::size_type pos;
67         string illegal_chars = "/\\"; /* DOS, POSIX. Yes, we're going to ignore HFS */
68         string legal;
69
70         legal = str;
71         pos = 0;
72
73         while ((pos = legal.find_first_of (illegal_chars, pos)) != string::npos) {
74                 legal.replace (pos, 1, "_");
75                 pos += 1;
76         }
77
78         return string (legal);
79 }
80
81 string
82 bump_name_once (const std::string& name, char delimiter)
83 {
84         string::size_type delim;
85         string newname;
86
87         if ((delim = name.find_last_of (delimiter)) == string::npos) {
88                 newname  = name;
89                 newname += delimiter;
90                 newname += "1";
91         } else {
92                 int isnumber = 1;
93                 const char *last_element = name.c_str() + delim + 1;
94                 for (size_t i = 0; i < strlen(last_element); i++) {
95                         if (!isdigit(last_element[i])) {
96                                 isnumber = 0;
97                                 break;
98                         }
99                 }
100
101                 errno = 0;
102                 int32_t version = strtol (name.c_str()+delim+1, (char **)NULL, 10);
103
104                 if (isnumber == 0 || errno != 0) {
105                         // last_element is not a number, or is too large
106                         newname  = name;
107                         newname  += delimiter;
108                         newname += "1";
109                 } else {
110                         char buf[32];
111
112                         snprintf (buf, sizeof(buf), "%d", version+1);
113
114                         newname  = name.substr (0, delim+1);
115                         newname += buf;
116                 }
117         }
118
119         return newname;
120
121 }
122
123 XMLNode *
124 find_named_node (const XMLNode& node, string name)
125 {
126         XMLNodeList nlist;
127         XMLNodeConstIterator niter;
128         XMLNode* child;
129
130         nlist = node.children();
131
132         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
133
134                 child = *niter;
135
136                 if (child->name() == name) {
137                         return child;
138                 }
139         }
140
141         return 0;
142 }
143
144 int
145 cmp_nocase (const string& s, const string& s2)
146 {
147         string::const_iterator p = s.begin();
148         string::const_iterator p2 = s2.begin();
149
150         while (p != s.end() && p2 != s2.end()) {
151                 if (toupper(*p) != toupper(*p2)) {
152                         return (toupper(*p) < toupper(*p2)) ? -1 : 1;
153                 }
154                 ++p;
155                 ++p2;
156         }
157
158         return (s2.size() == s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
159 }
160
161 int
162 touch_file (string path)
163 {
164         int fd = open (path.c_str(), O_RDWR|O_CREAT, 0660);
165         if (fd >= 0) {
166                 close (fd);
167                 return 0;
168         }
169         return 1;
170 }
171
172 string
173 region_name_from_path (string path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
174 {
175         path = PBD::basename_nosuffix (path);
176
177         if (strip_channels) {
178
179                 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
180
181                 string::size_type len = path.length();
182
183                 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
184                     (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
185
186                         path = path.substr (0, path.length() - 2);
187                 }
188         }
189
190         if (add_channel_suffix) {
191
192                 path += '%';
193
194                 if (total > 2) {
195                         path += (char) ('a' + this_one);
196                 } else {
197                         path += (char) (this_one == 0 ? 'L' : 'R');
198                 }
199         }
200
201         return path;
202 }
203
204 bool
205 path_is_paired (string path, string& pair_base)
206 {
207         string::size_type pos;
208
209         /* remove any leading path */
210
211         if ((pos = path.find_last_of (G_DIR_SEPARATOR)) != string::npos) {
212                 path = path.substr(pos+1);
213         }
214
215         /* remove filename suffixes etc. */
216
217         if ((pos = path.find_last_of ('.')) != string::npos) {
218                 path = path.substr (0, pos);
219         }
220
221         string::size_type len = path.length();
222
223         /* look for possible channel identifier: "?R", "%R", ".L" etc. */
224
225         if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
226             (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
227
228                 pair_base = path.substr (0, len-2);
229                 return true;
230
231         }
232
233         return false;
234 }
235
236 string
237 path_expand (string path)
238 {
239         if (path.empty()) {
240                 return path;
241         }
242
243         /* tilde expansion */
244
245         if (path[0] == '~') {
246                 if (path.length() == 1) {
247                         return Glib::get_home_dir();
248                 }
249
250                 if (path[1] == '/') {
251                         path.replace (0, 1, Glib::get_home_dir());
252                 } else {
253                         /* can't handle ~roger, so just leave it */
254                 }
255         }
256
257         /* now do $VAR substitution, since wordexp isn't reliable */
258
259         regex_t compiled_pattern;
260         const int nmatches = 100;
261         regmatch_t matches[nmatches];
262         
263         if (regcomp (&compiled_pattern, "\\$([a-zA-Z_][a-zA-Z0-9_]*|\\{[a-zA-Z_][a-zA-Z0-9_]*\\})", REG_EXTENDED)) {
264                 cerr << "bad regcomp\n";
265                 return path;
266         }
267
268         while (true) { 
269
270                 if (regexec (&compiled_pattern, path.c_str(), nmatches, matches, 0)) {
271                         break;
272                 }
273                 
274                 /* matches[0] gives the entire match */
275                 
276                 string match = path.substr (matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
277                 
278                 /* try to get match from the environment */
279
280                 if (match[1] == '{') {
281                         /* ${FOO} form */
282                         match = match.substr (2, match.length() - 3);
283                 }
284
285                 char* matched_value = getenv (match.c_str());
286
287                 if (matched_value) {
288                         path.replace (matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so, matched_value);
289                 } else {
290                         path.replace (matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so, string());
291                 }
292
293                 /* go back and do it again with whatever remains after the
294                  * substitution 
295                  */
296         }
297
298         regfree (&compiled_pattern);
299
300         /* canonicalize */
301
302         char buf[PATH_MAX+1];
303
304         if (realpath (path.c_str(), buf)) {
305                 return buf;
306         } else {
307                 return string();
308         }
309 }
310
311 string
312 search_path_expand (string path)
313 {
314         if (path.empty()) {
315                 return path;
316         }
317
318         vector<string> s;
319         vector<string> n;
320
321         split (path, s, ':');
322
323         for (vector<string>::iterator i = s.begin(); i != s.end(); ++i) {
324                 string exp = path_expand (*i);
325                 if (!exp.empty()) {
326                         n.push_back (exp);
327                 }
328         }
329
330         string r;
331
332         for (vector<string>::iterator i = n.begin(); i != n.end(); ++i) {
333                 if (!r.empty()) {
334                         r += ':';
335                 }
336                 r += *i;
337         }
338
339         return r;
340 }
341
342 #if __APPLE__
343 string
344 CFStringRefToStdString(CFStringRef stringRef)
345 {
346         CFIndex size =
347                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
348                 kCFStringEncodingUTF8);
349             char *buf = new char[size];
350
351         std::string result;
352
353         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
354             result = buf;
355         }
356         delete [] buf;
357         return result;
358 }
359 #endif // __APPLE__
360
361 void
362 compute_equal_power_fades (framecnt_t nframes, float* in, float* out)
363 {
364         double step;
365
366         step = 1.0/(nframes-1);
367
368         in[0] = 0.0f;
369
370         for (framecnt_t i = 1; i < nframes - 1; ++i) {
371                 in[i] = in[i-1] + step;
372         }
373
374         in[nframes-1] = 1.0;
375
376         const float pan_law_attenuation = -3.0f;
377         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
378
379         for (framecnt_t n = 0; n < nframes; ++n) {
380                 float inVal = in[n];
381                 float outVal = 1 - inVal;
382                 out[n] = outVal * (scale * outVal + 1.0f - scale);
383                 in[n] = inVal * (scale * inVal + 1.0f - scale);
384         }
385 }
386
387 EditMode
388 string_to_edit_mode (string str)
389 {
390         if (str == _("Splice")) {
391                 return Splice;
392         } else if (str == _("Slide")) {
393                 return Slide;
394         } else if (str == _("Lock")) {
395                 return Lock;
396         }
397         fatal << string_compose (_("programming error: unknown edit mode string \"%1\""), str) << endmsg;
398         /*NOTREACHED*/
399         return Slide;
400 }
401
402 const char*
403 edit_mode_to_string (EditMode mode)
404 {
405         switch (mode) {
406         case Slide:
407                 return _("Slide");
408
409         case Lock:
410                 return _("Lock");
411
412         default:
413         case Splice:
414                 return _("Splice");
415         }
416 }
417
418 SyncSource
419 string_to_sync_source (string str)
420 {
421         if (str == _("MIDI Timecode") || str == _("MTC")) {
422                 return MTC;
423         }
424
425         if (str == _("MIDI Clock")) {
426                 return MIDIClock;
427         }
428
429         if (str == _("JACK")) {
430                 return JACK;
431         }
432
433         fatal << string_compose (_("programming error: unknown sync source string \"%1\""), str) << endmsg;
434         /*NOTREACHED*/
435         return JACK;
436 }
437
438 /** @param sh Return a short version of the string */
439 const char*
440 sync_source_to_string (SyncSource src, bool sh)
441 {
442         switch (src) {
443         case JACK:
444                 return _("JACK");
445
446         case MTC:
447                 if (sh) {
448                         return _("MTC");
449                 } else {
450                         return _("MIDI Timecode");
451                 }
452
453         case MIDIClock:
454                 return _("MIDI Clock");
455
456         case LTC:
457                 return _("LTC");
458         }
459         /* GRRRR .... stupid, stupid gcc - you can't get here from there, all enum values are handled */
460         return _("JACK");
461 }
462
463 float
464 meter_falloff_to_float (MeterFalloff falloff)
465 {
466         switch (falloff) {
467         case MeterFalloffOff:
468                 return METER_FALLOFF_OFF;
469         case MeterFalloffSlowest:
470                 return METER_FALLOFF_SLOWEST;
471         case MeterFalloffSlow:
472                 return METER_FALLOFF_SLOW;
473         case MeterFalloffMedium:
474                 return METER_FALLOFF_MEDIUM;
475         case MeterFalloffFast:
476                 return METER_FALLOFF_FAST;
477         case MeterFalloffFaster:
478                 return METER_FALLOFF_FASTER;
479         case MeterFalloffFastest:
480                 return METER_FALLOFF_FASTEST;
481         default:
482                 return METER_FALLOFF_FAST;
483         }
484 }
485
486 MeterFalloff
487 meter_falloff_from_float (float val)
488 {
489         if (val == METER_FALLOFF_OFF) {
490                 return MeterFalloffOff;
491         }
492         else if (val <= METER_FALLOFF_SLOWEST) {
493                 return MeterFalloffSlowest;
494         }
495         else if (val <= METER_FALLOFF_SLOW) {
496                 return MeterFalloffSlow;
497         }
498         else if (val <= METER_FALLOFF_MEDIUM) {
499                 return MeterFalloffMedium;
500         }
501         else if (val <= METER_FALLOFF_FAST) {
502                 return MeterFalloffFast;
503         }
504         else if (val <= METER_FALLOFF_FASTER) {
505                 return MeterFalloffFaster;
506         }
507         else {
508                 return MeterFalloffFastest;
509         }
510 }
511
512 AutoState
513 ARDOUR::string_to_auto_state (std::string str)
514 {
515         if (str == X_("Off")) {
516                 return Off;
517         } else if (str == X_("Play")) {
518                 return Play;
519         } else if (str == X_("Write")) {
520                 return Write;
521         } else if (str == X_("Touch")) {
522                 return Touch;
523         }
524
525         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
526         /*NOTREACHED*/
527         return Touch;
528 }
529
530 string
531 ARDOUR::auto_state_to_string (AutoState as)
532 {
533         /* to be used only for XML serialization, no i18n done */
534
535         switch (as) {
536         case Off:
537                 return X_("Off");
538                 break;
539         case Play:
540                 return X_("Play");
541                 break;
542         case Write:
543                 return X_("Write");
544                 break;
545         case Touch:
546                 return X_("Touch");
547         }
548
549         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
550         /*NOTREACHED*/
551         return "";
552 }
553
554 AutoStyle
555 ARDOUR::string_to_auto_style (std::string str)
556 {
557         if (str == X_("Absolute")) {
558                 return Absolute;
559         } else if (str == X_("Trim")) {
560                 return Trim;
561         }
562
563         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle string: ", str) << endmsg;
564         /*NOTREACHED*/
565         return Trim;
566 }
567
568 string
569 ARDOUR::auto_style_to_string (AutoStyle as)
570 {
571         /* to be used only for XML serialization, no i18n done */
572
573         switch (as) {
574         case Absolute:
575                 return X_("Absolute");
576                 break;
577         case Trim:
578                 return X_("Trim");
579                 break;
580         }
581
582         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle type: ", as) << endmsg;
583         /*NOTREACHED*/
584         return "";
585 }
586
587 std::string
588 bool_as_string (bool yn)
589 {
590         return (yn ? "yes" : "no");
591 }
592
593 const char*
594 native_header_format_extension (HeaderFormat hf, const DataType& type)
595 {
596         if (type == DataType::MIDI) {
597                 return ".mid";
598         }
599
600         switch (hf) {
601         case BWF:
602                 return ".wav";
603         case WAVE:
604                 return ".wav";
605         case WAVE64:
606                 return ".w64";
607         case CAF:
608                 return ".caf";
609         case AIFF:
610                 return ".aif";
611         case iXML:
612                 return ".ixml";
613         case RF64:
614                 return ".rf64";
615         }
616
617         fatal << string_compose (_("programming error: unknown native header format: %1"), hf);
618         /*NOTREACHED*/
619         return ".wav";
620 }
621
622 bool
623 matching_unsuffixed_filename_exists_in (const string& dir, const string& path)
624 {
625         string bws = basename_nosuffix (path);
626         struct dirent* dentry;
627         struct stat statbuf;
628         DIR* dead;
629         bool ret = false;
630
631         if ((dead = ::opendir (dir.c_str())) == 0) {
632                 error << string_compose (_("cannot open directory %1 (%2)"), dir, strerror (errno)) << endl;
633                 return false;
634         }
635
636         while ((dentry = ::readdir (dead)) != 0) {
637
638                 /* avoid '.' and '..' */
639
640                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
641                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
642                         continue;
643                 }
644
645                 string fullpath = Glib::build_filename (dir, dentry->d_name);
646
647                 if (::stat (fullpath.c_str(), &statbuf)) {
648                         continue;
649                 }
650
651                 if (!S_ISREG (statbuf.st_mode)) {
652                         continue;
653                 }
654
655                 string bws2 = basename_nosuffix (dentry->d_name);
656
657                 if (bws2 == bws) {
658                         ret = true;
659                         break;
660                 }
661         }
662
663         ::closedir (dead);
664         return ret;
665 }
666
667 uint32_t
668 how_many_dsp_threads ()
669 {
670         /* CALLER MUST HOLD PROCESS LOCK */
671
672         int num_cpu = hardware_concurrency();
673         int pu = Config->get_processor_usage ();
674         uint32_t num_threads = max (num_cpu - 1, 2); // default to number of cpus minus one, or 2, whichever is larger
675
676         if (pu < 0) {
677                 /* pu is negative: use "pu" less cores for DSP than appear to be available
678                  */
679
680                 if (-pu < num_cpu) {
681                         num_threads = num_cpu + pu;
682                 }
683
684         } else if (pu == 0) {
685
686                 /* use all available CPUs
687                  */
688
689                 num_threads = num_cpu;
690
691         } else {
692                 /* use "pu" cores, if available
693                  */
694
695                 num_threads = min (num_cpu, pu);
696         }
697
698         return num_threads;
699 }
700
701 double gain_to_slider_position_with_max (double g, double max_gain)
702 {
703         return gain_to_slider_position (g * 2.0/max_gain);
704 }
705
706 double slider_position_to_gain_with_max (double g, double max_gain)
707 {
708         return slider_position_to_gain (g * max_gain/2.0);
709 }
710
711 extern "C" {
712         void c_stacktrace() { stacktrace (cerr); }
713 }