api.c 56.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (c) 2015 Hanspeter Portner (dev@open-music-kontrollers.ch)
 *
 * This is free software: you can redistribute it and/or modify
 * it under the terms of the Artistic License 2.0 as published by
 * The Perl Foundation.
 *
 * This source is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Artistic License 2.0 for more details.
 *
 * You should have received a copy of the Artistic License 2.0
 * along the source as a COPYING file. If not, obtain it from
 * http://www.perlfoundation.org/artistic_license_2_0.
 */

18
#include <limits.h> // INT_MAX
19
#include <math.h> // INFINITY
20
#include <inttypes.h>
21
#include <stdatomic.h>
22

23 24 25
#define ECB 1
#define CBC 0
#include <aes.h>
26
#include <osc.lv2/endian.h>
27

28 29
#include <api_atom.h>
#include <api_forge.h>
30
#include <api_stash.h>
31 32 33 34
#include <api_midi.h>
#include <api_osc.h>
#include <api_time.h>
#include <api_state.h>
35
#include <api_parameter.h>
36

37 38
#define RDF_PREFIX    "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
#define RDFS_PREFIX   "http://www.w3.org/2000/01/rdf-schema#"
39

40 41 42 43
#define RDF__value    RDF_PREFIX"value"
#define RDF__type     RDF_PREFIX"type"
#define RDFS__label   RDFS_PREFIX"label"
#define RDFS__range   RDFS_PREFIX"range"
44
#define RDFS__comment RDFS_PREFIX"comment"
45

Hanspeter Portner's avatar
Hanspeter Portner committed
46 47 48 49
#ifndef LV2_PATCH__Copy
#	define LV2_PATCH__Copy LV2_PATCH_PREFIX "Copy"
#endif

Hanspeter Portner's avatar
Hanspeter Portner committed
50 51 52 53
#ifndef LV2_UNITS__midiController
#	define LV2_UNITS__midiController LV2_UNITS_PREFIX "midiController"
#endif

54 55
static const char *moony_ref [MOONY_UDATA_COUNT] = {
	[MOONY_UDATA_ATOM]	= "latom",
56
	[MOONY_UDATA_FORGE]	= "lforge",
57
	[MOONY_UDATA_STASH]	= "lstash"
58 59 60 61
};

static const size_t moony_sz [MOONY_UDATA_COUNT] = {
	[MOONY_UDATA_ATOM]	= sizeof(latom_t),
62 63
	[MOONY_UDATA_FORGE]	= sizeof(lforge_t),
	[MOONY_UDATA_STASH]	= sizeof(lstash_t)
64 65
};

66
static _Atomic xpress_uuid_t voice_uuid = ATOMIC_VAR_INIT(INT64_MAX / UINT16_MAX * 2LL);
67

Hanspeter Portner's avatar
Hanspeter Portner committed
68 69
static int64_t
_voice_map_new_uuid(void *handle)
70
{
Hanspeter Portner's avatar
Hanspeter Portner committed
71 72
	_Atomic xpress_uuid_t *uuid = handle;
	return atomic_fetch_add_explicit(uuid, 1, memory_order_relaxed);
73 74 75
}

static xpress_map_t voice_map_fallback = {
Hanspeter Portner's avatar
Hanspeter Portner committed
76 77
	.handle = &voice_uuid,
	.new_uuid = _voice_map_new_uuid
78 79
};

80
static int
81
_hash_sort(const void *itm1, const void *itm2)
82
{
83 84
	const latom_driver_hash_t *hash1 = itm1;
	const latom_driver_hash_t *hash2 = itm2;
85

86 87 88 89 90 91 92
	if(hash1->type < hash2->type)
		return -1;
	else if(hash1->type > hash2->type)
		return 1;
	return 0;
}

93 94
static int
_lmap__index(lua_State *L)
95
{
96
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
97

Hanspeter Portner's avatar
Hanspeter Portner committed
98 99 100
	const char *uri = luaL_checkstring(L, 2);
	LV2_URID urid = moony->map->map(moony->map->handle, uri); // non-rt
	if(urid)
101
	{
Hanspeter Portner's avatar
Hanspeter Portner committed
102
		lua_pushinteger(L, urid);
103

Hanspeter Portner's avatar
Hanspeter Portner committed
104 105 106 107
		// cache it
		lua_pushvalue(L, 2); // uri
		lua_pushvalue(L, -2); // urid
		lua_rawset(L, 1);  // self
108
	}
Hanspeter Portner's avatar
Hanspeter Portner committed
109 110
	else
		lua_pushnil(L);
111

112 113 114
	return 1;
}

Hanspeter Portner's avatar
Hanspeter Portner committed
115 116 117 118 119 120
static const luaL_Reg lmap_mt [] = {
	{"__index", _lmap__index},
	{"__call", _lmap__index},
	{NULL, NULL}
};

121
static int
Hanspeter Portner's avatar
Hanspeter Portner committed
122
_lunmap__index(lua_State *L)
123
{
Hanspeter Portner's avatar
Hanspeter Portner committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));

	LV2_URID urid = luaL_checkinteger(L, 2);
	const char *uri = moony->unmap->unmap(moony->unmap->handle, urid); // non-rt
	if(uri)
	{
		lua_pushstring(L, uri);

		// cache it
		lua_pushvalue(L, 2); // urid
		lua_pushvalue(L, -2); // uri
		lua_rawset(L, 1);  // self
	}
	else
		lua_pushnil(L);
139 140 141 142

	return 1;
}

Hanspeter Portner's avatar
Hanspeter Portner committed
143 144 145
static const luaL_Reg lunmap_mt [] = {
	{"__index", _lunmap__index},
	{"__call", _lunmap__index},
146
	{NULL, NULL}
147 148
};

