CQTexperiment
vspader 2006-01-20 15:34:02 +00:00
parent 9887423c33
commit 733d0d78d0
59 changed files with 1544 additions and 319 deletions

View File

@ -1,30 +0,0 @@
//
// Controller.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/7/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface SoundController : NSObject {
InputController *input;
OutputController *output;
Converter *converter;
NSLock *outputLock;
NSLock *inputLock;
Semaphore *conversionSemaphore;
Semaphore *ioSemaphore;
NSMutableArray *amountConverted;
unsigned int amountPlayed; //when amountPlayed > amountConverted[0], amountPlayed -= amountConverted[0], pop(amountConverted[0]), song changed
}
- (void)convertedAmount:(int)amount; //called by converter...same thread?
- (void)playedAmount:(int)amount; //called by outputcontroller...different thread
@end

View File

@ -1,14 +0,0 @@
//
// Controller.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/7/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "Controller.h"
@implementation SoundController
@end

View File

@ -1,22 +0,0 @@
//
// Converter.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface Converter : NSObject {
SoundController *soundController;
}
- (void)setup;
- (void)cleanUp;
- (void)process;
- (int)convert:(void *)dest amount:(int)amount;
@end

View File

@ -1,116 +0,0 @@
//
// Converter.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "Converter.h"
@implementation Converter
//called from the complexfill when the audio is converted...good clean fun
static OSStatus ACInputProc(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets, AudioBufferList* ioData, AudioStreamPacketDescription** outDataPacketDescription, void* inUserData)
{
SoundController *soundController = (SoundController *)inUserData;
OSStatus err = noErr;
int amountToWrite;
int amountWritten;
amountToWrite = (*ioNumberDataPackets)*[[soundController input] format].mBytesPerPacket;
availInput = [[[soundController input] buffer] amountAvailableToReadReturningBuffer:&readPtr];
while (availInput == 0)
{
[conversionSemaphore wait];
availInput = [[[soundController input] buffer] amountAvailableToReadReturningBuffer:&readPtr];
}
if (availInput > amountToWrite)
availInput = amountToWrite;
*ioNumberDataPackets = availInput/format->mBytesPerPacket;
ioData->mBuffers[0].mData = readPtr;
ioData->mBuffers[0].mDataByteSize = availInput;
ioData->mBuffers[0].mNumberChannels = [[soundController input] format].mChannelsPerFrame;
ioData->mNumberBuffers = 1;
return err;
}
-(void)process
{
void *writePtr;
int availOutput;
int amountConverted;
while ([soundController shouldContinue] == YES)
{
[[soundController outputLock] lock];
availOutput = [[[soundController output] buffer] amountAvailableToWriteReturningBuffer:&writePtr];
while (availOutput == 0)
{
[[soundController outputLock] unlock];
[conversionSemaphore wait];
[[soundController outputLock] lock];
availOutput = [[[soundController output] buffer] amountAvailableToWriteReturningBuffer:&writePtr];
}
amountConverted = [self convert:writePtr amount:availOutput];
[[[soundController output] buffer] didWriteAmount:amountConverted];
[[soundController outputLock] unlock];
}
}
- (int)convert:(void *)dest amount:(int)amount
{
AudioBufferList ioData;
UInt32 ioNumberFrames;
OSStatus err;
ioNumberFrames = amount/[[soundController output] format].mBytesPerFrame;
ioData.mBuffers[0].mData = dest;
ioData.mBuffers[0].mDataByteSize = amount;
ioData.mBuffers[0].mNumberChannels = [[soundController output] format].mChannelsPerFrame;
ioData.mNumberBuffers = 1;
[[soundController inputLock] lock];
err = AudioConverterFillComplexBuffer(converter, ACInputProc, &[[soundController input] format], &ioNumberFrames, &ioData, NULL);
if (err != noErr)
DBLog(@"Converter error: %i", err);
[[soundController input] buffer] didReadLength:(ioNumberFrames * [[[soundController input] format].mBytesPerFrame]);
[[soundController inputLock] unlock];
[[soundController ioSemaphore] signal];
return ioData.mBuffers[0].mDataByteSize;
}
- (void)setup
{
//Make the converter
OSStatus stat = noErr;
stat = AudioConverterNew ( &sourceStreamFormat, &deviceFormat, &converter);
// DBLog(@"Created converter");
if (stat != noErr)
{
DBLog(@"Error creating converter %i", stat);
}
}
- (void)cleanUp
{
AudioConverterDispose(converter);
}
@end

View File

@ -1,17 +0,0 @@
//
// InputController.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface InputController : NSObject {
VirtualRingBuffer *buffer;
AudioStreamBasicDescription format;
}
@end

View File

@ -1,19 +0,0 @@
//
// InputController.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "InputController.h"
@implementation InputController
- (void)play
{
[soundFile open:filename];
}
@end

View File

@ -1,17 +0,0 @@
//
// OutputController.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface OutputController : NSObject {
VirtualRingBuffer *buffer;
AudioStreamBasicDescription format;
}
@end

View File

@ -1,14 +0,0 @@
//
// OutputController.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "OutputController.h"
@implementation OutputController
@end

View File

@ -1,20 +0,0 @@
//
// OutputCoreAudio.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface OutputCoreAudio : NSObject {
}
- (void)setup;
- (void)start;
- (void)stop;
@end

18
Playlist/Shuffle.h Normal file
View File

@ -0,0 +1,18 @@
//
// Shuffle.h
// Cog
//
// Created by Zaphod Beeblebrox on 1/14/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface Shuffle : NSObject {
}
+ (NSMutableArray *)shuffleList:(NSArray *)l;
@end

52
Playlist/Shuffle.m Normal file
View File

