aboutsummaryrefslogtreecommitdiff
path: root/src/pdj.c
blob: d76c4f93c7dcfef833400f2e71cbaaf6e7192d86 (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
#include <stdlib.h>
#include "pdj.h"
#include "type_handler.h"

JavaVM *jni_jvm = NULL;
t_class *inlet_proxy;
t_class *pdj_class;

#define PDTHREAD_STACKSIZE 1000000
static JNIEnv *pdthread_jnienv = NULL; 
static char *pdthread_stackaddr;

#define PROF_MIN 999

double prof_max = 0, prof_min = PROF_MIN, prof_tot = 0, prof_nb = 0, prof_tmp;

JNIEnv *pdjAttachVM() {
	const int N_REFS = 16;
	JNIEnv *env;
	char stack_pos; /* the position of this variable is relative to the 
	                   position in the stack of the main thread */
	
	PROF(prof_tmp = sys_getrealtime(););
	
	/* this avoids getting the JNIEnv when we are in the main thread. so
	 * if the current stack is more far than 1 meg of distance between the 
	 * main thread stack when pdj was initialized, it is considered a 
	 * "external thread"
	 */
	if ( abs(pdthread_stackaddr - (&stack_pos)) > PDTHREAD_STACKSIZE ) {
		(*jni_jvm)->AttachCurrentThread(jni_jvm, (void **)&env, NULL);	
		ASSERT(env);
	} else {
		env = pdthread_jnienv;
	}
	
	if ( (*env)->PushLocalFrame(env, N_REFS) < 0 ) {
		SHOWEXC;
		bug("pdj: java: out of memory!?!");
	}
	
	return env;
}


void pdjDetachVM(JNIEnv *env) {
#ifdef DEBUG
	if ( (*env)->ExceptionOccurred(env) ) {
		error("pdj: unhandled exception in JNI interface:");
		(*env)->ExceptionDescribe(env);
	}
#endif
	(*env)->PopLocalFrame(env, NULL);
	
	PROF(prof_tmp = sys_getrealtime() - prof_tmp;);
	PROF(prof_max = prof_tmp > prof_max ? prof_tmp : prof_max;);
	PROF(prof_min = prof_tmp < prof_min ? prof_tmp : prof_min;);
	PROF(prof_nb++;);
	PROF(prof_tot += prof_tmp;);
}


static void pdj_mapmethods(JNIEnv *env, t_pdj *pdj) {
	jclass base = pdjCaching.cls_MaxObject;
	jmethodID idBase, id;
	JASSERT(base);	
	
	id     = (*env)->GetMethodID(env, pdj->cls, "bang", "()V");
	idBase = (*env)->GetMethodID(env, base, "bang", "()V");
	(*env)->ExceptionClear(env);	
	if ( id != idBase ) {
		pdj->MIDbang = id;
	} else {
		pdj->MIDbang = NULL;
	}

	id     = (*env)->GetMethodID(env, pdj->cls, "inlet", "(F)V");
	idBase = (*env)->GetMethodID(env, base, "inlet", "(F)V");
	(*env)->ExceptionClear(env);		
	if ( id != idBase ) {
		pdj->MIDfloat = id;
	} else {
		pdj->MIDfloat = NULL;
		id     = (*env)->GetMethodID(env, pdj->cls, "inlet", "(I)V");
		idBase = (*env)->GetMethodID(env, base, "inlet", "(I)V");
		(*env)->ExceptionClear(env);		
		if ( id != idBase ) {
			pdj->MIDint = id;
		} else {
			pdj->MIDint = NULL;
		}		
	}

	id     = (*env)->GetMethodID(env, pdj->cls, "list", "([com/cycling74/max/Atom;)V");	
	idBase = (*env)->GetMethodID(env, base, "list", "([com/cycling74/max/Atom;)V");	
	(*env)->ExceptionClear(env);	
	if ( id != idBase ) {
		pdj->MIDlist = id;
	} else {
		pdj->MIDlist = NULL;
	}
	
	idBase = (*env)->GetMethodID(env, pdj->cls, "anything", "(Ljava/lang/String;[Lcom/cycling74/max/Atom;)V");	
	pdj->MIDanything = idBase;
}


static jobject init_pdj_class(JNIEnv *env, char *name, long cobj, int argc, t_atom *argv) {
	char *sig = "(Ljava/lang/String;J[Lcom/cycling74/max/Atom;)Lcom/cycling74/max/MaxObject;";
	jstring objectName;
	jmethodID id;
	jobject newMaxObject;
	jobjectArray args;
	jlong jval = cobj;
	
	id = (*env)->GetStaticMethodID(env, pdjCaching.cls_MaxObject, "registerObject", sig);
	JASSERT(id);

	objectName = (*env)->NewStringUTF(env, name);
	JASSERT(objectName);
	
	args = atoms2jatoms(env, argc, argv);
	JASSERT(args);

	newMaxObject = (*env)->CallStaticObjectMethod(env, pdjCaching.cls_MaxObject, id, objectName, jval, args);
	if ( (*env)->ExceptionOccurred(env) ) {
		(*env)->ExceptionDescribe(env);
	}
	if ( newMaxObject != NULL ) {
        jobject global = (*env)->NewGlobalRef(env, newMaxObject);
		(*env)->DeleteLocalRef(env, newMaxObject);        
		return global;
	}
	return NULL;
}


void *pdj_new(t_symbol *s, int argc, t_atom *argv) {
	JNIEnv *env = NULL; 
    t_pdj *x;

	if ( argc < 1 ) { 
		post("pdj: no class specified");
		return NULL;
	}

	if ( argv[0].a_type != A_SYMBOL ) {
		post("pdj: first argument must be a class name");
		return NULL;
	}
	
	if ( jni_jvm == NULL ) {
		env = init_jvm();	
		if ( env == NULL )
			return NULL;
	} else {
		(*jni_jvm)->AttachCurrentThread(jni_jvm, (void **)&env, NULL);
		ASSERT(env);
	}

	pdthread_jnienv = env;

	if ( s == gensym("pdj~") ) {
		x = (t_pdj *)pd_new(pdj_tilde_class);
	} else {
		x = (t_pdj *)pd_new(pdj_class);
	}
	ASSERT(x);
	x->jobject_name = argv[0].a_w.w_symbol->s_name;
	x->nb_inlet = 0;
    x->patch_path = canvas_getcurrentdir()->s_name;

    x->cache = NULL;
	x->obj = init_pdj_class(env, x->jobject_name, (long) x, argc, argv);

	if ( x->obj != NULL ) {
		jclass cls = (*env)->GetObjectClass(env, x->obj);
        JASSERT(cls);
        
        x->cls = (*env)->NewGlobalRef(env, cls); 
        pdj_mapmethods(env, x);
		return x;
	}
 	
	return NULL;
}


static void pdj_profiler(t_pdj *pdj) {
	if ( prof_nb != 0 )
		post("pdj-profiler: %f min %f max %f avg", prof_min, prof_max, prof_tot / prof_nb);
	prof_min = PROF_MIN;
	prof_max = 0;
	prof_tot = 0;
	prof_nb  = 0;
}


void pdj_free(t_pdj *pdj) {
	JNIEnv *env = pdjAttachVM();
	jmethodID id = (*env)->GetMethodID(env, pdj->cls, "notifyDeleted", "()V");
	JASSERT(id);
	
	(*env)->CallVoidMethod(env, pdj->obj, id);
	SHOWEXC;

	PROF(pdj_profiler(pdj););
	
	while (pdj->cache != NULL) {
		t_pdjcached_sym *next = pdj->cache->next;
		free(pdj->cache);
		pdj->cache = next;		
	}
	
	(*env)->DeleteGlobalRef(env, pdj->cls);
	(*env)->DeleteGlobalRef(env, pdj->obj);

	pdjDetachVM(env);	
}


static void pdj_addcache_sym(t_pdj *pdj, t_symbol *s, jmethodID id, int arged) {
	t_pdjcached_sym *n = malloc(sizeof(t_pdjcached_sym));
	
	n->sym = s;
	n->mid = id;
	n->arged = arged;
	n->next = pdj->cache;

	pdj->cache = n;	
}


static void pdj_process_inlet(int idx, t_pdj *pdj, t_symbol *s, int argc, t_atom atoms[]){
	JNIEnv *env = pdjAttachVM();
	jobjectArray args = NULL;
	t_pdjcached_sym *cache;
	jmethodID id;
	jboolean rc;
	jstring s_name;
	
	(*env)->SetIntField(env, pdj->obj, pdjCaching.FIDMaxObject_activity_inlet, idx);
	
	if ( s == &s_bang ) {
		if ( pdj->MIDbang != NULL ) {
			(*env)->CallVoidMethod(env, pdj->obj, pdj->MIDbang);
			SHOWEXC;
			pdjDetachVM(env);
			return;
		}
	} else if ( s == &s_float ) {
		if ( pdj->MIDfloat != NULL ) {
			(*env)->CallVoidMethod(env, pdj->obj, pdj->MIDfloat, atom_getfloatarg(0, argc, atoms));
			SHOWEXC;
			pdjDetachVM(env);
			return;
		}
		if ( pdj->MIDint != NULL ) {
			(*env)->CallVoidMethod(env, pdj->obj, pdj->MIDint, atom_getintarg(0, argc, atoms));
			SHOWEXC;
			pdjDetachVM(env);
			return;
		}
	} else if ( s == &s_list ) {
		if ( pdj->MIDlist != NULL ) {
			args = atoms2jatoms(env, argc, atoms);
			JASSERT(args);
			(*env)->CallVoidMethod(env, pdj->obj, pdj->MIDlist, args);
			SHOWEXC;
			pdjDetachVM(env);
			return;
		}
	}

	/* is the symbol in cache ? */
	cache = pdj->cache;
	while( cache != NULL ) {
		if ( cache->sym == s ) {
			if ( ! cache->arged ) {	
				(*env)->CallVoidMethod(env, pdj->obj, cache->mid, NULL);
			} else {
				args = atoms2jatoms(env, argc, atoms);
				JASSERT(args);
				(*env)->CallVoidMethod(env, pdj->obj, cache->mid, args);
			}
			SHOWEXC;
			pdjDetachVM(env);
			return;
		}
		cache = cache->next;
	}

	/* the last tries will require a Atom[] arguments */
	args = atoms2jatoms(env, argc, atoms);
	JASSERT(args);
		
	/* try with [name](Atom []) */
	id = (*env)->GetMethodID(env, pdj->cls, s->s_name, "([Lcom/cycling74/max/Atom;)V");
	(*env)->ExceptionClear(env);
	if ( id != NULL ) {
		(*env)->CallVoidMethod(env, pdj->obj, id, args);
		SHOWEXC;
		pdjDetachVM(env);
		pdj_addcache_sym(pdj, s, id, 1);
		return;
	}

	/* try again with [name]() */ 
	id = (*env)->GetMethodID(env, pdj->cls, s->s_name, "()V");
	(*env)->ExceptionClear(env);
	if ( id != NULL ) {
		(*env)->CallVoidMethod(env, pdj->obj, id, NULL);
		SHOWEXC;
		pdjDetachVM(env);
		pdj_addcache_sym(pdj, s, id, 0);
		return;
	}
	
	s_name = (*env)->NewStringUTF(env, s->s_name);
	JASSERT(s_name);			
	
	/* try with the setter */		
	rc = (*env)->CallBooleanMethod(env, pdj->obj, pdjCaching.MIDMaxObject_trySetter, s_name, args);
	if ( (*env)->ExceptionCheck(env) == 1 ) {
		/* we got an exception, the class do have a setter, but it trowed an
		 * exception: log it and don't try with anything() 
		 */
		(*env)->ExceptionDescribe(env);
		rc = 1;	
	}
	
	if ( rc == 0 ) {
		/* nothing... call the anything method anything... */
		(*env)->CallVoidMethod(env, pdj->obj, pdj->MIDanything, s_name, args);
		SHOWEXC;
	}
	
	// TODO: setters should be cached too
	pdjDetachVM(env);
}


static void pdj_anything(t_pdj *pdj, t_symbol *s, int argc, t_atom atoms[]){
	pdj_process_inlet(0, pdj, s, argc, atoms);
}


static void inlet_proxy_anything(t_inlet_proxy *proxy, t_symbol *s, int argc, t_atom atoms[]){
	pdj_process_inlet(proxy->idx, proxy->peer, s, argc, atoms);
}


static void pdj_loadbang(t_pdj *pdj) {
	JNIEnv *env = pdjAttachVM();
	jmethodID id = (*env)->GetMethodID(env, pdj->cls, "loadbang", "()V");
	JASSERT(id);
	
	(*env)->CallVoidMethod(env, pdj->obj, id, NULL);
	SHOWEXC;

	pdjDetachVM(env);
}


void pdj_setup(void) {
	char stack_pos;
	
    pdj_class = class_new(gensym("pdj"), 
        (t_newmethod)pdj_new, (t_method)pdj_free,
        sizeof(t_pdj), CLASS_DEFAULT|CLASS_NOINLET, A_GIMME, 0);
        
	class_addmethod(pdj_class, (t_method)pdj_loadbang, gensym("loadbang"), 
		A_CANT, A_NULL);
	class_addanything(pdj_class, (t_method)pdj_anything);
	
	/* pdj~ things */
    pdj_tilde_class = class_new(gensym("pdj~"), 
        (t_newmethod)pdj_tilde_new, (t_method)pdj_tilde_free,
        sizeof(t_pdj_tilde), CLASS_DEFAULT|CLASS_NOINLET, A_GIMME, 0);
        
	class_addmethod(pdj_tilde_class, (t_method)pdj_loadbang, gensym("loadbang"), 
		A_CANT, A_NULL);
	class_addanything(pdj_tilde_class, (t_method)pdj_anything);
    class_addmethod(pdj_tilde_class, (t_method)pdj_tilde_dsp, gensym("dsp"), 0);
    CLASS_MAINSIGNALIN(pdj_tilde_class, t_pdj_tilde, _dummy_f);
    
    /* inlet_proxy: we create a dummy class to catch all messages from cold
     * inlets */
	inlet_proxy = class_new(gensym("pdj_inlet_proxy"),
		NULL,NULL, sizeof(t_inlet_proxy),
		CLASS_PD|CLASS_NOINLET, A_NULL);
	class_addanything(inlet_proxy, (t_method)inlet_proxy_anything);

	/* main thread stack address */	
	pdthread_stackaddr = (void *) &(stack_pos);
}