149
static int
Hanspeter Portner's avatar
Hanspeter Portner committed
150
_lhash_map__index(lua_State *L)
151
{
Hanspeter Portner's avatar
Hanspeter Portner committed
152
	//moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
153

Hanspeter Portner's avatar
Hanspeter Portner committed
154
	if(lua_isstring(L, 2))
155
	{
Hanspeter Portner's avatar
Hanspeter Portner committed
156 157 158 159 160 161
		lua_getglobal(L, "Map");
		lua_pushvalue(L, lua_upvalueindex(2)); // uri.prefix
		lua_pushvalue(L, 2); // uri.postfix
		lua_concat(L, 2); // uri
		lua_gettable(L, -2); // Map[uri];
		if(lua_isinteger(L, -1))
162
		{
163
			// cache it
Hanspeter Portner's avatar
Hanspeter Portner committed
164 165
			lua_pushvalue(L, 2); // uri
			lua_pushvalue(L, -2); // urid
166
			lua_rawset(L, 1);  // self
167
		}
168 169
		else
			lua_pushnil(L);
170
	}
Hanspeter Portner's avatar
Hanspeter Portner committed
171 172
	else
		lua_pushnil(L);
173

174
	return 1;
175 176
}

Hanspeter Portner's avatar
Hanspeter Portner committed
177 178 179 180 181 182
static const luaL_Reg lhash_map_mt [] = {
	{"__index", _lhash_map__index},
	{"__call", _lhash_map__index},
	{NULL, NULL}
};

183
static int
Hanspeter Portner's avatar
Hanspeter Portner committed
184
_lhash_map(lua_State *L)
185
{
Hanspeter Portner's avatar
Hanspeter Portner committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));

	if(lua_isstring(L, 1))
	{
		lua_newtable(L);
		lua_newtable(L);
		lua_pushlightuserdata(L, moony); // @ upvalueindex 1
		lua_pushvalue(L, 1); // uri.prefix @ upvalueindex 2
		luaL_setfuncs(L, lhash_map_mt, 2);
		//_protect_metatable(L, -1); //TODO
		lua_setmetatable(L, -2);
	}
	else
		lua_pushnil(L);
200

201
	return 1;
202 203
}

204 205 206 207 208
static int
_lvoice_map(lua_State *L)
{
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));

Hanspeter Portner's avatar
Hanspeter Portner committed
209
	lua_pushinteger(L, moony->voice_map->new_uuid(moony->voice_map->handle));
210 211 212
	return 1;
}

213 214 215 216
static int
_lmidi2cps(lua_State *L)
{
	const lua_Number note = luaL_checknumber(L, 1);
217 218 219
	const lua_Number base = luaL_optnumber(L, 2, 69.0);
	const lua_Number noct = luaL_optnumber(L, 3, 12.0);
	const lua_Number fref = luaL_optnumber(L, 4, 440.0);
220

221
	const lua_Number cps = exp2( (note - base) / noct) * fref;
222 223 224 225 226 227 228 229 230

	lua_pushnumber(L, cps);
	return 1;
}

static int
_lcps2midi(lua_State *L)
{
	const lua_Number cps = luaL_checknumber(L, 1);
231 232 233
	const lua_Number base = luaL_optnumber(L, 2, 69.0);
	const lua_Number noct = luaL_optnumber(L, 3, 12.0);
	const lua_Number fref = luaL_optnumber(L, 4, 440.0);
234

235
	const lua_Number note = log2(cps / fref) * noct + base;
236 237 238 239 240

	lua_pushnumber(L, note);
	return 1;
}

241
static const char *note_keys [12] = {
Hanspeter Portner's avatar
Hanspeter Portner committed
242 243 244 245 246 247 248
	"C", "C#",
	"D", "D#",
	"E",
	"F", "F#",
	"G", "G#",
	"A", "A#",
	"H"
249 250 251 252 253
};

static int
_lnote__index(lua_State *L)
{
254
	//moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
255 256 257 258 259 260 261 262 263 264

	lua_settop(L, 2); // ignore superfluous arguments

	const int type = lua_type(L, 2);
	if(type == LUA_TNUMBER)
	{
		const int note = lua_tointeger(L, 2);

		if( (note >= 0) && (note < 0x80) )
		{
265
			char name [16];
Hanspeter Portner's avatar
Hanspeter Portner committed
266 267 268
			const int8_t octave = note / 12 - 1;
			const uint8_t key = note % 12;
			snprintf(name, 16, "%s%+"PRIi8, note_keys[key], octave);
269 270 271 272 273 274 275 276 277 278

			lua_pushstring(L, name);
			return 1;
		}
	}
	else if(type == LUA_TSTRING)
	{
		size_t str_len;
		const char *str = lua_tolstring(L, 2, &str_len);

279
		for(int i=0; i<12; i++)
280
		{
281 282
			const char *key = note_keys[i];
			const size_t key_len = strlen(key);
283

Hanspeter Portner's avatar
Hanspeter Portner committed
284
			if( (str_len - 2 == key_len) && !strncmp(str, key, key_len) )
285
			{
286
				const int octave = atoi(str + key_len);
Hanspeter Portner's avatar
Hanspeter Portner committed
287
				const int note = (octave + 1)*12 + i;
288
				if( (note >= 0) && (note < 0x80) )
289
				{
290 291
					lua_pushinteger(L, note);
					return 1;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
				}
			}
		}
	}

	lua_pushnil(L);
	return 1;
}

static int
_lnote__call(lua_State *L)
{
	lua_settop(L, 2);
	lua_gettable(L, -2); // self[uri]

	return 1;
}

static const luaL_Reg lnote_mt [] = {
	{"__index", _lnote__index},
	{"__call", _lnote__index},
	{NULL, NULL}
};

