aa0691291380cdee8bacdb0e7cc9392905ab023b
[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 cmp_nocase_utf8 (const string& s1, const string& s2)
236 {
237         const char *cstr1 = s1.c_str();
238         const char *cstr2 = s2.c_str();
239         gchar *cstr1folded = NULL;
240         gchar *cstr2folded = NULL;
241         int retval;
242
243         if (!g_utf8_validate (cstr1, -1, NULL) ||
244                 !g_utf8_validate (cstr2, -1, NULL)) {
245                 // fall back to comparing ASCII
246                 return g_ascii_strcasecmp (cstr1, cstr2);
247         }
248
249         cstr1folded = g_utf8_casefold (cstr1, -1);
250         cstr2folded = g_utf8_casefold (cstr2, -1);
251
252         if (cstr1folded && cstr2folded) {
253                 retval = strcmp (cstr1folded, cstr2folded);
254         } else {
255                 // this shouldn't happen, make the best of it
256                 retval = g_ascii_strcasecmp (cstr1, cstr2);
257         }
258
259         if (cstr1folded) {
260                 g_free (cstr1folded);
261         }
262
263         if (cstr2folded) {
264                 g_free (cstr2folded);
265         }
266
267         return retval;
268 }
269
270 int
271 touch_file (string path)
272 {
273         int fd = open (path.c_str(), O_RDWR|O_CREAT, 0660);
274         if (fd >= 0) {
275                 close (fd);
276                 return 0;
277         }
278         return 1;
279 }
280
281 string
282 region_name_from_path (string path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
283 {
284         path = PBD::basename_nosuffix (path);
285
286         if (strip_channels) {
287
288                 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
289
290                 string::size_type len = path.length();
291
292                 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
293                     (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
294
295                         path = path.substr (0, path.length() - 2);
296                 }
297         }
298
299         if (add_channel_suffix) {
300
301                 path += '%';
302
303                 if (total > 2) {
304                         path += (char) ('a' + this_one);
305                 } else {
306                         path += (char) (this_one == 0 ? 'L' : 'R');
307                 }
308         }
309
310         return path;
311 }
312
313 bool
314 path_is_paired (string path, string& pair_base)
315 {
316         string::size_type pos;
317
318         /* remove any leading path */
319
320         if ((pos = path.find_last_of (G_DIR_SEPARATOR)) != string::npos) {
321                 path = path.substr(pos+1);
322         }
323
324         /* remove filename suffixes etc. */
325
326         if ((pos = path.find_last_of ('.')) != string::npos) {
327                 path = path.substr (0, pos);
328         }
329
330         string::size_type len = path.length();
331
332         /* look for possible channel identifier: "?R", "%R", ".L" etc. */
333
334         if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
335             (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
336
337                 pair_base = path.substr (0, len-2);
338                 return true;
339
340         }
341
342         return false;
343 }
344
345 #if __APPLE__
346 string
347 CFStringRefToStdString(CFStringRef stringRef)
348 {
349         CFIndex size =
350                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
351                 kCFStringEncodingUTF8);
352             char *buf = new char[size];
353
354         std::string result;
355
356         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
357             result = buf;
358         }
359         delete [] buf;
360         return result;
361 }
362 #endif // __APPLE__
363
364 void
365 compute_equal_power_fades (framecnt_t nframes, float* in, float* out)
366 {
367         double step;
368
369         step = 1.0/(nframes-1);
370
371         in[0] = 0.0f;
372
373         for (framecnt_t i = 1; i < nframes - 1; ++i) {
374                 in[i] = in[i-1] + step;
375         }
376
377         in[nframes-1] = 1.0;
378
379         const float pan_law_attenuation = -3.0f;
380         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
381
382         for (framecnt_t n = 0; n < nframes; ++n) {
383                 float inVal = in[n];
384                 float outVal = 1 - inVal;
385                 out[n] = outVal * (scale * outVal + 1.0f - scale);
386                 in[n] = inVal * (scale * inVal + 1.0f - scale);
387         }
388 }
389
390 EditMode
391 string_to_edit_mode (string str)
392 {
393         if (str == _("Splice")) {
394                 return Splice;
395         } else if (str == _("Slide")) {
396                 return Slide;
397         } else if (str == _("Lock")) {
398                 return Lock;
399         }
400         fatal << string_compose (_("programming error: unknown edit mode string \"%1\""), str) << endmsg;
401         /*NOTREACHED*/
402         return Slide;
403 }
404
405 const char*
406 edit_mode_to_string (EditMode mode)
407 {
408         switch (mode) {
409         case Slide:
410                 return _("Slide");
411
412         case Lock:
413                 return _("Lock");
414
415         default:
416         case Splice:
417                 return _("Splice");
418         }
419 }
420
421 SyncSource
422 string_to_sync_source (string str)
423 {
424         if (str == _("MIDI Timecode") || str == _("MTC")) {
425                 return MTC;
426         }
427
428         if (str == _("MIDI Clock")) {
429                 return MIDIClock;
430         }
431
432         if (str == _("JACK")) {
433                 return Engine;
434         }
435
436         fatal << string_compose (_("programming error: unknown sync source string \"%1\""), str) << endmsg;
437         /*NOTREACHED*/
438         return Engine;
439 }
440
441 /** @param sh Return a short version of the string */
442 const char*
443 sync_source_to_string (SyncSource src, bool sh)
444 {
445         switch (src) {
446         case Engine:
447                 /* no other backends offer sync for now ... deal with this if we
448                  * ever have to.
449                  */
450                 return _("JACK");
451
452         case MTC:
453                 if (sh) {
454                         return _("MTC");
455                 } else {
456                         return _("MIDI Timecode");
457                 }
458
459         case MIDIClock:
460                 if (sh) {
461                         return _("M-Clock");
462                 } else {
463                         return _("MIDI Clock");
464                 }
465
466         case LTC:
467                 return _("LTC");
468         }
469         /* GRRRR .... stupid, stupid gcc - you can't get here from there, all enum values are handled */
470         return _("JACK");
471 }
472
473 float
474 meter_falloff_to_float (MeterFalloff falloff)
475 {
476         switch (falloff) {
477         case MeterFalloffOff:
478                 return METER_FALLOFF_OFF;
479         case MeterFalloffSlowest:
480                 return METER_FALLOFF_SLOWEST;
481         case MeterFalloffSlow:
482                 return METER_FALLOFF_SLOW;
483         case MeterFalloffSlowish:
484                 return METER_FALLOFF_SLOWISH;
485         case MeterFalloffMedium:
486                 return METER_FALLOFF_MEDIUM;
487         case MeterFalloffModerate:
488                 return METER_FALLOFF_MODERATE;
489         case MeterFalloffFast:
490                 return METER_FALLOFF_FAST;
491         case MeterFalloffFaster:
492                 return METER_FALLOFF_FASTER;
493         case MeterFalloffFastest:
494                 return METER_FALLOFF_FASTEST;
495         default:
496                 return METER_FALLOFF_FAST;
497         }
498 }
499
500 MeterFalloff
501 meter_falloff_from_float (float val)
502 {
503         if (val == METER_FALLOFF_OFF) {
504                 return MeterFalloffOff;
505         }
506         else if (val <= METER_FALLOFF_SLOWEST) {
507                 return MeterFalloffSlowest;
508         }
509         else if (val <= METER_FALLOFF_SLOW) {
510                 return MeterFalloffSlow;
511         }
512         else if (val <= METER_FALLOFF_SLOWISH) {
513                 return MeterFalloffSlowish;
514         }
515         else if (val <= METER_FALLOFF_MODERATE) {
516                 return MeterFalloffModerate;
517         }
518         else if (val <= METER_FALLOFF_MEDIUM) {
519                 return MeterFalloffMedium;
520         }
521         else if (val <= METER_FALLOFF_FAST) {
522                 return MeterFalloffFast;
523         }
524         else if (val <= METER_FALLOFF_FASTER) {
525                 return MeterFalloffFaster;
526         }
527         else {
528                 return MeterFalloffFastest;
529         }
530 }
531
532 AutoState
533 ARDOUR::string_to_auto_state (std::string str)
534 {
535         if (str == X_("Off")) {
536                 return Off;
537         } else if (str == X_("Play")) {
538                 return Play;
539         } else if (str == X_("Write")) {
540                 return Write;
541         } else if (str == X_("Touch")) {
542                 return Touch;
543         }
544
545         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
546         /*NOTREACHED*/
547         return Touch;
548 }
549
550 string
551 ARDOUR::auto_state_to_string (AutoState as)
552 {
553         /* to be used only for XML serialization, no i18n done */
554
555         switch (as) {
556         case Off:
557                 return X_("Off");
558                 break;
559         case Play:
560                 return X_("Play");
561                 break;
562         case Write:
563                 return X_("Write");
564                 break;
565         case Touch:
566                 return X_("Touch");
567         }
568
569         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
570         /*NOTREACHED*/
571         return "";
572 }
573
574 AutoStyle
575 ARDOUR::string_to_auto_style (std::string str)
576 {
577         if (str == X_("Absolute")) {
578                 return Absolute;
579         } else if (str == X_("Trim")) {
580                 return Trim;
581         }
582
583         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle string: ", str) << endmsg;
584         /*NOTREACHED*/
585         return Trim;
586 }
587
588 string
589 ARDOUR::auto_style_to_string (AutoStyle as)
590 {
591         /* to be used only for XML serialization, no i18n done */
592
593         switch (as) {
594         case Absolute:
595                 return X_("Absolute");
596                 break;
597         case Trim:
598                 return X_("Trim");
599                 break;
600         }
601
602         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle type: ", as) << endmsg;
603         /*NOTREACHED*/
604         return "";
605 }
606
607 std::string
608 bool_as_string (bool yn)
609 {
610         return (yn ? "yes" : "no");
611 }
612
613 const char*
614 native_header_format_extension (HeaderFormat hf, const DataType& type)
615 {
616         if (type == DataType::MIDI) {
617                 return ".mid";
618         }
619
620         switch (hf) {
621         case BWF:
622                 return ".wav";
623         case WAVE:
624                 return ".wav";
625         case WAVE64:
626                 return ".w64";
627         case CAF:
628                 return ".caf";
629         case AIFF:
630                 return ".aif";
631         case iXML:
632                 return ".ixml";
633         case RF64:
634                 return ".rf64";
635         }
636
637         fatal << string_compose (_("programming error: unknown native header format: %1"), hf);
638         /*NOTREACHED*/
639         return ".wav";
640 }
641
642 bool
643 matching_unsuffixed_filename_exists_in (const string& dir, const string& path)
644 {
645         string bws = basename_nosuffix (path);
646         struct dirent* dentry;
647         struct stat statbuf;
648         DIR* dead;
649         bool ret = false;
650
651         if ((dead = ::opendir (dir.c_str())) == 0) {
652                 error << string_compose (_("cannot open directory %1 (%2)"), dir, strerror (errno)) << endl;
653                 return false;
654         }
655
656         while ((dentry = ::readdir (dead)) != 0) {
657
658                 /* avoid '.' and '..' */
659
660                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
661                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
662                         continue;
663                 }
664
665                 string fullpath = Glib::build_filename (dir, dentry->d_name);
666
667                 if (::stat (fullpath.c_str(), &statbuf)) {
668                         continue;
669                 }
670
671                 if (!S_ISREG (statbuf.st_mode)) {
672                         continue;
673                 }
674
675                 string bws2 = basename_nosuffix (dentry->d_name);
676
677                 if (bws2 == bws) {
678                         ret = true;
679                         break;
680                 }
681         }
682
683         ::closedir (dead);
684         return ret;
685 }
686
687 uint32_t
688 how_many_dsp_threads ()
689 {
690         /* CALLER MUST HOLD PROCESS LOCK */
691
692         int num_cpu = hardware_concurrency();
693         int pu = Config->get_processor_usage ();
694         uint32_t num_threads = max (num_cpu - 1, 2); // default to number of cpus minus one, or 2, whichever is larger
695
696         if (pu < 0) {
697                 /* pu is negative: use "pu" less cores for DSP than appear to be available
698                  */
699
700                 if (-pu < num_cpu) {
701                         num_threads = num_cpu + pu;
702                 }
703
704         } else if (pu == 0) {
705
706                 /* use all available CPUs
707                  */
708
709                 num_threads = num_cpu;
710
711         } else {
712                 /* use "pu" cores, if available
713                  */
714
715                 num_threads = min (num_cpu, pu);
716         }
717
718         return num_threads;
719 }
720
721 double gain_to_slider_position_with_max (double g, double max_gain)
722 {
723         return gain_to_slider_position (g * 2.0/max_gain);
724 }
725
726 double slider_position_to_gain_with_max (double g, double max_gain)
727 {
728         return slider_position_to_gain (g * max_gain/2.0);
729 }
730
731 extern "C" {
732         void c_stacktrace() { stacktrace (cerr); }
733 }