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