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