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