package org.openkinect;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.Iterator;
import org.openkinect.Device;
public class Freenect implements Runnable
{
private static final int DEVICE_MOTOR = 0x01;
private static final int DEVICE_CAMERA = 0x02;
private static final int DEVICE_AUDIO = 0x04;
static {
System.loadLibrary("javakinect");
}
public Freenect() {
p_context = freenectInit();
if(this.p_context == 0)
throw new RuntimeException("Freenect context could not be initialized");
freenectSelectSubdevices(p_context, subdevices());
usb_processor = new Thread(this, "USB Processor");
usb_processor.start();
}
public Device open(int device_id)
{
Long dev = pointer_map.get(device_id);
if(dev == null) {
dev = freenectDevice(p_context, device_id);
if(dev != 0)
pointer_map.put(device_id, dev);
else
throw new RuntimeException("Freenect could not opened kinect devcie");
}
return new Device(dev);
}
public int devices()
{
return freenectNumDevices(p_context);
}
public native int subdevices();
public void shutdown()
{
Collection<Long> pointers = pointer_map.values();
Iterator<Long> it = pointers.iterator();
while(it.hasNext()) {
long p_device = it.next().longValue();
freenectCloseDevice(p_device);
}
try {
is_running = false;
usb_processor.join();
} catch(InterruptedException e) {
throw new RuntimeException("Freenect is interrupted waiting for usb processing thread");
}
freenectShutdown(this.p_context);
}
public void run()
{
freenectSetCallbackContextInfo();
while(is_running) {
if(!freenectProcessEvents(this.p_context, 2))
throw new RuntimeException("Freenect failed in processing usb events");
}
}
private long p_context;
private Thread usb_processor;
private static volatile boolean is_running = true;
private Map<Integer, Long> pointer_map = new HashMap<Integer, Long>();
private native void freenectSetCallbackContextInfo();
private native long freenectInit();
private native boolean freenectSelectSubdevices(long p_context, int flags);
private native int freenectNumDevices(long p_context);
private native boolean freenectProcessEvents(long p_context, int timeout_in_s);
private native boolean freenectShutdown(long p_context);
private native long freenectDevice(long p_context, int device_id);
private native boolean freenectCloseDevice(long p_device);
};