Source

kinect-viewer / KFKinect.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 "KFKinect.h"
#import "libfreenect.h"

@interface KFKinect ()
- (void)ioThread;
- (void)depthCallback: (freenect_depth *)buffer;
- (void)rgbCallback: (freenect_pixel *)buffer;
@end

static void depthCallback(freenect_device *dev, freenect_depth *depth, uint32_t timestamp) {
  [(KFKinect *)freenect_get_user(dev) depthCallback:depth];
}
static void rgbCallback(freenect_device *dev, freenect_pixel *rgb, uint32_t timestamp) {
  [(KFKinect *)freenect_get_user(dev) rgbCallback:rgb];
}

@implementation KFKinect

- initWithDepthDelegate: (id<KFKinectDepthDelegate>)dd
          colorDelegate: (id<KFKinectColorDelegate>)cd {
	if (![super init]) return nil;
	
	_running = NO;
	depthDelegate = dd;
  colorDelegate = cd;
	return self;
}

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

- (void)close {
  _running = NO;
}

- (void)ioThread
{
	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);
      if (depthDelegate) freenect_start_depth(_device);
      if (colorDelegate) 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");
	}
}

- (void)depthCallback: (freenect_depth *)buffer {
	[depthDelegate depthFieldUpdated: (const depth_t *)buffer from: self];
}

- (void)rgbCallback: (freenect_pixel *)buffer {
	[colorDelegate colorFieldUpdated: (const colors_t *)buffer from: self];
}

@end