summaryrefslogtreecommitdiff
path: root/tools/luadevel/luasession.cc
blob: e345fb750c3b7683b5cf587b25ffd544832d2f35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#include <stdint.h>
#include <assert.h>

#include <cstdio>
#include <iostream>
#include <string>
#include <list>
#include <vector>

#include <glibmm.h>

#include "pbd/debug.h"
#include "pbd/event_loop.h"
#include "pbd/error.h"
#include "pbd/failed_constructor.h"
#include "pbd/pthread_utils.h"
#include "pbd/reallocpool.h"
#include "pbd/receiver.h"
#include "pbd/transmitter.h"

#include "ardour/ardour.h"
#include "ardour/audioengine.h"
#include "ardour/filename_extensions.h"
#include "ardour/filesystem_paths.h"
#include "ardour/luabindings.h"
#include "ardour/session.h"
#include "ardour/types.h"
#include "ardour/vst_types.h"

#include <readline/readline.h>
#include <readline/history.h>

#include "lua/luastate.h"
#include "LuaBridge/LuaBridge.h"

using namespace std;
using namespace ARDOUR;
using namespace PBD;

static const char* localedir = LOCALEDIR;
static PBD::ScopedConnectionList engine_connections;
static PBD::ScopedConnectionList session_connections;
static Session* session = NULL;
static LuaState* lua;
static bool keep_running = true;

/* extern VST functions */
int vstfx_init (void*) { return 0; }
void vstfx_exit () {}
void vstfx_destroy_editor (VSTState*) {}

class LuaReceiver : public Receiver
{
  protected:
    void receive (Transmitter::Channel chn, const char * str)
		{
			const char *prefix = "";

			switch (chn) {
				case Transmitter::Error:
					prefix = "[ERROR]: ";
					break;
				case Transmitter::Info:
					/* ignore */
					return;
				case Transmitter::Warning:
					prefix = "[WARNING]: ";
					break;
				case Transmitter::Fatal:
					prefix = "[FATAL]: ";
					break;
				case Transmitter::Throw:
					/* this isn't supposed to happen */
					abort ();
			}

			/* note: iostreams are already thread-safe: no external
				 lock required.
				 */

			std::cout << prefix << str << std::endl;

			if (chn == Transmitter::Fatal) {
				::exit (9);
			}
		}
};

class MyEventLoop : public sigc::trackable, public EventLoop
{
	public:
		MyEventLoop (std::string const& name) : EventLoop (name) {
			run_loop_thread = Glib::Threads::Thread::self ();
		}

		void call_slot (InvalidationRecord* ir, const boost::function<void()>& f) {
			if (Glib::Threads::Thread::self () == run_loop_thread) {
				cout << string_compose ("%1/%2 direct dispatch of call slot via functor @ %3, invalidation %4\n", event_loop_name(), pthread_name(), &f, ir);
				f ();
			} else {
				cout << string_compose ("%1/%2 queue call-slot using functor @ %3, invalidation %4\n", event_loop_name(), pthread_name(), &f, ir);
				assert (!ir);
				f (); // XXX TODO, queue and process during run ()
			}
		}

		void run () {
			; // TODO process Events, if any
		}

		Glib::Threads::Mutex& slot_invalidation_mutex () { return request_buffer_map_lock; }

	private:
		Glib::Threads::Thread* run_loop_thread;
		Glib::Threads::Mutex   request_buffer_map_lock;
};

static MyEventLoop *event_loop = NULL;

/* ****************************************************************************/
/* internal helper fn and callbacks */

static void init ()
{
	if (!ARDOUR::init (false, true, localedir)) {
		cerr << "Ardour failed to initialize\n" << endl;
		::exit (EXIT_FAILURE);
	}

	assert (!event_loop);
	event_loop = new MyEventLoop ("lua");
	EventLoop::set_event_loop_for_thread (event_loop);
	SessionEvent::create_per_thread_pool ("lua", 4096);

	static LuaReceiver lua_receiver;

	lua_receiver.listen_to (error);
	lua_receiver.listen_to (info);
	lua_receiver.listen_to (fatal);
	lua_receiver.listen_to (warning);
}

