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