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