static void set_session (ARDOUR::Session *s)
{
	session = s;
	assert (lua);
	lua_State* L = lua->getState ();
	LuaBindings::set_session (L, session);
	lua->collect_garbage (); // drop references
}

static void unset_session ()
{
	session_connections.drop_connections ();
	set_session (NULL);
}

static int prepare_engine ()
{
	AudioEngine* engine = AudioEngine::instance ();

	if (!engine->current_backend ()) {
		if (!engine->set_backend ("None (Dummy)", "Unit-Test", "")) {
			std::cerr << "Cannot create Audio/MIDI engine\n";
			return -1;
		}
	}

	if (!engine->current_backend ()) {
		std::cerr << "Cannot create Audio/MIDI engine\n";
		return -1;
	}

	if (engine->running ()) {
		engine->stop ();
	}
	return 0;
}

static int start_engine (uint32_t rate)
{
	AudioEngine* engine = AudioEngine::instance ();

	if (engine->set_sample_rate (rate)) {
		std::cerr << "Cannot set session's samplerate.\n";
		return -1;
	}

	if (engine->start () != 0) {
		std::cerr << "Cannot start Audio/MIDI engine\n";
		return -1;
	}

	return 0;
}

static Session * _create_session (string dir, string state, uint32_t rate) // throws
{
	if (prepare_engine ()) {
		return 0;
	}

	std::string s = Glib::build_filename (dir, state + statefile_suffix);
	if (Glib::file_test (dir, Glib::FILE_TEST_EXISTS)) {
		std::cerr << "Session already exists: " << s << "\n";
		return 0;
	}

	if (start_engine (rate)) {
		return 0;
	}

	// TODO add option/bindings for this
	BusProfile bus_profile;
	bus_profile.master_out_channels = 2;

	AudioEngine* engine = AudioEngine::instance ();
	Session* session = new Session (*engine, dir, state, &bus_profile);
	return session;
}

static Session * _load_session (string dir, string state) // throws
{
	if (prepare_engine ()) {
		return 0;
	}

	float sr;
	SampleFormat sf;
	std::string v;
	std::string s = Glib::build_filename (dir, state + statefile_suffix);
	if (!Glib::file_test (dir, Glib::FILE_TEST_EXISTS)) {
		std::cerr << "Cannot find session: " << s << "\n";
		return 0;
	}

	if (Session::get_info_from_path (s, sr, sf, v) != 0) {
		std::cerr << "Cannot get samplerate from session.\n";
		return 0;
	}

	if (start_engine (sr)) {
		return 0;
	}

	AudioEngine* engine = AudioEngine::instance ();
	Session* session = new Session (*engine, dir, state);
	return session;
}

/* ****************************************************************************/
/* lua bound functions */

static Session* create_session (string dir, string state, uint32_t rate)
{
	Session* s = 0;
	if (session) {
		cerr << "Session already open" << "\n";
		return 0;
	}
	try {
		s = _create_session (dir, state, rate);
	} catch (failed_constructor& e) {
		cerr << "failed_constructor: " << e.what () << "\n";
		return 0;
	} catch (AudioEngine::PortRegistrationFailure& e) {
		cerr << "PortRegistrationFailure: " << e.what () << "\n";
		return 0;
	} catch (exception& e) {
		cerr << "exception: " << e.what () << "\n";
		return 0;
	} catch (...) {
		cerr << "unknown exception.\n";
		return 0;
	}
	Glib::usleep (1000000); // allow signal propagation, callback/thread-pool setup
	if (!s) {
		return 0;
	}
	set_session (s);
	s->DropReferences.connect_same_thread (session_connections, &unset_session);
	return s;
}

static Session* load_session (string dir, string state)
{
	Session* s = 0;
	if (session) {
		cerr << "Session already open" << "\n";
		return 0;
	}
	try {
		s = _load_session (dir, state);
	} catch (failed_constructor& e) {
		cerr << "failed_constructor: " << e.what () << "\n";
		return 0;
	} catch (AudioEngine::PortRegistrationFailure& e) {
		cerr << "PortRegistrationFailure: " << e.what () << "\n";
		return 0;
	} catch (exception& e) {
		cerr << "exception: " << e.what () << "\n";
		return 0;
	} catch (...) {
		cerr << "unknown exception.\n";
		return 0;
	}
	Glib::usleep (1000000); // allow signal propagation, callback/thread-pool setup
	if (!s) {
		return 0;
	}
	set_session (s);
	s->DropReferences.connect_same_thread (session_connections, &unset_session);
	return s;
}

