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