Source

kinect-viewer / KVKinectHardware.m

Full commit
/*
 * Copyright 2010 Cliff L. Biffle.  All Rights Reserved.
 * Use of this source code is governed by the Apache License 2.0,
 * which can be found in the LICENSE file.
 */

#import "KVKinectHardware.h"
#import <pthread.h>
#import "libfreenect.h"

@interface KVKinectHardware ()
- (void)ioThread;

@property (assign) NSData *latestDepthSamples;
@property (assign) NSData *latestColorSamples;
@end

static void depthCallback(freenect_device *dev, freenect_depth *depth, uint32_t timestamp) {
  ((KVKinectHardware *)freenect_get_user(dev)).latestDepthSamples =
      [NSData dataWithBytesNoCopy: depth length: (640 * 480 * sizeof(uint16_t)) freeWhenDone: NO];
}
static void rgbCallback(freenect_device *dev, freenect_pixel *rgb, uint32_t timestamp) {
  ((KVKinectHardware *)freenect_get_user(dev)).latestColorSamples =
      [NSData dataWithBytesNoCopy: rgb length: (640 * 480 * 3) freeWhenDone: NO];
}

@implementation KVKinectHardware

@synthesize latestDepthSamples, latestColorSamples;

- (void)open {
 	[NSThread detachNewThreadSelector:@selector(ioThread) toTarget:self withObject:nil]; 
}

- (void)close {
  running = NO;
}

- (void)ioThread
{
  [[NSThread currentThread] setName: @"kinect-io-thread"];
  pthread_setname_np("kinect-io-thread");
  
  running = YES;
  
	if(freenect_init(&context, NULL) >= 0) {
    if(freenect_open_device(context, &device, 0) >= 0) {
      freenect_set_user(device, self);
      freenect_set_depth_callback(device, depthCallback);
      freenect_set_rgb_callback(device, rgbCallback);
      freenect_set_rgb_format(device, FREENECT_FORMAT_RGB);
      freenect_set_depth_format(device, FREENECT_FORMAT_11_BIT);
      freenect_start_depth(device);
      freenect_start_rgb(device);
      
      NSLog(@"wheeee");
      
      while(running && freenect_process_events(context) >= 0);
      
      freenect_close_device(device);
      device = NULL;
      
      NSLog(@"Stopped");
    } else {
      NSLog(@"Could not open device");
    }
    freenect_shutdown(context);
    context = NULL;
  } else {
		NSLog(@"Could not init device");
	}
}

@end