static int set_debug_options (const char *opts)
{
	return PBD::parse_debug_options (opts);
}

static void close_session ()
{
	delete session;
	assert (!session);
}

static int close_session_lua (lua_State *L)
{
	if (!session) {
		cerr << "No open session" << "\n";
		return 0;
	}
	close_session ();
	return 0;
}

static void delay (float d) {
	if (d > 0) {
		Glib::usleep (d * 1000000);
	}
}

static int do_quit (lua_State *L)
{
	keep_running = false;
	return 0;
}

/* ****************************************************************************/

static void my_lua_print (std::string s) {
	std::cout << s << "\n";
}

static void setup_lua ()
{
	assert (!lua);

	lua = new LuaState ();
	lua->Print.connect (&my_lua_print);
	lua_State* L = lua->getState ();

	LuaBindings::stddef (L);
	LuaBindings::common (L);
	LuaBindings::session (L);
	LuaBindings::osc (L);

	luabridge::getGlobalNamespace (L)
		.beginNamespace ("_G")
		.addFunction ("create_session", &create_session)
		.addFunction ("load_session", &load_session)
		.addFunction ("close_session", &close_session)
		.addFunction ("sleep", &delay)
		.addFunction ("quit", &do_quit)
		.addFunction ("set_debug_options", &set_debug_options)
		.endNamespace ();

	// add a Session::close() method
	luabridge::getGlobalNamespace (L)
		.beginNamespace ("ARDOUR")
		.beginClass <Session> ("Session")
		.addExtCFunction ("close", &close_session_lua)
		.endClass ()
		.endNamespace ();

	// push instance to global namespace (C++ lifetime)
	luabridge::push <AudioEngine *> (L, AudioEngine::create ());
	lua_setglobal (L, "AudioEngine");

	AudioEngine::instance ()->stop ();
}

static int
incomplete (lua_State* L, int status) {
	if (status == LUA_ERRSYNTAX) {
		size_t lmsg;
		const char *msg = lua_tolstring (L, -1, &lmsg);
		if (lmsg >= 5 && strcmp(msg + lmsg - 5, "<eof>") == 0) {
			lua_pop(L, 1);
			return 1;
		}
	}
	return 0;
}

int main (int argc, char **argv)
{
	init ();
	setup_lua ();

	using_history ();
	std::string histfile = Glib::build_filename (user_config_directory(), "/luahist");

	rl_bind_key ('\t', rl_insert); // disable completion
	read_history (histfile.c_str());

	char *line = NULL;
	while (keep_running && (line = readline ("> "))) {
		event_loop->run();
		if (!strcmp (line, "quit")) {
			free (line); line = NULL;
			break;
		}

		if (strlen (line) == 0) {
			free (line); line = NULL;
			continue;
		}

		do {
			LuaState lt;
			lua_State* L = lt.getState ();
			int status = luaL_loadbuffer (L, line, strlen(line), "=stdin");
			if (!incomplete (L, status)) {
				break;
			}
			char *l2 = readline (">> ");
			if (!l2) {
				break;
			}
			if (strlen (l2) == 0) {
				continue;
			}
			line = (char*) realloc ((void*)line, (strlen(line) + strlen (l2) + 2) * sizeof(char));
			strcat (line, "\n");
			strcat (line, l2);
			free (l2);
		} while (1);

		if (lua->do_command (line)) {
			/* error */
			free (line); line = NULL;
			continue;
		}

		add_history (line);
		event_loop->run();
		free (line); line = NULL;
	}
	free (line);
	printf ("\n");

	if (session) {
		close_session ();
	}

	engine_connections.drop_connections ();

	delete lua;
	lua = NULL;

	write_history (histfile.c_str());

	AudioEngine::instance ()->stop ();
	AudioEngine::destroy ();

	// cleanup
	ARDOUR::cleanup ();
	delete event_loop;
	pthread_cancel_all ();
	return 0;
}