316
static int
317
_log(lua_State *L)
318 319
{
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
320
	int n = lua_gettop(L);
321

322
	if(!n)
323 324
		return 0;

325 326 327
	luaL_Buffer buf;
	luaL_buffinit(L, &buf);

328 329
  lua_getglobal(L, "tostring");
  for(int i=1; i<=n; i++)
330
	{
331 332 333 334 335 336 337 338 339 340
    lua_pushvalue(L, -1);  // function to be called
    lua_pushvalue(L, i);   // value to print
    lua_call(L, 1, 1);
    if(i>1)
			luaL_addlstring(&buf, "\t", 1);
		size_t len;
		const char *s = lua_tolstring(L, -1, &len);
		luaL_addlstring(&buf, s, len);
    lua_pop(L, 1);  // pop result
  }
341 342 343 344 345 346

	luaL_pushresult(&buf);

	const char *res = lua_tostring(L, -1);
	if(moony->log)
		lv2_log_trace(&moony->logger, "%s", res);
347

348 349 350 351 352
	// feedback to UI
	char *end = strrchr(moony->trace, '\0'); // search end of string
	if(end)
	{
		if(end != moony->trace)
Hanspeter Portner's avatar
Hanspeter Portner committed
353
		{
354
			*end++ = '\n'; // append to
Hanspeter Portner's avatar
Hanspeter Portner committed
355 356 357
			*end = '\0';
		}
		const size_t remaining = MOONY_MAX_ERROR_LEN - (end - moony->trace);
Hanspeter Portner's avatar
Hanspeter Portner committed
358
		snprintf(end, remaining, "%s", res);
359
		moony->trace_out = 1; // set flag
360 361 362 363 364
	}

	return 0;
}

365
static bool
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
_parse_key(lua_State *L, int idx, uint8_t key [16])
{
	size_t key_len;
	const char *pass = luaL_checklstring(L, idx, &key_len);

	switch(key_len)
	{
		case 16: // raw key
			memcpy(key, pass, 16);
			break;
		case 32: // hex-encoded key
			for(unsigned i=0; i<16; i++)
			{
				if(sscanf(&pass[i*2], "%02"SCNx8, &key[i]) != 1)
					return false; // sscanf failed
			}
			break;
		default: // invalid key
			return false;
	}

	return true; // success
}

static int
_lencrypt(lua_State *L)
{
	size_t input_len;
	const uint8_t *input = (const uint8_t *)luaL_checklstring(L, 1, &input_len);

	uint8_t key [16];
	if(!_parse_key(L, 2, key))
	{
		lua_pushnil(L);
		return 1;
	}

	const size_t offset_len = sizeof(uint32_t); // length of size prefix
	const uint32_t output_len = ((input_len + 15) & (~15)) + offset_len; // round to next 16 byte boundary

	luaL_Buffer buf;
	uint8_t *dst = (uint8_t *)luaL_buffinitsize(L, &buf, output_len);

	*(uint32_t *)dst = htobe32(input_len); // write chunk size

	aes_t aes;
	for(unsigned i=0; i<input_len; i+=16)
	{
		uint8_t temp [16];
		const unsigned rem = input_len - i;
		const unsigned len = rem < 16 ? rem : 16;

		if(len < 16)
			memset(temp, 0x0, 16); // pad remainder

		memcpy(temp, &input[i], 16);
		AES128_ECB_encrypt(&aes, temp, key, &dst[offset_len + i]);
	}
	luaL_addsize(&buf, output_len);
	luaL_pushresult(&buf);

	return 1;
}

static int
_ldecrypt(lua_State *L)
{
	size_t input_len;
	const uint8_t *input = (const uint8_t *)luaL_checklstring(L, 1, &input_len);

	uint8_t key [16];
	if(!_parse_key(L, 2, key))
	{
		lua_pushnil(L);
		return 1;
	}

	const uint32_t output_len = be32toh(*(uint32_t *)input); // read chunk size
	const size_t offset_len = sizeof(uint32_t); // length of size prefix

	luaL_Buffer buf;
	uint8_t *dst = (uint8_t *)luaL_buffinitsize(L, &buf, output_len);

	aes_t aes;
	for(unsigned i=0; i<output_len; i+=16)
	{
		uint8_t temp [16];

		memcpy(temp, &input[offset_len + i], 16);
		AES128_ECB_decrypt(&aes, temp, key, &dst[i]);
	}
	luaL_addsize(&buf, output_len);
	luaL_pushresult(&buf);

	// discriminate between code and string
	if(lua_isstring(L, -1))
	{
		size_t str_len;
		const char *str = lua_tolstring(L, -1, &str_len);

		if(luaL_loadbuffer(L, str, str_len, "decrypt") == LUA_OK)
		{
			return 1; // return code parsed from decrypted string
		}
		else
		{
			lua_pop(L, 1); // pop error code;
			return 1; // return decrypted string
		}
	}

	lua_pushnil(L);
	return 1;
}

481
LV2_Atom_Forge_Ref
482 483 484 485 486 487
_sink(LV2_Atom_Forge_Sink_Handle handle, const void *buf, uint32_t size)
{
	atom_ser_t *ser = handle;

	const LV2_Atom_Forge_Ref ref = ser->offset + 1;

488 489
	const uint32_t new_offset = ser->offset + size;
	if(new_offset > ser->size)
490
	{
491 492 493 494
		uint32_t new_size = ser->size << 1;
		while(new_offset > new_size)
			new_size <<= 1;

495
		if(ser->moony)
496
		{
497
			if(!(ser->buf = moony_realloc(ser->moony, ser->buf, ser->size, new_size)))
498 499 500 501 502 503 504 505 506 507 508 509
				return 0; // realloc failed
		}
		else
		{
			if(!(ser->buf = realloc(ser->buf, new_size)))
				return 0; // realloc failed
		}

		ser->size = new_size;
	}

	memcpy(ser->buf + ser->offset, buf, size);
510
	ser->offset = new_offset;
511 512 513 514

	return ref;
}

515
LV2_Atom *
516 517 518 519 520 521 522 523 524
_deref(LV2_Atom_Forge_Sink_Handle handle, LV2_Atom_Forge_Ref ref)
{
	atom_ser_t *ser = handle;

	const uint32_t offset = ref - 1;

	return (LV2_Atom *)(ser->buf + offset);
}

525 526
static int
_stash(lua_State *L)
527
{
528
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
529

530 531
	lua_getglobal(L, "stash");
	if(lua_isfunction(L, -1))
532
	{
533
		lforge_t *lframe = moony_newuserdata(L, moony, MOONY_UDATA_FORGE, true);
534 535 536
		lframe->depth = 0;
		lframe->last.frames = 0;
		lframe->forge = &moony->stash_forge;
537

538
		atom_ser_t ser = {
539
			.moony = moony,
540 541
			.size = 1024,
			.offset = 0
542
		};
543
		ser.buf = moony_alloc(moony, ser.size);
544

545 546
		if(ser.buf)
		{
547
			memset(ser.buf, 0x0, sizeof(LV2_Atom));
548

549 550
			lv2_atom_forge_set_sink(lframe->forge, _sink, _deref, &ser);
			lua_call(L, 1, 0);
551

552
			if(moony->stash_atom)
553
				moony_free(moony, moony->stash_atom, moony->stash_size);
554
			LV2_Atom *atom = (LV2_Atom *)ser.buf;
555
			moony->stash_atom = atom;
556
			moony->stash_size = ser.size;
557 558 559 560
		}
	}
	else
		lua_pop(L, 1);
561

562 563
	return 0;
}
564