@ -0,0 +1,52 @@
//
// Shuffle.m
// Cog
//
// Created by Zaphod Beeblebrox on 1/14/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import "Shuffle.h"
@implementation Shuffle
int sum(int n)
{
return (n*n+n)/2;
}
int reverse_sum(int n)
{
return (int)(ceil((-1.0 + sqrt(1.0 + 8.0*n))/2.0));
}
int randint(int low, int high)
{
return (random()%high)+low;
}
+ (NSMutableArray *)shuffleList:(NSArray *)l
{
NSMutableArray *a = [l mutableCopy];
NSMutableArray *b = [[NSMutableArray alloc] init];
while([a count] > 0)
{
int t, r, p;
t = sum([a count]);
r = randint(1, t);
p = reverse_sum(r) - 1;
printf("%i, %i, %i, %i\n", [a count], t, r, p);
[b insertObject:[a objectAtIndex:p] atIndex:0];
[a removeObjectAtIndex:p];
}
[a release];
return [b autorelease];
}
@end

34
Sound/BufferChain.h Normal file
View File

@ -0,0 +1,34 @@
//
// InputChain.h
// CogNew
//
// Created by Zaphod Beeblebrox on 1/4/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "InputNode.h"
#import "ConverterNode.h"
#import "SoundController.h"
@interface BufferChain : NSObject {
InputNode *inputNode;
ConverterNode *converterNode;
NSArray *effects; //Not needed as of now, but for EFFECTS PLUGINS OF THE FUTURE!
id finalNode; //Final buffer in the chain.
id soundController;
}
- (id)initWithController:(id)c;
- (void)buildChain;
- (BOOL)open:(const char *)filename;
- (void)launchThreads;
- (id)finalNode;
@end

63
Sound/BufferChain.m Normal file
View File

@ -0,0 +1,63 @@
//
// InputChain.m
// CogNew
//
// Created by Zaphod Beeblebrox on 1/4/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import "BufferChain.h"
#import "OutputNode.h"
@implementation BufferChain
- (id)initWithController:(id)c
{
self = [super init];
if (self)
{
soundController = c;
}
return self;
}
- (void)buildChain
{
inputNode = [[InputNode alloc] initWithController:soundController previous:nil];
converterNode = [[ConverterNode alloc] initWithController:soundController previous:inputNode];
finalNode = converterNode;
}
- (BOOL)open:(NSString *)filename
{
[self buildChain];
[inputNode open:filename];
[converterNode setupWithInputFormat:(AudioStreamBasicDescription)[inputNode format] outputFormat:[[soundController output] format] ];
return YES;
}
- (void)launchThreads
{
DBLog(@"LAUNCHING THREAD FOR INPUT");
[inputNode launchThread];
DBLog(@"LAUNCHING THREAD FOR CONVERTER");
[converterNode launchThread];
}
- (id)finalNode
{
return finalNode;
}
- (void)setShouldContinue:(BOOL)s
{
[inputNode setShouldContinue:s];
[converterNode setShouldContinue:s];
}
@end

31
Sound/ConverterNode.h Normal file
View File

@ -0,0 +1,31 @@
//
// Converter.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <CoreAudio/AudioHardware.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AudioUnit/AudioUnit.h>
#import "Node.h"
@interface ConverterNode : Node {
AudioConverterRef converter;
void *callbackBuffer;
AudioStreamBasicDescription inputFormat;
AudioStreamBasicDescription outputFormat;
}
- (void)setupWithInputFormat:(AudioStreamBasicDescription)inputFormat outputFormat:(AudioStreamBasicDescription)outputFormat;
- (void)cleanUp;
- (void)process;
- (int)convert:(void *)dest amount:(int)amount;
@end

214
Sound/ConverterNode.m Normal file
View File

