From 733d0d78d00fcb14e5c74e76f0ca90ab189edc6a Mon Sep 17 00:00:00 2001 From: vspader Date: Fri, 20 Jan 2006 15:34:02 +0000 Subject: [PATCH] New Core --- Controller.h | 30 -- Controller.m | 14 - Converter.h | 22 -- Converter.m | 116 ------- InputController.h | 17 - InputController.m | 19 -- Sound.h => Old/Sound.h | 0 Sound.m => Old/Sound.m | 0 SoundController.h => Old/SoundController.h | 0 SoundController.m => Old/SoundController.m | 0 OutputController.h | 17 - OutputController.m | 14 - OutputCoreAudio.h | 20 -- Playlist/Shuffle.h | 18 + Playlist/Shuffle.m | 52 +++ Sound/BufferChain.h | 34 ++ Sound/BufferChain.m | 63 ++++ Sound/ConverterNode.h | 31 ++ Sound/ConverterNode.m | 214 ++++++++++++ Sound/InputNode.h | 27 ++ Sound/InputNode.m | 54 +++ Sound/Node.h | 48 +++ Sound/Node.m | 152 +++++++++ Sound/OutputCoreAudio.h | 30 ++ OutputCoreAudio.m => Sound/OutputCoreAudio.m | 95 +++--- Sound/OutputNode.h | 36 ++ Sound/OutputNode.m | 83 +++++ Sound/SOUNDTODO | 55 ++++ Sound/SoundController.h | 43 +++ Sound/SoundController.m | 138 ++++++++ {SoundFile => Sound/SoundFile}/AACFile.h | 0 {SoundFile => Sound/SoundFile}/AACFile.m | 0 {SoundFile => Sound/SoundFile}/FlacFile.h | 0 {SoundFile => Sound/SoundFile}/FlacFile.m | 0 {SoundFile => Sound/SoundFile}/MPEGFile.h | 0 .../MPEGFile.m => Sound/SoundFile/MPEGFile.mm | 0 {SoundFile => Sound/SoundFile}/MonkeysFile.h | 0 .../SoundFile/MonkeysFile.mm | 0 {SoundFile => Sound/SoundFile}/MusepackFile.h | 0 {SoundFile => Sound/SoundFile}/MusepackFile.m | 0 {SoundFile => Sound/SoundFile}/ShnFile.h | 0 {SoundFile => Sound/SoundFile}/ShnFile.m | 0 {SoundFile => Sound/SoundFile}/SoundFile.h | 0 .../SoundFile/SoundFile.mm | 1 + {SoundFile => Sound/SoundFile}/VorbisFile.h | 0 {SoundFile => Sound/SoundFile}/VorbisFile.m | 0 {SoundFile => Sound/SoundFile}/WavPackFile.h | 0 {SoundFile => Sound/SoundFile}/WavPackFile.m | 0 {SoundFile => Sound/SoundFile}/WaveFile.h | 0 {SoundFile => Sound/SoundFile}/WaveFile.m | 0 Sound/Status.h | 18 + .../VirtualRingBuffer.h | 0 Sound/VirtualRingBuffer.m | 309 ++++++++++++++++++ DBLog.h => Utils/DBLog.h | 0 DBLog.c => Utils/DBLog.m | 0 Semaphore.h => Utils/Semaphore.h | 0 Semaphore.m => Utils/Semaphore.m | 5 +- Utils/VirtualRingBuffer.h | 88 +++++ .../VirtualRingBuffer.m | 0 59 files changed, 1544 insertions(+), 319 deletions(-) delete mode 100644 Controller.h delete mode 100644 Controller.m delete mode 100644 Converter.h delete mode 100644 Converter.m delete mode 100644 InputController.h delete mode 100644 InputController.m rename Sound.h => Old/Sound.h (100%) rename Sound.m => Old/Sound.m (100%) rename SoundController.h => Old/SoundController.h (100%) rename SoundController.m => Old/SoundController.m (100%) delete mode 100644 OutputController.h delete mode 100644 OutputController.m delete mode 100644 OutputCoreAudio.h create mode 100644 Playlist/Shuffle.h create mode 100644 Playlist/Shuffle.m create mode 100644 Sound/BufferChain.h create mode 100644 Sound/BufferChain.m create mode 100644 Sound/ConverterNode.h create mode 100644 Sound/ConverterNode.m create mode 100644 Sound/InputNode.h create mode 100644 Sound/InputNode.m create mode 100644 Sound/Node.h create mode 100644 Sound/Node.m create mode 100644 Sound/OutputCoreAudio.h rename OutputCoreAudio.m => Sound/OutputCoreAudio.m (64%) create mode 100644 Sound/OutputNode.h create mode 100644 Sound/OutputNode.m create mode 100644 Sound/SOUNDTODO create mode 100644 Sound/SoundController.h create mode 100644 Sound/SoundController.m rename {SoundFile => Sound/SoundFile}/AACFile.h (100%) rename {SoundFile => Sound/SoundFile}/AACFile.m (100%) rename {SoundFile => Sound/SoundFile}/FlacFile.h (100%) rename {SoundFile => Sound/SoundFile}/FlacFile.m (100%) rename {SoundFile => Sound/SoundFile}/MPEGFile.h (100%) rename SoundFile/MPEGFile.m => Sound/SoundFile/MPEGFile.mm (100%) rename {SoundFile => Sound/SoundFile}/MonkeysFile.h (100%) rename SoundFile/MonkeysFile.m => Sound/SoundFile/MonkeysFile.mm (100%) rename {SoundFile => Sound/SoundFile}/MusepackFile.h (100%) rename {SoundFile => Sound/SoundFile}/MusepackFile.m (100%) rename {SoundFile => Sound/SoundFile}/ShnFile.h (100%) rename {SoundFile => Sound/SoundFile}/ShnFile.m (100%) rename {SoundFile => Sound/SoundFile}/SoundFile.h (100%) rename SoundFile/SoundFile.m => Sound/SoundFile/SoundFile.mm (99%) rename {SoundFile => Sound/SoundFile}/VorbisFile.h (100%) rename {SoundFile => Sound/SoundFile}/VorbisFile.m (100%) rename {SoundFile => Sound/SoundFile}/WavPackFile.h (100%) rename {SoundFile => Sound/SoundFile}/WavPackFile.m (100%) rename {SoundFile => Sound/SoundFile}/WaveFile.h (100%) rename {SoundFile => Sound/SoundFile}/WaveFile.m (100%) create mode 100644 Sound/Status.h rename VirtualRingBuffer.h => Sound/VirtualRingBuffer.h (100%) create mode 100644 Sound/VirtualRingBuffer.m rename DBLog.h => Utils/DBLog.h (100%) rename DBLog.c => Utils/DBLog.m (100%) rename Semaphore.h => Utils/Semaphore.h (100%) rename Semaphore.m => Utils/Semaphore.m (80%) create mode 100644 Utils/VirtualRingBuffer.h rename VirtualRingBuffer.m => Utils/VirtualRingBuffer.m (100%) diff --git a/Controller.h b/Controller.h deleted file mode 100644 index 1ce91c45b..000000000 --- a/Controller.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// Controller.h -// Cog -// -// Created by Zaphod Beeblebrox on 8/7/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. -// - -#import - - -@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 diff --git a/Controller.m b/Controller.m deleted file mode 100644 index 696614178..000000000 --- a/Controller.m +++ /dev/null @@ -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 diff --git a/Converter.h b/Converter.h deleted file mode 100644 index 03d6e9001..000000000 --- a/Converter.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// Converter.h -// Cog -// -// Created by Zaphod Beeblebrox on 8/2/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. -// - -#import - - -@interface Converter : NSObject { - SoundController *soundController; -} - -- (void)setup; -- (void)cleanUp; - -- (void)process; -- (int)convert:(void *)dest amount:(int)amount; - -@end diff --git a/Converter.m b/Converter.m deleted file mode 100644 index 52ff2dd2a..000000000 --- a/Converter.m +++ /dev/null @@ -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 diff --git a/InputController.h b/InputController.h deleted file mode 100644 index c37b9c9ae..000000000 --- a/InputController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// InputController.h -// Cog -// -// Created by Zaphod Beeblebrox on 8/2/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. -// - -#import - - -@interface InputController : NSObject { - VirtualRingBuffer *buffer; - AudioStreamBasicDescription format; -} - -@end diff --git a/InputController.m b/InputController.m deleted file mode 100644 index c467b780f..000000000 --- a/InputController.m +++ /dev/null @@ -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 diff --git a/Sound.h b/Old/Sound.h similarity index 100% rename from Sound.h rename to Old/Sound.h diff --git a/Sound.m b/Old/Sound.m similarity index 100% rename from Sound.m rename to Old/Sound.m diff --git a/SoundController.h b/Old/SoundController.h similarity index 100% rename from SoundController.h rename to Old/SoundController.h diff --git a/SoundController.m b/Old/SoundController.m similarity index 100% rename from SoundController.m rename to Old/SoundController.m diff --git a/OutputController.h b/OutputController.h deleted file mode 100644 index 1a97c7c7b..000000000 --- a/OutputController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// OutputController.h -// Cog -// -// Created by Zaphod Beeblebrox on 8/2/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. -// - -#import - - -@interface OutputController : NSObject { - VirtualRingBuffer *buffer; - AudioStreamBasicDescription format; -} - -@end diff --git a/OutputController.m b/OutputController.m deleted file mode 100644 index 4370b9dea..000000000 --- a/OutputController.m +++ /dev/null @@ -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 diff --git a/OutputCoreAudio.h b/OutputCoreAudio.h deleted file mode 100644 index afdaaaa6d..000000000 --- a/OutputCoreAudio.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// OutputCoreAudio.h -// Cog -// -// Created by Zaphod Beeblebrox on 8/2/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. -// - -#import - - -@interface OutputCoreAudio : NSObject { - -} - -- (void)setup; -- (void)start; -- (void)stop; - -@end diff --git a/Playlist/Shuffle.h b/Playlist/Shuffle.h new file mode 100644 index 000000000..f0dd47804 --- /dev/null +++ b/Playlist/Shuffle.h @@ -0,0 +1,18 @@ +// +// Shuffle.h +// Cog +// +// Created by Zaphod Beeblebrox on 1/14/06. +// Copyright 2006 __MyCompanyName__. All rights reserved. +// + +#import + + +@interface Shuffle : NSObject { + +} + ++ (NSMutableArray *)shuffleList:(NSArray *)l; + +@end diff --git a/Playlist/Shuffle.m b/Playlist/Shuffle.m new file mode 100644 index 000000000..d00ee2aef --- /dev/null +++ b/Playlist/Shuffle.m @@ -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 diff --git a/Sound/BufferChain.h b/Sound/BufferChain.h new file mode 100644 index 000000000..a465153f8 --- /dev/null +++ b/Sound/BufferChain.h @@ -0,0 +1,34 @@ +// +// InputChain.h +// CogNew +// +// Created by Zaphod Beeblebrox on 1/4/06. +// Copyright 2006 __MyCompanyName__. All rights reserved. +// + +#import + +#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 diff --git a/Sound/BufferChain.m b/Sound/BufferChain.m new file mode 100644 index 000000000..9c22c7cd6 --- /dev/null +++ b/Sound/BufferChain.m @@ -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 diff --git a/Sound/ConverterNode.h b/Sound/ConverterNode.h new file mode 100644 index 000000000..f878666c4 --- /dev/null +++ b/Sound/ConverterNode.h @@ -0,0 +1,31 @@ +// +// Converter.h +// Cog +// +// Created by Zaphod Beeblebrox on 8/2/05. +// Copyright 2005 __MyCompanyName__. All rights reserved. +// + +#import + +#import +#import +#import + +#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 diff --git a/Sound/ConverterNode.m b/Sound/ConverterNode.m new file mode 100644 index 000000000..554dcad08 --- /dev/null +++ b/Sound/ConverterNode.m @@ -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 diff --git a/Sound/InputNode.h b/Sound/InputNode.h new file mode 100644 index 000000000..cc1e3f232 --- /dev/null +++ b/Sound/InputNode.h @@ -0,0 +1,27 @@ +// +// InputController.h +// Cog +// +// Created by Zaphod Beeblebrox on 8/2/05. +// Copyright 2005 __MyCompanyName__. All rights reserved. +// + +#import + +#import +#import +#import + +#import "SoundFile.h" +#import "Node.h" + +@interface InputNode : Node { + AudioStreamBasicDescription format; + + SoundFile *soundFile; +} + +- (void)process; +- (AudioStreamBasicDescription) format; + +@end diff --git a/Sound/InputNode.m b/Sound/InputNode.m new file mode 100644 index 000000000..2c8167681 --- /dev/null +++ b/Sound/InputNode.m @@ -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 diff --git a/Sound/Node.h b/Sound/Node.h new file mode 100644 index 000000000..50d0f2d28 --- /dev/null +++ b/Sound/Node.h @@ -0,0 +1,48 @@ +// +// InputChainLink.h +// CogNew +// +// Created by Zaphod Beeblebrox on 1/4/06. +// Copyright 2006 __MyCompanyName__. All rights reserved. +// + +#import +#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 diff --git a/Sound/Node.m b/Sound/Node.m new file mode 100644 index 000000000..28e6add8a --- /dev/null +++ b/Sound/Node.m @@ -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 diff --git a/Sound/OutputCoreAudio.h b/Sound/OutputCoreAudio.h new file mode 100644 index 000000000..6cf570d55 --- /dev/null +++ b/Sound/OutputCoreAudio.h @@ -0,0 +1,30 @@ +// +// OutputCoreAudio.h +// Cog +// +// Created by Zaphod Beeblebrox on 8/2/05. +// Copyright 2005 __MyCompanyName__. All rights reserved. +// + +#import + +#import +#import +#import + +@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 diff --git a/OutputCoreAudio.m b/Sound/OutputCoreAudio.m similarity index 64% rename from OutputCoreAudio.m rename to Sound/OutputCoreAudio.m index a3c219a9c..5b0157852 100644 --- a/OutputCoreAudio.m +++ b/Sound/OutputCoreAudio.m @@ -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 diff --git a/Sound/OutputNode.h b/Sound/OutputNode.h new file mode 100644 index 000000000..2f45fc9d7 --- /dev/null +++ b/Sound/OutputNode.h @@ -0,0 +1,36 @@ +// +// OutputController.h +// Cog +// +// Created by Zaphod Beeblebrox on 8/2/05. +// Copyright 2005 __MyCompanyName__. All rights reserved. +// + +#import + +#import +#import +#import + +#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 diff --git a/Sound/OutputNode.m b/Sound/OutputNode.m new file mode 100644 index 000000000..43cc8f5a7 --- /dev/null +++ b/Sound/OutputNode.m @@ -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 diff --git a/Sound/SOUNDTODO b/Sound/SOUNDTODO new file mode 100644 index 000000000..b1ab8134b --- /dev/null +++ b/Sound/SOUNDTODO @@ -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. + diff --git a/Sound/SoundController.h b/Sound/SoundController.h new file mode 100644 index 000000000..5160e6204 --- /dev/null +++ b/Sound/SoundController.h @@ -0,0 +1,43 @@ +// +// SoundController.h +// Cog +// +// Created by Zaphod Beeblebrox on 8/7/05. +// Copyright 2005 __MyCompanyName__. All rights reserved. +// + +#import + +#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 diff --git a/Sound/SoundController.m b/Sound/SoundController.m new file mode 100644 index 000000000..fafeaf915 --- /dev/null +++ b/Sound/SoundController.m @@ -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 diff --git a/SoundFile/AACFile.h b/Sound/SoundFile/AACFile.h similarity index 100% rename from SoundFile/AACFile.h rename to Sound/SoundFile/AACFile.h diff --git a/SoundFile/AACFile.m b/Sound/SoundFile/AACFile.m similarity index 100% rename from SoundFile/AACFile.m rename to Sound/SoundFile/AACFile.m diff --git a/SoundFile/FlacFile.h b/Sound/SoundFile/FlacFile.h similarity index 100% rename from SoundFile/FlacFile.h rename to Sound/SoundFile/FlacFile.h diff --git a/SoundFile/FlacFile.m b/Sound/SoundFile/FlacFile.m similarity index 100% rename from SoundFile/FlacFile.m rename to Sound/SoundFile/FlacFile.m diff --git a/SoundFile/MPEGFile.h b/Sound/SoundFile/MPEGFile.h similarity index 100% rename from SoundFile/MPEGFile.h rename to Sound/SoundFile/MPEGFile.h diff --git a/SoundFile/MPEGFile.m b/Sound/SoundFile/MPEGFile.mm similarity index 100% rename from SoundFile/MPEGFile.m rename to Sound/SoundFile/MPEGFile.mm diff --git a/SoundFile/MonkeysFile.h b/Sound/SoundFile/MonkeysFile.h similarity index 100% rename from SoundFile/MonkeysFile.h rename to Sound/SoundFile/MonkeysFile.h diff --git a/SoundFile/MonkeysFile.m b/Sound/SoundFile/MonkeysFile.mm similarity index 100% rename from SoundFile/MonkeysFile.m rename to Sound/SoundFile/MonkeysFile.mm diff --git a/SoundFile/MusepackFile.h b/Sound/SoundFile/MusepackFile.h similarity index 100% rename from SoundFile/MusepackFile.h rename to Sound/SoundFile/MusepackFile.h diff --git a/SoundFile/MusepackFile.m b/Sound/SoundFile/MusepackFile.m similarity index 100% rename from SoundFile/MusepackFile.m rename to Sound/SoundFile/MusepackFile.m diff --git a/SoundFile/ShnFile.h b/Sound/SoundFile/ShnFile.h similarity index 100% rename from SoundFile/ShnFile.h rename to Sound/SoundFile/ShnFile.h diff --git a/SoundFile/ShnFile.m b/Sound/SoundFile/ShnFile.m similarity index 100% rename from SoundFile/ShnFile.m rename to Sound/SoundFile/ShnFile.m diff --git a/SoundFile/SoundFile.h b/Sound/SoundFile/SoundFile.h similarity index 100% rename from SoundFile/SoundFile.h rename to Sound/SoundFile/SoundFile.h diff --git a/SoundFile/SoundFile.m b/Sound/SoundFile/SoundFile.mm similarity index 99% rename from SoundFile/SoundFile.m rename to Sound/SoundFile/SoundFile.mm index b1275a0b0..d3d73c54d 100644 --- a/SoundFile/SoundFile.m +++ b/Sound/SoundFile/SoundFile.mm @@ -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)) { diff --git a/SoundFile/VorbisFile.h b/Sound/SoundFile/VorbisFile.h similarity index 100% rename from SoundFile/VorbisFile.h rename to Sound/SoundFile/VorbisFile.h diff --git a/SoundFile/VorbisFile.m b/Sound/SoundFile/VorbisFile.m similarity index 100% rename from SoundFile/VorbisFile.m rename to Sound/SoundFile/VorbisFile.m diff --git a/SoundFile/WavPackFile.h b/Sound/SoundFile/WavPackFile.h similarity index 100% rename from SoundFile/WavPackFile.h rename to Sound/SoundFile/WavPackFile.h diff --git a/SoundFile/WavPackFile.m b/Sound/SoundFile/WavPackFile.m similarity index 100% rename from SoundFile/WavPackFile.m rename to Sound/SoundFile/WavPackFile.m diff --git a/SoundFile/WaveFile.h b/Sound/SoundFile/WaveFile.h similarity index 100% rename from SoundFile/WaveFile.h rename to Sound/SoundFile/WaveFile.h diff --git a/SoundFile/WaveFile.m b/Sound/SoundFile/WaveFile.m similarity index 100% rename from SoundFile/WaveFile.m rename to Sound/SoundFile/WaveFile.m diff --git a/Sound/Status.h b/Sound/Status.h new file mode 100644 index 000000000..8e095dbc4 --- /dev/null +++ b/Sound/Status.h @@ -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 +}; diff --git a/VirtualRingBuffer.h b/Sound/VirtualRingBuffer.h similarity index 100% rename from VirtualRingBuffer.h rename to Sound/VirtualRingBuffer.h diff --git a/Sound/VirtualRingBuffer.m b/Sound/VirtualRingBuffer.m new file mode 100644 index 000000000..d085614ee --- /dev/null +++ b/Sound/VirtualRingBuffer.m @@ -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 +#include + + +@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 + } +} diff --git a/DBLog.h b/Utils/DBLog.h similarity index 100% rename from DBLog.h rename to Utils/DBLog.h diff --git a/DBLog.c b/Utils/DBLog.m similarity index 100% rename from DBLog.c rename to Utils/DBLog.m diff --git a/Semaphore.h b/Utils/Semaphore.h similarity index 100% rename from Semaphore.h rename to Utils/Semaphore.h diff --git a/Semaphore.m b/Utils/Semaphore.m similarity index 80% rename from Semaphore.m rename to Utils/Semaphore.m index c35d7677e..7aa2e84f6 100644 --- a/Semaphore.m +++ b/Utils/Semaphore.m @@ -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 diff --git a/Utils/VirtualRingBuffer.h b/Utils/VirtualRingBuffer.h new file mode 100644 index 000000000..3f2c1544a --- /dev/null +++ b/Utils/VirtualRingBuffer.h @@ -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 (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 + + +@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 diff --git a/VirtualRingBuffer.m b/Utils/VirtualRingBuffer.m similarity index 100% rename from VirtualRingBuffer.m rename to Utils/VirtualRingBuffer.m