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