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