@ -0,0 +1,214 @@
//
// Converter.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "ConverterNode.h"
#define BUFFER_SIZE 512 * 1024
#define CHUNK_SIZE 16 * 1024
void PrintStreamDesc (AudioStreamBasicDescription *inDesc)
{
if (!inDesc) {
printf ("Can't print a NULL desc!\n");
return;
}
printf ("- - - - - - - - - - - - - - - - - - - -\n");
printf (" Sample Rate:%f\n", inDesc->mSampleRate);
printf (" Format ID:%s\n", (char*)&inDesc->mFormatID);
printf (" Format Flags:%lX\n", inDesc->mFormatFlags);
printf (" Bytes per Packet:%ld\n", inDesc->mBytesPerPacket);
printf (" Frames per Packet:%ld\n", inDesc->mFramesPerPacket);
printf (" Bytes per Frame:%ld\n", inDesc->mBytesPerFrame);
printf (" Channels per Frame:%ld\n", inDesc->mChannelsPerFrame);
printf (" Bits per Channel:%ld\n", inDesc->mBitsPerChannel);
printf ("- - - - - - - - - - - - - - - - - - - -\n");
}
@implementation ConverterNode
//called from the complexfill when the audio is converted...good clean fun
static OSStatus ACInputProc(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets, AudioBufferList* ioData, AudioStreamPacketDescription** outDataPacketDescription, void* inUserData)
{
ConverterNode *converter = (ConverterNode *)inUserData;
id previousNode = [converter previousNode];
OSStatus err = noErr;
void *readPtr;
int amountToWrite;
int availInput;
if ([converter shouldContinue] == NO)
{
ioData->mBuffers[0].mDataByteSize = 0;
*ioNumberDataPackets = 0;
return noErr;
}
amountToWrite = (*ioNumberDataPackets)*(converter->inputFormat.mBytesPerPacket);
availInput = [[previousNode buffer] lengthAvailableToReadReturningPointer:&readPtr];
if (availInput == 0 )
{
// NSLog(@"0 INPUT");
ioData->mBuffers[0].mDataByteSize = 0;
*ioNumberDataPackets = 0;
if ([previousNode endOfInput] == YES)
{
NSLog(@"END OF CONVERTER INPUT");
[converter setEndOfInput:YES];
[converter setShouldContinue:NO];
return noErr;
}
return 100; //Keep asking for data
}
if (amountToWrite > availInput)
amountToWrite = availInput;
*ioNumberDataPackets = amountToWrite/(converter->inputFormat.mBytesPerPacket);
if (converter->callbackBuffer != NULL)
free(converter->callbackBuffer);
converter->callbackBuffer = malloc(amountToWrite);
memcpy(converter->callbackBuffer, readPtr, amountToWrite);
if (amountToWrite > 0)
{
[[previousNode buffer] didReadLength:amountToWrite];
[[previousNode semaphore] signal];
}
ioData->mBuffers[0].mData = converter->callbackBuffer;
ioData->mBuffers[0].mDataByteSize = amountToWrite;
ioData->mBuffers[0].mNumberChannels = (converter->inputFormat.mChannelsPerFrame);
ioData->mNumberBuffers = 1;
return err;
}
-(void)process
{
void *writePtr;
int availOutput;
int amountConverted;
while ([self shouldContinue] == YES)
{
availOutput = [buffer lengthAvailableToWriteReturningPointer:&writePtr];
while (availOutput == 0)
{
[semaphore wait];
if (shouldContinue == NO)
{
return;
}
availOutput = [buffer lengthAvailableToWriteReturningPointer:&writePtr];
}
amountConverted = [self convert:writePtr amount:availOutput];
if (amountConverted > 0)
[buffer didWriteLength:amountConverted];
}
}
- (int)convert:(void *)dest amount:(int)amount
{
AudioBufferList ioData;
UInt32 ioNumberFrames;
OSStatus err;
ioNumberFrames = amount/outputFormat.mBytesPerFrame;
ioData.mBuffers[0].mData = dest;
ioData.mBuffers[0].mDataByteSize = amount;
ioData.mBuffers[0].mNumberChannels = outputFormat.mChannelsPerFrame;
ioData.mNumberBuffers = 1;
err = AudioConverterFillComplexBuffer(converter, ACInputProc, self, &ioNumberFrames, &ioData, NULL);
// if (err != noErr)
// DBLog(@"Converter error: %i", err);
return ioData.mBuffers[0].mDataByteSize;
/*
void *readPtr;
int availInput;
availInput = [[previousLink buffer] lengthAvailableToReadReturningPointer:&readPtr];
// NSLog(@"AMOUNT: %i %i", amount, availInput);
if (availInput == 0)
{
if ([previousLink endOfInput] == YES)
{
endOfInput = YES;
NSLog(@"EOI");
shouldContinue = NO;
return 0;
}
}
if (availInput < amount)
amount = availInput;
memcpy(dest, readPtr, amount);
if (amount > 0)
{
// NSLog(@"READ: %i", amount);
[[previousLink buffer] didReadLength:amount];
[[previousLink semaphore] signal];
}
return amount;
*/
}
- (void)setupWithInputFormat:(AudioStreamBasicDescription)inf outputFormat:(AudioStreamBasicDescription)outf
{
//Make the converter
OSStatus stat = noErr;
inputFormat = inf;
outputFormat = outf;
stat = AudioConverterNew ( &inputFormat, &outputFormat, &converter);
if (stat != noErr)
{
DBLog(@"Error creating converter %i", stat);
}
if (inputFormat.mChannelsPerFrame == 1)
{
SInt32 channelMap[2] = { 0, 0 };
stat = AudioConverterSetProperty(converter,kAudioConverterChannelMap,sizeof(channelMap),channelMap);
if (stat != noErr)
{
DBLog(@"Error mapping channels %i", stat);
}
}
// DBLog(@"Created converter");
PrintStreamDesc(&inf);
PrintStreamDesc(&outf);
}
- (void)cleanUp
{
AudioConverterDispose(converter);
}
@end

27
Sound/InputNode.h Normal file
View File

@ -0,0 +1,27 @@
//
// InputController.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <CoreAudio/AudioHardware.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AudioUnit/AudioUnit.h>
#import "SoundFile.h"
#import "Node.h"
@interface InputNode : Node {
AudioStreamBasicDescription format;
SoundFile *soundFile;
}
- (void)process;
- (AudioStreamBasicDescription) format;
@end

54
Sound/InputNode.m Normal file
View File

@ -0,0 +1,54 @@
//
// InputController.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "InputNode.h"
@implementation InputNode
- (void)open:(NSString *)filename
{
soundFile = [SoundFile open:filename];
[soundFile getFormat:&format];
endOfInput = NO;
}
- (void)process
{
const int chunk_size = CHUNK_SIZE;
char buf[chunk_size];
int amountRead;
DBLog(@"Playing file.\n");
while ([self shouldContinue] == YES)
{
amountRead = [soundFile fillBuffer:buf ofSize: chunk_size];
if (amountRead <= 0)
{
endOfInput = YES;
NSLog(@"END OF INPUT WAS REACHED");
[controller endOfInputReached];
shouldContinue = NO;
[soundFile close];
return; //eof
}
[self writeData:buf amount:amountRead];
}
[soundFile close];
}
- (AudioStreamBasicDescription) format
{
return format;
}
@end

48
Sound/Node.h Normal file
View File

@ -0,0 +1,48 @@
//
// InputChainLink.h
// CogNew
//
// Created by Zaphod Beeblebrox on 1/4/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "VirtualRingBuffer.h"
#import "Semaphore.h"
#define BUFFER_SIZE 512 * 1024
#define CHUNK_SIZE 16 * 1024
@interface Node : NSObject {
VirtualRingBuffer *buffer;
Semaphore *semaphore;
id previousNode;
id controller;
BOOL shouldContinue;
BOOL endOfInput; //All data is now in buffer
}
- (id)initWithPrevious:(id)p;
- (int)writeData:(void *)ptr amount:(int)a;
- (int)readData:(void *)ptr amount:(int)a;
- (void)process; //Should be overwriten by subclass
- (void)threadEntry:(id)arg;
- (void)launchThread;
- (id)previousNode;
- (BOOL)shouldContinue;
- (void)setShouldContinue:(BOOL)s;
- (VirtualRingBuffer *)buffer;
- (Semaphore *)semaphore;
- (BOOL)endOfInput;
- (void)setEndOfInput:(BOOL)e;
@end

