Remove unnecessary 0 checks before delete; see http://www.parashift.com/c++-faq-lite...
[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 #define __STDC_FORMAT_MACROS 1
21 #include <stdint.h>
22
23 #include <cstdio> /* for sprintf */
24 #include <cstring>
25 #include <cmath>
26 #include <cctype>
27 #include <cstring>
28 #include <cerrno>
29 #include <iostream>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #ifdef HAVE_WORDEXP
37 #include <wordexp.h>
38 #endif
39
40 #include <pbd/error.h>
41 #include <pbd/stacktrace.h>
42 #include <pbd/xml++.h>
43 #include <pbd/basename.h>
44 #include <ardour/utils.h>
45
46 #include "i18n.h"
47
48 using namespace ARDOUR;
49 using namespace std;
50 using namespace PBD;
51 using Glib::ustring;
52
53 ustring
54 legalize_for_path (ustring str)
55 {
56         ustring::size_type pos;
57         ustring legal_chars = "abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+=: ";
58         ustring legal;
59
60         legal = str;
61         pos = 0;
62
63         while ((pos = legal.find_first_not_of (legal_chars, pos)) != string::npos) {
64                 legal.replace (pos, 1, "_");
65                 pos += 1;
66         }
67
68         return legal;
69 }
70
71 string bump_name_once(std::string name)
72 {
73         string::size_type period;
74         string newname;
75
76         if ((period = name.find_last_of ('.')) == string::npos) {
77                 newname  = name;
78                 newname += ".1";
79         } else {
80                 int isnumber = 1;
81                 const char *last_element = name.c_str() + period + 1;
82                 for (size_t i = 0; i < strlen(last_element); i++) {
83                         if (!isdigit(last_element[i])) {
84                                 isnumber = 0;
85                                 break;
86                         }
87                 }
88
89                 errno = 0;
90                 long int version = strtol (name.c_str()+period+1, (char **)NULL, 10);
91
92                 if (isnumber == 0 || errno != 0) {
93                         // last_element is not a number, or is too large
94                         newname  = name;
95                         newname += ".1";
96                 } else {
97                         char buf[32];
98
99                         snprintf (buf, sizeof(buf), "%ld", version+1);
100
101                         newname  = name.substr (0, period+1);
102                         newname += buf;
103                 }
104         }
105
106         return newname;
107
108 }
109
110 ostream&
111 operator<< (ostream& o, const BBT_Time& bbt)
112 {
113         o << bbt.bars << '|' << bbt.beats << '|' << bbt.ticks;
114         return o;
115 }
116
117 XMLNode *
118 find_named_node (const XMLNode& node, string name)
119 {
120         XMLNodeList nlist;
121         XMLNodeConstIterator niter;
122         XMLNode* child;
123
124         nlist = node.children();
125
126         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
127
128                 child = *niter;
129
130                 if (child->name() == name) {
131                         return child;
132                 }
133         }
134
135         return 0;
136 }
137
138 int
139 cmp_nocase (const string& s, const string& s2)
140 {
141         string::const_iterator p = s.begin();
142         string::const_iterator p2 = s2.begin();
143
144         while (p != s.end() && p2 != s2.end()) {
145                 if (toupper(*p) != toupper(*p2)) {
146                         return (toupper(*p) < toupper(*p2)) ? -1 : 1;
147                 }
148                 ++p;
149                 ++p2;
150         }
151
152         return (s2.size() == s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
153 }
154
155 int
156 touch_file (ustring path)
157 {
158         int fd = open (path.c_str(), O_RDWR|O_CREAT, 0660);
159         if (fd >= 0) {
160                 close (fd);
161                 return 0;
162         }
163         return 1;
164 }
165
166 ustring
167 region_name_from_path (ustring path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
168 {
169         path = PBD::basename_nosuffix (path);
170
171         if (strip_channels) {
172
173                 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
174
175                 ustring::size_type len = path.length();
176
177                 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
178                     (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
179
180                         path = path.substr (0, path.length() - 2);
181                 }
182         }
183
184         if (add_channel_suffix) {
185
186                 path += '%';
187
188                 if (total > 2) {
189                         path += (char) ('a' + this_one);
190                 } else {
191                         path += (char) (this_one == 0 ? 'L' : 'R');
192                 }
193         }
194
195         return path;
196 }
197
198 bool
199 path_is_paired (ustring path, ustring& pair_base)
200 {
201         ustring::size_type pos;
202
203         /* remove any leading path */
204
205         if ((pos = path.find_last_of ('/')) != string::npos) {
206                 path = path.substr(pos+1);
207         }
208
209         /* remove filename suffixes etc. */
210
211         if ((pos = path.find_last_of ('.')) != string::npos) {
212                 path = path.substr (0, pos);
213         }
214
215         ustring::size_type len = path.length();
216
217         /* look for possible channel identifier: "?R", "%R", ".L" etc. */
218
219         if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
220             (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
221
222                 pair_base = path.substr (0, len-2);
223                 return true;
224
225         }
226
227         return false;
228 }
229
230 ustring
231 path_expand (ustring path)
232 {
233 #ifdef HAVE_WORDEXP
234         /* Handle tilde and environment variable expansion in session path */
235         string ret = path;
236
237         wordexp_t expansion;
238         switch (wordexp (path.c_str(), &expansion, WRDE_NOCMD|WRDE_UNDEF)) {
239         case 0:
240                 break;
241         default:
242                 error << string_compose (_("illegal or badly-formed string used for path (%1)"), path) << endmsg;
243                 goto out;
244         }
245
246         if (expansion.we_wordc > 1) {
247                 error << string_compose (_("path (%1) is ambiguous"), path) << endmsg;
248                 goto out;
249         }
250
251         ret = expansion.we_wordv[0];
252   out:
253         wordfree (&expansion);
254         return ret;
255
256 #else
257         return path;
258 #endif
259 }
260
261 #if defined(HAVE_COREAUDIO) || defined(HAVE_AUDIOUNITS)
262 string
263 CFStringRefToStdString(CFStringRef stringRef)
264 {
265         CFIndex size =
266                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
267                 kCFStringEncodingUTF8);
268             char *buf = new char[size];
269
270         std::string result;
271
272         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
273             result = buf;
274         }
275         delete [] buf;
276         return result;
277 }
278 #endif // HAVE_COREAUDIO
279
280 void
281 compute_equal_power_fades (nframes_t nframes, float* in, float* out)
282 {
283         double step;
284
285         step = 1.0/(nframes-1);
286
287         in[0] = 0.0f;
288
289         for (nframes_t i = 1; i < nframes - 1; ++i) {
290                 in[i] = in[i-1] + step;
291         }
292
293         in[nframes-1] = 1.0;
294
295         const float pan_law_attenuation = -3.0f;
296         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
297
298         for (nframes_t n = 0; n < nframes; ++n) {
299                 float inVal = in[n];
300                 float outVal = 1 - inVal;
301                 out[n] = outVal * (scale * outVal + 1.0f - scale);
302                 in[n] = inVal * (scale * inVal + 1.0f - scale);
303         }
304 }
305
306 EditMode
307 string_to_edit_mode (string str)
308 {
309         if (str == _("Splice Edit")) {
310                 return Splice;
311         } else if (str == _("Slide Edit")) {
312                 return Slide;
313         } else if (str == _("Lock Edit")) {
314                 return Lock;
315         }
316         fatal << string_compose (_("programming error: unknown edit mode string \"%1\""), str) << endmsg;
317         /*NOTREACHED*/
318         return Slide;
319 }
320
321 const char*
322 edit_mode_to_string (EditMode mode)
323 {
324         switch (mode) {
325         case Slide:
326                 return _("Slide Edit");
327
328         case Lock:
329                 return _("Lock Edit");
330
331         default:
332         case Splice:
333                 return _("Splice Edit");
334         }
335 }
336
337 SlaveSource
338 string_to_slave_source (string str)
339 {
340         if (str == _("Internal")) {
341                 return None;
342         }
343
344         if (str == _("MTC")) {
345                 return MTC;
346         }
347
348         if (str == _("MIDI Clock")) {
349                 return MIDIClock;
350         }
351
352         if (str == _("JACK")) {
353                 return JACK;
354         }
355
356         fatal << string_compose (_("programming error: unknown slave source string \"%1\""), str) << endmsg;
357         /*NOTREACHED*/
358         return None;
359 }
360
361 const char*
362 slave_source_to_string (SlaveSource src)
363 {
364         switch (src) {
365         case JACK:
366                 return _("JACK");
367
368         case MTC:
369                 return _("MTC");
370
371         case MIDIClock:
372                 return _("MIDI Clock");
373
374         default:
375         case None:
376                 return _("Internal");
377
378         }
379 }
380
381 /* I don't really like hard-coding these falloff rates here
382  * Probably should use a map of some kind that could be configured
383  * These rates are db/sec.
384 */
385
386 #define METER_FALLOFF_OFF     0.0f
387 #define METER_FALLOFF_SLOWEST 6.6f // BBC standard
388 #define METER_FALLOFF_SLOW    8.6f // BBC standard
389 #define METER_FALLOFF_MEDIUM  20.0f
390 #define METER_FALLOFF_FAST    32.0f
391 #define METER_FALLOFF_FASTER  46.0f
392 #define METER_FALLOFF_FASTEST 70.0f
393
394 float
395 meter_falloff_to_float (MeterFalloff falloff)
396 {
397         switch (falloff) {
398         case MeterFalloffOff:
399                 return METER_FALLOFF_OFF;
400         case MeterFalloffSlowest:
401                 return METER_FALLOFF_SLOWEST;
402         case MeterFalloffSlow:
403                 return METER_FALLOFF_SLOW;
404         case MeterFalloffMedium:
405                 return METER_FALLOFF_MEDIUM;
406         case MeterFalloffFast:
407                 return METER_FALLOFF_FAST;
408         case MeterFalloffFaster:
409                 return METER_FALLOFF_FASTER;
410         case MeterFalloffFastest:
411                 return METER_FALLOFF_FASTEST;
412         default:
413                 return METER_FALLOFF_FAST;
414         }
415 }
416
417 MeterFalloff
418 meter_falloff_from_float (float val)
419 {
420         if (val == METER_FALLOFF_OFF) {
421                 return MeterFalloffOff;
422         }
423         else if (val <= METER_FALLOFF_SLOWEST) {
424                 return MeterFalloffSlowest;
425         }
426         else if (val <= METER_FALLOFF_SLOW) {
427                 return MeterFalloffSlow;
428         }
429         else if (val <= METER_FALLOFF_MEDIUM) {
430                 return MeterFalloffMedium;
431         }
432         else if (val <= METER_FALLOFF_FAST) {
433                 return MeterFalloffFast;
434         }
435         else if (val <= METER_FALLOFF_FASTER) {
436                 return MeterFalloffFaster;
437         }
438         else {
439                 return MeterFalloffFastest;
440         }
441 }
442
443 float
444 meter_hold_to_float (MeterHold hold)
445 {
446         switch (hold) {
447         case MeterHoldOff:
448                 return 0.0f;
449         case MeterHoldShort:
450                 return 40.0f;
451         case MeterHoldMedium:
452                 return 100.0f;
453         case MeterHoldLong:
454         default:
455                 return 200.0f;
456         }
457 }
458
459 AutoState
460 ARDOUR::string_to_auto_state (std::string str)
461 {
462         if (str == X_("Off")) {
463                 return Off;
464         } else if (str == X_("Play")) {
465                 return Play;
466         } else if (str == X_("Write")) {
467                 return Write;
468         } else if (str == X_("Touch")) {
469                 return Touch;
470         }
471
472         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
473         /*NOTREACHED*/
474         return Touch;
475 }
476
477 string
478 ARDOUR::auto_state_to_string (AutoState as)
479 {
480         /* to be used only for XML serialization, no i18n done */
481
482         switch (as) {
483         case Off:
484                 return X_("Off");
485                 break;
486         case Play:
487                 return X_("Play");
488                 break;
489         case Write:
490                 return X_("Write");
491                 break;
492         case Touch:
493                 return X_("Touch");
494         }
495
496         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
497         /*NOTREACHED*/
498         return "";
499 }
500
501 AutoStyle
502 ARDOUR::string_to_auto_style (std::string str)
503 {
504         if (str == X_("Absolute")) {
505                 return Absolute;
506         } else if (str == X_("Trim")) {
507                 return Trim;
508         }
509
510         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle string: ", str) << endmsg;
511         /*NOTREACHED*/
512         return Trim;
513 }
514
515 string
516 ARDOUR::auto_style_to_string (AutoStyle as)
517 {
518         /* to be used only for XML serialization, no i18n done */
519
520         switch (as) {
521         case Absolute:
522                 return X_("Absolute");
523                 break;
524         case Trim:
525                 return X_("Trim");
526                 break;
527         }
528
529         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle type: ", as) << endmsg;
530         /*NOTREACHED*/
531         return "";
532 }
533
534 extern "C" {
535         void c_stacktrace() { stacktrace (cerr); }
536 }