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