565 566 567 568
static int
_apply(lua_State *L)
{
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
569

570 571 572
	lua_getglobal(L, "apply");
	if(lua_isfunction(L, -1))
	{
573
		_latom_new(L, moony->stash_atom, true);
574 575 576 577
		lua_call(L, 1, 0);
	}
	else
		lua_pop(L, 1);
578

579 580
	return 0;
}
581

582 583 584 585
static int
_save(lua_State *L)
{
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
586

587 588
	if(lua_getglobal(L, "save") == LUA_TFUNCTION)
	{
589
		lforge_t *lframe = moony_newuserdata(L, moony, MOONY_UDATA_FORGE, true);
590 591 592
		lframe->depth = 0;
		lframe->last.frames = 0;
		lframe->forge = &moony->state_forge;
593

594 595
		lua_call(L, 1, 0);
	}
596

597 598
	return 0;
}
599

600 601 602 603 604
static LV2_State_Status
_state_save(LV2_Handle instance, LV2_State_Store_Function store,
	LV2_State_Handle state, uint32_t flags, const LV2_Feature *const *features)
{
	moony_t *moony = (moony_t *)instance;
605

606 607
	LV2_State_Status status = LV2_STATE_SUCCESS;
	char *chunk = NULL;
608

609
	_spin_lock(&moony->lock.state);
610
	chunk = strdup(moony->chunk);
611
	_unlock(&moony->lock.state);
612

613 614 615 616 617 618 619 620 621
	if(chunk)
	{
		status = store(
			state,
			moony->uris.moony_code,
			chunk,
			strlen(chunk) + 1,
			moony->forge.String,
			LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE);
Hanspeter Portner's avatar
Hanspeter Portner committed
622
		(void)status; //TODO check status
623

624 625
		free(chunk);
	}
626 627 628 629 630 631 632 633 634

	const int32_t minor_version = MOONY_MINOR_VERSION;
	status = store(
		state,
		moony->uris.core_minor_version,
		&minor_version,
		sizeof(int32_t),
		moony->forge.Int,
		LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE);
Hanspeter Portner's avatar
Hanspeter Portner committed
635
	(void)status; //TODO check status
636 637 638 639 640 641 642 643 644

	const int32_t micro_version = MOONY_MICRO_VERSION;
	status = store(
		state,
		moony->uris.core_micro_version,
		&micro_version,
		sizeof(int32_t),
		moony->forge.Int,
		LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE);
Hanspeter Portner's avatar
Hanspeter Portner committed
645
	(void)status; //TODO check status
646

647
	atom_ser_t ser = {
648
		.moony = NULL,
649 650
		.size = 1024,
		.offset = 0
651
	};
652
	ser.buf = malloc(ser.size);
653

654 655
	if(ser.buf)
	{
656
		memset(ser.buf, 0x0, sizeof(LV2_Atom));
657

658
		lv2_atom_forge_set_sink(&moony->state_forge, _sink, _deref, &ser);
659

660 661
		// lock Lua state, so it cannot be accessed by realtime thread
		_spin_lock(&moony->lock.state);
662

663 664 665 666 667 668 669 670 671
		// restore Lua defined properties
		lua_State *L = moony->vm.L;
		lua_rawgeti(L, LUA_REGISTRYINDEX, UDATA_OFFSET + MOONY_UDATA_COUNT + MOONY_CCLOSURE_SAVE);
		if(lua_pcall(L, 0, 0, 0))
		{
			if(moony->log) //TODO send to UI, too
				lv2_log_error(&moony->logger, "%s", lua_tostring(L, -1));
			lua_pop(L, 1);
		}
672
#ifdef USE_MANUAL_GC
673
		lua_gc(L, LUA_GCSTEP, 0);
674
#endif
675

676
		_unlock(&moony->lock.state);
677

678
		LV2_Atom *atom = (LV2_Atom *)ser.buf;
679 680 681 682 683 684 685 686 687 688
		if( (atom->type) && (atom->size) )
		{
			status = store(
				state,
				moony->uris.moony_state,
				LV2_ATOM_BODY(atom),
				atom->size,
				atom->type,
				LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE);
		}
689

690 691 692 693
		if(moony->state_atom)
			free(moony->state_atom);
		moony->state_atom = atom;
	}
694

695 696
	return status;
}
697

698 699 700 701
static int
_restore(lua_State *L)
{
	moony_t *moony = lua_touserdata(L, lua_upvalueindex(1));
702

703
	if(lua_getglobal(L, "restore") == LUA_TFUNCTION)
704
	{
705
		_latom_new(L, moony->state_atom, false);
706
		lua_call(L, 1, 0);
707
	}
708

709 710 711
	return 0;
}

712 713 714 715 716 717 718 719 720 721 722 723 724 725
static void
_clear_global_callbacks(lua_State *L)
{
	lua_pushnil(L);
	lua_setglobal(L, "stash");

	lua_pushnil(L);
	lua_setglobal(L, "apply");

	lua_pushnil(L);
	lua_setglobal(L, "save");

	lua_pushnil(L);
	lua_setglobal(L, "restore");
726

727 728 729 730 731 732 733
	lua_pushnil(L);
	lua_setglobal(L, "once");

	lua_pushnil(L);
	lua_setglobal(L, "run");
}

