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