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