734 735
static LV2_State_Status
_state_restore(LV2_Handle instance, LV2_State_Retrieve_Function retrieve, LV2_State_Handle state, uint32_t flags, const LV2_Feature *const *features)
736
{
737 738
	moony_t *moony = (moony_t *)instance;
	lua_State *L = moony->vm.L;
739

740 741 742
	size_t size;
	uint32_t type;
	uint32_t flags2;
743

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
	// get minor version
	const int32_t *minor_version = retrieve(
		state,
		moony->uris.core_minor_version,
		&size,
		&type,
		&flags2);
	if(!minor_version || (size != sizeof(int32_t)) || (type != moony->forge.Int) )
		minor_version = NULL;

	// get micro version
	const int32_t *micro_version = retrieve(
		state,
		moony->uris.core_micro_version,
		&size,
		&type,
		&flags2);
	if(!micro_version || (size != sizeof(int32_t)) || (type != moony->forge.Int) )
		micro_version = NULL;

Hanspeter Portner's avatar
Hanspeter Portner committed
764
	//TODO check preset version with current plugin version for API compatibility
765 766

	// get code chunk
767 768 769 770 771
	const char *chunk = retrieve(
		state,
		moony->uris.moony_code,
		&size,
		&type,
772
		&flags2);
Hanspeter Portner's avatar
Hanspeter Portner committed
773

774
	if(chunk && size && (type == moony->forge.String) )
775
	{
776 777
		if(size <= MOONY_MAX_CHUNK_LEN)
		{
778 779 780
			// lock Lua state, so it cannot be accessed by realtime thread
			_spin_lock(&moony->lock.state);

781
			strncpy(moony->chunk, chunk, size);
782

783 784 785 786 787
			_clear_global_callbacks(L);
			if(luaL_dostring(L, moony->chunk))
				moony_error(moony);
			else
				moony->error[0] = 0x0; // reset error flag
788

789
			moony->dirty_out = 1; // trigger update of UI
790
			moony->error_out = 1; // trigger update of UI
791 792
			moony->props_out = 1; // trigger update of UI
			moony->once = true; // trigger call of 'once'
793 794

			_unlock(&moony->lock.state);
795 796 797 798 799
		}
		else
		{
			moony_err(moony, "restore: moony:code too long");
		}
800
	}
Hanspeter Portner's avatar
Hanspeter Portner committed
801 802
	else
	{
803
		moony_err(moony, "restore: moony:code property not found");
Hanspeter Portner's avatar
Hanspeter Portner committed
804
	}
805

806 807 808 809 810 811 812
	const uint8_t *body = retrieve(
		state,
		moony->uris.moony_state,
		&size,
		&type,
		&flags2
	);
813

814
	if(body && size && type)
815
	{
816
		// allocate new state_atom
817 818
		LV2_Atom *state_atom = malloc(sizeof(LV2_Atom) + size);
		if(state_atom)
819
		{
820 821 822 823 824 825 826
			// lock Lua state, so it cannot be accessed by realtime thread
			_spin_lock(&moony->lock.state);

			if(moony->state_atom) // clear old state_atom
				free(moony->state_atom);
			moony->state_atom = state_atom;

827 828 829 830 831 832 833 834 835 836 837 838
			moony->state_atom->size = size;
			moony->state_atom->type = type;
			memcpy(LV2_ATOM_BODY(moony->state_atom), body, size);

			// restore Lua defined properties
			lua_rawgeti(L, LUA_REGISTRYINDEX, UDATA_OFFSET + MOONY_UDATA_COUNT + MOONY_CCLOSURE_RESTORE);
			if(lua_pcall(L, 0, 0, 0))
			{
				if(moony->log) //TODO send to UI, too
					lv2_log_error(&moony->logger, "%s", lua_tostring(L, -1));
				lua_pop(L, 1);
			}
839
#ifdef USE_MANUAL_GC
840
			lua_gc(L, LUA_GCSTEP, 0);
841
#endif
842 843

			_unlock(&moony->lock.state);
844
		}
845
	}
846

847 848
	return LV2_STATE_SUCCESS;
}
849

850 851 852 853
static const LV2_State_Interface state_iface = {
	.save = _state_save,
	.restore = _state_restore
};
854

855 856 857 858 859 860 861 862 863
// non-rt thread
static LV2_Worker_Status
_work(LV2_Handle instance,
	LV2_Worker_Respond_Function respond,
	LV2_Worker_Respond_Handle target,
	uint32_t size,
	const void *body)
{
	moony_t *moony = instance;
864

865 866 867
	assert(size == sizeof(moony_mem_t));
	const moony_mem_t *request = body;
	uint32_t i = request->i;
868

869
	if(request->mem) // request to free memory from _work_response
870
	{
871
		moony_vm_mem_free(request->mem, moony->vm.size[i]);
872
	}
873
	else // request to allocate memory from moony_vm_mem_extend
874
	{
875
		moony->vm.area[i] = moony_vm_mem_alloc(moony->vm.size[i]);
876

877
		respond(target, size, body); // signal to _work_response
878
	}
879

880 881
	return LV2_WORKER_SUCCESS;
}
882

883 884 885 886 887 888 889 890 891
// rt-thread
static LV2_Worker_Status
_work_response(LV2_Handle instance, uint32_t size, const void *body)
{
	moony_t *moony = instance;

	assert(size == sizeof(moony_mem_t));
	const moony_mem_t *request = body;
	uint32_t i = request->i;
892

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
	if(!moony->vm.area[i]) // allocation failed
		return LV2_WORKER_ERR_UNKNOWN;

	// tlsf add pool
	moony->vm.pool[i] = tlsf_add_pool(moony->vm.tlsf,
		moony->vm.area[i], moony->vm.size[i]);

	if(!moony->vm.pool[i]) // pool addition failed
	{
		const moony_mem_t req = {
			.i = i,
			.mem = moony->vm.area[i]
		};
		moony->vm.area[i] = NULL;

		// schedule freeing of memory to _work
		LV2_Worker_Status status = moony->sched->schedule_work(
			moony->sched->handle, sizeof(moony_mem_t), &req);
		if( (status != LV2_WORKER_SUCCESS) && moony->log)
			lv2_log_warning(&moony->logger, "moony: schedule_work failed");

		return LV2_WORKER_ERR_UNKNOWN;
Hanspeter Portner's avatar
Hanspeter Portner committed
915
	}
916

917 918
	moony->vm.space += moony->vm.size[i];
	//printf("mem extended to %zu KB\n", moony->vm.space / 1024);
Hanspeter Portner's avatar
Hanspeter Portner committed
919

920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
	return LV2_WORKER_SUCCESS;
}