152
Sound/Node.m Normal file
View File

@ -0,0 +1,152 @@
//
// InputChainLink.m
// CogNew
//
// Created by Zaphod Beeblebrox on 1/4/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import "Node.h"
@implementation Node
- (id)initWithController:(id)c previous:(id)p
{
self = [super init];
if (self)
{
buffer = [[VirtualRingBuffer alloc] initWithLength:BUFFER_SIZE];
semaphore = [[Semaphore alloc] init];
controller = c;
previousNode = p;
endOfInput = NO;
}
return self;
}
- (int)writeData:(void *)ptr amount:(int)amount
{
void *writePtr;
int amountToCopy, availOutput;
int amountLeft = amount;
do
{
availOutput = [buffer lengthAvailableToWriteReturningPointer:&writePtr];
while (availOutput < CHUNK_SIZE)
{
[semaphore wait];
if (shouldContinue == NO)
{
return (amount - amountLeft);
}
availOutput = [buffer lengthAvailableToWriteReturningPointer:&writePtr];
}
amountToCopy = availOutput;
if (amountToCopy > amountLeft)
amountToCopy = amountLeft;
memcpy(writePtr, &((char *)ptr)[amount - amountLeft], amountToCopy);
if (amountToCopy > 0)
{
[buffer didWriteLength:amountToCopy];
}
amountLeft -= amountToCopy;
} while (amountLeft > 0);
return (amount - amountLeft);
}
//Should be overwriten by subclass.
- (void)process
{
DBLog(@"WRONG PROCESS");
}
- (void)threadEntry:(id)arg
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
DBLog(@"In thread entry");
[self process];
[pool release];
}
- (int)readData:(void *)ptr amount:(int)amount
{
void *readPtr;
int amountToCopy;
int availInput;
availInput = [[previousNode buffer] lengthAvailableToReadReturningPointer:&readPtr];
amountToCopy = availInput;
if (availInput > amount)
{
amountToCopy = amount;
}
memcpy(ptr, readPtr, amountToCopy);
if (amountToCopy > 0)
{
[[previousNode buffer] didReadLength:amountToCopy];
[[previousNode semaphore] signal];
}
//Do endOfInput fun now...
if ((amountToCopy <= 0) && ([previousNode endOfInput] == YES))
{
endOfInput = YES;
shouldContinue = NO;
}
return amountToCopy;
}
- (void)launchThread
{
DBLog(@"THREAD LAUNCHED");
[NSThread detachNewThreadSelector:@selector(threadEntry:) toTarget:self withObject:nil];
}
- (id)previousNode
{
return previousNode;
}
- (BOOL)shouldContinue
{
return shouldContinue;
}
- (void)setShouldContinue:(BOOL)s
{
shouldContinue = s;
}
- (VirtualRingBuffer *)buffer
{
return buffer;
}
- (Semaphore *)semaphore
{
return semaphore;
}
- (BOOL)endOfInput
{
return endOfInput;
}
- (void)setEndOfInput:(BOOL)e
{
endOfInput = e;
}
@end

30
Sound/OutputCoreAudio.h Normal file
View File

@ -0,0 +1,30 @@
//
// OutputCoreAudio.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <CoreAudio/AudioHardware.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AudioUnit/AudioUnit.h>
@interface OutputCoreAudio : NSObject {
id outputController;
AudioUnit outputUnit;
AURenderCallbackStruct renderCallback;
AudioStreamBasicDescription deviceFormat; // info about the default device
}
- (id)initWithController:(id)c;
- (BOOL)setup;
- (void)start;
- (void)setVolume:(double) v;
@end

View File

