reset DiskReader "no disk output" flag in a couple of exceptional cases
[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 <climits>
29 #include <cstdlib>
30 #include <cmath>
31 #include <cctype>
32 #include <cstring>
33 #include <cerrno>
34 #include <iostream>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <fcntl.h>
38 #ifndef COMPILER_MSVC
39 #include <dirent.h>
40 #endif
41 #include <errno.h>
42 #include <regex.h>
43
44 #include "pbd/gstdio_compat.h"
45
46 #include <glibmm/miscutils.h>
47 #include <glibmm/fileutils.h>
48
49 #include "pbd/cpus.h"
50 #include "pbd/control_math.h"
51 #include "pbd/error.h"
52 #include "pbd/stacktrace.h"
53 #include "pbd/xml++.h"
54 #include "pbd/basename.h"
55 #include "pbd/scoped_file_descriptor.h"
56 #include "pbd/strsplit.h"
57 #include "pbd/replace_all.h"
58
59 #include "ardour/utils.h"
60 #include "ardour/rc_configuration.h"
61
62 #include "pbd/i18n.h"
63
64 using namespace ARDOUR;
65 using namespace std;
66 using namespace PBD;
67
68 static string
69 replace_chars (const string& str, const string& illegal_chars)
70 {
71         string::size_type pos;
72         Glib::ustring legal;
73
74         /* this is the one place in Ardour where we need to iterate across
75          * potential multibyte characters, and thus we need Glib::ustring
76          */
77
78         legal = str;
79         pos = 0;
80
81         while ((pos = legal.find_first_of (illegal_chars, pos)) != string::npos) {
82                 legal.replace (pos, 1, "_");
83                 pos += 1;
84         }
85
86         return string (legal);
87 }
88 /** take an arbitrary string as an argument, and return a version of it
89  * suitable for use as a path (directory/folder name). This is the Ardour 3.X
90  * and later version of this code. It defines a very small number of characters
91  * that are not allowed in a path on the build target filesystem (basically,
92  * POSIX or Windows) and replaces any instances of them with an underscore.
93  *
94  * NOTE: this is intended only to legalize for the filesystem that Ardour
95  * is running on. Export should use legalize_for_universal_path() since
96  * the goal there is to be legal across filesystems.
97  */
98 string
99 ARDOUR::legalize_for_path (const string& str)
100 {
101         return replace_chars (str, "/\\");
102 }
103
104 /** take an arbitrary string as an argument, and return a version of it
105  * suitable for use as a path (directory/folder name). This is the Ardour 3.X
106  * and later version of this code. It defines a small number
107  * of characters that are not allowed in a path on any of our target
108  * filesystems, and replaces any instances of them with an underscore.
109  *
110  * NOTE: this is intended to create paths that should be legal on
111  * ANY filesystem.
112  */
113 string
114 ARDOUR::legalize_for_universal_path (const string& str)
115 {
116         return replace_chars (str, "<>:\"/\\|?*");
117 }
118
119 /** Legalize for a URI path component.  This is like
120  * legalize_for_universal_path, but stricter, disallowing spaces and hash.
121  * This avoids %20 escapes in URIs, but probably needs work to be more strictly
122  * correct.
123  */
124 string
125 ARDOUR::legalize_for_uri (const string& str)
126 {
127         return replace_chars (str, "<>:\"/\\|?* #");
128 }
129
130 /** take an arbitrary string as an argument, and return a version of it
131  * suitable for use as a path (directory/folder name). This is the Ardour 2.X
132  * version of this code, which used an approach that came to be seen as
133  * problematic: defining the characters that were allowed and replacing all
134  * others with underscores. See legalize_for_path() for the 3.X and later
135  * version.
136  */
137
138 string
139 ARDOUR::legalize_for_path_2X (const string& str)
140 {
141         string::size_type pos;
142         string legal_chars = "abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+=: ";
143         Glib::ustring legal;
144
145         /* this is the one place in Ardour where we need to iterate across
146          * potential multibyte characters, and thus we need Glib::ustring
147          */
148
149         legal = str;
150         pos = 0;
151
152         while ((pos = legal.find_first_not_of (legal_chars, pos)) != string::npos) {
153                 legal.replace (pos, 1, "_");
154                 pos += 1;
155         }
156
157         return string (legal);
158 }
159
160 string
161 ARDOUR::bump_name_once (const std::string& name, char delimiter)
162 {
163         string::size_type delim;
164         string newname;
165
166         if ((delim = name.find_last_of (delimiter)) == string::npos) {
167                 newname  = name;
168                 newname += delimiter;
169                 newname += "1";
170         } else {
171                 int isnumber = 1;
172                 const char *last_element = name.c_str() + delim + 1;
173                 for (size_t i = 0; i < strlen(last_element); i++) {
174                         if (!isdigit(last_element[i])) {
175                                 isnumber = 0;
176                                 break;
177                         }
178                 }
179
180                 errno = 0;
181                 int32_t version = strtol (name.c_str()+delim+1, (char **)NULL, 10);
182
183                 if (isnumber == 0 || errno != 0) {
184                         // last_element is not a number, or is too large
185                         newname  = name;
186                         newname  += delimiter;
187                         newname += "1";
188                 } else {
189                         char buf[32];
190
191                         snprintf (buf, sizeof(buf), "%d", version+1);
192
193                         newname  = name.substr (0, delim+1);
194                         newname += buf;
195                 }
196         }
197
198         return newname;
199
200 }
201
202 string
203 ARDOUR::bump_name_number (const std::string& name)
204 {
205         size_t pos = name.length();
206         size_t num = 0;
207         bool have_number = false;
208         while (pos > 0 && isdigit(name.at(--pos))) {
209                 have_number = true;
210                 num = pos;
211         }
212
213         string newname;
214         if (have_number) {
215                 int32_t seq = strtol (name.c_str() + num, (char **)NULL, 10);
216                 char buf[32];
217                 snprintf (buf, sizeof(buf), "%d", seq + 1);
218                 newname = name.substr (0, num);
219                 newname += buf;
220         } else {
221                 newname = name;
222                 newname += "1";
223         }
224
225         return newname;
226 }
227
228 XMLNode *
229 ARDOUR::find_named_node (const XMLNode& node, string name)
230 {
231         XMLNodeList nlist;
232         XMLNodeConstIterator niter;
233         XMLNode* child;
234
235         nlist = node.children();
236
237         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
238
239                 child = *niter;
240
241                 if (child->name() == name) {
242                         return child;
243                 }
244         }
245
246         return 0;
247 }
248
249 int
250 ARDOUR::cmp_nocase (const string& s, const string& s2)
251 {
252         string::const_iterator p = s.begin();
253         string::const_iterator p2 = s2.begin();
254
255         while (p != s.end() && p2 != s2.end()) {
256                 if (toupper(*p) != toupper(*p2)) {
257                         return (toupper(*p) < toupper(*p2)) ? -1 : 1;
258                 }
259                 ++p;
260                 ++p2;
261         }
262
263         return (s2.size() == s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
264 }
265
266 int
267 ARDOUR::cmp_nocase_utf8 (const string& s1, const string& s2)
268 {
269         const char *cstr1 = s1.c_str();
270         const char *cstr2 = s2.c_str();
271         gchar *cstr1folded = NULL;
272         gchar *cstr2folded = NULL;
273         int retval;
274
275         if (!g_utf8_validate (cstr1, -1, NULL) ||
276                 !g_utf8_validate (cstr2, -1, NULL)) {
277                 // fall back to comparing ASCII
278                 return g_ascii_strcasecmp (cstr1, cstr2);
279         }
280
281         cstr1folded = g_utf8_casefold (cstr1, -1);
282         cstr2folded = g_utf8_casefold (cstr2, -1);
283
284         if (cstr1folded && cstr2folded) {
285                 retval = strcmp (cstr1folded, cstr2folded);
286         } else {
287                 // this shouldn't happen, make the best of it
288                 retval = g_ascii_strcasecmp (cstr1, cstr2);
289         }
290
291         if (cstr1folded) {
292                 g_free (cstr1folded);
293         }
294
295         if (cstr2folded) {
296                 g_free (cstr2folded);
297         }
298
299         return retval;
300 }
301
302 string
303 ARDOUR::region_name_from_path (string path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
304 {
305         path = PBD::basename_nosuffix (path);
306
307         if (strip_channels) {
308
309                 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
310
311                 string::size_type len = path.length();
312
313                 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
314                     (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
315
316                         path = path.substr (0, path.length() - 2);
317                 }
318         }
319
320         if (add_channel_suffix) {
321
322                 path += '%';
323
324                 if (total > 2) {
325                         path += (char) ('a' + this_one);
326                 } else {
327                         path += (char) (this_one == 0 ? 'L' : 'R');
328                 }
329         }
330
331         return path;
332 }
333
334 bool
335 ARDOUR::path_is_paired (string path, string& pair_base)
336 {
337         string::size_type pos;
338
339         /* remove any leading path */
340
341         if ((pos = path.find_last_of (G_DIR_SEPARATOR)) != string::npos) {
342                 path = path.substr(pos+1);
343         }
344
345         /* remove filename suffixes etc. */
346
347         if ((pos = path.find_last_of ('.')) != string::npos) {
348                 path = path.substr (0, pos);
349         }
350
351         string::size_type len = path.length();
352
353         /* look for possible channel identifier: "?R", "%R", ".L" etc. */
354
355         if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
356             (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
357
358                 pair_base = path.substr (0, len-2);
359                 return true;
360
361         }
362
363         return false;
364 }
365
366 #if __APPLE__
367 string
368 ARDOUR::CFStringRefToStdString(CFStringRef stringRef)
369 {
370         CFIndex size =
371                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
372                 kCFStringEncodingUTF8);
373             char *buf = new char[size];
374
375         std::string result;
376
377         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
378             result = buf;
379         }
380         delete [] buf;
381         return result;
382 }
383 #endif // __APPLE__
384
385 void
386 ARDOUR::compute_equal_power_fades (framecnt_t nframes, float* in, float* out)
387 {
388         double step;
389
390         step = 1.0/(nframes-1);
391
392         in[0] = 0.0f;
393
394         for (framecnt_t i = 1; i < nframes - 1; ++i) {
395                 in[i] = in[i-1] + step;
396         }
397
398         in[nframes-1] = 1.0;
399
400         const float pan_law_attenuation = -3.0f;
401         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
402
403         for (framecnt_t n = 0; n < nframes; ++n) {
404                 float inVal = in[n];
405                 float outVal = 1 - inVal;
406                 out[n] = outVal * (scale * outVal + 1.0f - scale);
407                 in[n] = inVal * (scale * inVal + 1.0f - scale);
408         }
409 }
410
411 EditMode
412 ARDOUR::string_to_edit_mode (string str)
413 {
414         if (str == _("Splice")) {
415                 return Splice;
416         } else if (str == _("Slide")) {
417                 return Slide;
418         } else if (str == _("Ripple")) {
419                 return Ripple;
420         } else if (str == _("Lock")) {
421                 return Lock;
422         }
423         fatal << string_compose (_("programming error: unknown edit mode string \"%1\""), str) << endmsg;
424         abort(); /*NOTREACHED*/
425         return Slide;
426 }
427
428 const char*
429 ARDOUR::edit_mode_to_string (EditMode mode)
430 {
431         switch (mode) {
432         case Slide:
433                 return _("Slide");
434
435         case Lock:
436                 return _("Lock");
437
438         case Ripple:
439                 return _("Ripple");
440
441         default:
442         case Splice:
443                 return _("Splice");
444         }
445 }
446
447 SyncSource
448 ARDOUR::string_to_sync_source (string str)
449 {
450         if (str == _("MIDI Timecode") || str == _("MTC")) {
451                 return MTC;
452         }
453
454         if (str == _("MIDI Clock")) {
455                 return MIDIClock;
456         }
457
458         if (str == _("JACK")) {
459                 return Engine;
460         }
461
462         if (str == _("LTC")) {
463                 return LTC;
464         }
465
466         fatal << string_compose (_("programming error: unknown sync source string \"%1\""), str) << endmsg;
467         abort(); /*NOTREACHED*/
468         return Engine;
469 }
470
471 /** @param sh Return a short version of the string */
472 const char*
473 ARDOUR::sync_source_to_string (SyncSource src, bool sh)
474 {
475         switch (src) {
476         case Engine:
477                 /* no other backends offer sync for now ... deal with this if we
478                  * ever have to.
479                  */
480                 return S_("SyncSource|JACK");
481
482         case MTC:
483                 if (sh) {
484                         return S_("SyncSource|MTC");
485                 } else {
486                         return _("MIDI Timecode");
487                 }
488
489         case MIDIClock:
490                 if (sh) {
491                         return S_("SyncSource|M-Clk");
492                 } else {
493                         return _("MIDI Clock");
494                 }
495
496         case LTC:
497                 return S_("SyncSource|LTC");
498         }
499         /* GRRRR .... stupid, stupid gcc - you can't get here from there, all enum values are handled */
500         return S_("SyncSource|JACK");
501 }
502
503 float
504 ARDOUR::meter_falloff_to_float (MeterFalloff falloff)
505 {
506         switch (falloff) {
507         case MeterFalloffOff:
508                 return METER_FALLOFF_OFF;
509         case MeterFalloffSlowest:
510                 return METER_FALLOFF_SLOWEST;
511         case MeterFalloffSlow:
512                 return METER_FALLOFF_SLOW;
513         case MeterFalloffSlowish:
514                 return METER_FALLOFF_SLOWISH;
515         case MeterFalloffMedium:
516                 return METER_FALLOFF_MEDIUM;
517         case MeterFalloffModerate:
518                 return METER_FALLOFF_MODERATE;
519         case MeterFalloffFast:
520         case MeterFalloffFaster:  // backwards compat enum MeterFalloff
521         case MeterFalloffFastest:
522         default:
523                 return METER_FALLOFF_FAST;
524         }
525 }
526
527 MeterFalloff
528 ARDOUR::meter_falloff_from_float (float val)
529 {
530         if (val == METER_FALLOFF_OFF) {
531                 return MeterFalloffOff;
532         }
533         else if (val <= METER_FALLOFF_SLOWEST) {
534                 return MeterFalloffSlowest;
535         }
536         else if (val <= METER_FALLOFF_SLOW) {
537                 return MeterFalloffSlow;
538         }
539         else if (val <= METER_FALLOFF_SLOWISH) {
540                 return MeterFalloffSlowish;
541         }
542         else if (val <= METER_FALLOFF_MODERATE) {
543                 return MeterFalloffModerate;
544         }
545         else if (val <= METER_FALLOFF_MEDIUM) {
546                 return MeterFalloffMedium;
547         }
548         else {
549                 return MeterFalloffFast;
550         }
551 }
552
553 AutoState
554 ARDOUR::string_to_auto_state (std::string str)
555 {
556         if (str == X_("Off")) {
557                 return Off;
558         } else if (str == X_("Play")) {
559                 return Play;
560         } else if (str == X_("Write")) {
561                 return Write;
562         } else if (str == X_("Touch")) {
563                 return Touch;
564         } else if (str == X_("Latch")) {
565                 return Latch;
566         }
567
568         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
569         abort(); /*NOTREACHED*/
570         return Touch;
571 }
572
573 string
574 ARDOUR::auto_state_to_string (AutoState as)
575 {
576         /* to be used only for XML serialization, no i18n done */
577
578         switch (as) {
579         case Off:
580                 return X_("Off");
581                 break;
582         case Play:
583                 return X_("Play");
584                 break;
585         case Write:
586                 return X_("Write");
587                 break;
588         case Touch:
589                 return X_("Touch");
590                 break;
591         case Latch:
592                 return X_("Latch");
593                 break;
594         }
595
596         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
597         abort(); /*NOTREACHED*/
598         return "";
599 }
600
601 std::string
602 bool_as_string (bool yn)
603 {
604         return (yn ? "yes" : "no");
605 }
606
607 const char*
608 ARDOUR::native_header_format_extension (HeaderFormat hf, const DataType& type)
609 {
610         if (type == DataType::MIDI) {
611                 return ".mid";
612         }
613
614         switch (hf) {
615         case BWF:
616                 return ".wav";
617         case WAVE:
618                 return ".wav";
619         case WAVE64:
620                 return ".w64";
621         case CAF:
622                 return ".caf";
623         case AIFF:
624                 return ".aif";
625         case iXML:
626                 return ".ixml";
627         case RF64:
628         case RF64_WAV:
629         case MBWF:
630                 return ".rf64";
631         }
632
633         fatal << string_compose (_("programming error: unknown native header format: %1"), hf);
634         abort(); /*NOTREACHED*/
635         return ".wav";
636 }
637
638 bool
639 ARDOUR::matching_unsuffixed_filename_exists_in (const string& dir, const string& path)
640 {
641         string bws = basename_nosuffix (path);
642         struct dirent* dentry;
643         GStatBuf statbuf;
644         DIR* dead;
645         bool ret = false;
646
647         if ((dead = ::opendir (dir.c_str())) == 0) {
648                 error << string_compose (_("cannot open directory %1 (%2)"), dir, strerror (errno)) << endl;
649                 return false;
650         }
651
652         while ((dentry = ::readdir (dead)) != 0) {
653
654                 /* avoid '.' and '..' */
655
656                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
657                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
658                         continue;
659                 }
660
661                 string fullpath = Glib::build_filename (dir, dentry->d_name);
662
663                 if (g_stat (fullpath.c_str(), &statbuf)) {
664                         continue;
665                 }
666
667                 if (!S_ISREG (statbuf.st_mode)) {
668                         continue;
669                 }
670
671                 string bws2 = basename_nosuffix (dentry->d_name);
672
673                 if (bws2 == bws) {
674                         ret = true;
675                         break;
676                 }
677         }
678
679         ::closedir (dead);
680         return ret;
681 }
682
683 uint32_t
684 ARDOUR::how_many_dsp_threads ()
685 {
686         /* CALLER MUST HOLD PROCESS LOCK */
687
688         int num_cpu = hardware_concurrency();
689         int pu = Config->get_processor_usage ();
690         uint32_t num_threads = max (num_cpu - 1, 2); // default to number of cpus minus one, or 2, whichever is larger
691
692         if (pu < 0) {
693                 /* pu is negative: use "pu" less cores for DSP than appear to be available
694                  */
695
696                 if (-pu < num_cpu) {
697                         num_threads = num_cpu + pu;
698                 }
699
700         } else if (pu == 0) {
701
702                 /* use all available CPUs
703                  */
704
705                 num_threads = num_cpu;
706
707         } else {
708                 /* use "pu" cores, if available
709                  */
710
711                 num_threads = min (num_cpu, pu);
712         }
713
714         return num_threads;
715 }
716
717 double
718 ARDOUR::gain_to_slider_position_with_max (double g, double max_gain)
719 {
720         return gain_to_position (g * 2.0 / max_gain);
721 }
722
723 double
724 ARDOUR::slider_position_to_gain_with_max (double g, double max_gain)
725 {
726         return position_to_gain (g) * max_gain / 2.0;
727 }
728
729 #include "sha1.c"
730
731 std::string
732 ARDOUR::compute_sha1_of_file (std::string path)
733 {
734         PBD::ScopedFileDescriptor fd (g_open (path.c_str(), O_RDONLY, 0444));
735         if (fd < 0) {
736                 return std::string ();
737         }
738         char buf[4096];
739         ssize_t n_read;
740         char hash[41];
741         Sha1Digest s;
742         sha1_init (&s);
743
744         while ((n_read = ::read(fd, buf, sizeof(buf))) > 0) {
745                 sha1_write (&s, (const uint8_t*) buf, n_read);
746         }
747
748         sha1_result_hash (&s, hash);
749         return std::string (hash);
750 }
751
752 extern "C" {
753         void c_stacktrace() { stacktrace (cerr); }
754 }
755