cleanup regexp after use
[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 #include <dirent.h>
40 #include <errno.h>
41 #include <regex.h>
42
43 #include <glibmm/miscutils.h>
44 #include <glibmm/fileutils.h>
45
46 #include "pbd/cpus.h"
47 #include "pbd/error.h"
48 #include "pbd/stacktrace.h"
49 #include "pbd/xml++.h"
50 #include "pbd/basename.h"
51 #include "pbd/strsplit.h"
52 #include "pbd/replace_all.h"
53
54 #include "ardour/utils.h"
55 #include "ardour/rc_configuration.h"
56
57 #include "i18n.h"
58
59 using namespace ARDOUR;
60 using namespace std;
61 using namespace PBD;
62
63 string
64 legalize_for_path (const string& str)
65 {
66         string::size_type pos;
67         string illegal_chars = "/\\"; /* DOS, POSIX. Yes, we're going to ignore HFS */
68         string legal;
69
70         legal = str;
71         pos = 0;
72
73         while ((pos = legal.find_first_of (illegal_chars, pos)) != string::npos) {
74                 legal.replace (pos, 1, "_");
75                 pos += 1;
76         }
77
78         return string (legal);
79 }
80
81 string
82 bump_name_once (const std::string& name, char delimiter)
83 {
84         string::size_type delim;
85         string newname;
86
87         if ((delim = name.find_last_of (delimiter)) == string::npos) {
88                 newname  = name;
89                 newname += delimiter;
90                 newname += "1";
91         } else {
92                 int isnumber = 1;
93                 const char *last_element = name.c_str() + delim + 1;
94                 for (size_t i = 0; i < strlen(last_element); i++) {
95                         if (!isdigit(last_element[i])) {
96                                 isnumber = 0;
97                                 break;
98                         }
99                 }
100
101                 errno = 0;
102                 int32_t version = strtol (name.c_str()+delim+1, (char **)NULL, 10);
103
104                 if (isnumber == 0 || errno != 0) {
105                         // last_element is not a number, or is too large
106                         newname  = name;
107                         newname  += delimiter;
108                         newname += "1";
109                 } else {
110                         char buf[32];
111
112                         snprintf (buf, sizeof(buf), "%d", version+1);
113
114                         newname  = name.substr (0, delim+1);
115                         newname += buf;
116                 }
117         }
118
119         return newname;
120
121 }
122
123 bool
124 could_be_a_valid_path (const string& path)
125 {
126         vector<string> posix_dirs;
127         vector<string> dos_dirs;
128         string testpath;
129
130         split (path, posix_dirs, '/');
131         split (path, dos_dirs, '\\');
132
133         /* remove the last component of each */
134
135         posix_dirs.erase (--posix_dirs.end());
136         dos_dirs.erase (--dos_dirs.end());
137
138         if (G_DIR_SEPARATOR == '/') {
139                 for (vector<string>::iterator x = posix_dirs.begin(); x != posix_dirs.end(); ++x) {
140                         testpath = Glib::build_filename (testpath, *x);
141                         cerr << "Testing " << testpath << endl;
142                         if (!Glib::file_test (testpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
143                                 return false;
144                         }
145                 }
146         }
147
148         if (G_DIR_SEPARATOR == '\\') {
149                 testpath = "";
150                 for (vector<string>::iterator x = dos_dirs.begin(); x != dos_dirs.end(); ++x) {
151                         testpath = Glib::build_filename (testpath, *x);
152                         cerr << "Testing " << testpath << endl;
153                         if (!Glib::file_test (testpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
154                                 return false;
155                         }
156                 }
157         }
158
159         return true;
160 }
161
162
163 XMLNode *
164 find_named_node (const XMLNode& node, string name)
165 {
166         XMLNodeList nlist;
167         XMLNodeConstIterator niter;
168         XMLNode* child;
169
170         nlist = node.children();
171
172         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
173
174                 child = *niter;
175
176                 if (child->name() == name) {
177                         return child;
178                 }
179         }
180
181         return 0;
182 }
183
184 int
185 cmp_nocase (const string& s, const string& s2)
186 {
187         string::const_iterator p = s.begin();
188         string::const_iterator p2 = s2.begin();
189
190         while (p != s.end() && p2 != s2.end()) {
191                 if (toupper(*p) != toupper(*p2)) {
192                         return (toupper(*p) < toupper(*p2)) ? -1 : 1;
193                 }
194                 ++p;
195                 ++p2;
196         }
197
198         return (s2.size() == s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
199 }
200
201 int
202 touch_file (string path)
203 {
204         int fd = open (path.c_str(), O_RDWR|O_CREAT, 0660);
205         if (fd >= 0) {
206                 close (fd);
207                 return 0;
208         }
209         return 1;
210 }
211
212 string
213 region_name_from_path (string path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
214 {
215         path = PBD::basename_nosuffix (path);
216
217         if (strip_channels) {
218
219                 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
220
221                 string::size_type len = path.length();
222
223                 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
224                     (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
225
226                         path = path.substr (0, path.length() - 2);
227                 }
228         }
229
230         if (add_channel_suffix) {
231
232                 path += '%';
233
234                 if (total > 2) {
235                         path += (char) ('a' + this_one);
236                 } else {
237                         path += (char) (this_one == 0 ? 'L' : 'R');
238                 }
239         }
240
241         return path;
242 }
243
244 bool
245 path_is_paired (string path, string& pair_base)
246 {
247         string::size_type pos;
248
249         /* remove any leading path */
250
251         if ((pos = path.find_last_of (G_DIR_SEPARATOR)) != string::npos) {
252                 path = path.substr(pos+1);
253         }
254
255         /* remove filename suffixes etc. */
256
257         if ((pos = path.find_last_of ('.')) != string::npos) {
258                 path = path.substr (0, pos);
259         }
260
261         string::size_type len = path.length();
262
263         /* look for possible channel identifier: "?R", "%R", ".L" etc. */
264
265         if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
266             (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
267
268                 pair_base = path.substr (0, len-2);
269                 return true;
270
271         }
272
273         return false;
274 }
275
276 string
277 path_expand (string path)
278 {
279         if (path.empty()) {
280                 return path;
281         }
282
283         /* tilde expansion */
284
285         if (path[0] == '~') {
286                 if (path.length() == 1) {
287                         return Glib::get_home_dir();
288                 }
289
290                 if (path[1] == '/') {
291                         path.replace (0, 1, Glib::get_home_dir());
292                 } else {
293                         /* can't handle ~roger, so just leave it */
294                 }
295         }
296
297         /* now do $VAR substitution, since wordexp isn't reliable */
298
299         regex_t compiled_pattern;
300         const int nmatches = 100;
301         regmatch_t matches[nmatches];
302         
303         if (regcomp (&compiled_pattern, "\\$([a-zA-Z_][a-zA-Z0-9_]*|\\{[a-zA-Z_][a-zA-Z0-9_]*\\})", REG_EXTENDED)) {
304                 cerr << "bad regcomp\n";
305                 return path;
306         }
307
308         while (true) { 
309
310                 cerr << "working on " << path << endl;
311
312                 if (regexec (&compiled_pattern, path.c_str(), nmatches, matches, 0)) {
313                         break;
314                 }
315                 
316                 /* matches[0] gives the entire match */
317                 
318                 string match = path.substr (matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
319                 
320                 /* try to get match from the environment */
321
322                 if (match[1] == '{') {
323                         /* ${FOO} form */
324                         match = match.substr (2, match.length() - 3);
325                 }
326
327                 char* matched_value = getenv (match.c_str());
328
329                 if (matched_value) {
330                         path.replace (matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so, matched_value);
331                 } else {
332                         path.replace (matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so, string());
333                 }
334
335                 /* go back and do it again with whatever remains after the
336                  * substitution 
337                  */
338         }
339
340         regfree (&compiled_pattern);
341
342         /* canonicalize */
343
344         char buf[PATH_MAX+1];
345         realpath (path.c_str(), buf);
346         return buf;
347 }
348
349 #if __APPLE__
350 string
351 CFStringRefToStdString(CFStringRef stringRef)
352 {
353         CFIndex size =
354                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
355                 kCFStringEncodingUTF8);
356             char *buf = new char[size];
357
358         std::string result;
359
360         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
361             result = buf;
362         }
363         delete [] buf;
364         return result;
365 }
366 #endif // __APPLE__
367
368 void
369 compute_equal_power_fades (framecnt_t nframes, float* in, float* out)
370 {
371         double step;
372
373         step = 1.0/(nframes-1);
374
375         in[0] = 0.0f;
376
377         for (framecnt_t i = 1; i < nframes - 1; ++i) {
378                 in[i] = in[i-1] + step;
379         }
380
381         in[nframes-1] = 1.0;
382
383         const float pan_law_attenuation = -3.0f;
384         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
385
386         for (framecnt_t n = 0; n < nframes; ++n) {
387                 float inVal = in[n];
388                 float outVal = 1 - inVal;
389                 out[n] = outVal * (scale * outVal + 1.0f - scale);
390                 in[n] = inVal * (scale * inVal + 1.0f - scale);
391         }
392 }
393
394 EditMode
395 string_to_edit_mode (string str)
396 {
397         if (str == _("Splice")) {
398                 return Splice;
399         } else if (str == _("Slide")) {
400                 return Slide;
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         default:
420         case Splice:
421                 return _("Splice");
422         }
423 }
424
425 SyncSource
426 string_to_sync_source (string str)
427 {
428         if (str == _("MIDI Timecode") || str == _("MTC")) {
429                 return MTC;
430         }
431
432         if (str == _("MIDI Clock")) {
433                 return MIDIClock;
434         }
435
436         if (str == _("JACK")) {
437                 return JACK;
438         }
439
440         fatal << string_compose (_("programming error: unknown sync source string \"%1\""), str) << endmsg;
441         /*NOTREACHED*/
442         return JACK;
443 }
444
445 /** @param sh Return a short version of the string */
446 const char*
447 sync_source_to_string (SyncSource src, bool sh)
448 {
449         switch (src) {
450         case JACK:
451                 return _("JACK");
452
453         case MTC:
454                 if (sh) {
455                         return _("MTC");
456                 } else {
457                         return _("MIDI Timecode");
458                 }
459
460         case MIDIClock:
461                 return _("MIDI Clock");
462         }
463         /* GRRRR .... stupid, stupid gcc - you can't get here from there, all enum values are handled */
464         return _("JACK");
465 }
466
467 float
468 meter_falloff_to_float (MeterFalloff falloff)
469 {
470         switch (falloff) {
471         case MeterFalloffOff:
472                 return METER_FALLOFF_OFF;
473         case MeterFalloffSlowest:
474                 return METER_FALLOFF_SLOWEST;
475         case MeterFalloffSlow:
476                 return METER_FALLOFF_SLOW;
477         case MeterFalloffMedium:
478                 return METER_FALLOFF_MEDIUM;
479         case MeterFalloffFast:
480                 return METER_FALLOFF_FAST;
481         case MeterFalloffFaster:
482                 return METER_FALLOFF_FASTER;
483         case MeterFalloffFastest:
484                 return METER_FALLOFF_FASTEST;
485         default:
486                 return METER_FALLOFF_FAST;
487         }
488 }
489
490 MeterFalloff
491 meter_falloff_from_float (float val)
492 {
493         if (val == METER_FALLOFF_OFF) {
494                 return MeterFalloffOff;
495         }
496         else if (val <= METER_FALLOFF_SLOWEST) {
497                 return MeterFalloffSlowest;
498         }
499         else if (val <= METER_FALLOFF_SLOW) {
500                 return MeterFalloffSlow;
501         }
502         else if (val <= METER_FALLOFF_MEDIUM) {
503                 return MeterFalloffMedium;
504         }
505         else if (val <= METER_FALLOFF_FAST) {
506                 return MeterFalloffFast;
507         }
508         else if (val <= METER_FALLOFF_FASTER) {
509                 return MeterFalloffFaster;
510         }
511         else {
512                 return MeterFalloffFastest;
513         }
514 }
515
516 AutoState
517 ARDOUR::string_to_auto_state (std::string str)
518 {
519         if (str == X_("Off")) {
520                 return Off;
521         } else if (str == X_("Play")) {
522                 return Play;
523         } else if (str == X_("Write")) {
524                 return Write;
525         } else if (str == X_("Touch")) {
526                 return Touch;
527         }
528
529         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
530         /*NOTREACHED*/
531         return Touch;
532 }
533
534 string
535 ARDOUR::auto_state_to_string (AutoState as)
536 {
537         /* to be used only for XML serialization, no i18n done */
538
539         switch (as) {
540         case Off:
541                 return X_("Off");
542                 break;
543         case Play:
544                 return X_("Play");
545                 break;
546         case Write:
547                 return X_("Write");
548                 break;
549         case Touch:
550                 return X_("Touch");
551         }
552
553         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
554         /*NOTREACHED*/
555         return "";
556 }
557
558 AutoStyle
559 ARDOUR::string_to_auto_style (std::string str)
560 {
561         if (str == X_("Absolute")) {
562                 return Absolute;
563         } else if (str == X_("Trim")) {
564                 return Trim;
565         }
566
567         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle string: ", str) << endmsg;
568         /*NOTREACHED*/
569         return Trim;
570 }
571
572 string
573 ARDOUR::auto_style_to_string (AutoStyle as)
574 {
575         /* to be used only for XML serialization, no i18n done */
576
577         switch (as) {
578         case Absolute:
579                 return X_("Absolute");
580                 break;
581         case Trim:
582                 return X_("Trim");
583                 break;
584         }
585
586         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle type: ", as) << endmsg;
587         /*NOTREACHED*/
588         return "";
589 }
590
591 std::string
592 bool_as_string (bool yn)
593 {
594         return (yn ? "yes" : "no");
595 }
596
597 bool
598 string_is_affirmative (const std::string& str)
599 {
600         /* to be used only with XML data - not intended to handle user input */
601
602         if (str.empty ()) {
603                 return false;
604         }
605
606         /* the use of g_strncasecmp() is solely to get around issues with
607          * charsets posed by trying to use C++ for the same
608          * comparison. switching a std::string to its lower- or upper-case
609          * version has several issues, but handled by default
610          * in the way we desire when doing it in C.
611          */
612
613         return str == "1" || str == "y" || str == "Y" || (!g_strncasecmp(str.c_str(), "yes", str.length()));
614 }
615
616 const char*
617 native_header_format_extension (HeaderFormat hf, const DataType& type)
618 {
619         if (type == DataType::MIDI) {
620                 return ".mid";
621         }
622
623         switch (hf) {
624         case BWF:
625                 return ".wav";
626         case WAVE:
627                 return ".wav";
628         case WAVE64:
629                 return ".w64";
630         case CAF:
631                 return ".caf";
632         case AIFF:
633                 return ".aif";
634         case iXML:
635                 return ".ixml";
636         case RF64:
637                 return ".rf64";
638         }
639
640         fatal << string_compose (_("programming error: unknown native header format: %1"), hf);
641         /*NOTREACHED*/
642         return ".wav";
643 }
644
645 bool
646 matching_unsuffixed_filename_exists_in (const string& dir, const string& path)
647 {
648         string bws = basename_nosuffix (path);
649         struct dirent* dentry;
650         struct stat statbuf;
651         DIR* dead;
652         bool ret = false;
653
654         if ((dead = ::opendir (dir.c_str())) == 0) {
655                 error << string_compose (_("cannot open directory %1 (%2)"), dir, strerror (errno)) << endl;
656                 return false;
657         }
658
659         while ((dentry = ::readdir (dead)) != 0) {
660
661                 /* avoid '.' and '..' */
662
663                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
664                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
665                         continue;
666                 }
667
668                 string fullpath = Glib::build_filename (dir, dentry->d_name);
669
670                 if (::stat (fullpath.c_str(), &statbuf)) {
671                         continue;
672                 }
673
674                 if (!S_ISREG (statbuf.st_mode)) {
675                         continue;
676                 }
677
678                 string bws2 = basename_nosuffix (dentry->d_name);
679
680                 if (bws2 == bws) {
681                         ret = true;
682                         break;
683                 }
684         }
685
686         ::closedir (dead);
687         return ret;
688 }
689
690 uint32_t
691 how_many_dsp_threads ()
692 {
693         /* CALLER MUST HOLD PROCESS LOCK */
694
695         int num_cpu = hardware_concurrency();
696         int pu = Config->get_processor_usage ();
697         uint32_t num_threads = max (num_cpu - 1, 2); // default to number of cpus minus one, or 2, whichever is larger
698
699         if (pu < 0) {
700                 /* pu is negative: use "pu" less cores for DSP than appear to be available
701                  */
702
703                 if (-pu < num_cpu) {
704                         num_threads = num_cpu + pu;
705                 }
706
707         } else if (pu == 0) {
708
709                 /* use all available CPUs
710                  */
711
712                 num_threads = num_cpu;
713
714         } else {
715                 /* use "pu" cores, if available
716                  */
717
718                 num_threads = min (num_cpu, pu);
719         }
720
721         return num_threads;
722 }
723
724 double gain_to_slider_position_with_max (double g, double max_gain)
725 {
726         return gain_to_slider_position (g * 2.0/max_gain);
727 }
728
729 double slider_position_to_gain_with_max (double g, double max_gain)
730 {
731         return slider_position_to_gain (g * max_gain/2.0);
732 }
733
734 extern "C" {
735         void c_stacktrace() { stacktrace (cerr); }
736 }