2016-01-05 04:12:47 +00:00
|
|
|
//
|
|
|
|
// CSMachine.m
|
|
|
|
// Clock Signal
|
|
|
|
//
|
|
|
|
// Created by Thomas Harte on 04/01/2016.
|
|
|
|
// Copyright © 2016 Thomas Harte. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
#import "CSMachine.h"
|
|
|
|
#import "CSMachine+Subclassing.h"
|
|
|
|
|
2016-01-14 03:38:59 +00:00
|
|
|
struct SpeakerDelegate: public Outputs::Speaker::Delegate {
|
|
|
|
__weak CSMachine *machine;
|
2016-01-15 01:33:22 +00:00
|
|
|
void speaker_did_complete_samples(Outputs::Speaker *speaker, const int16_t *buffer, int buffer_size) {
|
2016-01-14 03:38:59 +00:00
|
|
|
[machine speaker:speaker didCompleteSamples:buffer length:buffer_size];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-01-05 04:12:47 +00:00
|
|
|
typedef NS_ENUM(NSInteger, CSAtari2600RunningState) {
|
|
|
|
CSMachineRunningStateRunning,
|
|
|
|
CSMachineRunningStateStopped
|
|
|
|
};
|
|
|
|
|
|
|
|
@implementation CSMachine {
|
2016-01-14 03:38:59 +00:00
|
|
|
SpeakerDelegate _speakerDelegate;
|
2016-01-05 04:12:47 +00:00
|
|
|
|
|
|
|
dispatch_queue_t _serialDispatchQueue;
|
|
|
|
NSConditionLock *_runningLock;
|
|
|
|
}
|
|
|
|
|
|
|
|
- (void)perform:(dispatch_block_t)action {
|
|
|
|
dispatch_async(_serialDispatchQueue, action);
|
|
|
|
}
|
|
|
|
|
2016-01-15 01:33:22 +00:00
|
|
|
- (void)speaker:(Outputs::Speaker *)speaker didCompleteSamples:(const int16_t *)samples length:(int)length {
|
|
|
|
[self.audioQueue enqueueAudioBuffer:samples numberOfSamples:(unsigned int)length];
|
2016-01-14 03:38:59 +00:00
|
|
|
}
|
|
|
|
|
2016-01-05 04:12:47 +00:00
|
|
|
- (void)runForNumberOfCycles:(int)cycles {
|
|
|
|
if([_runningLock tryLockWhenCondition:CSMachineRunningStateStopped]) {
|
|
|
|
[_runningLock unlockWithCondition:CSMachineRunningStateRunning];
|
|
|
|
dispatch_async(_serialDispatchQueue, ^{
|
|
|
|
[_runningLock lockWhenCondition:CSMachineRunningStateRunning];
|
|
|
|
[self doRunForNumberOfCycles:cycles];
|
|
|
|
[_runningLock unlockWithCondition:CSMachineRunningStateStopped];
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-13 03:30:06 +00:00
|
|
|
- (void)sync {
|
|
|
|
dispatch_sync(_serialDispatchQueue, ^{});
|
|
|
|
}
|
|
|
|
|
2016-01-05 04:12:47 +00:00
|
|
|
- (instancetype)init {
|
|
|
|
self = [super init];
|
|
|
|
|
|
|
|
if (self) {
|
|
|
|
_serialDispatchQueue = dispatch_queue_create("Machine queue", DISPATCH_QUEUE_SERIAL);
|
|
|
|
_runningLock = [[NSConditionLock alloc] initWithCondition:CSMachineRunningStateStopped];
|
2016-01-14 03:38:59 +00:00
|
|
|
|
|
|
|
_speakerDelegate.machine = self;
|
|
|
|
[self setSpeakerDelegate:&_speakerDelegate sampleRate:44100];
|
2016-01-05 04:12:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return self;
|
|
|
|
}
|
|
|
|
|
2016-01-14 03:38:59 +00:00
|
|
|
- (BOOL)setSpeakerDelegate:(Outputs::Speaker::Delegate *)delegate sampleRate:(int)sampleRate {
|
|
|
|
return NO;
|
|
|
|
}
|
2016-01-05 04:40:43 +00:00
|
|
|
- (void)doRunForNumberOfCycles:(int)numberOfCycles {}
|
|
|
|
|
2016-01-05 04:12:47 +00:00
|
|
|
@end
|