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