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