//
//  TestController.m
//  SequenceGrabberTest
//
//  Created by Tim Omernick on 3/18/05.
//  Copyright 2005 Tim Omernick. All rights reserved.
//

#import "TestController.h"

#import <CocoaSequenceGrabber/CocoaSequenceGrabber.h>

// Only define one of these at a time
//#define INSTANT_RATE
//#define AVG_RATE
#define PULL_RATE

static const int frameCount = 10;

@implementation TestController

// Init and dealloc
- (id)init
{
	if( self = [super init] )
	{
		// Start recording
		camera = [[CSGCamera alloc] init];
		[camera setDelegate:self];
		cameraStarted = NO;
		index = 0;
		for( int i=0; i<frameCount; ++i )
			rates[i] = 0.0;
		lastPulledTime = -1.0;
		[self setVideoWidth:320];
		[self setVideoHeight:240];
//		[camera startWithSize:NSMakeSize(640, 480)];		
	}
	return self;
}


- (void)dealloc;
{
	if( cameraStarted )
		[camera stop];
	[camera release];
	[lastImage release];
	[super dealloc];
}

- (CSGImage *)lastImage
{
#ifdef PULL_RATE
	NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
	if( lastPulledTime > -1.0 )
		rates[index++] = now - lastPulledTime;
	lastPulledTime = now;
	if( index >= frameCount ) index = 0;
#endif
    return [[lastImage retain] autorelease];
}

- (void)setLastImage:(CSGImage *)value
{
    if (lastImage != value)
	{
		if( lastImage )
		{
#ifdef INSTANT_RATE
			NSTimeInterval diff = [value sampleTime] - [lastImage sampleTime];
			rates[0] = 1.0/diff;
#elif AVG_RATE
			NSTimeInterval diff = [value sampleTime] - [lastImage sampleTime];
			rates[index++] = diff;
			if( index >= frameCount ) index = 0;
#endif
		}
		
        [lastImage release];
        lastImage = [value retain];
    }
}

- (NSTimeInterval)frameRate
{
#ifdef INSTANT_RATE
	return rates[0];
#elifdef AVG_RATE
	NSTimeInterval rate = 0.0;
	for( int i=0; i<frameCount; ++i )
		rate += rates[i];
	return frameCount / rate;
#endif
#ifdef PULL_RATE
	NSTimeInterval rate = 0.0;
	for( int i=0; i<frameCount; ++i )
		rate += rates[i];
	return frameCount / rate;
#endif
}

- (float)videoWidth {
    return videoWidth;
}

- (void)setVideoWidth:(float)value {
    if (videoWidth != value) {
        videoWidth = value;
    }
}

- (float)videoHeight {
    return videoHeight;
}

- (void)setVideoHeight:(float)value {
    if (videoHeight != value) {
        videoHeight = value;
    }
}

- (BOOL)cameraStarted
{
    return cameraStarted;
}

- (void)start
{
	cameraStarted = [camera startWithSize:NSMakeSize( videoWidth, videoHeight )]; // Preference
}

- (void)stop
{
	if( cameraStarted )
		[camera stop];
	
	for( int i=0; i<frameCount; ++i )
		rates[i] = 0.0;
}

// CSGCamera delegate

- (void)camera:(CSGCamera *)aCamera didReceiveFrame:(CSGImage *)aFrame;
{
	[self setLastImage:aFrame];
}

// NSWindow delegate

- (void)windowWillClose:(NSNotification *)notification;
{
	[camera stop];
}

@end