// rt-thread
static LV2_Worker_Status
_end_run(LV2_Handle instance)
{
	moony_t *moony = instance;

	// do nothing
	moony->working = 0;

	return LV2_WORKER_SUCCESS;
}

static const LV2_Worker_Interface work_iface = {
	.work = _work,
	.work_response = _work_response,
	.end_run = _end_run
};

941
#ifdef BUILD_INLINE_DISPLAY
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
static inline LV2_Inline_Display_Image_Surface *
_cairo_init(moony_t *moony, int w, int h)
{
	LV2_Inline_Display_Image_Surface *surf = &moony->image_surface;

	surf->width = w;
	surf->height = w > h ? h : w; // try to use 1:1 ratio
	surf->stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, surf->width);
	surf->data = realloc(surf->data, surf->stride * surf->height);
	if(!surf->data)
		return NULL;

	moony->cairo.surface = cairo_image_surface_create_for_data(
		surf->data, CAIRO_FORMAT_ARGB32, surf->width, surf->height, surf->stride);

	if(moony->cairo.surface)
958
	{
959
		cairo_surface_set_device_scale(moony->cairo.surface, surf->width, surf->height);
960

961 962
		moony->cairo.ctx = cairo_create(moony->cairo.surface);
		if(moony->cairo.ctx)
963
		{
964
			cairo_select_font_face(moony->cairo.ctx, "cairo:monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
965 966
		}
	}
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993

	return surf;
}

static inline void
_cairo_deinit(moony_t *moony)
{
	LV2_Inline_Display_Image_Surface *surf = &moony->image_surface;

	if(moony->cairo.ctx)
	{
		cairo_destroy(moony->cairo.ctx);
		moony->cairo.ctx = NULL;
	}

	if(moony->cairo.surface)
	{
		cairo_surface_finish(moony->cairo.surface);
		cairo_surface_destroy(moony->cairo.surface);
		moony->cairo.surface = NULL;
	}

	if(surf->data)
	{
		free(surf->data);
		surf->data = NULL;
	}
994
}
995
#endif
996 997 998 999 1000 1001 1002

// non-rt
static LV2_Inline_Display_Image_Surface *
_render(LV2_Handle instance, uint32_t w, uint32_t h)
{
	moony_t *moony = instance;

1003
#ifdef BUILD_INLINE_DISPLAY
1004 1005 1006 1007 1008
	// prepare pixel surface in all cases
	LV2_Inline_Display_Image_Surface *surf = &moony->image_surface;

	if( (surf->width != (int)w) || (surf->height > (int)h) || !surf->data)
	{
1009 1010
		_cairo_deinit(moony);
		surf = _cairo_init(moony, w, h);
1011 1012
	}

1013 1014
	if(!surf)
		return NULL;
1015 1016

	_spin_lock(&moony->lock.render)
1017
	if(moony->render.graph)
1018
	{
1019
		lv2_canvas_render(&moony->canvas, moony->cairo.ctx, moony->render.graph);
1020 1021
	}
	else
1022
	{
1023
		surf = NULL;
1024
	}
1025
	_unlock(&moony->lock.render);
1026

1027
	return surf;
1028 1029 1030
#else
	return NULL;
#endif
1031 1032 1033 1034 1035 1036
}

static const LV2_Inline_Display_Interface inlinedisplay_iface = {
	.render = _render
};

1037 1038 1039 1040 1041 1042 1043
const void*
extension_data(const char* uri)
{
	if(!strcmp(uri, LV2_WORKER__interface))
		return &work_iface;
	else if(!strcmp(uri, LV2_STATE__interface))
		return &state_iface;
1044 1045
	else if(!strcmp(uri, LV2_INLINEDISPLAY__interface))
		return &inlinedisplay_iface;
1046 1047 1048 1049 1050 1051 1052 1053 1054
	else
		return NULL;
}

