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