1 /*
2  * Copyright (C) 2016-2017 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2016-2018 Robin Gareus <robin@gareus.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #include <cstring>
20 #include <vamp-hostsdk/PluginLoader.h>
21 
22 #include "pbd/basename.h"
23 #include "pbd/compose.h"
24 #include "pbd/error.h"
25 #include "pbd/failed_constructor.h"
26 
27 #include "ardour/analyser.h"
28 #include "ardour/audioengine.h"
29 #include "ardour/audiofilesource.h"
30 #include "ardour/audiosource.h"
31 #include "ardour/internal_send.h"
32 #include "ardour/lua_api.h"
33 #include "ardour/luaproc.h"
34 #include "ardour/luascripting.h"
35 #include "ardour/plugin.h"
36 #include "ardour/plugin_insert.h"
37 #include "ardour/plugin_manager.h"
38 #include "ardour/readable.h"
39 #include "ardour/region_factory.h"
40 #include "ardour/source_factory.h"
41 
42 #include "LuaBridge/LuaBridge.h"
43 
44 #include "pbd/i18n.h"
45 
46 using namespace ARDOUR;
47 using namespace PBD;
48 using namespace std;
49 
50 int
datatype_ctor_null(lua_State * L)51 ARDOUR::LuaAPI::datatype_ctor_null (lua_State *L)
52 {
53 	DataType dt (DataType::NIL);
54 	luabridge::Stack <DataType>::push (L, dt);
55 	return 1;
56 }
57 
58 int
datatype_ctor_audio(lua_State * L)59 ARDOUR::LuaAPI::datatype_ctor_audio (lua_State *L)
60 {
61 	DataType dt (DataType::AUDIO);
62 	// NB luabridge will copy construct the object and manage lifetime.
63 	luabridge::Stack <DataType>::push (L, dt);
64 	return 1;
65 }
66 
67 int
datatype_ctor_midi(lua_State * L)68 ARDOUR::LuaAPI::datatype_ctor_midi (lua_State *L)
69 {
70 	DataType dt (DataType::MIDI);
71 	luabridge::Stack <DataType>::push (L, dt);
72 	return 1;
73 }
74 
75 boost::shared_ptr<Processor>
nil_processor()76 ARDOUR::LuaAPI::nil_processor ()
77 {
78 	return boost::shared_ptr<Processor> ();
79 }
80 
81 boost::shared_ptr<Processor>
new_luaproc(Session * s,const string & name)82 ARDOUR::LuaAPI::new_luaproc (Session *s, const string& name)
83 {
84 	if (!s) {
85 		return boost::shared_ptr<Processor> ();
86 	}
87 
88 	LuaScriptInfoPtr spi;
89 	ARDOUR::LuaScriptList & _scripts (LuaScripting::instance ().scripts (LuaScriptInfo::DSP));
90 	for (LuaScriptList::const_iterator i = _scripts.begin (); i != _scripts.end (); ++i) {
91 		if (name == (*i)->name) {
92 			spi = *i;
93 			break;
94 		}
95 	}
96 
97 	if (!spi) {
98 		warning << _("Script with given name was not found\n");
99 		return boost::shared_ptr<Processor> ();
100 	}
101 
102 	PluginPtr p;
103 	try {
104 		LuaPluginInfoPtr lpi (new LuaPluginInfo (spi));
105 		p = (lpi->load (*s));
106 	} catch (...) {
107 		warning << _("Failed to instantiate Lua Processor\n");
108 		return boost::shared_ptr<Processor> ();
109 	}
110 
111 	return boost::shared_ptr<Processor> (new PluginInsert (*s, p));
112 }
113 
114 boost::shared_ptr<Processor>
new_send(Session * s,boost::shared_ptr<Route> r,boost::shared_ptr<Processor> before)115 ARDOUR::LuaAPI::new_send (Session* s, boost::shared_ptr<Route> r, boost::shared_ptr<Processor> before)
116 {
117 	if (!s) {
118 		return boost::shared_ptr<Processor> ();
119 	}
120 
121 	boost::shared_ptr<Send> send (new Send (*s, r->pannable (), r->mute_master ()));
122 
123 	/* make an educated guess at the initial number of outputs for the send */
124 	ChanCount outs = before ? before->input_streams () : r->n_outputs();
125 
126 	try {
127 		Glib::Threads::Mutex::Lock lm (AudioEngine::instance ()->process_lock ());
128 		send->output()->ensure_io (outs, false, r.get());
129 	} catch (AudioEngine::PortRegistrationFailure& err) {
130 		error << string_compose (_("Cannot set up new send: %1"), err.what ()) << endmsg;
131 		return boost::shared_ptr<Processor> ();
132 	}
133 
134 	if (0 == r->add_processor (send, before)) {
135 		return send;
136 	}
137 
138 	return boost::shared_ptr<Processor> ();
139 }
140 
141 std::string
dump_untagged_plugins()142 ARDOUR::LuaAPI::dump_untagged_plugins ()
143 {
144 	PluginManager& manager = PluginManager::instance ();
145 	return manager.dump_untagged_plugins();
146 }
147 
148 PluginInfoList
list_plugins()149 ARDOUR::LuaAPI::list_plugins ()
150 {
151 	PluginManager& manager = PluginManager::instance ();
152 	PluginInfoList all_plugs;
153 	all_plugs.insert (all_plugs.end (), manager.ladspa_plugin_info ().begin (), manager.ladspa_plugin_info ().end ());
154 	all_plugs.insert (all_plugs.end (), manager.lua_plugin_info ().begin (), manager.lua_plugin_info ().end ());
155 #ifdef WINDOWS_VST_SUPPORT
156 	all_plugs.insert (all_plugs.end (), manager.windows_vst_plugin_info ().begin (), manager.windows_vst_plugin_info ().end ());
157 #endif
158 #ifdef MACVST_SUPPORT
159 	all_plugs.insert (all_plugs.end (), manager.mac_vst_plugin_info ().begin (), manager.mac_vst_plugin_info ().end ());
160 #endif
161 #ifdef LXVST_SUPPORT
162 	all_plugs.insert (all_plugs.end (), manager.lxvst_plugin_info ().begin (), manager.lxvst_plugin_info ().end ());
163 #endif
164 #ifdef VST3_SUPPORT
165 	all_plugs.insert (all_plugs.end (), manager.vst3_plugin_info ().begin (), manager.vst3_plugin_info ().end ());
166 #endif
167 #ifdef AUDIOUNIT_SUPPORT
168 	all_plugs.insert (all_plugs.end (), manager.au_plugin_info ().begin (), manager.au_plugin_info ().end ());
169 #endif
170 	all_plugs.insert (all_plugs.end (), manager.lv2_plugin_info ().begin (), manager.lv2_plugin_info ().end ());
171 	all_plugs.insert (all_plugs.end (), manager.lua_plugin_info ().begin (), manager.lua_plugin_info ().end ());
172 
173 	return all_plugs;
174 }
175 
176 PluginInfoPtr
new_plugin_info(const string & name,ARDOUR::PluginType type)177 ARDOUR::LuaAPI::new_plugin_info (const string& name, ARDOUR::PluginType type)
178 {
179 	PluginManager& manager = PluginManager::instance ();
180 	PluginInfoList all_plugs;
181 	all_plugs.insert (all_plugs.end (), manager.ladspa_plugin_info ().begin (), manager.ladspa_plugin_info ().end ());
182 	all_plugs.insert (all_plugs.end (), manager.lua_plugin_info ().begin (), manager.lua_plugin_info ().end ());
183 #ifdef WINDOWS_VST_SUPPORT
184 	all_plugs.insert (all_plugs.end (), manager.windows_vst_plugin_info ().begin (), manager.windows_vst_plugin_info ().end ());
185 #endif
186 #ifdef MACVST_SUPPORT
187 	all_plugs.insert (all_plugs.end (), manager.mac_vst_plugin_info ().begin (), manager.mac_vst_plugin_info ().end ());
188 #endif
189 #ifdef LXVST_SUPPORT
190 	all_plugs.insert (all_plugs.end (), manager.lxvst_plugin_info ().begin (), manager.lxvst_plugin_info ().end ());
191 #endif
192 #ifdef VST3_SUPPORT
193 	all_plugs.insert (all_plugs.end (), manager.vst3_plugin_info ().begin (), manager.vst3_plugin_info ().end ());
194 #endif
195 #ifdef AUDIOUNIT_SUPPORT
196 	all_plugs.insert (all_plugs.end (), manager.au_plugin_info ().begin (), manager.au_plugin_info ().end ());
197 #endif
198 	all_plugs.insert (all_plugs.end (), manager.lv2_plugin_info ().begin (), manager.lv2_plugin_info ().end ());
199 	all_plugs.insert (all_plugs.end (), manager.lua_plugin_info ().begin (), manager.lua_plugin_info ().end ());
200 
201 	for (PluginInfoList::const_iterator i = all_plugs.begin (); i != all_plugs.end (); ++i) {
202 		if (((*i)->name == name || (*i)->unique_id == name) && (*i)->type == type) {
203 			return *i;
204 		}
205 	}
206 	return PluginInfoPtr ();
207 }
208 
209 boost::shared_ptr<Processor>
new_plugin(Session * s,const string & name,ARDOUR::PluginType type,const string & preset)210 ARDOUR::LuaAPI::new_plugin (Session *s, const string& name, ARDOUR::PluginType type, const string& preset)
211 {
212 	if (!s) {
213 		return boost::shared_ptr<Processor> ();
214 	}
215 
216 	PluginInfoPtr pip = new_plugin_info (name, type);
217 
218 	if (!pip) {
219 		return boost::shared_ptr<Processor> ();
220 	}
221 
222 	PluginPtr p = pip->load (*s);
223 	if (!p) {
224 		return boost::shared_ptr<Processor> ();
225 	}
226 
227 	if (!preset.empty ()) {
228 		const Plugin::PresetRecord *pr = p->preset_by_label (preset);
229 		if (pr) {
230 			p->load_preset (*pr);
231 		}
232 	}
233 
234 	return boost::shared_ptr<Processor> (new PluginInsert (*s, p));
235 }
236 
237 bool
set_plugin_insert_param(boost::shared_ptr<PluginInsert> pi,uint32_t which,float val)238 ARDOUR::LuaAPI::set_plugin_insert_param (boost::shared_ptr<PluginInsert> pi, uint32_t which, float val)
239 {
240 	boost::shared_ptr<Plugin> plugin = pi->plugin ();
241 	if (!plugin) { return false; }
242 
243 	bool ok=false;
244 	uint32_t controlid = plugin->nth_parameter (which, ok);
245 	if (!ok) { return false; }
246 	if (!plugin->parameter_is_input (controlid)) { return false; }
247 
248 	ParameterDescriptor pd;
249 	if (plugin->get_parameter_descriptor (controlid, pd) != 0) { return false; }
250 	if (val < pd.lower || val > pd.upper) { return false; }
251 
252 	boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter (PluginAutomation, 0, controlid));
253 	c->set_value (val, PBD::Controllable::NoGroup);
254 	return true;
255 }
256 
257 float
get_plugin_insert_param(boost::shared_ptr<PluginInsert> pi,uint32_t which,bool & ok)258 ARDOUR::LuaAPI::get_plugin_insert_param (boost::shared_ptr<PluginInsert> pi, uint32_t which, bool &ok)
259 {
260 	ok=false;
261 	boost::shared_ptr<Plugin> plugin = pi->plugin ();
262 	if (!plugin) { return 0; }
263 	uint32_t controlid = plugin->nth_parameter (which, ok);
264 	if (!ok) { return 0; }
265 	return plugin->get_parameter ( controlid );
266 }
267 
268 bool
set_processor_param(boost::shared_ptr<Processor> proc,uint32_t which,float val)269 ARDOUR::LuaAPI::set_processor_param (boost::shared_ptr<Processor> proc, uint32_t which, float val)
270 {
271 	boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
272 	if (!pi) { return false; }
273 	return set_plugin_insert_param (pi, which, val);
274 }
275 
276 float
get_processor_param(boost::shared_ptr<Processor> proc,uint32_t which,bool & ok)277 ARDOUR::LuaAPI::get_processor_param (boost::shared_ptr<Processor> proc, uint32_t which, bool &ok)
278 {
279 	ok=false;
280 	boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
281 	if (!pi) { ok = false; return 0;}
282 	return get_plugin_insert_param (pi, which, ok);
283 }
284 
285 bool
reset_processor_to_default(boost::shared_ptr<Processor> proc)286 ARDOUR::LuaAPI::reset_processor_to_default ( boost::shared_ptr<Processor> proc )
287 {
288 	boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
289 	if (pi) {
290 		pi->reset_parameters_to_default();
291 		return true;
292 	}
293 	return false;
294 }
295 
296 int
plugin_automation(lua_State * L)297 ARDOUR::LuaAPI::plugin_automation (lua_State *L)
298 {
299 	typedef boost::shared_ptr<Processor> T;
300 
301 	int top = lua_gettop (L);
302 	if (top < 2) {
303 		return luaL_argerror (L, 1, "invalid number of arguments, :plugin_automation (plugin, parameter_number)");
304 	}
305 	T* const p = luabridge::Userdata::get<T> (L, 1, false);
306 	uint32_t which = luabridge::Stack<uint32_t>::get (L, 2);
307 	if (!p) {
308 		return luaL_error (L, "Invalid pointer to Ardour:Processor");
309 	}
310 	boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*p);
311 	if (!pi) {
312 		return luaL_error (L, "Given Processor is not a Plugin Insert");
313 	}
314 	boost::shared_ptr<Plugin> plugin = pi->plugin ();
315 	if (!plugin) {
316 		return luaL_error (L, "Given Processor is not a Plugin");
317 	}
318 
319 	bool ok=false;
320 	uint32_t controlid = plugin->nth_parameter (which, ok);
321 	if (!ok) {
322 		return luaL_error (L, "Invalid Parameter");
323 	}
324 	if (!plugin->parameter_is_input (controlid)) {
325 		return luaL_error (L, "Given Parameter is not an input");
326 	}
327 
328 	ParameterDescriptor pd;
329 	if (plugin->get_parameter_descriptor (controlid, pd) != 0) {
330 		return luaL_error (L, "Cannot describe parameter");
331 	}
332 
333 	boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter (PluginAutomation, 0, controlid));
334 
335 	luabridge::Stack<boost::shared_ptr<AutomationList> >::push (L, c->alist ());
336 	luabridge::Stack<boost::shared_ptr<Evoral::ControlList> >::push (L, c->list ());
337 	luabridge::Stack<ParameterDescriptor>::push (L, pd);
338 	return 3;
339 }
340 
341 int
desc_scale_points(lua_State * L)342 ARDOUR::LuaAPI::desc_scale_points (lua_State *L)
343 {
344 	typedef ParameterDescriptor T;
345 
346 	int top = lua_gettop (L);
347 	if (top < 1) {
348 		return luaL_argerror (L, 1, "invalid number of arguments, :plugin_scale_points (ParameterDescriptor)");
349 	}
350 
351 	T* const pd = luabridge::Userdata::get<T> (L, 1, false);
352 	luabridge::LuaRef tbl (luabridge::newTable (L));
353 
354 	if (pd && pd->scale_points) {
355 		for (ARDOUR::ScalePoints::const_iterator i = pd->scale_points->begin(); i != pd->scale_points->end(); ++i) {
356 			tbl[i->first] = i->second;
357 		}
358 	}
359 	luabridge::push (L, tbl);
360 	return 1;
361 }
362 
363 int
sample_to_timecode(lua_State * L)364 ARDOUR::LuaAPI::sample_to_timecode (lua_State *L)
365 {
366 	int top = lua_gettop (L);
367 	if (top < 3) {
368 		return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (TimecodeFormat, sample_rate, sample)");
369 	}
370 	typedef Timecode::TimecodeFormat T;
371 	T tf = luabridge::Stack<T>::get (L, 1);
372 	double sample_rate = luabridge::Stack<double>::get (L, 2);
373 	int64_t sample = luabridge::Stack<int64_t>::get (L, 3);
374 
375 	Timecode::Time timecode;
376 
377 	Timecode::sample_to_timecode (
378 			sample, timecode, false, false,
379 			Timecode::timecode_to_frames_per_second (tf),
380 			Timecode::timecode_has_drop_frames (tf),
381 			sample_rate,
382 			0, false, 0);
383 
384 	luabridge::Stack<uint32_t>::push (L, timecode.hours);
385 	luabridge::Stack<uint32_t>::push (L, timecode.minutes);
386 	luabridge::Stack<uint32_t>::push (L, timecode.seconds);
387 	luabridge::Stack<uint32_t>::push (L, timecode.frames);
388 	return 4;
389 }
390 
391 int
timecode_to_sample(lua_State * L)392 ARDOUR::LuaAPI::timecode_to_sample (lua_State *L)
393 {
394 	int top = lua_gettop (L);
395 	if (top < 6) {
396 		return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (TimecodeFormat, sample_rate, hh, mm, ss, ff)");
397 	}
398 	typedef Timecode::TimecodeFormat T;
399 	T tf = luabridge::Stack<T>::get (L, 1);
400 	double sample_rate = luabridge::Stack<double>::get (L, 2);
401 	int hh = luabridge::Stack<int>::get (L, 3);
402 	int mm = luabridge::Stack<int>::get (L, 4);
403 	int ss = luabridge::Stack<int>::get (L, 5);
404 	int ff = luabridge::Stack<int>::get (L, 6);
405 
406 	Timecode::Time timecode;
407 	timecode.negative = false;
408 	timecode.hours = hh;
409 	timecode.minutes = mm;
410 	timecode.seconds = ss;
411 	timecode.frames = ff;
412 	timecode.subframes = 0;
413 	timecode.rate = Timecode::timecode_to_frames_per_second (tf);
414 	timecode.drop = Timecode::timecode_has_drop_frames (tf);
415 
416 	int64_t sample;
417 
418 	Timecode::timecode_to_sample (
419 			timecode, sample, false, false,
420 			sample_rate, 0, false, 0);
421 
422 	luabridge::Stack<int64_t>::push (L, sample);
423 	return 1;
424 }
425 
426 int
sample_to_timecode_lua(lua_State * L)427 ARDOUR::LuaAPI::sample_to_timecode_lua (lua_State *L)
428 {
429 	int top = lua_gettop (L);
430 	if (top < 2) {
431 		return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (sample)");
432 	}
433 	Session const* const s = luabridge::Userdata::get <Session> (L, 1, true);
434 	int64_t sample = luabridge::Stack<int64_t>::get (L, 2);
435 
436 	Timecode::Time timecode;
437 
438 	Timecode::sample_to_timecode (
439 			sample, timecode, false, false,
440 			s->timecode_frames_per_second (),
441 			s->timecode_drop_frames (),
442 			s->sample_rate (),
443 			0, false, 0);
444 
445 	luabridge::Stack<uint32_t>::push (L, timecode.hours);
446 	luabridge::Stack<uint32_t>::push (L, timecode.minutes);
447 	luabridge::Stack<uint32_t>::push (L, timecode.seconds);
448 	luabridge::Stack<uint32_t>::push (L, timecode.frames);
449 	return 4;
450 }
451 int
timecode_to_sample_lua(lua_State * L)452 ARDOUR::LuaAPI::timecode_to_sample_lua (lua_State *L)
453 {
454 	int top = lua_gettop (L);
455 	if (top < 5) {
456 		return luaL_argerror (L, 1, "invalid number of arguments sample_to_timecode (hh, mm, ss, ff)");
457 	}
458 	Session const* const s = luabridge::Userdata::get <Session> (L, 1, true);
459 	int hh = luabridge::Stack<int>::get (L, 2);
460 	int mm = luabridge::Stack<int>::get (L, 3);
461 	int ss = luabridge::Stack<int>::get (L, 4);
462 	int ff = luabridge::Stack<int>::get (L, 5);
463 
464 	Timecode::Time timecode;
465 	timecode.negative = false;
466 	timecode.hours = hh;
467 	timecode.minutes = mm;
468 	timecode.seconds = ss;
469 	timecode.frames = ff;
470 	timecode.subframes = 0;
471 	timecode.rate = s->timecode_frames_per_second ();
472 	timecode.drop = s->timecode_drop_frames ();
473 
474 	int64_t sample;
475 
476 	Timecode::timecode_to_sample (
477 			timecode, sample, false, false,
478 			s->sample_rate (),
479 			0, false, 0);
480 
481 	luabridge::Stack<int64_t>::push (L, sample);
482 	return 1;
483 }
484 
485 
486 static
proc_cycle_start(size_t * cnt)487 void proc_cycle_start (size_t* cnt)
488 {
489 	++*cnt;
490 }
491 
492 bool
wait_for_process_callback(size_t n_cycles,int64_t timeout_ms)493 ARDOUR::LuaAPI::wait_for_process_callback (size_t n_cycles, int64_t timeout_ms)
494 {
495 	if (!AudioEngine::instance()->running()) {
496 		return false;
497 	}
498 #if 0
499 	if (AudioEngine::instance()->freewheeling()) {
500 		return false;
501 	}
502 #endif
503 	if (AudioEngine::instance()->measuring_latency() != AudioEngine::MeasureNone) {
504 		return false;
505 	}
506 	if (!AudioEngine::instance()->session() ) {
507 		return false;
508 	}
509 
510 	size_t cnt = 0;
511 	ScopedConnection c;
512 
513 	InternalSend::CycleStart.connect_same_thread (c, boost::bind (&proc_cycle_start, &cnt));
514 	while (cnt <= n_cycles) {
515 		Glib::usleep (1000);
516 		if (timeout_ms > 0) {
517 			if (--timeout_ms == 0) {
518 				return cnt > n_cycles;
519 			}
520 		}
521 	}
522 	return true;
523 }
524 
525 void
segfault()526 ARDOUR::LuaAPI::segfault ()
527 {
528 	int* p = NULL;
529 	*p = 0;
530 }
531 
532 int
send(lua_State * L)533 ARDOUR::LuaOSC::Address::send (lua_State *L)
534 {
535 	Address * const luaosc = luabridge::Userdata::get <Address> (L, 1, false);
536 	if (!luaosc) {
537 		return luaL_error (L, "Invalid pointer to OSC.Address");
538 	}
539 	if (!luaosc->_addr) {
540 		return luaL_error (L, "Invalid Destination Address");
541 	}
542 
543 	int top = lua_gettop (L);
544 	if (top < 3) {
545 		return luaL_argerror (L, 1, "invalid number of arguments, :send (path, type, ...)");
546 	}
547 
548 	const char* path = luaL_checkstring (L, 2);
549 	const char* type = luaL_checkstring (L, 3);
550 	assert (path && type);
551 
552 	if ((int) strlen (type) != top - 3) {
553 		return luaL_argerror (L, 3, "type description does not match arguments");
554 	}
555 
556 	lo_message msg = lo_message_new ();
557 
558 	for (int i = 4; i <= top; ++i) {
559 		char t = type[i - 4];
560 		int lt = lua_type (L, i);
561 		int ok = -1;
562 		switch (lt) {
563 			case LUA_TSTRING:
564 				if (t == LO_STRING) {
565 					ok = lo_message_add_string (msg, luaL_checkstring (L, i));
566 				} else if (t == LO_CHAR) {
567 					char c = luaL_checkstring (L, i) [0];
568 					ok = lo_message_add_char (msg, c);
569 				}
570 				break;
571 			case LUA_TBOOLEAN:
572 				if (t == LO_TRUE || t == LO_FALSE) {
573 					if (lua_toboolean (L, i)) {
574 						ok = lo_message_add_true (msg);
575 					} else {
576 						ok = lo_message_add_false (msg);
577 					}
578 				}
579 				break;
580 			case LUA_TNUMBER:
581 				if (t == LO_INT32) {
582 					ok = lo_message_add_int32 (msg, (int32_t) luaL_checkinteger (L, i));
583 				}
584 				else if (t == LO_FLOAT) {
585 					ok = lo_message_add_float (msg, (float) luaL_checknumber (L, i));
586 				}
587 				else if (t == LO_DOUBLE) {
588 					ok = lo_message_add_double (msg, (double) luaL_checknumber (L, i));
589 				}
590 				else if (t == LO_INT64) {
591 					ok = lo_message_add_double (msg, (int64_t) luaL_checknumber (L, i));
592 				}
593 				break;
594 			default:
595 				break;
596 		}
597 		if (ok != 0) {
598 			return luaL_argerror (L, i, "type description does not match parameter");
599 		}
600 	}
601 
602 	int rv = lo_send_message (luaosc->_addr, path, msg);
603 	lo_message_free (msg);
604 	luabridge::Stack<bool>::push (L, (rv == 0));
605 	return 1;
606 }
607 
hue2rgb(const double p,const double q,double t)608 static double hue2rgb (const double p, const double q, double t) {
609 	if (t < 0.0) t += 1.0;
610 	if (t > 1.0) t -= 1.0;
611 	if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t;
612 	if (t < 1.0 / 2.0) return q;
613 	if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
614 	return p;
615 }
616 
617 int
hsla_to_rgba(lua_State * L)618 ARDOUR::LuaAPI::hsla_to_rgba (lua_State *L)
619 {
620 	int top = lua_gettop (L);
621 	if (top < 3) {
622 		return luaL_argerror (L, 1, "invalid number of arguments, :hsla_to_rgba (h, s, l [,a])");
623 	}
624 	double h = luabridge::Stack<double>::get (L, 1);
625 	double s = luabridge::Stack<double>::get (L, 2);
626 	double l = luabridge::Stack<double>::get (L, 3);
627 	double a = 1.0;
628 	if (top > 3) {
629 		a = luabridge::Stack<double>::get (L, 4);
630 	}
631 
632 	// we can't use Gtkmm2ext::hsva_to_color here
633 	// besides we want HSL not HSV and without intermediate
634 	// color_to_rgba (rgba_to_color ())
635 	double r, g, b;
636 	const double cq = l < 0.5 ? l * (1 + s) : l + s - l * s;
637 	const double cp = 2.f * l - cq;
638 	r = hue2rgb (cp, cq, h + 1.0 / 3.0);
639 	g = hue2rgb (cp, cq, h);
640 	b = hue2rgb (cp, cq, h - 1.0 / 3.0);
641 
642 	luabridge::Stack<double>::push (L, r);
643 	luabridge::Stack<double>::push (L, g);
644 	luabridge::Stack<double>::push (L, b);
645 	luabridge::Stack<double>::push (L, a);
646 	return 4;
647 }
648 
649 std::string
ascii_dtostr(const double d)650 ARDOUR::LuaAPI::ascii_dtostr (const double d)
651 {
652 	gchar buf[G_ASCII_DTOSTR_BUF_SIZE];
653 	g_ascii_dtostr (buf, sizeof(buf), d);
654 	return std::string (buf);
655 }
656 
657 int
color_to_rgba(lua_State * L)658 ARDOUR::LuaAPI::color_to_rgba (lua_State *L)
659 {
660 	int top = lua_gettop (L);
661 	if (top < 1) {
662 		return luaL_argerror (L, 1, "invalid number of arguments, color_to_rgba (uint32_t)");
663 	}
664 	uint32_t color = luabridge::Stack<uint32_t>::get (L, 1);
665 	double r, g, b, a;
666 
667 	/* libardour is no user of libcanvas, otherwise
668 	 * we could just call
669 	 * Gtkmm2ext::color_to_rgba (color, r, g, b, a);
670 	 */
671 	r = ((color >> 24) & 0xff) / 255.0;
672 	g = ((color >> 16) & 0xff) / 255.0;
673 	b = ((color >>  8) & 0xff) / 255.0;
674 	a = ((color >>  0) & 0xff) / 255.0;
675 
676 	luabridge::Stack <double>::push (L, r);
677 	luabridge::Stack <double>::push (L, g);
678 	luabridge::Stack <double>::push (L, b);
679 	luabridge::Stack <double>::push (L, a);
680 	return 4;
681 }
682 
683 int
build_filename(lua_State * L)684 ARDOUR::LuaAPI::build_filename (lua_State *L)
685 {
686 	std::vector<std::string> elem;
687 	int top = lua_gettop (L);
688 	if (top < 1) {
689 		return luaL_argerror (L, 1, "invalid number of arguments, build_filename (path, ...)");
690 	}
691 	for (int i = 1; i <= top; ++i) {
692 		int lt = lua_type (L, i);
693 		if (lt != LUA_TSTRING) {
694 			return luaL_argerror (L, i, "invalid argument type, expected string");
695 		}
696 		elem.push_back (luaL_checkstring (L, i));
697 	}
698 
699 	luabridge::Stack<std::string>::push (L, Glib::build_filename (elem));
700 	return 1;
701 }
702 
703 luabridge::LuaRef::Proxy&
clone_instance(const void * classkey,void * p)704 luabridge::LuaRef::Proxy::clone_instance (const void* classkey, void* p) {
705 	lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
706 	lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
707 
708 	luabridge::UserdataPtr::push_raw (m_L, p, classkey);
709 
710 	lua_rawset (m_L, -3);
711 	lua_pop (m_L, 1);
712 	return *this;
713 }
714 
LuaTableRef()715 LuaTableRef::LuaTableRef () {}
~LuaTableRef()716 LuaTableRef::~LuaTableRef () {}
717 
718 int
get(lua_State * L)719 LuaTableRef::get (lua_State* L)
720 {
721 	luabridge::LuaRef rv (luabridge::newTable (L));
722 	for (std::vector<LuaTableEntry>::const_iterator i = _data.begin (); i != _data.end (); ++i) {
723 		switch ((*i).keytype) {
724 			case LUA_TSTRING:
725 				assign (&rv, i->k_s, *i);
726 				break;
727 			case LUA_TNUMBER:
728 				assign (&rv, i->k_n, *i);
729 				break;
730 		}
731 	}
732 	luabridge::push (L, rv);
733 	return 1;
734 }
735 
736 int
set(lua_State * L)737 LuaTableRef::set (lua_State* L)
738 {
739 	if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
740 	_data.clear ();
741 
742 	lua_pushvalue (L, -1);
743 	lua_pushnil (L);
744 	while (lua_next (L, -2)) {
745 		lua_pushvalue (L, -2);
746 
747 		LuaTableEntry s (lua_type (L, -1), lua_type (L, -2));
748 		switch (lua_type (L, -1)) {
749 			case LUA_TSTRING:
750 				s.k_s = luabridge::Stack<std::string>::get (L, -1);
751 				break;
752 				;
753 			case LUA_TNUMBER:
754 				s.k_n = luabridge::Stack<unsigned int>::get (L, -1);
755 				break;
756 			default:
757 				// invalid key
758 				lua_pop (L, 2);
759 				continue;
760 		}
761 
762 		switch (lua_type (L, -2)) {
763 			case LUA_TSTRING:
764 				s.s = luabridge::Stack<std::string>::get (L, -2);
765 				break;
766 			case LUA_TBOOLEAN:
767 				s.b = lua_toboolean (L, -2);
768 				break;
769 			case LUA_TNUMBER:
770 				s.n = lua_tonumber (L, -2);
771 				break;
772 			case LUA_TUSERDATA:
773 				{
774 					bool ok = false;
775 					lua_getmetatable (L, -2);
776 					lua_rawgetp (L, -1, luabridge::getIdentityKey ());
777 					if (lua_isboolean (L, -1)) {
778 						lua_pop (L, 1);
779 						const void* key = lua_topointer (L, -1);
780 						lua_pop (L, 1);
781 						void const* classkey = findclasskey (L, key);
782 
783 						if (classkey) {
784 							ok = true;
785 							s.c = classkey;
786 							s.p = luabridge::Userdata::get_ptr (L, -2);
787 						}
788 					} else {
789 						lua_pop (L, 2);
790 					}
791 
792 					if (ok) {
793 						break;
794 					}
795 					// invalid userdata -- fall through
796 				}
797 				/* fallthrough */
798 			case LUA_TFUNCTION: // no support -- we could... string.format("%q", string.dump(value, true))
799 				/* fallthrough */
800 			case LUA_TTABLE: // no nested tables, sorry.
801 			case LUA_TNIL:
802 			default:
803 				// invalid value
804 				lua_pop (L, 2);
805 				continue;
806 		}
807 
808 		_data.push_back (s);
809 		lua_pop (L, 2);
810 	}
811 	return 0;
812 }
813 
814 void*
findclasskey(lua_State * L,const void * key)815 LuaTableRef::findclasskey (lua_State *L, const void* key)
816 {
817 	lua_pushvalue (L, LUA_REGISTRYINDEX);
818 	lua_pushnil (L);
819 	while (lua_next (L, -2)) {
820 		lua_pushvalue (L, -2);
821 		if (lua_topointer (L, -2) == key) {
822 			void* rv = lua_touserdata (L, -1);
823 			lua_pop (L, 4);
824 			return rv;
825 		}
826 		lua_pop (L, 2);
827 	}
828 	lua_pop (L, 1);
829 	return NULL;
830 }
831 
832 template<typename T>
assign(luabridge::LuaRef * rv,T key,const LuaTableEntry & s)833 void LuaTableRef::assign (luabridge::LuaRef* rv, T key, const LuaTableEntry& s)
834 {
835 	switch (s.valuetype) {
836 		case LUA_TSTRING:
837 			(*rv)[key] = s.s;
838 			break;
839 		case LUA_TBOOLEAN:
840 			(*rv)[key] = s.b;
841 			break;
842 		case LUA_TNUMBER:
843 			(*rv)[key] = s.n;
844 			break;
845 		case LUA_TUSERDATA:
846 			(*rv)[key].clone_instance (s.c, s.p);
847 			break;
848 		default:
849 			assert (0);
850 			break;
851 	}
852 }
853 
854 std::vector<std::string>
list_plugins()855 LuaAPI::Vamp::list_plugins ()
856 {
857 	using namespace ::Vamp::HostExt;
858 	PluginLoader* loader (PluginLoader::getInstance());
859 	return loader->listPlugins ();
860 }
861 
Vamp(const std::string & key,float sample_rate)862 LuaAPI::Vamp::Vamp (const std::string& key, float sample_rate)
863 	: _plugin (0)
864 	, _sample_rate (sample_rate)
865 	, _bufsize (1024)
866 	, _stepsize (1024)
867 	, _initialized (false)
868 {
869 	using namespace ::Vamp::HostExt;
870 
871 	PluginLoader* loader (PluginLoader::getInstance());
872 	_plugin = loader->loadPlugin (key, _sample_rate, PluginLoader::ADAPT_ALL_SAFE);
873 
874 	if (!_plugin) {
875 		PBD::error << string_compose (_("VAMP Plugin \"%1\" could not be loaded"), key) << endmsg;
876 		throw failed_constructor ();
877 	}
878 
879 	size_t bs = _plugin->getPreferredBlockSize ();
880 	size_t ss = _plugin->getPreferredStepSize ();
881 
882 	if (bs > 0 && ss > 0 && bs <= 8192 && ss <= 8192) {
883 		_bufsize = bs;
884 		_stepsize = ss;
885 	}
886 }
887 
~Vamp()888 LuaAPI::Vamp::~Vamp ()
889 {
890 	delete _plugin;
891 }
892 
893 void
reset()894 LuaAPI::Vamp::reset ()
895 {
896 	_initialized = false;
897 	if (_plugin) {
898 		_plugin->reset ();
899 	}
900 }
901 
902 bool
initialize()903 LuaAPI::Vamp::initialize ()
904 {
905 	if (!_plugin || _plugin->getMinChannelCount() > 1) {
906 		return false;
907 	}
908 	if (!_plugin->initialise (1, _stepsize, _bufsize)) {
909 		return false;
910 	}
911 	_initialized = true;
912 	return true;
913 }
914 
915 int
analyze(boost::shared_ptr<ARDOUR::Readable> r,uint32_t channel,luabridge::LuaRef cb)916 LuaAPI::Vamp::analyze (boost::shared_ptr<ARDOUR::Readable> r, uint32_t channel, luabridge::LuaRef cb)
917 {
918 	if (!_initialized) {
919 		if (!initialize ()) {
920 			return -1;
921 		}
922 	}
923 	assert (_initialized);
924 
925 	::Vamp::Plugin::FeatureSet features;
926 	float* data = new float[_bufsize];
927 	float* bufs[1] = { data };
928 
929 	samplecnt_t len = r->readable_length();
930 	samplepos_t pos = 0;
931 
932 	int rv = 0;
933 	while (1) {
934 		samplecnt_t to_read = std::min ((len - pos), _bufsize);
935 		if (r->read (data, pos, to_read, channel) != to_read) {
936 			rv = -1;
937 			break;
938 		}
939 		if (to_read != _bufsize) {
940 			memset (data + to_read, 0, (_bufsize - to_read) * sizeof (float));
941 		}
942 
943 		features = _plugin->process (bufs, ::Vamp::RealTime::fromSeconds ((double) pos / _sample_rate));
944 
945 		if (cb.type () == LUA_TFUNCTION) {
946 			if (cb (&features, pos)) {
947 				break;
948 			}
949 		}
950 
951 		pos += std::min (_stepsize, to_read);
952 
953 		if (pos >= len) {
954 			break;
955 		}
956 	}
957 
958 	delete [] data;
959 	return rv;
960 }
961 
962 ::Vamp::Plugin::FeatureSet
process(const std::vector<float * > & d,::Vamp::RealTime rt)963 LuaAPI::Vamp::process (const std::vector<float*>& d, ::Vamp::RealTime rt)
964 {
965 	if (!_plugin || d.size() == 0) {
966 		return ::Vamp::Plugin::FeatureSet ();
967 	}
968 	const float* const* bufs = &d[0];
969 	return _plugin->process (bufs, rt);
970 }
971 
972 boost::shared_ptr<Evoral::Note<Temporal::Beats> >
new_noteptr(uint8_t chan,Temporal::Beats beat_time,Temporal::Beats length,uint8_t note,uint8_t velocity)973 LuaAPI::new_noteptr (uint8_t chan, Temporal::Beats beat_time, Temporal::Beats length, uint8_t note, uint8_t velocity)
974 {
975 	return boost::shared_ptr<Evoral::Note<Temporal::Beats> > (new Evoral::Note<Temporal::Beats>(chan, beat_time, length, note, velocity));
976 }
977 
978 std::list<boost::shared_ptr<Evoral::Note<Temporal::Beats> > >
note_list(boost::shared_ptr<MidiModel> mm)979 LuaAPI::note_list (boost::shared_ptr<MidiModel> mm)
980 {
981 	typedef boost::shared_ptr<Evoral::Note<Temporal::Beats> > NotePtr;
982 
983 	std::list<NotePtr> note_ptr_list;
984 
985 	const MidiModel::Notes& notes = mm->notes();
986 	for (MidiModel::Notes::const_iterator i = notes.begin(); i != notes.end(); ++i) {
987 		note_ptr_list.push_back (*i);
988 	}
989 	return note_ptr_list;
990 }
991 
992 /* ****************************************************************************/
993 
994 const samplecnt_t LuaAPI::Rubberband::_bufsize = 256;
995 
Rubberband(boost::shared_ptr<AudioRegion> r,bool percussive)996 LuaAPI::Rubberband::Rubberband (boost::shared_ptr<AudioRegion> r, bool percussive)
997 	: _region (r)
998 	, _rbs (r->session().sample_rate(), r->n_channels(),
999 	        percussive ? RubberBand::RubberBandStretcher::DefaultOptions : RubberBand::RubberBandStretcher::PercussiveOptions,
1000 	        r->stretch (), r->shift ())
1001 	, _stretch_ratio (r->stretch ())
1002 	, _pitch_ratio (r->shift ())
1003 	, _cb (0)
1004 {
1005 	_n_channels  = r->n_channels ();
1006 	_read_len    = r->length () / (double)r->stretch ();
1007 	_read_start  = r->ancestral_start () + samplecnt_t (r->start () / (double)r->stretch ());
1008 	_read_offset = _read_start - r->start () + r->position ();
1009 }
1010 
~Rubberband()1011 LuaAPI::Rubberband::~Rubberband ()
1012 {
1013 }
1014 
1015 bool
set_strech_and_pitch(double stretch_ratio,double pitch_ratio)1016 LuaAPI::Rubberband::set_strech_and_pitch (double stretch_ratio, double pitch_ratio)
1017 {
1018 	if (stretch_ratio <= 0 || pitch_ratio <= 0) {
1019 		return false;
1020 	}
1021 	_stretch_ratio = stretch_ratio * _region->stretch ();
1022 	_pitch_ratio   = pitch_ratio   * _region->shift ();
1023 	return true;
1024 }
1025 
1026 bool
set_mapping(luabridge::LuaRef tbl)1027 LuaAPI::Rubberband::set_mapping (luabridge::LuaRef tbl)
1028 {
1029 	if (!tbl.isTable ()) {
1030 		return false;
1031 	}
1032 
1033 	_mapping.clear ();
1034 
1035 	for (luabridge::Iterator i (tbl); !i.isNil (); ++i) {
1036 		if (!i.key ().isNumber () || !i.value ().isNumber ()) {
1037 			continue;
1038 		}
1039 		size_t ss = i.key ().cast<double> ();
1040 		size_t ds = i.value ().cast<double> ();
1041 		printf ("ADD %ld %ld\n", ss, ds);
1042 		_mapping[ss] = ds;
1043 	}
1044 	return !_mapping.empty ();
1045 }
1046 
1047 samplecnt_t
read(Sample * buf,samplepos_t pos,samplecnt_t cnt,int channel) const1048 LuaAPI::Rubberband::read (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
1049 {
1050 	return _region->master_read_at (buf, NULL, NULL, _read_offset + pos, cnt, channel);
1051 }
1052 
null_deleter(LuaAPI::Rubberband *)1053 static void null_deleter (LuaAPI::Rubberband*) {}
1054 
1055 boost::shared_ptr<Readable>
readable()1056 LuaAPI::Rubberband::readable ()
1057 {
1058 	if (!_self) {
1059 		_self = boost::shared_ptr<Rubberband> (this, &null_deleter);
1060 	}
1061 	return boost::dynamic_pointer_cast<Readable> (_self);
1062 }
1063 
1064 bool
read_region(bool study)1065 LuaAPI::Rubberband::read_region (bool study)
1066 {
1067 	samplepos_t pos = 0;
1068 
1069 	float** buffers = new float*[_n_channels];
1070 	for (uint32_t c = 0; c < _n_channels; ++c) {
1071 		buffers[c] = new float[_bufsize];
1072 	}
1073 
1074 	while (pos < _read_len) {
1075 		samplecnt_t n_read = 0;
1076 		for (uint32_t c = 0; c < _n_channels; ++c) {
1077 			samplepos_t to_read = std::min (_bufsize, _read_len - pos);
1078 			n_read = read (buffers[c], pos, to_read, c);
1079 			if (n_read != to_read) {
1080 				pos = 0;
1081 				goto errout;
1082 			}
1083 		}
1084 
1085 		pos += n_read;
1086 
1087 		assert (!_cb || _cb->type () == LUA_TFUNCTION);
1088 		if ((*_cb) (NULL, pos * .5 + (study ? 0 : _read_len / 2))) {
1089 			pos = 0;
1090 			goto errout;
1091 		}
1092 
1093 		if (study) {
1094 			_rbs.study (buffers, n_read, pos == _read_len);
1095 			continue;
1096 		}
1097 
1098 		assert (_asrc.size () == _n_channels);
1099 		_rbs.process (buffers, n_read, pos == _read_len);
1100 
1101 		if (!retrieve (buffers)) {
1102 			pos = 0;
1103 			goto errout;
1104 		}
1105 	}
1106 
1107 	if (!retrieve (buffers)) {
1108 		pos = 0;
1109 	}
1110 
1111 errout:
1112 	if (buffers) {
1113 		for (uint32_t c = 0; c < _n_channels; ++c) {
1114 			delete[] buffers[c];
1115 		}
1116 		delete[] buffers;
1117 	}
1118 	return pos == _read_len;
1119 }
1120 
1121 bool
retrieve(float ** buffers)1122 LuaAPI::Rubberband::retrieve (float** buffers)
1123 {
1124 	samplecnt_t avail = 0;
1125 	while ((avail = _rbs.available ()) > 0) {
1126 		samplepos_t to_read = std::min (_bufsize, avail);
1127 		_rbs.retrieve (buffers, to_read);
1128 
1129 		for (uint32_t c = 0; c < _asrc.size (); ++c) {
1130 			if (_asrc[c]->write (buffers[c], to_read) != to_read) {
1131 				return false;
1132 			}
1133 		}
1134 	}
1135 	return true;
1136 }
1137 
1138 boost::shared_ptr<AudioRegion>
process(luabridge::LuaRef cb)1139 LuaAPI::Rubberband::process (luabridge::LuaRef cb)
1140 {
1141 	boost::shared_ptr<AudioRegion> rv;
1142 	if (cb.type () == LUA_TFUNCTION) {
1143 		_cb = new luabridge::LuaRef (cb);
1144 	}
1145 
1146 	_rbs.reset ();
1147 	_rbs.setDebugLevel (1);
1148 	_rbs.setTimeRatio (_stretch_ratio);
1149 	_rbs.setPitchScale (_pitch_ratio);
1150 	_rbs.setExpectedInputDuration (_read_len);
1151 
1152 	/* compare to Filter::make_new_sources */
1153 	vector<string> names    = _region->master_source_names ();
1154 	Session&    session     = _region->session ();
1155 	samplecnt_t sample_rate = session.sample_rate ();
1156 
1157 	for (uint32_t c = 0; c < _n_channels; ++c) {
1158 		string       name = PBD::basename_nosuffix (names[c]) + "(rb)";
1159 		const string path = session.new_audio_source_path (name, _n_channels, c, false);
1160 		if (path.empty ()) {
1161 			cleanup (true);
1162 			return rv;
1163 		}
1164 		try {
1165 
1166 			_asrc.push_back (boost::dynamic_pointer_cast<AudioSource> (SourceFactory::createWritable (DataType::AUDIO, session, path, sample_rate)));
1167 
1168 		} catch (failed_constructor& err) {
1169 			cleanup (true);
1170 			return rv;
1171 		}
1172 	}
1173 
1174 	/* study */
1175 	if (!read_region (true)) {
1176 		cleanup (true);
1177 		return rv;
1178 	}
1179 
1180 	if (!_mapping.empty ()) {
1181 		_rbs.setKeyFrameMap (_mapping);
1182 	}
1183 
1184 	/* process */
1185 	if (!read_region (false)) {
1186 		cleanup (true);
1187 		return rv;
1188 	}
1189 
1190 	rv = finalize ();
1191 
1192 	cleanup (false);
1193 	return rv;
1194 }
1195 
1196 boost::shared_ptr<AudioRegion>
finalize()1197 LuaAPI::Rubberband::finalize ()
1198 {
1199 	time_t     xnow = time (NULL);
1200 	struct tm* now  = localtime (&xnow);
1201 
1202 	/* this is the same as RBEffect::finish, Filter::finish */
1203 	SourceList sl;
1204 	for (std::vector<boost::shared_ptr<AudioSource> >::iterator i = _asrc.begin (); i != _asrc.end (); ++i) {
1205 		boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
1206 		assert (afs);
1207 		afs->done_with_peakfile_writes ();
1208 		afs->update_header (_region->position (), *now, xnow);
1209 		afs->mark_immutable ();
1210 		Analyser::queue_source_for_analysis (*i, false);
1211 		sl.push_back (*i);
1212 	}
1213 
1214 	/* create a new region */
1215 	std::string region_name = RegionFactory::new_region_name (_region->name ());
1216 
1217 	PropertyList plist;
1218 	plist.add (Properties::start, 0);
1219 	plist.add (Properties::length, _region->length ());
1220 	plist.add (Properties::name, region_name);
1221 	plist.add (Properties::whole_file, true);
1222 	plist.add (Properties::position, _region->position ());
1223 
1224 	boost::shared_ptr<Region>      r  = RegionFactory::create (sl, plist);
1225 	boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (r);
1226 
1227 	ar->set_scale_amplitude (_region->scale_amplitude ());
1228 	ar->set_fade_in_active (_region->fade_in_active ());
1229 	ar->set_fade_in (_region->fade_in ());
1230 	ar->set_fade_out_active (_region->fade_out_active ());
1231 	ar->set_fade_out (_region->fade_out ());
1232 	*(ar->envelope ()) = *(_region->envelope ());
1233 
1234 	ar->set_ancestral_data (_read_start, _read_len, _stretch_ratio, _pitch_ratio);
1235 	ar->set_master_sources (_region->master_sources ());
1236 	ar->set_length (ar->length () * _stretch_ratio, 0); // XXX
1237 	if (_stretch_ratio != 1.0) {
1238 		// TODO: apply mapping
1239 		ar->envelope ()->x_scale (_stretch_ratio);
1240 	}
1241 
1242 	return ar;
1243 }
1244 
1245 void
cleanup(bool abort)1246 LuaAPI::Rubberband::cleanup (bool abort)
1247 {
1248 	if (abort) {
1249 		for (std::vector<boost::shared_ptr<AudioSource> >::iterator i = _asrc.begin (); i != _asrc.end (); ++i) {
1250 			(*i)->mark_for_remove ();
1251 		}
1252 	}
1253 	_asrc.clear ();
1254 	delete (_cb);
1255 	_cb = 0;
1256 }
1257