int
moony_init(moony_t *moony, const char *subject, double sample_rate,
	const LV2_Feature *const *features)
{
	if(moony_vm_init(&moony->vm))
1055
	{
1056 1057
		fprintf(stderr, "Lua VM cannot be initialized\n");
		return -1;
1058
	}
1059

1060 1061
	LV2_Options_Option *opts = NULL;
	bool load_default_state = false;
1062

1063
	for(unsigned i=0; features[i]; i++)
1064
	{
1065
		if(!strcmp(features[i]->URI, LV2_URID__map))
1066
			moony->map = features[i]->data;
1067
		else if(!strcmp(features[i]->URI, LV2_URID__unmap))
1068
			moony->unmap = features[i]->data;
1069
		else if(!strcmp(features[i]->URI, LV2_WORKER__schedule))
1070
			moony->sched = features[i]->data;
1071
		else if(!strcmp(features[i]->URI, LV2_LOG__log))
1072
			moony->log = features[i]->data;
1073
		else if(!strcmp(features[i]->URI, LV2_OPTIONS__options))
1074 1075 1076
			opts = features[i]->data;
		else if(!strcmp(features[i]->URI, LV2_OSC__schedule))
			moony->osc_sched = features[i]->data;
1077 1078
		else if(!strcmp(features[i]->URI, LV2_STATE__loadDefaultState))
			load_default_state = true;
1079 1080
		else if(!strcmp(features[i]->URI, XPRESS_VOICE_MAP))
			moony->voice_map = features[i]->data;
1081 1082
		else if(!strcmp(features[i]->URI, LV2_INLINEDISPLAY__queue_draw))
			moony->queue_draw = features[i]->data;
1083 1084
	}

1085
	if(!moony->map)
1086
	{
1087 1088
		fprintf(stderr, "Host does not support urid:map\n");
		return -1;
1089
	}
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
	if(!moony->unmap)
	{
		fprintf(stderr, "Host does not support urid:unmap\n");
		return -1;
	}
	if(!moony->sched)
	{
		fprintf(stderr, "Host does not support worker:schedule\n");
		return -1;
	}
	if(!load_default_state)
	{
		strcpy(moony->chunk,
			"-- host does not support state:loadDefaultState feature\n\n"
1104
			"function run(n, control, notify, ...)\n"
1105 1106
			"end");
	}
1107 1108
	if(!moony->voice_map)
		moony->voice_map = &voice_map_fallback;
1109 1110 1111 1112 1113 1114 1115 1116

	moony->uris.moony_code = moony->map->map(moony->map->handle, MOONY_CODE_URI);
	moony->uris.moony_selection = moony->map->map(moony->map->handle, MOONY_SELECTION_URI);
	moony->uris.moony_error = moony->map->map(moony->map->handle, MOONY_ERROR_URI);
	moony->uris.moony_trace = moony->map->map(moony->map->handle, MOONY_TRACE_URI);
	moony->uris.moony_state = moony->map->map(moony->map->handle, MOONY_STATE_URI);

	moony->uris.midi_event = moony->map->map(moony->map->handle, LV2_MIDI__MidiEvent);
1117

1118 1119 1120 1121 1122 1123 1124
	moony->uris.bufsz_min_block_length = moony->map->map(moony->map->handle,
		LV2_BUF_SIZE__minBlockLength);
	moony->uris.bufsz_max_block_length = moony->map->map(moony->map->handle,
		LV2_BUF_SIZE__maxBlockLength);
	moony->uris.bufsz_sequence_size = moony->map->map(moony->map->handle,
		LV2_BUF_SIZE__sequenceSize);

1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
	moony->uris.patch.self = moony->map->map(moony->map->handle, subject);

	moony->uris.patch.get = moony->map->map(moony->map->handle, LV2_PATCH__Get);
	moony->uris.patch.set = moony->map->map(moony->map->handle, LV2_PATCH__Set);
	moony->uris.patch.put = moony->map->map(moony->map->handle, LV2_PATCH__Put);
	moony->uris.patch.patch = moony->map->map(moony->map->handle, LV2_PATCH__Patch);
	moony->uris.patch.body = moony->map->map(moony->map->handle, LV2_PATCH__body);
	moony->uris.patch.subject = moony->map->map(moony->map->handle, LV2_PATCH__subject);
	moony->uris.patch.property = moony->map->map(moony->map->handle, LV2_PATCH__property);
	moony->uris.patch.value = moony->map->map(moony->map->handle, LV2_PATCH__value);
	moony->uris.patch.add = moony->map->map(moony->map->handle, LV2_PATCH__add);
	moony->uris.patch.remove = moony->map->map(moony->map->handle, LV2_PATCH__remove);
	moony->uris.patch.wildcard = moony->map->map(moony->map->handle, LV2_PATCH__wildcard);
	moony->uris.patch.writable = moony->map->map(moony->map->handle, LV2_PATCH__writable);
	moony->uris.patch.readable = moony->map->map(moony->map->handle, LV2_PATCH__readable);
1140 1141 1142 1143
	moony->uris.patch.destination = moony->map->map(moony->map->handle, LV2_PATCH__destination);
	moony->uris.patch.sequence = moony->map->map(moony->map->handle, LV2_PATCH__sequenceNumber);
	moony->uris.patch.error = moony->map->map(moony->map->handle, LV2_PATCH__Error);
	moony->uris.patch.ack = moony->map->map(moony->map->handle, LV2_PATCH__Ack);
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

	moony->uris.rdfs_label = moony->map->map(moony->map->handle, RDFS__label);
	moony->uris.rdfs_range = moony->map->map(moony->map->handle, RDFS__range);
	moony->uris.rdfs_comment = moony->map->map(moony->map->handle, RDFS__comment);

	moony->uris.rdf_value = moony->map->map(moony->map->handle, RDF__value);

	moony->uris.core_minimum = moony->map->map(moony->map->handle, LV2_CORE__minimum);
	moony->uris.core_maximum = moony->map->map(moony->map->handle, LV2_CORE__maximum);
	moony->uris.core_scale_point = moony->map->map(moony->map->handle, LV2_CORE__scalePoint);
1154 1155
	moony->uris.core_minor_version= moony->map->map(moony->map->handle, LV2_CORE__minorVersion);
	moony->uris.core_micro_version= moony->map->map(moony->map->handle, LV2_CORE__microVersion);
1156 1157

	moony->uris.units_unit = moony->map->map(moony->map->handle, LV2_UNITS__unit);
1158
	moony->uris.units_symbol = moony->map->map(moony->map->handle, LV2_UNITS__symbol);
1159

1160 1161 1162
	moony->uris.atom_frame_time = moony->map->map(moony->map->handle, LV2_ATOM__frameTime);
	moony->uris.atom_beat_time = moony->map->map(moony->map->handle, LV2_ATOM__beatTime);

1163 1164 1165 1166
#ifdef BUILD_INLINE_DISPLAY
	lv2_canvas_init(&moony->canvas, moony->map);
#endif
	lv2_canvas_urid_init(&moony->canvas_urid, moony->map);
1167

1168
	lv2_osc_urid_init(&moony->osc_urid, moony->map);
1169 1170 1171
	lv2_atom_forge_init(&moony->forge, moony->map);
	lv2_atom_forge_init(&moony->state_forge, moony->map);
	lv2_atom_forge_init(&moony->stash_forge, moony->map);
1172
	lv2_atom_forge_init(&moony->notify_forge, moony->map);
1173 1174 1175 1176 1177 1178
	if(moony->log)
		lv2_log_logger_init(&moony->logger, moony->map, moony->log);

	latom_driver_hash_t *latom_driver_hash = moony->atom_driver_hash;
	unsigned pos = 0;

1179 1180 1181
	latom_driver_hash[pos].type = 0;
	latom_driver_hash[pos++].driver = &latom_nil_driver;

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
	latom_driver_hash[pos].type = moony->forge.Int;
	latom_driver_hash[pos++].driver = &latom_int_driver;

	latom_driver_hash[pos].type = moony->forge.Long;
	latom_driver_hash[pos++].driver = &latom_long_driver;

	latom_driver_hash[pos].type = moony->forge.Float;
	latom_driver_hash[pos++].driver = &latom_float_driver;

	latom_driver_hash[pos].type = moony->forge.Double;
	latom_driver_hash[pos++].driver = &latom_double_driver;

	latom_driver_hash[pos].type = moony->forge.Bool;
	latom_driver_hash[pos++].driver = &latom_bool_driver;

	latom_driver_hash[pos].type = moony->forge.URID;
	latom_driver_hash[pos++].driver = &latom_urid_driver;

	latom_driver_hash[pos].type = moony->forge.String;
	latom_driver_hash[pos++].driver = &latom_string_driver;

	latom_driver_hash[pos].type = moony->forge.URI;
	latom_driver_hash[pos++].driver = &latom_string_driver;

	latom_driver_hash[pos].type = moony->forge.Path;
	latom_driver_hash[pos++].driver = &latom_string_driver;

	latom_driver_hash[pos].type = moony->forge.Literal;
	latom_driver_hash[pos++].driver = &latom_literal_driver;

	latom_driver_hash[pos].type = moony->forge.Tuple;
	latom_driver_hash[pos++].driver = &latom_tuple_driver;
1214

1215 1216
	latom_driver_hash[pos].type = moony->forge.Object;
	latom_driver_hash[pos++].driver = &latom_object_driver;
1217

1218 1219
	latom_driver_hash[pos].type = moony->forge.Vector;
	latom_driver_hash[pos++].driver = &latom_vector_driver;
1220

1221 1222
	latom_driver_hash[pos].type = moony->forge.Sequence;
	latom_driver_hash[pos++].driver = &latom_sequence_driver;
1223

Hanspeter Portner's avatar
Hanspeter Portner committed
1224
	assert(pos == DRIVER_HASH_MAX);
1225
	qsort(latom_driver_hash, DRIVER_HASH_MAX, sizeof(latom_driver_hash_t), _hash_sort);
1226

1227
	if(opts)
1228
	{
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
		for(LV2_Options_Option *opt = opts;
			(opt->key != 0) && (opt->value != NULL);
			opt++)
		{
			if(opt->key == moony->uris.bufsz_min_block_length)
				moony->opts.min_block_length = *(int32_t *)opt->value;
			else if(opt->key == moony->uris.bufsz_max_block_length)
				moony->opts.max_block_length = *(int32_t *)opt->value;
			else if(opt->key == moony->uris.bufsz_sequence_size)
				moony->opts.sequence_size = *(int32_t *)opt->value;
		}
1240
	}
1241
	moony->opts.sample_rate = sample_rate;
1242

1243
	moony->dirty_out = 1; // trigger update of UI
1244
	moony->props_out = 1; // trigger update of UI
1245

1246
	atomic_flag_clear_explicit(&moony->lock.state, memory_order_relaxed);
1247
	atomic_flag_clear_explicit(&moony->lock.render, memory_order_relaxed);
1248

1249
	moony_freeuserdata(moony);
1250

1251 1252
	return 0;
}
1253