@ -11,65 +11,43 @@
@implementation OutputCoreAudio
- (id)initWithController:(id)c
{
self = [super init];
if (self)
{
outputController = c;
}
return self;
}
static OSStatus Sound_Renderer(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData)
{
Sound *sound = (Sound *)inRefCon;
OutputCoreAudio *output = (OutputCoreAudio *)inRefCon;
OSStatus err = noErr;
void *readPointer = ioData->mBuffers[0].mData;
int amountAvailable;
int amountToRead;
void *readPointer;
[sound->readLock lock];
amountAvailable = [sound->readRingBuffer lengthAvailableToReadReturningPointer:&readPointer];
if (sound->playbackStatus == kCogStatusEndOfFile && amountAvailable == 0)
int amountToRead, amountRead;
if ([output->outputController shouldContinue] == NO)
{
DBLog(@"FILE CHANGED!!!!!");
[sound sendPortMessage:kCogFileChangedMessage];
sound->readRingBuffer = [sound oppositeBuffer:sound->readRingBuffer];
[sound setPlaybackStatus:kCogStatusPlaying];
sound->currentPosition = 0;
double time = [sound calculateTime:sound->totalLength];
int bitrate = [sound->soundFile bitRate];
[sound sendPortMessage:kCogLengthUpdateMessage withData:&time ofSize:(sizeof(double))];
[sound sendPortMessage:kCogBitrateUpdateMessage withData:&bitrate ofSize:(sizeof(int))];
}
if (sound->playbackStatus == kCogStatusEndOfPlaylist && amountAvailable == 0)
{
//Stop playback
[sound setPlaybackStatus:kCogStatusStopped];
// return err;
AudioOutputUnitStop(output->outputUnit);
return err;
}
if (amountAvailable < ([sound->readRingBuffer bufferLength] - BUFFER_WRITE_CHUNK))
{
// DBLog(@"AVAILABLE: %i", amountAvailable);
[sound fireFillTimer];
}
if (amountAvailable > inNumberFrames*sound->deviceFormat.mBytesPerPacket)
amountToRead = inNumberFrames*sound->deviceFormat.mBytesPerPacket;
else
amountToRead = amountAvailable;
memcpy(ioData->mBuffers[0].mData, readPointer, amountToRead);
ioData->mBuffers[0].mDataByteSize = amountToRead;
[sound->readRingBuffer didReadLength:amountToRead];
sound->currentPosition += amountToRead;
[sound->readLock unlock];
amountToRead = inNumberFrames*(output->deviceFormat.mBytesPerPacket);
amountRead = [output->outputController readData:(readPointer) amount:amountToRead];
ioData->mBuffers[0].mDataByteSize = amountRead;
return err;
}
- (void)setup
- (BOOL)setup
{
NSLog(@"SETUP");
ComponentDescription desc;
OSStatus err;
@ -116,6 +94,8 @@ static OSStatus Sound_Renderer(void *inRefCon, AudioUnitRenderActionFlags *ioAc
// change output format...
///Seems some 3rd party devices return incorrect stuff...or I just don't like noninterleaved data.
deviceFormat.mFormatFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
// deviceFormat.mFormatFlags &= ~kLinearPCMFormatFlagIsFloat;
// deviceFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
deviceFormat.mBytesPerFrame = deviceFormat.mChannelsPerFrame*(deviceFormat.mBitsPerChannel/8);
deviceFormat.mBytesPerPacket = deviceFormat.mBytesPerFrame * deviceFormat.mFramesPerPacket;
// DBLog(@"stuff: %i %i %i %i", deviceFormat.mBitsPerChannel, deviceFormat.mBytesPerFrame, deviceFormat.mBytesPerPacket, deviceFormat.mFramesPerPacket);
@ -139,20 +119,39 @@ static OSStatus Sound_Renderer(void *inRefCon, AudioUnitRenderActionFlags *ioAc
renderCallback.inputProcRefCon = self;
AudioUnitSetProperty(outputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
[outputController setFormat:&deviceFormat];
// DBLog(@"Audio output successfully initialized");
DBLog(@"Audio output successfully initialized");
return (err == noErr);
}
- (void)setVolume:(double)v
{
AudioUnitSetParameter (outputUnit,
kHALOutputParam_Volume,
kAudioUnitScope_Global,
0,
v * 0.01f,
0);
}
- (void)start
{
NSLog(@"START OUTPUT\n");
AudioOutputUnitStart(outputUnit);
}
- (void)stop
{
NSLog(@"STOP!");
if (outputUnit)
{
AudioOutputUnitStop(outputUnit);
AudioUnitUninitialize (outputUnit);
CloseComponent(outputUnit);
}
}
@end

36
Sound/OutputNode.h Normal file
View File

@ -0,0 +1,36 @@
//
// OutputController.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <CoreAudio/AudioHardware.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AudioUnit/AudioUnit.h>
#import "Node.h"
#import "OutputCoreAudio.h"
@interface OutputNode : Node {
AudioStreamBasicDescription format;
OutputCoreAudio *output;
}
- (id)initWithController:(id)c previousLink:p;
- (void)setup;
- (void)process;
- (int)readData:(void *)ptr amount:(int)amount;
- (void)setFormat:(AudioStreamBasicDescription *)f;
- (AudioStreamBasicDescription) format;
- (void)setVolume:(double) v;
@end

83
Sound/OutputNode.m Normal file
View File

@ -0,0 +1,83 @@
//
// OutputController.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/2/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "OutputNode.h"
#import "OutputCoreAudio.h"
@implementation OutputNode
- (void)setup
{
output = [[OutputCoreAudio alloc] initWithController:self];
[output setup];
}
- (void)process
{
[output start];
}
- (int)readData:(void *)ptr amount:(int)amount
{
int n;
previousNode = [[controller bufferChain] finalNode];
n = [super readData:ptr amount:amount];
if ((n == 0) && (endOfInput == YES))
{
endOfInput = NO;
shouldContinue = YES;
NSLog(@"DONE IN");
return 0;
}
void *tempPtr;
if (([[[[controller bufferChain] finalNode] buffer] lengthAvailableToReadReturningPointer:&tempPtr] == 0) && ([[[controller bufferChain] finalNode] endOfInput] == YES))
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"END OF OUTPUT INPUT?!");
[controller endOfInputPlayed];
endOfInput = YES;
[pool release];
return n + [self readData:&ptr[n] amount:(amount-n)];
}
return n;
}
- (AudioStreamBasicDescription) format
{
return format;
}
- (void)setFormat:(AudioStreamBasicDescription *)f
{
format = *f;
}
- (void)setVolume:(double) v
{
[output setVolume:v];
}
- (void)setShouldContinue:(BOOL)s
{
[super setShouldContinue:s];
if (s == NO)
[output stop];
}
@end

55
Sound/SOUNDTODO Normal file
View File

@ -0,0 +1,55 @@
Need to have soundcontroller or outputnode keep a count of how much was played.
Need to integrate with UI (AppController).
Limit the number of queued elements (2 would probably be good, maybe 3).
Need to finish implementation of setVolume, seekToTime, pause, play, resume, stop, etc.
------------------------------------------------------------------------------------------------------
InputChain
InputController
Input - reads data from file, puts it in buffer
ConverterController?
Converter - reads data from buffer, puts it in next buffer
EffectsController?
Effects - reads data from buffer, puts it in next buffer
outputBuffer - the final buffer, to be read by output
Filename/URL
OutputController
output
-Reads data from the outputbuffer and outputs
SoundController
InputChain
OutputController
ChainQueue
On Input EOF, it will signal SoundController.
SoundController will create a new InputChain for the next file. The NEW InputChain will get placed in the ChainQueue.
When all data has been played from the current InputChain, it is released. Then, pop the first item from the Queue, and make it the new InputChain. Signal the delegate that a song change has taken place.
How to get the next file from the delegate?
/*Perhaps have it keep a copy of the playlist? No. Playlist changes would be a problem. Could have delegate call method like signalPlaylistChanged. Code to make modifications would be a pain.
*/
Need an offset for how many songs (chains) have been queued, probably.
Delegate can get the offset, and tell it nextFile from that.
Delegate will keep track of changes to the playlist. If the playlist is modified so it affected within the currently playing index to index + offset, then signal the soundcontroller, telling it had a playlist change. Would have to clear the ChainQueue and start again.
/*Might want soundcontroller to keep track of changes, and have a signalPlaylistChanged, however. This means the soundcontroller wouldnt be independent of the playlist, however, which is a Nice Thing®.
*/
So, soundcontroller will signal delegate when a file is first opened, to fill the nextfile. Also, when input hits EOF for the current file, nextFile becomes current, and it will signal the delegate for nextFile.

43
Sound/SoundController.h Normal file
View File

@ -0,0 +1,43 @@
//
// SoundController.h
// Cog
//
// Created by Zaphod Beeblebrox on 8/7/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "BufferChain.h"
#import "OutputNode.h"
@class BufferChain;
@class OutputNode;
@interface SoundController : NSObject {
BufferChain *bufferChain;
OutputNode *output;
NSMutableArray *chainQueue;
NSString *nextSong; //Updated whenever the playlist changes?
id delegate;
}
- (OutputNode *) output;
- (BufferChain *) bufferChain;
- (id)initWithDelegate:(id)d;
- (void)play:(NSString *)filename;
- (void)stop;
- (void)pause;
- (void)resume;
- (void)seekToTime:(double)time;
- (void)setVolume:(double)v;
- (void)setNextSong:(NSString *)s;
@end

138
Sound/SoundController.m Normal file
View File

@ -0,0 +1,138 @@
//
// Controller.m
// Cog
//
// Created by Zaphod Beeblebrox on 8/7/05.
// Copyright 2005 __MyCompanyName__. All rights reserved.
//
#import "SoundController.h"
@implementation SoundController
- (id)initWithDelegate:(id)d
{
DBLog(@"Initializing\n");
self = [super init];
if (self)
{
//things
output = [[OutputNode alloc] initWithController:self previous:nil];
bufferChain = [[BufferChain alloc] initWithController:self];
chainQueue = [[NSMutableArray alloc] init];
delegate = d;
}
return self;
}
- (void)play:(NSString *)filename
{
DBLog(@"OPENING FILE: %s\n", filename);
[output setup];
[bufferChain open:filename];
[self setShouldContinue:YES];
DBLog(@"DETACHING THREADS");
[output launchThread];
[bufferChain launchThreads];
}
- (void)stop
{
//Set shouldoContinue to NO on allll things
[self setShouldContinue:NO];
}
- (void)pause
{
[output pause];
}
- (void)resume
{
[output resume];
}
- (void)seekToTime:(double)time
{
//Need to reset everything's buffers, and then seek?
}
- (void)setVolume:(double)v
{
[output setVolume:v];
}
- (void)setNextSong:(NSString *)s
{
//Need to lock things, and set it...this may be calling from any threads...also, if its nil then that signals end of playlist
[s retain];
[nextSong release];
nextSong = s;
}
- (void)setShouldContinue:(BOOL)s
{
[bufferChain setShouldContinue:s];
[output setShouldContinue:s];
}
- (void)endOfInputReached
{
[delegate delegateRequestNextSong:[chainQueue count]];
NSLog(@"END OF INPUT REACHED");
if (nextSong == nil)
return;
BufferChain *newChain = [[BufferChain alloc] initWithController:self];
[newChain open:nextSong];
[newChain setShouldContinue:YES];
[newChain launchThreads];
[chainQueue insertObject:newChain atIndex:[chainQueue count]];
[newChain release];
}
- (void)endOfInputPlayed
{
if ([chainQueue count] <= 0)
return;
// NSLog(@"SWAPPING BUFFERS");
[bufferChain release];
NSLog(@"END OF INPUT PLAYED");
bufferChain = [chainQueue objectAtIndex:0];
[bufferChain retain];
[chainQueue removeObjectAtIndex:0];
NSLog(@"SONG CHANGED");
[delegate delegateNotifySongChanged:0.0];
// NSLog(@"SWAPPED");
}
- (BufferChain *)bufferChain
{
return bufferChain;
}
- (OutputNode *) output
{
return output;
}
@end

View File

@ -65,6 +65,7 @@
+ (SoundFile *)soundFileFromFilename:(NSString *)filename
{
SoundFile *soundFile;
DBLog(@"Filename: %@", filename);
if (([[filename pathExtension] caseInsensitiveCompare:@"wav"] == NSOrderedSame) || ([[filename pathExtension] caseInsensitiveCompare:@"aiff"] == NSOrderedSame) || ([[filename pathExtension] caseInsensitiveCompare:@"aif"] == NSOrderedSame))
{

18
Sound/Status.h Normal file
View File

@ -0,0 +1,18 @@
/*
* Status.h
* Cog
*
* Created by Zaphod Beeblebrox on 1/14/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
enum
{
kCogStatusPaused = 0,
kCogStatusStopped,
kCogStatusPlaying,
// kCogStatusEndOfFile,
// kCogStatusEndOfPlaylist,
// kCogStatusPlaybackEnded
};

309
Sound/VirtualRingBuffer.m Normal file
View File

@ -0,0 +1,309 @@
//
// VirtualRingBuffer.m
// PlayBufferedSoundFile
//
/*
Copyright (c) 2002, Kurt Revis. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Snoize nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "VirtualRingBuffer.h"
#include <mach/mach.h>
#include <mach/mach_error.h>
@implementation VirtualRingBuffer
static void *allocateVirtualBuffer(UInt32 bufferLength);
static void deallocateVirtualBuffer(void *buffer, UInt32 bufferLength);
- (id)initWithLength:(UInt32)length
{
if (![super init])
return nil;
// We need to allocate entire VM pages, so round the specified length up to the next page if necessary.
bufferLength = round_page(length);
buffer = allocateVirtualBuffer(bufferLength);
if (buffer) {
bufferEnd = buffer + bufferLength;
} else {
[self release];
return nil;
}
readPointer = NULL;
writePointer = NULL;
return self;
}
- (void)dealloc
{
if (buffer)
deallocateVirtualBuffer(buffer, bufferLength);
[super dealloc];
}
- (void)empty
{
// Assumption:
// No one is reading or writing from the buffer, in any thread, when this method is called.
readPointer = NULL;
writePointer = NULL;
}
- (BOOL)isEmpty
{
return (readPointer != NULL && writePointer != NULL);
}
- (UInt32)bufferLength
{
return bufferLength;
}
//
// Theory of operation:
//
// This class keeps a pointer to the next byte to be read (readPointer) and a pointer to the next byte to be written (writePointer).
// readPointer is only advanced in the reading thread (except for one case: when the buffer first has data written to it).
// writePointer is only advanced in the writing thread.
//
// Since loading and storing word length data is atomic, each pointer can safely be modified in one thread while the other thread
// uses it, IF each thread is careful to make a local copy of the "opposite" pointer when necessary.
//
//
// Read operations
//
- (UInt32)lengthAvailableToReadReturningPointer:(void **)returnedReadPointer
{
// Assumptions:
// returnedReadPointer != NULL
UInt32 length;
// Read this pointer exactly once, so we're safe in case it is changed in another thread
void *localWritePointer = writePointer;
// Depending on out-of-order execution and memory storage, either one of these may be NULL when the buffer is empty. So we must check both.
if (!readPointer || !localWritePointer) {
// The buffer is empty
length = 0;
} else if (localWritePointer > readPointer) {
// Write is ahead of read in the buffer
length = localWritePointer - readPointer;
} else {
// Write has wrapped around past read, OR write == read (the buffer is full)
length = bufferLength - (readPointer - localWritePointer);
}
*returnedReadPointer = readPointer;
return length;
}
- (void)didReadLength:(UInt32)length
{
// Assumptions:
// [self lengthAvailableToReadReturningPointer:] currently returns a value >= length
// length > 0
void *newReadPointer;
newReadPointer = readPointer + length;
if (newReadPointer >= bufferEnd)
newReadPointer -= bufferLength;
if (newReadPointer == writePointer) {
// We just read the last data out of the buffer, so it is now empty.
newReadPointer = NULL;
}
// Store the new read pointer. This is the only place this happens in the read thread.
readPointer = newReadPointer;
}
//
// Write operations
//
- (UInt32)lengthAvailableToWriteReturningPointer:(void **)returnedWritePointer
{
// Assumptions:
// returnedWritePointer != NULL
UInt32 length;
// Read this pointer exactly once, so we're safe in case it is changed in another thread
void *localReadPointer = readPointer;
// Either one of these may be NULL when the buffer is empty. So we must check both.
if (!localReadPointer || !writePointer) {
// The buffer is empty. Set it up to be written into.
// This is one of the two places the write pointer can change; both are in the write thread.
writePointer = buffer;
length = bufferLength;
} else if (writePointer <= localReadPointer) {
// Write is before read in the buffer, OR write == read (meaning that the buffer is full).
length = localReadPointer - writePointer;
} else {
// Write is behind read in the buffer. The available space wraps around.
length = (bufferEnd - writePointer) + (localReadPointer - buffer);
}
*returnedWritePointer = writePointer;
return length;
}
- (void)didWriteLength:(UInt32)length
{
// Assumptions:
// [self lengthAvailableToWriteReturningPointer:] currently returns a value >= length
// length > 0
void *oldWritePointer = writePointer;
void *newWritePointer;
// Advance the write pointer, wrapping around if necessary.
newWritePointer = writePointer + length;
if (newWritePointer >= bufferEnd)
newWritePointer -= bufferLength;
// This is one of the two places the write pointer can change; both are in the write thread.
writePointer = newWritePointer;
// Also, if the read pointer is NULL, then we just wrote into a previously empty buffer, so set the read pointer.
// This is the only place the read pointer is changed in the write thread.
// The read thread should never change the read pointer when it is NULL, so this is safe.
if (!readPointer)
readPointer = oldWritePointer;
}
@end
void *allocateVirtualBuffer(UInt32 bufferLength)
{
kern_return_t error;
vm_address_t originalAddress = (vm_address_t)NULL;
vm_address_t realAddress = (vm_address_t)NULL;
mach_port_t memoryEntry;
vm_size_t memoryEntryLength;
vm_address_t virtualAddress = (vm_address_t)NULL;
// We want to find where we can get 2 * bufferLength bytes of contiguous address space.
// So let's just allocate that space, remember its address, and deallocate it.
// (This doesn't actually have to touch all of that memory so it's not terribly expensive.)
error = vm_allocate(mach_task_self(), &originalAddress, 2 * bufferLength, TRUE);
if (error) {
#if DEBUG
mach_error("vm_allocate initial chunk", error);
#endif
return NULL;
}
error = vm_deallocate(mach_task_self(), originalAddress, 2 * bufferLength);
if (error) {
#if DEBUG
mach_error("vm_deallocate initial chunk", error);
#endif
return NULL;
}
// Then allocate a "real" block of memory at the same address, but with the normal bufferLength.
realAddress = originalAddress;
error = vm_allocate(mach_task_self(), &realAddress, bufferLength, FALSE);
if (error) {
#if DEBUG
mach_error("vm_allocate real chunk", error);
#endif
return NULL;
}
if (realAddress != originalAddress) {
#if DEBUG
DBLog(@"allocateVirtualBuffer: vm_allocate 2nd time didn't return same address (%p vs %p)", originalAddress, realAddress);
#endif
goto errorReturn;
}
// Then make a memory entry for the area we just allocated.
memoryEntryLength = bufferLength;
error = mach_make_memory_entry(mach_task_self(), &memoryEntryLength, realAddress, VM_PROT_READ | VM_PROT_WRITE, &memoryEntry, (vm_address_t)NULL);
if (error) {
#if DEBUG
mach_error("mach_make_memory_entry", error);
#endif
goto errorReturn;
}
if (!memoryEntry) {
#if DEBUG
DBLog(@"mach_make_memory_entry: returned memoryEntry of NULL");
#endif
goto errorReturn;
}
if (memoryEntryLength != bufferLength) {
#if DEBUG
DBLog(@"mach_make_memory_entry: size changed (from %0x to %0x)", bufferLength, memoryEntryLength);
#endif
goto errorReturn;
}
// And map the area immediately after the first block, with length bufferLength, to that memory entry.
virtualAddress = realAddress + bufferLength;
error = vm_map(mach_task_self(), &virtualAddress, bufferLength, 0, FALSE, memoryEntry, 0, FALSE, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_READ | VM_PROT_WRITE, VM_INHERIT_DEFAULT);
if (error) {
#if DEBUG
mach_error("vm_map", error);
#endif
// TODO Retry from the beginning, instead of failing completely. There is a tiny (but > 0) probability that someone
// will allocate this space out from under us.
virtualAddress = (vm_address_t)NULL;
goto errorReturn;
}
if (virtualAddress != realAddress + bufferLength) {
#if DEBUG
DBLog(@"vm_map: didn't return correct address (%p vs %p)", realAddress + bufferLength, virtualAddress);
#endif
goto errorReturn;
}
// Success!
return (void *)realAddress;
errorReturn:
if (realAddress)
vm_deallocate(mach_task_self(), realAddress, bufferLength);
if (virtualAddress)
vm_deallocate(mach_task_self(), virtualAddress, bufferLength);
return NULL;
}
void deallocateVirtualBuffer(void *buffer, UInt32 bufferLength)
{
kern_return_t error;
// We can conveniently deallocate both the vm_allocated memory and
// the vm_mapped region at the same time.
error = vm_deallocate(mach_task_self(), (vm_address_t)buffer, bufferLength * 2);
if (error) {
#if DEBUG
mach_error("vm_deallocate in dealloc", error);
#endif
}
}

View File

@ -24,7 +24,7 @@
-(void)signal
{
semaphore_signal(semaphore);
semaphore_signal_all(semaphore);
}
-(void)timedWait:(int)seconds
@ -36,7 +36,8 @@
-(void)wait
{
semaphore_wait(semaphore);
mach_timespec_t t = {2.0, 0.0}; //2 second timeout
semaphore_timedwait(semaphore, t);
}
@end

88
Utils/VirtualRingBuffer.h Normal file
View File

@ -0,0 +1,88 @@
//
// VirtualRingBuffer.h
// PlayBufferedSoundFile
//
/*
Copyright (c) 2002, Kurt Revis. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Snoize nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// VirtualRingBuffer implements a classic ring buffer (or circular buffer), with a couple of twists.
//
// * It allows reads and writes to happen in different threads, with no explicit locking,
// so readers and writers will never block. This is useful if either thread uses the
// time-constraint scheduling policy, since it is bad for such threads to block for
// indefinite amounts of time.
//
// * It uses a virtual memory trick to allow the client to read or write using just one
// operation, even if the data involved wraps around the end of the buffer. We allocate
// our buffer normally, and then place a VM region immediately after it in the address
// space which maps back to the "real" buffer. So reads and writes into both sections
// are transparently translated into the same physical memory.
// This makes the API much simpler to use, and saves us from doing some math to
// calculate the wraparound points.
// The tradeoff is that we use twice as much address space for the buffer than we would
// otherwise. Address space is not typically constrained for most applications, though,
// so this isn't a big problem.
// The idea for this trick came from <http://phil.ipal.org/freeware/vrb/> (via sweetcode.org),
// although none of that code is used here. (We use the Mach VM API directly.)
//
// Threading note:
// It is expected that this object will be shared between exactly two threads; one will
// always read and the other will always write. In that situation, the implementation is
// thread-safe, and this object will never block or yield.
// It will also work in one thread, of course (although I don't know why you'd bother).
// However, if you have multiple reader or writer threads, all bets are off!
#import <Foundation/Foundation.h>
@interface VirtualRingBuffer : NSObject
{
void *buffer;
void *bufferEnd;
UInt32 bufferLength;
// buffer is the start of the ring buffer's address space.
// bufferEnd is the end of the "real" buffer (always buffer + bufferLength).
// Note that the "virtual" portion of the buffer extends from bufferEnd to bufferEnd+bufferLength.
void *readPointer;
void *writePointer;
}
- (id)initWithLength:(UInt32)length;
// Note: The specified length will be rounded up to an integral number of VM pages.
// Empties the buffer. It is NOT safe to do this while anyone is reading from or writing to the buffer.
- (void)empty;
// Checks if the buffer is empty or not. This is safe in any thread.
- (BOOL)isEmpty;
- (UInt32)bufferLength;
// Read operations:
// The reading thread must call this method first.
- (UInt32)lengthAvailableToReadReturningPointer:(void **)returnedReadPointer;
// Iff a value > 0 is returned, the reading thread may go on to read that much data from the returned pointer.
// Afterwards, the reading thread must call didReadLength:.
- (void)didReadLength:(UInt32)length;
// Write operations:
// The writing thread must call this method first.
- (UInt32)lengthAvailableToWriteReturningPointer:(void **)returnedWritePointer;
// Iff a value > 0 is returned, the writing thread may then write that much data into the returned pointer.
// Afterwards, the writing thread must call didWriteLength:.
- (void)didWriteLength:(UInt32)length;
@end