aboutsummaryrefslogtreecommitdiffhomepage
path: root/backends/osc.c
blob: b12ae40de94a62180c14fccaa531de5253ccf5ab (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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
#include <string.h>
#include <ctype.h>
#include <errno.h>

#include "libmmbackend.h"
#include "osc.h"

/*
 * TODO
 * ping method
 */

#define osc_align(a) ((((a) / 4) + (((a) % 4) ? 1 : 0)) * 4)
#define BACKEND_NAME "osc"

static struct {
	uint8_t detect;
} osc_global_config = {
	.detect = 0
};

MM_PLUGIN_API int init(){
	backend osc = {
		.name = BACKEND_NAME,
		.conf = osc_configure,
		.create = osc_instance,
		.conf_instance = osc_configure_instance,
		.channel = osc_map_channel,
		.handle = osc_set,
		.process = osc_handle,
		.start = osc_start,
		.shutdown = osc_shutdown
	};

	if(sizeof(osc_channel_ident) != sizeof(uint64_t)){
		fprintf(stderr, "OSC channel identification union out of bounds\n");
		return 1;
	}

	//register backend
	if(mm_backend_register(osc)){
		fprintf(stderr, "Failed to register OSC backend\n");
		return 1;
	}
	return 0;
}

static size_t osc_data_length(osc_parameter_type t){
	//binary representation lengths for osc data types
	switch(t){
		case int32:
		case float32:
			return 4;
		case int64:
		case double64:
			return 8;
		default:
			fprintf(stderr, "Invalid OSC format specified %c\n", t);
			return 0;
	}
}

static inline void osc_defaults(osc_parameter_type t, osc_parameter_value* max, osc_parameter_value* min){
	//data type default ranges
	memset(max, 0, sizeof(osc_parameter_value));
	memset(min, 0, sizeof(osc_parameter_value));
	switch(t){
		case int32:
			max->i32 = 255;
			return;
		case float32:
			max->f = 1.0;
			return;
		case int64:
			max->i64 = 1024;
			return;
		case double64:
			max->d = 1.0;
			return;
		default:
			fprintf(stderr, "Invalid OSC type, not setting any sane defaults\n");
			return;
	}
}

static inline osc_parameter_value osc_parse(osc_parameter_type t, uint8_t* data){
	//read value from binary representation
	osc_parameter_value v = {0};
	switch(t){
		case int32:
		case float32:
			v.i32 = be32toh(*((int32_t*) data));
			break;
		case int64:
		case double64:
			v.i64 = be64toh(*((int64_t*) data));
			break;
		default:
			fprintf(stderr, "Invalid OSC type passed to parsing routine\n");
	}
	return v;
}

static inline int osc_deparse(osc_parameter_type t, osc_parameter_value v, uint8_t* data){
	//write value to binary representation
	uint64_t u64 = 0;
	uint32_t u32 = 0;
	switch(t){
		case int32:
		case float32:
			u32 = htobe32(v.i32);
			memcpy(data, &u32, sizeof(u32));
			break;
		case int64:
		case double64:
			u64 = htobe64(v.i64);
			memcpy(data, &u64, sizeof(u64));
			break;
		default:
			fprintf(stderr, "Invalid OSC type passed to parsing routine\n");
			return 1;
	}
	return 0;
}

static inline osc_parameter_value osc_parse_value_spec(osc_parameter_type t, char* value){
	//read value from string
	osc_parameter_value v = {0};
	switch(t){
		case int32:
			v.i32 = strtol(value, NULL, 0);
			break;
		case float32:
			v.f = strtof(value, NULL);
			break;
		case int64:
			v.i64 = strtoll(value, NULL, 0);
			break;
		case double64:
			v.d = strtod(value, NULL);
			break;
		default:
			fprintf(stderr, "Invalid OSC type passed to value parser\n");
	}
	return v;
}

static inline channel_value osc_parameter_normalise(osc_parameter_type t, osc_parameter_value min, osc_parameter_value max, osc_parameter_value cur){
	//normalise osc value wrt given min/max
	channel_value v = {
		.raw = {0},
		.normalised = 0
	};

	union {
		uint32_t u32;
		float f32;
		uint64_t u64;
		double d64;
	} range;

	switch(t){
		case int32:
			range.u32 = max.i32 - min.i32;
			v.raw.u64 = cur.i32 - min.i32;
			v.normalised = v.raw.u64 / range.u32;
			break;
		case float32:
			range.f32 = max.f - min.f;
			v.raw.dbl = cur.f - min.f;
			v.normalised = v.raw.dbl / range.f32;
			break;
		case int64:
			range.u64 = max.i64 - min.i64;
			v.raw.u64 = cur.i64 - min.i64;
			v.normalised = v.raw.u64 / range.u64;
			break;
		case double64:
			range.d64 = max.d - min.d;
			v.raw.dbl = cur.d - min.d;
			v.normalised = v.raw.dbl / range.d64;
			break;
		default:
			fprintf(stderr, "Invalid OSC type passed to interpolation routine\n");
	}

	//clamp to range
	v.normalised = clamp(v.normalised, 1.0, 0.0);
	return v;
}

static inline osc_parameter_value osc_parameter_denormalise(osc_parameter_type t, osc_parameter_value min, osc_parameter_value max, channel_value cur){
	//convert normalised value to osc value wrt given min/max
	osc_parameter_value v = {0};

	union {
		uint32_t u32;
		float f32;
		uint64_t u64;
		double d64;
	} range;

	switch(t){
		case int32:
			range.u32 = max.i32 - min.i32;
			v.i32 = (range.u32 * cur.normalised) + min.i32;
			break;
		case float32:
			range.f32 = max.f - min.f;
			v.f = (range.f32 * cur.normalised) + min.f;
			break;
		case int64:
			range.u64 = max.i64 - min.i64;
			v.i64 = (range.u64 * cur.normalised) + min.i64;
			break;
		case double64:
			range.d64 = max.d - min.d;
			v.d = (range.d64 * cur.normalised) + min.d;
			break;
		default:
			fprintf(stderr, "Invalid OSC type passed to interpolation routine\n");
	}

	return v;
}

static int osc_path_validate(char* path, uint8_t allow_patterns){
	//validate osc path or pattern
	char illegal_chars[] = " #,";
	char pattern_chars[] = "?[]{}*";
	size_t u, c;
	uint8_t square_open = 0, curly_open = 0;
	
	if(path[0] != '/'){
		fprintf(stderr, "%s is not a valid OSC path: Missing root /\n", path);
		return 1;
	}

	for(u = 0; u < strlen(path); u++){
		for(c = 0; c < sizeof(illegal_chars); c++){
			if(path[u] == illegal_chars[c]){
				fprintf(stderr, "%s is not a valid OSC path: Illegal '%c' at %" PRIsize_t "\n", path, illegal_chars[c], u);
				return 1;
			}
		}

		if(!isgraph(path[u])){
			fprintf(stderr, "%s is not a valid OSC path: Illegal '%c' at %" PRIsize_t "\n", path, pattern_chars[c], u);
			return 1;
		}

		if(!allow_patterns){
			for(c = 0; c < sizeof(pattern_chars); c++){
				if(path[u] == pattern_chars[c]){
					fprintf(stderr, "%s is not a valid OSC path: Illegal '%c' at %" PRIsize_t "\n", path, pattern_chars[c], u);
					return 1;
				}
			}
		}

		switch(path[u]){
			case '{':
				if(square_open || curly_open){
					fprintf(stderr, "%s is not a valid OSC path: Illegal '%c' at %" PRIsize_t "\n", path, pattern_chars[c], u);
					return 1;
				}
				curly_open = 1;
				break;
			case '[':
				if(square_open || curly_open){
					fprintf(stderr, "%s is not a valid OSC path: Illegal '%c' at %" PRIsize_t "\n", path, pattern_chars[c], u);
					return 1;
				}
				square_open = 1;
				break;
			case '}':
				curly_open = 0;
				break;
			case ']':
				square_open = 0;
				break;
			case '/':
				if(square_open || curly_open){
					fprintf(stderr, "%s is not a valid OSC path: Pattern across part boundaries\n", path);
					return 1;
				}
		}
	}

	if(square_open || curly_open){
		fprintf(stderr, "%s is not a valid OSC path: Unterminated pattern expression\n", path);
		return 1;
	}
	return 0;
}

static int osc_path_match(char* pattern, char* path){
	size_t u, p = 0, match_begin, match_end;
	uint8_t match_any = 0, inverted, match;

	for(u = 0; u < strlen(path); u++){
		switch(pattern[p]){
			case '/':
				if(match_any){
					for(; path[u] && path[u] != '/'; u++){
					}
				}
				if(path[u] != '/'){
					return 0;
				}
				match_any = 0;
				p++;
				break;
			case '?':
				match_any = 0;
				p++;
				break;
			case '*':
				match_any = 1;
				p++;
				break;
			case '[':
				inverted = (pattern[p + 1] == '!') ? 1 : 0;
				match_end = match_begin = inverted ? p + 2 : p + 1;
				match = 0;
				for(; pattern[match_end] != ']'; match_end++){
					if(pattern[match_end] == path[u]){
						match = 1;
						break;
					}

					if(pattern[match_end + 1] == '-' && pattern[match_end + 2] != ']'){
						if((pattern[match_end] > pattern[match_end + 2] 
									&& path[u] >= pattern[match_end + 2]
									&& path[u] <= pattern[match_end])
								|| (pattern[match_end] <= pattern[match_end + 2]
									&& path[u] >= pattern[match_end]
									&& path[u] <= pattern[match_end + 2])){
							match = 1;
							break;
						}
						match_end += 2;
					}

					if(pattern[match_end + 1] == ']' && match_any && !match
							&& path[u + 1] && path[u + 1] != '/'){
						match_end = match_begin - 1;
						u++;
					}
				}

				if(match == inverted){
					return 0;
				}

				match_any = 0;
				//advance to end of pattern
				for(; pattern[p] != ']'; p++){
				}
				p++;
				break;
			case '{':
				for(match_begin = p + 1; pattern[match_begin] != '}'; match_begin++){
					//find end
					for(match_end = match_begin; pattern[match_end] != ',' && pattern[match_end] != '}'; match_end++){
					}

					if(!strncmp(path + u, pattern + match_begin, match_end - match_begin)){
						//advance pattern
						for(; pattern[p] != '}'; p++){
						}
						p++;
						//advance path
						u += match_end - match_begin - 1;
						break;
					}

					if(pattern[match_end] == '}'){
						//retry with next if in match_any
						if(match_any && path[u + 1] && path[u + 1] != '/'){
							u++;
							match_begin = p;
							continue;
						}
						return 0;
					}
					match_begin = match_end;
				}
				match_any = 0;
				break;
			case 0:
				if(match_any){
					for(; path[u] && path[u] != '/'; u++){
					}
				}
				if(path[u]){
					return 0;
				}
				break;
			default:
				if(match_any){
					for(; path[u] && path[u] != '/' && path[u] != pattern[p]; u++){
					}
				}
				if(pattern[p] != path[u]){
					return 0;
				}
				p++;
				break;
		}
	}
	return 1;
}

static int osc_configure(char* option, char* value){
	if(!strcmp(option, "detect")){
		osc_global_config.detect = 1;
		if(!strcmp(value, "off")){
			osc_global_config.detect = 0;
		}
		return 0;
	}

	fprintf(stderr, "Unknown configuration parameter %s for OSC backend\n", option);
	return 1;
}

static int osc_register_pattern(osc_instance_data* data, char* pattern_path, char* configuration){
	size_t u, pattern;
	char* format = NULL, *token = NULL;

	if(osc_path_validate(pattern_path, 1)){
		fprintf(stderr, "Not a valid OSC pattern: %s\n", pattern_path);
		return 1;
	}

	//tokenize configuration
	format = strtok(configuration, " ");
	if(!format || strlen(format) < 1){
		fprintf(stderr, "Not a valid format specification for OSC pattern %s\n", pattern_path);
		return 1;
	}

	//create pattern
	data->pattern = realloc(data->pattern, (data->patterns + 1) * sizeof(osc_channel));
	if(!data->pattern){
		fprintf(stderr, "Failed to allocate memory\n");
		return 1;
	}
	pattern = data->patterns;

	data->pattern[pattern].params = strlen(format);
	data->pattern[pattern].path = strdup(pattern_path);
	data->pattern[pattern].type = calloc(strlen(format), sizeof(osc_parameter_type));
	data->pattern[pattern].max = calloc(strlen(format), sizeof(osc_parameter_value));
	data->pattern[pattern].min = calloc(strlen(format), sizeof(osc_parameter_value));

	if(!data->pattern[pattern].path
			|| !data->pattern[pattern].type
			|| !data->pattern[pattern].max
			|| !data->pattern[pattern].min){
		//this should fail config parsing and thus call the shutdown function,
		//which should properly free the rest of the data
		fprintf(stderr, "Failed to allocate memory\n");
		return 1;
	}

	//check format validity and store min/max values
	for(u = 0; u < strlen(format); u++){
		if(!osc_data_length(format[u])){
			fprintf(stderr, "Invalid format specifier %c for pattern %s\n", format[u], pattern_path);
			return 1;
		}

		data->pattern[pattern].type[u] = format[u];

		//parse min/max values
		token = strtok(NULL, " ");
		if(!token){
			fprintf(stderr, "Missing minimum specification for parameter %" PRIsize_t " of OSC pattern %s\n", u, pattern_path);
			return 1;
		}
		data->pattern[pattern].min[u] = osc_parse_value_spec(format[u], token);

		token = strtok(NULL, " ");
		if(!token){
			fprintf(stderr, "Missing maximum specification for parameter %" PRIsize_t " of OSC pattern %s\n", u, pattern_path);
			return 1;
		}
		data->pattern[pattern].max[u] = osc_parse_value_spec(format[u], token);
	}

	data->patterns++;
	return 0;
}

static int osc_configure_instance(instance* inst, char* option, char* value){
	osc_instance_data* data = (osc_instance_data*) inst->impl;
	char* host = NULL, *port = NULL;

	if(!strcmp(option, "root")){
		if(osc_path_validate(value, 0)){
			fprintf(stderr, "Not a valid OSC root: %s\n", value);
			return 1;
		}

		if(data->root){
			free(data->root);
		}
		data->root = strdup(value);

		if(!data->root){
			fprintf(stderr, "Failed to allocate memory\n");
			return 1;
		}
		return 0;
	}
	else if(!strcmp(option, "bind")){
		mmbackend_parse_hostspec(value, &host, &port);
		if(!host || !port){
			fprintf(stderr, "Invalid bind address for instance %s\n", inst->name);
			return 1;
		}

		//this requests a socket with SO_BROADCAST set, whether this is useful functionality for OSC is up for debate
		data->fd = mmbackend_socket(host, port, SOCK_DGRAM, 1, 1);
		if(data->fd < 0){
			fprintf(stderr, "Failed to bind for instance %s\n", inst->name);
			return 1;
		}
		return 0;
	}
	else if(!strcmp(option, "dest") || !strcmp(option, "destination")){
		if(!strncmp(value, "learn", 5)){
			data->learn = 1;

			//check if a forced port was provided
			if(value[5] == '@'){
				data->forced_rport = strtoul(value + 6, NULL, 0);
			}
			return 0;
		}

		mmbackend_parse_hostspec(value, &host, &port);
		if(!host || !port){
			fprintf(stderr, "Invalid destination address for instance %s\n", inst->name);
			return 1;
		}

		if(mmbackend_parse_sockaddr(host, port, &data->dest, &data->dest_len)){
			fprintf(stderr, "Failed to parse destination address for instance %s\n", inst->name);
			return 1;
		}
		return 0;
	}
	else if(*option == '/'){
		return osc_register_pattern(data, option, value);
	}

	fprintf(stderr, "Unknown configuration parameter %s for OSC instance %s\n", option, inst->name);
	return 1;
}

static instance* osc_instance(){
	instance* inst = mm_instance();
	if(!inst){
		return NULL;
	}

	osc_instance_data* data = calloc(1, sizeof(osc_instance_data));
	if(!data){
		fprintf(stderr, "Failed to allocate memory\n");
		return NULL;
	}

	data->fd = -1;
	inst->impl = data;
	return inst;
}

static channel* osc_map_channel(instance* inst, char* spec, uint8_t flags){
	size_t u, p;
	osc_instance_data* data = (osc_instance_data*) inst->impl;
	osc_channel_ident ident = {
		.label = 0
	};

	//check spec for correctness
	if(osc_path_validate(spec, 0)){
		return NULL;
	}

	//parse parameter offset
	if(strrchr(spec, ':')){
		ident.fields.parameter = strtoul(strrchr(spec, ':') + 1, NULL, 10);
		*(strrchr(spec, ':')) = 0;
	}

	//find matching channel
	for(u = 0; u < data->channels; u++){
		if(!strcmp(spec, data->channel[u].path)){
			break;
		}
	}

	//allocate new channel
	if(u == data->channels){
		for(p = 0; p < data->patterns; p++){
			if(osc_path_match(data->pattern[p].path, spec)){
				break;
			}
		}

		data->channel = realloc(data->channel, (u + 1) * sizeof(osc_channel));
		if(!data->channel){
			fprintf(stderr, "Failed to allocate memory\n");
			return NULL;
		}

		memset(data->channel + u, 0, sizeof(osc_channel));
		data->channel[u].path = strdup(spec);
		if(p != data->patterns){
			fprintf(stderr, "Matched pattern %s for %s\n", data->pattern[p].path, spec);
			data->channel[u].params = data->pattern[p].params;
			//just reuse the pointers from the pattern
			data->channel[u].type = data->pattern[p].type;
			data->channel[u].max = data->pattern[p].max;
			data->channel[u].min = data->pattern[p].min;

			//these are per channel
			data->channel[u].in = calloc(data->channel[u].params, sizeof(osc_parameter_value));
			data->channel[u].out = calloc(data->channel[u].params, sizeof(osc_parameter_value));
		}
		else if(data->patterns){
			fprintf(stderr, "No pattern match found for %s\n", spec);
		}

		if(!data->channel[u].path
				|| (data->channel[u].params && (!data->channel[u].in || !data->channel[u].out))){
			fprintf(stderr, "Failed to allocate memory\n");
			return NULL;
		}
		data->channels++;
	}

	ident.fields.channel = u;
	return mm_channel(inst, ident.label, 1);
}

static int osc_output_channel(instance* inst, size_t channel){
	osc_instance_data* data = (osc_instance_data*) inst->impl;
	uint8_t xmit_buf[OSC_XMIT_BUF] = "", *format = NULL;
	size_t offset = 0, p;

	//fix destination rport if required
	if(data->forced_rport){
		//cheating a bit because both IPv4 and IPv6 have the port at the same offset
		struct sockaddr_in* sockadd = (struct sockaddr_in*) &(data->dest);
		sockadd->sin_port = htobe16(data->forced_rport);
	}

	//determine minimum packet size
	if(osc_align((data->root ? strlen(data->root) : 0) + strlen(data->channel[channel].path) + 1) + osc_align(data->channel[channel].params + 2)  >= sizeof(xmit_buf)){
		fprintf(stderr, "Insufficient buffer size for OSC transmitting channel %s.%s\n", inst->name, data->channel[channel].path);
		return 1;
	}

	//copy osc target path
	if(data->root){
		memcpy(xmit_buf, data->root, strlen(data->root));
		offset += strlen(data->root);
	}
	
	memcpy(xmit_buf + offset, data->channel[channel].path, strlen(data->channel[channel].path));
	offset += strlen(data->channel[channel].path) + 1;
	offset = osc_align(offset);

	//get format string offset, initialize
	format = xmit_buf + offset;
	offset += osc_align(data->channel[channel].params + 2);
	*format = ',';
	format++;

	for(p = 0; p < data->channel[channel].params; p++){
		//write format specifier
		format[p] = data->channel[channel].type[p];

		//write data
		if(offset + osc_data_length(data->channel[channel].type[p]) >= sizeof(xmit_buf)){
			fprintf(stderr, "Insufficient buffer size for OSC transmitting channel %s.%s at parameter %" PRIsize_t "\n", inst->name, data->channel[channel].path, p);
			return 1;
		}

		osc_deparse(data->channel[channel].type[p],
				data->channel[channel].out[p],
				xmit_buf + offset);
		offset += osc_data_length(data->channel[channel].type[p]);
	}

	//output packet
	if(sendto(data->fd, xmit_buf, offset, 0, (struct sockaddr*) &(data->dest), data->dest_len) < 0){
		fprintf(stderr, "Failed to transmit OSC packet: %s\n", strerror(errno));
	}
	return 0;
}

static int osc_set(instance* inst, size_t num, channel** c, channel_value* v){
	size_t evt = 0, mark = 0;
	int rv = 0;
	osc_channel_ident ident = {
		.label = 0
	};
	osc_parameter_value current;

	if(!num){
		return 0;
	}

	osc_instance_data* data = (osc_instance_data*) inst->impl;
	if(!data->dest_len){
		fprintf(stderr, "OSC instance %s does not have a destination, output is disabled (%" PRIsize_t " channels)\n", inst->name, num);
		return 0;
	}

	for(evt = 0; evt < num; evt++){
		ident.label = c[evt]->ident;

		//sanity check
		if(ident.fields.channel >= data->channels
				|| ident.fields.parameter >= data->channel[ident.fields.channel].params){
			fprintf(stderr, "OSC channel identifier out of range\n");
			return 1;
		}

		//if the format is unknown, don't output
		if(!data->channel[ident.fields.channel].params){
			fprintf(stderr, "OSC channel %s.%s requires format specification for output\n", inst->name, data->channel[ident.fields.channel].path);
			continue;
		}

		//only output on change
		current = osc_parameter_denormalise(data->channel[ident.fields.channel].type[ident.fields.parameter],
				data->channel[ident.fields.channel].min[ident.fields.parameter],
				data->channel[ident.fields.channel].max[ident.fields.parameter],
				v[evt]);
		if(memcmp(&current, &data->channel[ident.fields.channel].out[ident.fields.parameter], sizeof(current))){
			//update current value
			data->channel[ident.fields.channel].out[ident.fields.parameter] = current;
			//mark channel
			data->channel[ident.fields.channel].mark = 1;
			mark = 1;
		}
	}
	
	if(mark){
		//output all marked channels
		for(evt = 0; !rv && evt < num; evt++){
			ident.label = c[evt]->ident;
			if(data->channel[ident.fields.channel].mark){
				rv |= osc_output_channel(inst, ident.fields.channel);
				data->channel[ident.fields.channel].mark = 0;
			}
		}
	}
	return rv;
}

static int osc_process_packet(instance* inst, char* local_path, char* format, uint8_t* payload, size_t payload_len){
	osc_instance_data* data = (osc_instance_data*) inst->impl;
	size_t c, p, offset = 0;
	osc_parameter_value min, max, cur;
	channel_value evt;
	osc_channel_ident ident = {
		.label = 0
	};
	channel* chan = NULL;

	if(payload_len % 4){
		fprintf(stderr, "Invalid OSC packet, data length %" PRIsize_t "\n", payload_len);
		return 0;
	}

	for(c = 0; c < data->channels; c++){
		if(!strcmp(local_path, data->channel[c].path)){
			ident.fields.channel = c;
			//unconfigured input should work without errors (using default limits)
			if(data->channel[c].params && strlen(format) != data->channel[c].params){
				fprintf(stderr, "OSC message %s.%s had format %s, internal representation has %" PRIsize_t " parameters\n", inst->name, local_path, format, data->channel[c].params);
				continue;
			}

			for(p = 0; p < strlen(format); p++){
				ident.fields.parameter = p;
				if(data->channel[c].params){
					max = data->channel[c].max[p];
					min = data->channel[c].min[p];
				}
				else{
					osc_defaults(format[p], &max, &min);
				}
				cur = osc_parse(format[p], payload + offset);
				if(!data->channel[c].params || memcmp(&cur, &data->channel[c].in, sizeof(cur))){
					evt = osc_parameter_normalise(format[p], min, max, cur);
					chan = mm_channel(inst, ident.label, 0);
					if(chan){
						mm_channel_event(chan, evt);
					}
				}

				//skip to next parameter data
				offset += osc_data_length(format[p]);
				//TODO check offset against payload length
			}
		}
	}

	return 0;
}

static int osc_handle(size_t num, managed_fd* fds){
	size_t fd;
	char recv_buf[OSC_RECV_BUF];
	instance* inst = NULL;
	osc_instance_data* data = NULL;
	ssize_t bytes_read = 0;
	char* osc_fmt = NULL;
	char* osc_local = NULL;
	uint8_t* osc_data = NULL;

	for(fd = 0; fd < num; fd++){
		inst = (instance*) fds[fd].impl;
		if(!inst){
			fprintf(stderr, "OSC backend signaled for unknown fd\n");
			continue;
		}

		data = (osc_instance_data*) inst->impl;

		do{
			if(data->learn){
				data->dest_len = sizeof(data->dest);
				bytes_read = recvfrom(fds[fd].fd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr*) &(data->dest), &(data->dest_len));
			}
			else{
				bytes_read = recv(fds[fd].fd, recv_buf, sizeof(recv_buf), 0);
			}

			if(bytes_read <= 0){
				break;
			}

			if(data->root && strncmp(recv_buf, data->root, min(bytes_read, strlen(data->root)))){
				//ignore packet for different root
				continue;
			}
			osc_local = recv_buf + (data->root ? strlen(data->root) : 0);

			osc_fmt = recv_buf + osc_align(strlen(recv_buf) + 1);
			if(*osc_fmt != ','){
				//invalid format string
				fprintf(stderr, "Invalid OSC format string in packet\n");
				continue;
			}
			osc_fmt++;

			if(osc_global_config.detect){
				fprintf(stderr, "Incoming OSC data: Path %s.%s Format %s\n", inst->name, osc_local, osc_fmt);
			}

			//FIXME check supplied data length
			osc_data = (uint8_t*) osc_fmt + (osc_align(strlen(osc_fmt) + 2) - 1);

			if(osc_process_packet(inst, osc_local, osc_fmt, osc_data, bytes_read - (osc_data - (uint8_t*) recv_buf))){
				return 1;
			}
		} while(bytes_read > 0);

		#ifdef _WIN32
		if(bytes_read < 0 && WSAGetLastError() != WSAEWOULDBLOCK){
		#else
		if(bytes_read < 0 && errno != EAGAIN){
		#endif
			fprintf(stderr, "OSC failed to receive data for instance %s: %s\n", inst->name, strerror(errno));
		}

		if(bytes_read == 0){
			fprintf(stderr, "OSC descriptor for instance %s closed\n", inst->name);
			return 1;
		}
	}

	return 0;
}

static int osc_start(){
	size_t n, u, fds = 0;
	instance** inst = NULL;
	osc_instance_data* data = NULL;

	//fetch all instances
	if(mm_backend_instances(BACKEND_NAME, &n, &inst)){
		fprintf(stderr, "Failed to fetch instance list\n");
		return 1;
	}

	if(!n){
		free(inst);
		return 0;
	}

	//update instance identifiers
	for(u = 0; u < n; u++){
		data = (osc_instance_data*) inst[u]->impl;

		if(data->fd >= 0){
			inst[u]->ident = data->fd;
			if(mm_manage_fd(data->fd, BACKEND_NAME, 1, inst[u])){
				fprintf(stderr, "Failed to register OSC descriptor for instance %s\n", inst[u]->name);
				free(inst);
				return 1;
			}
			fds++;
		}
		else{
			inst[u]->ident = -1;
		}
	}

	fprintf(stderr, "OSC backend registered %" PRIsize_t " descriptors to core\n", fds);

	free(inst);
	return 0;
}

static int osc_shutdown(){
	size_t n, u, c;
	instance** inst = NULL;
	osc_instance_data* data = NULL;

	if(mm_backend_instances(BACKEND_NAME, &n, &inst)){
		fprintf(stderr, "Failed to fetch instance list\n");
		return 1;
	}

	for(u = 0; u < n; u++){
		data = (osc_instance_data*) inst[u]->impl;
		for(c = 0; c < data->channels; c++){
			free(data->channel[c].path);
			free(data->channel[c].in);
			free(data->channel[c].out);
		}
		free(data->channel);
		for(c = 0; c < data->patterns; c++){
			free(data->pattern[c].path);
			free(data->pattern[c].type);
			free(data->pattern[c].min);
			free(data->pattern[c].max);
		}
		free(data->pattern);

		free(data->root);
		if(data->fd >= 0){
			close(data->fd);
		}
		data->fd = -1;
		data->channels = 0;
		data->patterns = 0;
		free(inst[u]->impl);
	}

	free(inst);
	fprintf(stderr, "OSC backend shut down\n");
	return 0;
}