1254 1255 1256 1257 1258 1259
void
moony_deinit(moony_t *moony)
{
	if(moony->state_atom)
		free(moony->state_atom);
	moony->state_atom = NULL;
1260

1261
	if(moony->stash_atom)
1262
		moony_free(moony, moony->stash_atom, moony->stash_size);
1263
	moony->stash_atom = NULL;
1264
	moony->stash_size = 0;
1265

1266 1267 1268
	if(moony->render.graph)
		moony_free(moony, moony->render.graph, moony->render.size);
	moony->render.graph = NULL;
1269 1270
	moony->render.size = 0;

1271 1272 1273 1274
#ifdef BUILD_INLINE_DISPLAY
	_cairo_deinit(moony);
#endif

1275 1276 1277 1278
	if(moony->image_surface.data)
		free(moony->image_surface.data);
	moony->image_surface.data = NULL;

1279 1280
	moony_vm_deinit(&moony->vm);
}
1281

1282 1283 1284 1285 1286 1287 1288 1289
#define _protect_metatable(L, idx) \
	lua_pushboolean(L, 0); \
	lua_setfield(L, idx - 1, "__metatable");

#define _index_metatable(L, idx) \
	lua_pushvalue(L, idx); \
	lua_setfield(L, idx - 1, "__index");

1290 1291 1292 1293
void
moony_open(moony_t *moony, lua_State *L, bool use_assert)
{
	luaL_newmetatable(L, "latom");
1294
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
1295
	luaL_setfuncs (L, latom_mt, 1);
1296
	_protect_metatable(L, -1);
1297
	lua_pop(L, 1);
1298

1299
	luaL_newmetatable(L, "lforge");
1300
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
1301
	luaL_setfuncs (L, lforge_mt, 1);
1302 1303
	_protect_metatable(L, -1);
	_index_metatable(L, -1);
1304
	lua_pop(L, 1);
1305

1306 1307 1308
	luaL_newmetatable(L, "lstash");
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
	luaL_setfuncs (L, lstash_mt, 1);
1309 1310
	_protect_metatable(L, -1);
	_index_metatable(L, -1);
1311
	lua_pop(L, 1);
1312

1313 1314 1315
	// lv2.map
	lua_newtable(L);
	lua_newtable(L);
1316
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
1317
	luaL_setfuncs(L, lmap_mt, 1);
1318
	_protect_metatable(L, -1);
1319 1320
	lua_setmetatable(L, -2);
	lua_setglobal(L, "Map");
1321

1322 1323 1324
	// lv2.unmap
	lua_newtable(L);
	lua_newtable(L);
1325
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
1326
	luaL_setfuncs(L, lunmap_mt, 1);
1327
	_protect_metatable(L, -1);
1328 1329
	lua_setmetatable(L, -2);
	lua_setglobal(L, "Unmap");
1330

Hanspeter Portner's avatar
Hanspeter Portner committed
1331 1332 1333 1334 1335
	// lv2.hash
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
	lua_pushcclosure(L, _lhash_map, 1);
	lua_setglobal(L, "HashMap");

1336 1337 1338 1339 1340
	// lv2.voiceMap
	lua_pushlightuserdata(L, moony); // @ upvalueindex 1
	lua_pushcclosure(L, _lvoice_map, 1);
	lua_setglobal(L, "VoiceMap");