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