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